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