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