147fdce3b7e2c015eb20741964327954f70a924a
[mussa.git] / alg / sequence.cpp
1 //  This file is part of the Mussa source distribution.
2 //  http://mussa.caltech.edu/
3 //  Contact author: Tristan  De Buysscher, tristan@caltech.edu
4
5 // This program and all associated source code files are Copyright (C) 2005
6 // the California Institute of Technology, Pasadena, CA, 91125 USA.  It is
7 // under the GNU Public License; please see the included LICENSE.txt
8 // file for more information, or contact Tristan directly.
9
10
11 //  This file is part of the Mussa source distribution.
12 //  http://mussa.caltech.edu/
13 //  Contact author: Tristan  De Buysscher, tristan@caltech.edu
14
15 // This program and all associated source code files are Copyright (C) 2005
16 // the California Institute of Technology, Pasadena, CA, 91125 USA.  It is
17 // under the GNU Public License; please see the included LICENSE.txt
18 // file for more information, or contact Tristan directly.
19
20
21 //                        ----------------------------------------
22 //                           ---------- sequence.cc -----------
23 //                        ----------------------------------------
24 #include <boost/filesystem/fstream.hpp>
25 namespace fs = boost::filesystem;
26
27 #include <boost/spirit/core.hpp>
28 #include <boost/spirit/actor/push_back_actor.hpp>
29 #include <boost/spirit/iterator/file_iterator.hpp>
30 #include <boost/spirit/utility/chset.hpp>
31 namespace spirit = boost::spirit;
32
33 #include "alg/sequence.hpp"
34 #include "mussa_exceptions.hpp"
35
36 #include <string>
37 #include <stdexcept>
38 #include <iostream>
39 #include <sstream>
40 #include <set>
41
42 annot::annot() 
43  : begin(0),
44    end(0),
45    type(""),
46    name("")
47 {
48 }
49
50 annot::annot(int begin, int end, std::string type, std::string name)
51  : begin(begin),
52    end(end),
53    type(type),
54    name(name)
55 {
56 }
57
58 annot::~annot()
59 {
60 }
61
62 bool operator==(const annot& left, const annot& right)
63 {
64   return ((left.begin== right.begin) and
65           (left.end == right.end) and
66           (left.type == right.type) and
67           (left.name == right.name));
68 }
69
70 motif::motif(int begin, std::string motif)
71  : annot(begin, begin+motif.size(), "motif", motif),
72    sequence(motif)
73 {
74 }
75
76 motif::~motif()
77 {
78 }
79
80
81 Sequence::Sequence(alphabet_ref alphabet_)
82   : parent(0),
83     alphabet(alphabet_),
84     seq_start(0),
85     seq_count(0),
86     strand(UnknownStrand)
87 {
88 }
89
90 Sequence::~Sequence()
91 {
92 }
93
94 Sequence::Sequence(const char *seq, alphabet_ref alphabet_)
95   : parent(0),
96     alphabet(alphabet_),
97     seq_start(0),
98     seq_count(0),
99     strand(UnknownStrand),
100     header(""),
101     species("")
102 {
103   set_filtered_sequence(seq, alphabet);
104 }
105
106 Sequence::Sequence(const std::string& seq, alphabet_ref alphabet_) 
107   : parent(0),
108     alphabet(alphabet_),
109     seq_start(0),
110     seq_count(0),
111     strand(UnknownStrand),
112     header(""),
113     species("")
114 {
115   set_filtered_sequence(seq, alphabet);
116 }
117
118 Sequence::Sequence(const Sequence& o)
119   : parent(o.parent),
120     seq(o.seq),
121     alphabet(o.alphabet),
122     seq_start(o.seq_start),
123     seq_count(o.seq_count),
124     strand(o.strand),
125     header(o.header),
126     species(o.species),
127     annots(o.annots),
128     motif_list(o.motif_list)
129 {
130 }
131
132 Sequence &Sequence::operator=(const Sequence& s)
133 {
134   if (this != &s) {
135     parent = s.parent;
136     seq = s.seq;
137     alphabet = s.alphabet;
138     seq_start = s.seq_start;
139     seq_count = s.seq_count;
140     strand = s.strand;
141     header = s.header;
142     species = s.species;
143     annots = s.annots;
144     motif_list = s.motif_list;
145   }
146   return *this;
147 }
148
149 static void multiplatform_getline(std::istream& in, std::string& line)
150 {
151   line.clear();
152   char c;
153   in.get(c);
154   while(in.good() and !(c == '\012' or c == '\015') ) {
155     line.push_back(c);
156     in.get(c);
157   }
158   // if we have cr-lf eat it
159   c = in.peek();
160   if (c=='\012' or c == '\015') {
161     in.get();
162   }
163 }
164
165 void Sequence::load_fasta(fs::path file_path, int seq_num, int start_index, int end_index)
166 {
167   load_fasta(file_path, alphabet, seq_num, start_index, end_index);
168 }
169
170 //! load a fasta file into a sequence
171 void Sequence::load_fasta(fs::path file_path, alphabet_ref a, 
172                           int seq_num, int start_index, int end_index)
173 {
174   fs::fstream data_file;
175   data_file.open(file_path, std::ios::in);
176
177   if (!data_file.good())
178   {    
179     throw mussa_load_error("Sequence File: "+file_path.string()+" not found"); 
180   } else {
181     try {
182       load_fasta(data_file, a, seq_num, start_index, end_index);
183     } catch(sequence_empty_error e) {
184       // there doesn't appear to be any sequence
185       // catch and rethrow to include the filename
186       std::stringstream msg;
187       msg << "The selected sequence in " 
188           << file_path.native_file_string()
189           << " appears to be empty"; 
190       throw sequence_empty_error(msg.str());
191     } catch(sequence_empty_file_error e) {
192       std::stringstream errormsg;
193       errormsg << file_path.native_file_string()
194                << " did not have any fasta sequences" << std::endl;
195       throw sequence_empty_file_error(errormsg.str());
196     } catch(sequence_invalid_load_error e) {
197       std::ostringstream msg;
198       msg << file_path.native_file_string();
199       msg << " " << e.what();
200       throw sequence_invalid_load_error(msg.str());
201     }
202   }
203 }
204
205 void Sequence::load_fasta(std::istream& file, 
206                           int seq_num, int start_index, int end_index)
207 {
208   load_fasta(file, alphabet, seq_num, start_index, end_index);
209 }
210
211 void
212 Sequence::load_fasta(std::istream& data_file, alphabet_ref a, 
213                      int seq_num, 
214                      int start_index, int end_index)
215 {
216   std::string file_data_line;
217   int header_counter = 0;
218   size_t line_counter = 0;
219   bool read_seq = true;
220   std::string rev_comp;
221   std::string sequence_raw;
222   std::string seq_tmp;      // holds sequence during basic filtering
223   const Alphabet &alpha = get_alphabet(a);
224
225   if (seq_num == 0) {
226     throw mussa_load_error("fasta sequence number is 1 based (can't be 0)");
227   }
228
229   // search for the header of the fasta sequence we want
230   while ( (!data_file.eof()) && (header_counter < seq_num) )
231   {
232     multiplatform_getline(data_file, file_data_line);
233     ++line_counter;
234     if (file_data_line.substr(0,1) == ">")
235       header_counter++;
236   }
237
238   if (header_counter > 0) {
239     header = file_data_line.substr(1);
240
241     sequence_raw = "";
242
243     while ( !data_file.eof() && read_seq ) {
244       multiplatform_getline(data_file,file_data_line);
245       ++line_counter;
246       if (file_data_line.substr(0,1) == ">")
247         read_seq = false;
248       else {
249         for (std::string::const_iterator line_i = file_data_line.begin();
250              line_i != file_data_line.end();
251              ++line_i)
252          {
253            if(alpha.exists(*line_i)) {
254              sequence_raw += *line_i;
255            } else {
256             std::ostringstream msg;
257             msg << "Unrecognized characters in fasta sequence at line ";
258             msg << line_counter;
259             throw sequence_invalid_load_error(msg.str());
260            }
261          }
262       }
263     }
264
265     // Lastly, if subselection of the sequence was specified we keep cut out
266     // and only keep that part
267     // end_index = 0 means no end was specified, so cut to the end 
268     if (end_index == 0)
269       end_index = sequence_raw.size();
270
271     // sequence filtering for upcasing agctn and convert non AGCTN to N
272     if (end_index-start_index <= 0) {
273       std::string msg("The selected sequence appears to be empty"); 
274       throw sequence_empty_error(msg);
275     }
276     set_filtered_sequence(sequence_raw, a, start_index, end_index-start_index);
277   } else {
278     std::string errormsg("There were no fasta sequences");
279     throw sequence_empty_file_error(errormsg);
280   }
281 }
282
283 void Sequence::set_filtered_sequence(const std::string &in_seq,
284                                      alphabet_ref alphabet_,
285                                      size_type start,
286                                      size_type count,
287                                      strand_type strand_)
288 {
289   alphabet = alphabet_;
290   if ( count == npos)
291     count = in_seq.size() - start;
292   boost::shared_ptr<seq_string> new_seq(new seq_string);
293   new_seq->reserve(count);
294
295   // finally, the actual conversion loop
296   const Alphabet& alpha_impl = get_alphabet(); // go get one of our actual alphabets
297   std::string::const_iterator seq_i = in_seq.begin()+start;
298   for(size_type i = 0; i != count; ++i, ++seq_i)
299   {
300     if (alpha_impl.exists(*seq_i)) {
301       new_seq->append(1, toupper(*seq_i));
302     } else {
303       new_seq->append(1, 'N');
304     }
305   }
306   parent = 0;
307   seq = new_seq;
308   seq_start = 0;
309   seq_count = count;
310   strand = strand_;
311 }
312
313 void
314 Sequence::load_annot(fs::path file_path, int start_index, int end_index)
315 {
316   fs::fstream data_stream(file_path, std::ios::in);
317   if (!data_stream)
318   {
319     throw mussa_load_error("Sequence File: " + file_path.string() + " not found");
320   }
321
322   // so i should probably be passing the parse function some iterators
323   // but the annotations files are (currently) small, so i think i can 
324   // get away with loading the whole file into memory
325   std::string data;
326   char c;
327   while(data_stream.good()) {
328     data_stream.get(c);
329     data.push_back(c);
330   }
331   data_stream.close();
332
333   try {  
334     parse_annot(data, start_index, end_index);
335   } catch(annotation_load_error e) {
336     std::ostringstream msg;
337     msg << file_path.native_file_string()
338         << " "
339         << e.what();
340     throw annotation_load_error(msg.str());
341   }
342 }
343
344 /* If this works, yikes, this is some brain hurting code.
345  *
346  * what's going on is that when pb_annot is instantiated it stores references
347  * to begin, end, name, type, declared in the parse function, then
348  * when operator() is called it grabs values from those references
349  * and uses that to instantiate an annot object and append that to our
350  * annotation list.
351  *
352  * This weirdness is because the spirit library requires that actions
353  * conform to a specific prototype operator()(IteratorT, IteratorT)
354  * which doesn't provide any useful opportunity for me to actually
355  * grab the results of our parsing.
356  *
357  * so I instantiate this structure in order to have a place to grab
358  * my data from.
359  */
360   
361 struct push_back_annot {
362   std::list<annot>& annot_list;
363   int& begin;
364   int& end;
365   std::string& name;
366   std::string& type;
367   int &parsed;
368
369   push_back_annot(std::list<annot>& annot_list_, 
370                   int& begin_, 
371                   int& end_, 
372                   std::string& name_, 
373                   std::string& type_,
374                   int &parsed_) 
375   : annot_list(annot_list_), 
376     begin(begin_),
377     end(end_),
378     name(name_),
379     type(type_),
380     parsed(parsed_)
381   {
382   }
383
384   void operator()(std::string::const_iterator, 
385                   std::string::const_iterator) const 
386   {
387     //std::cout << "adding annot: " << begin << "|" << end << "|" << name << "|" << type << std::endl;
388     annot_list.push_back(annot(begin, end, name, type));
389     ++parsed;
390   };
391 };
392
393 struct push_back_seq {
394   std::list<Sequence>& seq_list;
395   std::string& name;
396   std::string& seq;
397   int &parsed;
398
399   push_back_seq(std::list<Sequence>& seq_list_,
400                 std::string& name_, 
401                 std::string& seq_,
402                 int &parsed_)
403   : seq_list(seq_list_), 
404     name(name_),
405     seq(seq_),
406     parsed(parsed_)
407   {
408   }
409
410   void operator()(std::string::const_iterator, 
411                   std::string::const_iterator) const 
412   {
413     // filter out newlines from our sequence
414     std::string new_seq;
415     for(std::string::const_iterator seq_i = seq.begin();
416         seq_i != seq.end();
417         ++seq_i)
418     {
419       if (*seq_i != '\015' && *seq_i != '\012') new_seq += *seq_i;
420     }
421     //std::cout << "adding seq: " << name << " " << new_seq << std::endl;
422     
423     Sequence s(new_seq);
424     s.set_fasta_header(name);
425     seq_list.push_back(s);
426     ++parsed;
427   };
428 };
429
430 void
431 Sequence::parse_annot(std::string data, int start_index, int end_index)
432 {
433   int start=0;
434   int end=0;
435   std::string name;
436   std::string type;
437   std::string seq;
438   std::list<annot> parsed_annots;
439   std::list<Sequence> query_seqs;
440   int parsed=0;
441
442   bool ok = spirit::parse(data.begin(), data.end(),
443               (
444                //begin grammar
445                  !(
446                     (
447                       spirit::alpha_p >> 
448                       +(spirit::graph_p)
449                     )[spirit::assign_a(species)] >> 
450                     +(spirit::space_p)
451                   ) >>
452                   *(
453                      ( // ignore html tags
454                        *(spirit::space_p) >>
455                        spirit::ch_p('<') >> 
456                        +(~spirit::ch_p('>')) >>
457                        spirit::ch_p('>') >>
458                        *(spirit::space_p)
459                      )
460                    |
461                     ( // parse an absolute location name
462                      (spirit::uint_p[spirit::assign_a(start)] >> 
463                       +spirit::space_p >>
464                       spirit::uint_p[spirit::assign_a(end)] >> 
465                       +spirit::space_p >>
466                       ( 
467                          spirit::alpha_p >> 
468                          *spirit::graph_p
469                       )[spirit::assign_a(name)] >> 
470                       // optional type
471                       !(
472                           +spirit::space_p >>
473                           (
474                             spirit::alpha_p >>
475                             *spirit::graph_p
476                           )[spirit::assign_a(type)]
477                       )
478                       // to understand how this group gets set
479                       // read the comment above struct push_back_annot
480                      )[push_back_annot(parsed_annots, start, end, type, name, parsed)]
481                    |
482                     ((spirit::ch_p('>')|spirit::str_p("&gt;")) >> 
483                        (*(spirit::print_p))[spirit::assign_a(name)] >>
484                        spirit::eol_p >> 
485                        (+(spirit::chset<>(Alphabet::nucleic_cstr)))[spirit::assign_a(seq)]
486                      )[push_back_seq(query_seqs, name, seq, parsed)]
487                     ) >>
488                     *spirit::space_p
489                    )
490               //end grammar
491               )).full;
492   if (not ok) {
493     std::stringstream msg;
494     msg << "Error parsing annotation #" << parsed;
495     throw annotation_load_error(msg.str());
496   }
497   // add newly parsed annotations to our sequence
498   std::copy(parsed_annots.begin(), parsed_annots.end(), std::back_inserter(annots));
499   // go seearch for query sequences 
500   find_sequences(query_seqs.begin(), query_seqs.end());
501 }
502
503 void Sequence::add_annotation(const annot& a)
504 {
505   annots.push_back(a);
506 }
507
508 const std::list<annot>& Sequence::annotations() const
509 {
510   return annots;
511 }
512
513 Sequence
514 Sequence::subseq(int start, int count)
515 {
516   if (!seq) {
517     Sequence new_seq;
518     return new_seq;
519   }
520
521   // there might be an off by one error with start+count > size()
522   if ( count == npos || start+count > size()) {
523     count = size()-start;
524   }
525   Sequence new_seq(*this);
526   new_seq.parent = this;
527   new_seq.seq_start = seq_start+start;
528   new_seq.seq_count = count;
529
530   new_seq.motif_list = motif_list;
531   new_seq.annots.clear();
532   // attempt to copy & reannotate position based annotations 
533   int end = start+count;
534
535   for(std::list<annot>::const_iterator annot_i = annots.begin();
536       annot_i != annots.end();
537       ++annot_i)
538   {
539     int annot_begin= annot_i->begin;
540     int annot_end = annot_i->end;
541
542     if (annot_begin < end) {
543       if (annot_begin >= start) {
544         annot_begin -= start;
545       } else {
546         annot_begin = 0;
547       }
548
549       if (annot_end < end) {
550         annot_end -= start;
551       } else {
552         annot_end = count;
553       }
554
555       annot new_annot(annot_begin, annot_end, annot_i->type, annot_i->name);
556       new_seq.annots.push_back(new_annot);
557     }
558   }
559
560   return new_seq;
561 }
562
563 std::string Sequence::create_reverse_map() const 
564 {
565   std::string rc_map(256, '~');
566   // if we're rna, use U instead of T
567   // we might want to add an "is_rna" to sequence at somepoint
568   char TU = (alphabet == reduced_rna_alphabet) ? 'U' : 'T';
569   char tu = (alphabet == reduced_rna_alphabet) ? 'u' : 't';
570   rc_map['A'] = TU ; rc_map['a'] = tu ;
571   rc_map['T'] = 'A'; rc_map['t'] = 'a';
572   rc_map['U'] = 'A'; rc_map['u'] = 'a';
573   rc_map['G'] = 'C'; rc_map['g'] = 'c';
574   rc_map['C'] = 'G'; rc_map['c'] = 'g';
575   rc_map['M'] = 'K'; rc_map['m'] = 'k';
576   rc_map['R'] = 'Y'; rc_map['r'] = 'y';
577   rc_map['W'] = 'W'; rc_map['w'] = 'w';
578   rc_map['S'] = 'S'; rc_map['s'] = 's';
579   rc_map['Y'] = 'R'; rc_map['y'] = 'r';
580   rc_map['K'] = 'M'; rc_map['k'] = 'm';
581   rc_map['V'] = 'B'; rc_map['v'] = 'b';
582   rc_map['H'] = 'D'; rc_map['h'] = 'd';
583   rc_map['D'] = 'H'; rc_map['d'] = 'h';
584   rc_map['B'] = 'V'; rc_map['b'] = 'v';  
585   rc_map['N'] = 'N'; rc_map['n'] = 'n';
586   rc_map['X'] = 'X'; rc_map['x'] = 'x';
587   rc_map['?'] = '?'; 
588   rc_map['.'] = '.'; 
589   rc_map['-'] = '-'; 
590   rc_map['~'] = '~'; // not really needed, but perhaps it's clearer. 
591   return rc_map;
592 }
593
594 Sequence Sequence::rev_comp() const
595 {
596   std::string rev_comp;
597   rev_comp.reserve(length());
598   
599   std::string rc_map = create_reverse_map();
600
601   // reverse and convert
602   Sequence::const_reverse_iterator seq_i;
603   Sequence::const_reverse_iterator seq_end = rend();  
604   for(seq_i = rbegin(); 
605       seq_i != seq_end;
606       ++seq_i)
607   {
608     rev_comp.append(1, rc_map[*seq_i]);
609   }
610   return Sequence(rev_comp, alphabet); 
611 }
612
613 void Sequence::set_fasta_header(std::string header_)
614 {
615   header = header_;
616 }
617
618 void Sequence::set_species(const std::string& name)
619 {
620   species = name;
621 }
622
623 std::string Sequence::get_species() const
624 {
625   return species;
626 }
627
628
629 std::string
630 Sequence::get_fasta_header() const
631 {
632   return header;
633 }
634
635 std::string
636 Sequence::get_name() const
637 {
638   if (header.size() > 0) 
639     return header;
640   else if (species.size() > 0)
641     return species;
642   else
643     return "";
644 }
645
646 const Alphabet& Sequence::get_alphabet() const
647 {
648   return get_alphabet(alphabet);
649 }
650
651 const Alphabet& Sequence::get_alphabet(alphabet_ref alpha) const
652 {
653   switch (alpha) {
654     case reduced_dna_alphabet:
655       return Alphabet::reduced_dna_alphabet();
656     case reduced_rna_alphabet:
657       return Alphabet::reduced_rna_alphabet();
658     case reduced_nucleic_alphabet:
659       return Alphabet::reduced_nucleic_alphabet();
660     case nucleic_alphabet:
661       return Alphabet::nucleic_alphabet();
662     case protein_alphabet:
663       return Alphabet::protein_alphabet();    
664     default:
665       throw std::runtime_error("unrecognized alphabet type");
666       break;
667   }
668 }
669
670 void Sequence::set_sequence(const std::string& s, alphabet_ref a) 
671 {
672   set_filtered_sequence(s, a);
673 }
674
675 std::string Sequence::get_sequence() const
676 {
677   if (seq) 
678     return *seq;
679   else
680     return std::string();
681 }
682
683 Sequence::const_reference Sequence::operator[](Sequence::size_type i) const
684 {
685   return at(i);
686 }
687
688 Sequence::const_reference Sequence::at(Sequence::size_type i) const
689 {
690   if (!seq) throw std::out_of_range("empty sequence");
691   return seq->at(i+seq_start);
692 }
693
694 void
695 Sequence::clear()
696 {
697   parent = 0;
698   seq.reset();
699   seq_start = 0;
700   seq_count = 0;
701   strand = UnknownStrand;
702   header.clear();
703   species.clear();
704   annots.clear();
705   motif_list.clear();
706 }
707
708 const char *Sequence::c_str() const
709 {
710   if (seq) 
711     return seq->c_str()+seq_start;
712   else 
713     return 0;
714 }
715
716 Sequence::const_iterator Sequence::begin() const
717 {
718   if (seq and seq_count != 0)
719     return seq->begin()+seq_start;
720   else 
721     return Sequence::const_iterator(0);
722 }
723
724 Sequence::const_iterator Sequence::end() const
725 {
726   if (seq and seq_count != 0) {
727     return seq->begin() + seq_start + seq_count;
728   } else {
729     return Sequence::const_iterator(0);
730   }
731 }
732
733 Sequence::const_reverse_iterator Sequence::rbegin() const
734 {
735   if (seq and seq_count != 0)
736     return seq->rbegin()+(seq->size()-(seq_start+seq_count));
737   else 
738     return Sequence::const_reverse_iterator();
739 }
740
741 Sequence::const_reverse_iterator Sequence::rend() const
742 {
743   if (seq and seq_count != 0) {
744     return rbegin() + seq_count;
745   } else {
746     return Sequence::const_reverse_iterator();
747   }
748 }
749
750 bool Sequence::empty() const
751 {
752   return (seq_count == 0) ? true : false;
753 }
754
755 Sequence::size_type Sequence::find_first_not_of(
756   const std::string& query, 
757   Sequence::size_type index)
758 {
759   typedef std::set<std::string::value_type> sequence_set;
760   sequence_set match_set;
761   
762   for(const_iterator query_item = query.begin();
763       query_item != query.end();
764       ++query_item)
765   {
766     match_set.insert(*query_item);
767   }  
768   for(const_iterator base = begin();
769       base != end();
770       ++base)
771   {
772     if(match_set.find(*base) == match_set.end()) {
773       return base-begin();
774     } 
775   }
776   return Sequence::npos;
777 }
778  
779 Sequence::size_type Sequence::start() const
780 {
781   if (parent)
782     return seq_start - parent->start();
783   else
784     return seq_start;
785 }
786
787 Sequence::size_type Sequence::stop() const
788 {
789   return start() + seq_count;
790 }
791
792 Sequence::size_type Sequence::size() const
793 {
794   return seq_count;
795 }
796
797 Sequence::size_type Sequence::length() const
798 {
799   return size();
800 }
801
802 void
803 Sequence::save(fs::fstream &save_file)
804 {
805   //fstream save_file;
806   std::list<annot>::iterator annots_i;
807
808   // not sure why, or if i'm doing something wrong, but can't seem to pass
809   // file pointers down to this method from the mussa control class
810   // so each call to save a sequence appends to the file started by mussa_class
811   //save_file.open(save_file_path.c_str(), std::ios::app);
812
813   save_file << "<Sequence>" << std::endl;
814   save_file << *this << std::endl;
815   save_file << "</Sequence>" << std::endl;
816
817   save_file << "<Annotations>" << std::endl;
818   save_file << species << std::endl;
819   for (annots_i = annots.begin(); annots_i != annots.end(); ++annots_i)
820   {
821     save_file << annots_i->begin << " " << annots_i->end << " " ;
822     save_file << annots_i->name << " " << annots_i->type << std::endl;
823   }
824   save_file << "</Annotations>" << std::endl;
825   //save_file.close();
826 }
827
828 void
829 Sequence::load_museq(fs::path load_file_path, int seq_num)
830 {
831   fs::fstream load_file;
832   std::string file_data_line;
833   int seq_counter;
834   annot an_annot;
835   std::string::size_type space_split_i;
836   std::string annot_value;
837
838   annots.clear();
839   load_file.open(load_file_path, std::ios::in);
840
841   seq_counter = 0;
842   // search for the seq_num-th sequence 
843   while ( (!load_file.eof()) && (seq_counter < seq_num) )
844   {
845     getline(load_file,file_data_line);
846     if (file_data_line == "<Sequence>")
847       seq_counter++;
848   }
849   getline(load_file, file_data_line);
850   // looks like the sequence is written as a single line
851   set_filtered_sequence(file_data_line, reduced_dna_alphabet);
852   getline(load_file, file_data_line);
853   getline(load_file, file_data_line);
854   if (file_data_line == "<Annotations>")
855   {
856     getline(load_file, file_data_line);
857     species = file_data_line;
858     while ( (!load_file.eof())  && (file_data_line != "</Annotations>") )
859     {
860       getline(load_file,file_data_line);
861       if ((file_data_line != "") && (file_data_line != "</Annotations>"))  
862       {
863         // need to get 4 values...almost same code 4 times...
864         // get annot start index
865         space_split_i = file_data_line.find(" ");
866         annot_value = file_data_line.substr(0,space_split_i);
867         an_annot.begin = atoi (annot_value.c_str());
868         file_data_line = file_data_line.substr(space_split_i+1);
869         // get annot end index
870         space_split_i = file_data_line.find(" ");
871         annot_value = file_data_line.substr(0,space_split_i);
872         an_annot.end = atoi (annot_value.c_str());
873
874         if (space_split_i == std::string::npos)  // no entry for type or name
875         {
876           std::cout << "seq, annots - no type or name\n";
877           an_annot.type = "";
878           an_annot.name = "";
879         }
880         else   // else get annot type
881         {
882           file_data_line = file_data_line.substr(space_split_i+1);
883           space_split_i = file_data_line.find(" ");
884           annot_value = file_data_line.substr(0,space_split_i);
885           an_annot.type = annot_value;
886           if (space_split_i == std::string::npos)  // no entry for name
887           {
888             std::cout << "seq, annots - no name\n";
889             an_annot.name = "";
890           }
891           else          // get annot name
892           {
893             file_data_line = file_data_line.substr(space_split_i+1);
894             space_split_i = file_data_line.find(" ");
895             annot_value = file_data_line.substr(0,space_split_i);
896             an_annot.type = annot_value;
897           }
898         }
899         annots.push_back(an_annot);  // don't forget to actually add the annot
900       }
901       //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
902       //     << "-->" << an_annot.type << "::" << an_annot.name << std::endl;
903     }
904   }
905   load_file.close();
906 }
907
908
909 void Sequence::add_motif(const Sequence& a_motif)
910 {
911   std::vector<int> motif_starts = find_motif(a_motif);
912
913   for(std::vector<int>::iterator motif_start_i = motif_starts.begin();
914       motif_start_i != motif_starts.end();
915       ++motif_start_i)
916   {
917     motif_list.push_back(motif(*motif_start_i, a_motif.get_sequence()));
918   }
919 }
920
921 void Sequence::clear_motifs()
922 {
923   motif_list.clear();
924 }
925
926 const std::list<motif>& Sequence::motifs() const
927 {
928   return motif_list;
929 }
930
931 std::vector<int>
932 Sequence::find_motif(const Sequence& a_motif) const
933 {
934   std::vector<int> motif_match_starts;
935   Sequence norm_motif_rc;
936
937   motif_match_starts.clear();
938   // std::cout << "motif is: " << norm_motif << std::endl;
939
940   if (a_motif.size() > 0)
941   {
942     //std::cout << "Sequence: none blank motif\n";
943     motif_scan(a_motif, &motif_match_starts);
944
945     norm_motif_rc = a_motif.rev_comp();;
946     // make sure not to do search again if it is a palindrome
947     if (norm_motif_rc != a_motif) {
948       motif_scan(norm_motif_rc, &motif_match_starts);
949     }
950   }
951   return motif_match_starts;
952 }
953
954 void
955 Sequence::motif_scan(const Sequence& a_motif, std::vector<int> * motif_match_starts) const
956 {
957   // if there's no sequence we can't scan for it?
958   // should this throw an exception?
959   if (!seq) return;
960
961   std::string::size_type seq_i = 0;
962   Sequence::size_type motif_i = 0;
963   Sequence::size_type motif_len = a_motif.length();
964   Sequence::value_type motif_char;
965   Sequence::value_type seq_char;
966
967   while (seq_i < size())
968   {
969     // this is pretty much a straight translation of Nora's python code
970     // to match iupac letter codes
971     motif_char = toupper(a_motif[motif_i]);
972     seq_char = toupper(seq->at(seq_start+seq_i));
973     if (motif_char =='N')
974       motif_i++;
975     else if (motif_char == seq_char)
976       motif_i++;
977     else if ((motif_char =='M') && ((seq_char=='A') || (seq_char=='C')))
978       motif_i++;
979     else if ((motif_char =='R') && ((seq_char=='A') || (seq_char=='G')))
980       motif_i++;
981     else if ((motif_char =='W') && ((seq_char=='A') || (seq_char=='T')))
982       motif_i++;
983     else if ((motif_char =='S') && ((seq_char=='C') || (seq_char=='G')))
984       motif_i++;
985     else if ((motif_char =='Y') && ((seq_char=='C') || (seq_char=='T')))
986       motif_i++;
987     else if ((motif_char =='K') && ((seq_char=='G') || (seq_char=='T')))
988       motif_i++;
989     else if ((motif_char =='V') && 
990              ((seq_char=='A') || (seq_char=='C') || (seq_char=='G')))
991       motif_i++;
992     else if ((motif_char =='H') && 
993              ((seq_char=='A') || (seq_char=='C') || (seq_char=='T')))
994       motif_i++;
995     else if ((motif_char =='D') &&
996              ((seq_char=='A') || (seq_char=='G') || (seq_char=='T')))
997       motif_i++;
998     else if ((motif_char =='B') &&
999              ((seq_char=='C') || (seq_char=='G') || (seq_char=='T')))
1000       motif_i++;
1001     else
1002     {
1003       // if a motif doesn't match, erase our current trial and try again
1004       seq_i -= motif_i;
1005       motif_i = 0;
1006     }
1007
1008     // end Nora stuff, now we see if a match is found this pass
1009     if (motif_i == motif_len)
1010     {
1011       annot new_motif;
1012       motif_match_starts->push_back(seq_i - motif_len + 1);
1013       motif_i = 0;
1014     }
1015
1016     seq_i++;
1017   }
1018   //std::cout << std::endl;
1019 }
1020
1021 void Sequence::add_string_annotation(std::string a_seq, 
1022                                      std::string name)
1023 {
1024   std::vector<int> seq_starts = find_motif(a_seq);
1025   
1026   //std::cout << "searching for " << a_seq << " found " << seq_starts.size() << std::endl;
1027
1028   for(std::vector<int>::iterator seq_start_i = seq_starts.begin();
1029       seq_start_i != seq_starts.end();
1030       ++seq_start_i)
1031   {
1032     annots.push_back(annot(*seq_start_i, 
1033                            *seq_start_i+a_seq.size(),
1034                            "",
1035                            name));
1036   }
1037 }
1038
1039 void Sequence::find_sequences(std::list<Sequence>::iterator start, 
1040                               std::list<Sequence>::iterator end)
1041 {
1042   while (start != end) {
1043     add_string_annotation(start->get_sequence(), start->get_fasta_header());
1044     ++start;
1045   }
1046 }
1047
1048
1049 std::ostream& operator<<(std::ostream& out, const Sequence& s)
1050 {
1051   for(Sequence::const_iterator s_i = s.begin(); s_i != s.end(); ++s_i) {
1052     out << *s_i;
1053   }
1054   return out;
1055 }
1056
1057 bool operator<(const Sequence& x, const Sequence& y)
1058 {
1059   Sequence::const_iterator x_i = x.begin();
1060   Sequence::const_iterator y_i = y.begin();
1061   // for sequences there's some computation associated with computing .end
1062   // so lets cache it.
1063   Sequence::const_iterator xend = x.end();
1064   Sequence::const_iterator yend = y.end();
1065   while(1) {
1066     if( x_i == xend and y_i == yend ) {
1067       return false;
1068     } else if ( x_i == xend ) {
1069       return true;
1070     } else if ( y_i == yend ) {
1071       return false;
1072     } else if ( (*x_i) < (*y_i)) {
1073       return true;
1074     } else if ( (*x_i) > (*y_i) ) {
1075       return false;
1076     } else {
1077       ++x_i;
1078       ++y_i;
1079     }
1080   }
1081 }
1082
1083 bool operator==(const Sequence& x, const Sequence& y) 
1084 {
1085   if (x.empty() and y.empty()) {
1086     // if there's no sequence in either sequence structure, they're equal
1087     return true;
1088   } else if (x.empty() or y.empty()) {
1089     // if we fail the first test, and we discover one is empty,
1090     // we know they can't be equal. (and we need to do this
1091     // to prevent dereferencing an empty pointer)
1092     return false;
1093   } else if (x.seq_count != y.seq_count) {
1094     // if they're of different lenghts, they're not equal
1095     return false;
1096   }
1097   Sequence::const_iterator xseq_i = x.begin();
1098   Sequence::const_iterator yseq_i = y.begin();
1099   // since the length of the two sequences is equal, we only need to
1100   // test one.
1101   for(; xseq_i != x.end(); ++xseq_i, ++yseq_i) {
1102     if (toupper(*xseq_i) != toupper(*yseq_i)) {
1103       return false;
1104     }
1105   }
1106   return true;
1107 }
1108
1109 bool operator!=(const Sequence& x, const Sequence& y) 
1110 {
1111   return not operator==(x, y);
1112 }