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