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