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