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