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