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