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