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