try to read fasta blocks in the annotation file
[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     std::cout << "adding seq: " << name << " " << seq << std::endl;
301     Sequence s(seq);
302     s.set_header(name);
303     seq_list.push_back(s);
304   };
305 };
306
307 void
308 Sequence::parse_annot(std::string data, int start_index, int end_index)
309 {
310   int start=0;
311   int end=0;
312   std::string name;
313   std::string type;
314   std::string seq;
315   std::list<Sequence> query_seqs;
316
317   bool status = spirit::parse(data.begin(), data.end(),
318                 //begin grammar
319                 (
320                 (+(spirit::alpha_p))[spirit::assign_a(species)] >> 
321                     *(
322                        // parse an absolute location name
323                        (spirit::uint_p[spirit::assign_a(start)] >> 
324                         spirit::uint_p[spirit::assign_a(end)] >> 
325                         (*(spirit::alpha_p))[spirit::assign_a(name)]/* >> 
326                         (*(spirit::alpha_p))[spirit::assign_a(type)]*/
327                         // to understand how this group gets set
328                         // read the comment above struct push_back_annot
329                        )[push_back_annot(annots, start, end, type, name)]
330                      |
331                       (spirit::ch_p('>') >> 
332                        (*(spirit::alpha_p))[spirit::assign_a(name)] >>
333                        (+(spirit::ch_p('A')|
334                           spirit::ch_p('G')|
335                           spirit::ch_p('C')|
336                           spirit::ch_p('T'))[spirit::assign_a(seq)])
337                        )[push_back_seq(query_seqs, name, seq)]
338                      )
339                 ),
340                 //end grammar
341                 spirit::space_p).full;
342 }
343
344 /*
345 void
346 Sequence::load_annot(std::istream& data_stream, int start_index, int end_index)
347 {
348   std::string file_data_line;
349   annot an_annot;
350   std::string::size_type space_split_i;
351   std::string annot_value;
352   std::list<annot>::iterator list_i;
353   std::string err_msg;
354
355   annots.clear();
356
357   getline(data_stream,file_data_line);
358   species = file_data_line;
359
360   // end_index = 0 means no end was specified, so cut to the end 
361   if (end_index == 0)
362     end_index = sequence.length();
363
364   //std::cout << "START: " << start_index << " END: " << end_index << std::endl;
365
366   while ( !data_stream.eof() )
367   {
368     getline(data_stream,file_data_line);
369     if (file_data_line != "")
370     {
371       // need to get 4 values...almost same code 4 times...
372       // get annot start index
373       space_split_i = file_data_line.find(" ");
374       annot_value = file_data_line.substr(0,space_split_i);
375       an_annot.start = atoi (annot_value.c_str());
376       file_data_line = file_data_line.substr(space_split_i+1);
377       // get annot end index
378       space_split_i = file_data_line.find(" ");
379       annot_value = file_data_line.substr(0,space_split_i);
380       an_annot.end = atoi (annot_value.c_str());
381       file_data_line = file_data_line.substr(space_split_i+1);
382
383       //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
384       //     << std::endl;
385
386       // get annot name
387       space_split_i = file_data_line.find(" ");
388       if (space_split_i == std::string::npos)  // no entries for name & type
389       {
390         std::cout << "seq, annots - no name or type\n";
391         an_annot.name = "";
392         an_annot.type = "";
393       }
394       else
395       {
396         annot_value = file_data_line.substr(0,space_split_i);
397         an_annot.name = annot_value;
398         file_data_line = file_data_line.substr(space_split_i+1);
399         // get annot type
400         space_split_i = file_data_line.find(" ");
401         if (space_split_i == std::string::npos)  // no entry for type
402           an_annot.type = "";
403         else
404         {
405           annot_value = file_data_line.substr(0,space_split_i);
406           an_annot.type = annot_value;
407         }
408       }
409
410
411       // add annot to list if it falls within the range of sequence specified
412       if ((start_index <= an_annot.start) && (end_index >= an_annot.end)) 
413       {
414         an_annot.start -= start_index;
415         an_annot.end -= start_index;
416         annots.push_back(an_annot);
417       }
418       // else no (or bogus) annotations
419     }
420   }
421 }
422 */
423
424 const std::string& Sequence::get_species() const
425 {
426   return species;
427 }
428
429 bool Sequence::empty() const
430 {
431   return (size() == 0);
432 }
433
434 const std::list<annot>& Sequence::annotations() const
435 {
436   return annots;
437 }
438
439 std::string::size_type Sequence::length() const
440 {
441   return size();
442 }
443
444 std::string::size_type Sequence::size() const
445 {
446   return sequence.size();
447 }
448
449 Sequence::iterator Sequence::begin()
450 {
451   return sequence.begin();
452 }
453
454 Sequence::const_iterator Sequence::begin() const
455 {
456   return sequence.begin();
457 }
458
459 Sequence::iterator Sequence::end()
460 {
461   return sequence.end();
462 }
463
464 Sequence::const_iterator Sequence::end() const
465 {
466   return sequence.end();
467 }
468
469
470 const std::string&
471 Sequence::get_seq() const
472 {
473   return sequence;
474 }
475
476
477 std::string
478 Sequence::subseq(int start, int end) const
479 {
480   return sequence.substr(start, end);
481 }
482
483
484 const char *
485 Sequence::c_seq() const
486 {
487   return sequence.c_str();
488 }
489
490 std::string
491 Sequence::rev_comp() const
492 {
493   std::string rev_comp;
494   char conversionTable[257];
495   int seq_i, table_i, len;
496
497   len = sequence.length();
498   rev_comp.reserve(len);
499   // make a conversion table
500   // init all parts of conversion table to '~' character
501   // '~' I doubt will ever appear in a sequence file (jeez, I hope)
502   // and may the fleas of 1000 camels infest the genitals of any biologist (and
503   // seven generations of their progeny) who decides to make it mean
504   // something special!!!
505   // PS - double the curse for any smartass non-biologist who tries it as well
506   for(table_i=0; table_i < 256; table_i++)
507   {
508     conversionTable[table_i] = '~';
509   }
510   // add end of string character for printing out table for testing purposes
511   conversionTable[256] = '\0';
512
513   // add in the characters for the bases we want to convert
514   conversionTable[(int)'A'] = 'T';
515   conversionTable[(int)'T'] = 'A';
516   conversionTable[(int)'G'] = 'C';
517   conversionTable[(int)'C'] = 'G';
518   conversionTable[(int)'N'] = 'N';
519
520   // finally, the actual conversion loop
521   for(seq_i = len - 1; seq_i >= 0; seq_i--)
522   {
523     table_i = (int) sequence[seq_i];
524     rev_comp += conversionTable[table_i];
525   }
526
527   return rev_comp;
528 }
529
530 void Sequence::set_header(std::string &header_)
531 {
532   header = header_;
533 }
534
535 const std::string&
536 Sequence::get_header() const
537 {
538   return header;
539 }
540 /*
541 //FIXME: i don't think this code is callable
542 std::string 
543 Sequence::sp_name() const
544 {
545   return species;
546 }
547 */
548
549 void
550 Sequence::set_seq(const std::string& a_seq)
551 {
552   set_filtered_sequence(a_seq);
553 }
554
555
556 /*
557 std::string 
558 Sequence::species()
559 {
560   return species;
561 }
562 */
563
564 void
565 Sequence::clear()
566 {
567   sequence = "";
568   header = "";
569   species = "";
570   annots.clear();
571 }
572
573 void
574 Sequence::save(fs::fstream &save_file)
575                //std::string save_file_path)
576 {
577   //fstream save_file;
578   std::list<annot>::iterator annots_i;
579
580   // not sure why, or if i'm doing something wrong, but can't seem to pass
581   // file pointers down to this method from the mussa control class
582   // so each call to save a sequence appends to the file started by mussa_class
583   //save_file.open(save_file_path.c_str(), std::ios::app);
584
585   save_file << "<Sequence>" << std::endl;
586   save_file << sequence << std::endl;
587   save_file << "</Sequence>" << std::endl;
588
589   save_file << "<Annotations>" << std::endl;
590   save_file << species << std::endl;
591   for (annots_i = annots.begin(); annots_i != annots.end(); ++annots_i)
592   {
593     save_file << annots_i->start << " " << annots_i->end << " " ;
594     save_file << annots_i->name << " " << annots_i->type << std::endl;
595   }
596   save_file << "</Annotations>" << std::endl;
597   //save_file.close();
598 }
599
600 void
601 Sequence::load_museq(fs::path load_file_path, int seq_num)
602 {
603   fs::fstream load_file;
604   std::string file_data_line;
605   int seq_counter;
606   annot an_annot;
607   std::string::size_type space_split_i;
608   std::string annot_value;
609
610   annots.clear();
611   load_file.open(load_file_path, std::ios::in);
612
613   seq_counter = 0;
614   // search for the seq_num-th sequence 
615   while ( (!load_file.eof()) && (seq_counter < seq_num) )
616   {
617     getline(load_file,file_data_line);
618     if (file_data_line == "<Sequence>")
619       seq_counter++;
620   }
621   getline(load_file, file_data_line);
622   sequence = file_data_line;
623   getline(load_file, file_data_line);
624   getline(load_file, file_data_line);
625   if (file_data_line == "<Annotations>")
626   {
627     getline(load_file, file_data_line);
628     species = file_data_line;
629     while ( (!load_file.eof())  && (file_data_line != "</Annotations>") )
630     {
631       getline(load_file,file_data_line);
632       if ((file_data_line != "") && (file_data_line != "</Annotations>"))  
633       {
634         // need to get 4 values...almost same code 4 times...
635         // get annot start index
636         space_split_i = file_data_line.find(" ");
637         annot_value = file_data_line.substr(0,space_split_i);
638         an_annot.start = atoi (annot_value.c_str());
639         file_data_line = file_data_line.substr(space_split_i+1);
640         // get annot end index
641         space_split_i = file_data_line.find(" ");
642         annot_value = file_data_line.substr(0,space_split_i);
643         an_annot.end = atoi (annot_value.c_str());
644
645         if (space_split_i == std::string::npos)  // no entry for type or name
646         {
647           std::cout << "seq, annots - no type or name\n";
648           an_annot.type = "";
649           an_annot.name = "";
650         }
651         else   // else get annot type
652         {
653           file_data_line = file_data_line.substr(space_split_i+1);
654           space_split_i = file_data_line.find(" ");
655           annot_value = file_data_line.substr(0,space_split_i);
656           an_annot.type = annot_value;
657           if (space_split_i == std::string::npos)  // no entry for name
658           {
659             std::cout << "seq, annots - no name\n";
660             an_annot.name = "";
661           }
662           else          // get annot name
663           {
664             file_data_line = file_data_line.substr(space_split_i+1);
665             space_split_i = file_data_line.find(" ");
666             annot_value = file_data_line.substr(0,space_split_i);
667             an_annot.type = annot_value;
668           }
669         }
670         annots.push_back(an_annot);  // don't forget to actually add the annot
671       }
672       //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
673       //     << "-->" << an_annot.type << "::" << an_annot.name << std::endl;
674     }
675   }
676   load_file.close();
677 }
678
679
680 std::string
681 Sequence::rc_motif(std::string a_motif)
682 {
683   std::string rev_comp;
684   char conversionTable[257];
685   int seq_i, table_i, len;
686
687   len = a_motif.length();
688   rev_comp.reserve(len);
689
690   for(table_i=0; table_i < 256; table_i++)
691   {
692     conversionTable[table_i] = '~';
693   }
694   // add end of std::string character for printing out table for testing purposes
695   conversionTable[256] = '\0';
696
697   // add in the characters for the bases we want to convert (IUPAC)
698   conversionTable[(int)'A'] = 'T';
699   conversionTable[(int)'T'] = 'A';
700   conversionTable[(int)'G'] = 'C';
701   conversionTable[(int)'C'] = 'G';
702   conversionTable[(int)'N'] = 'N';
703   conversionTable[(int)'M'] = 'K';
704   conversionTable[(int)'R'] = 'Y';
705   conversionTable[(int)'W'] = 'W';
706   conversionTable[(int)'S'] = 'S';
707   conversionTable[(int)'Y'] = 'R';
708   conversionTable[(int)'K'] = 'M';
709   conversionTable[(int)'V'] = 'B';
710   conversionTable[(int)'H'] = 'D';
711   conversionTable[(int)'D'] = 'H';
712   conversionTable[(int)'B'] = 'V';
713
714   // finally, the actual conversion loop
715   for(seq_i = len - 1; seq_i >= 0; seq_i--)
716   {
717     //std::cout << "** i = " << seq_i << " bp = " << 
718     table_i = (int) a_motif[seq_i];
719     rev_comp += conversionTable[table_i];
720   }
721
722   //std::cout << "seq: " << a_motif << std::endl;
723   //std::cout << "rc:  " << rev_comp << std::endl;
724
725   return rev_comp;
726 }
727
728 std::string
729 Sequence::motif_normalize(std::string a_motif)
730 {
731   std::string valid_motif;
732   int seq_i, len;
733
734   len = a_motif.length();
735   valid_motif.reserve(len);
736
737   // this just upcases IUPAC symbols.  Eventually should return an error if non IUPAC is present.
738   // current nonIUPAC symbols are omitted, which is not reported atm
739   for(seq_i = 0; seq_i < len; seq_i++)
740   {
741     if ((a_motif[seq_i] == 'a') || (a_motif[seq_i] == 'A'))
742       valid_motif += 'A';
743     else if ((a_motif[seq_i] == 't') || (a_motif[seq_i] == 'T'))
744       valid_motif += 'T';
745     else if ((a_motif[seq_i] == 'g') || (a_motif[seq_i] == 'G'))
746       valid_motif += 'G';
747     else if ((a_motif[seq_i] == 'c') || (a_motif[seq_i] == 'C'))
748       valid_motif += 'C';
749     else if ((a_motif[seq_i] == 'n') || (a_motif[seq_i] == 'N'))
750       valid_motif += 'N';
751     else if ((a_motif[seq_i] == 'm') || (a_motif[seq_i] == 'M'))
752       valid_motif += 'M';
753     else if ((a_motif[seq_i] == 'r') || (a_motif[seq_i] == 'R'))
754       valid_motif += 'R';
755     else if ((a_motif[seq_i] == 'w') || (a_motif[seq_i] == 'W'))
756       valid_motif += 'W';
757     else if ((a_motif[seq_i] == 's') || (a_motif[seq_i] == 'S'))
758       valid_motif += 'S';
759     else if ((a_motif[seq_i] == 'y') || (a_motif[seq_i] == 'Y'))
760       valid_motif += 'Y';
761     else if ((a_motif[seq_i] == 'k') || (a_motif[seq_i] == 'K'))
762       valid_motif += 'G';
763     else if ((a_motif[seq_i] == 'v') || (a_motif[seq_i] == 'V'))
764       valid_motif += 'V';
765     else if ((a_motif[seq_i] == 'h') || (a_motif[seq_i] == 'H'))
766       valid_motif += 'H';
767     else if ((a_motif[seq_i] == 'd') || (a_motif[seq_i] == 'D'))
768       valid_motif += 'D';
769     else if ((a_motif[seq_i] == 'b') || (a_motif[seq_i] == 'B'))
770       valid_motif += 'B';
771     else {
772       std::string msg = "Letter ";
773       msg += a_motif[seq_i];
774       msg += " is not a valid IUPAC symbol";
775       throw motif_normalize_error(msg);
776     }
777   }
778   //std::cout << "valid_motif is: " << valid_motif << std::endl;
779   return valid_motif;
780 }
781
782 void Sequence::add_motif(std::string a_motif)
783 {
784   std::vector<int> motif_starts = find_motif(a_motif);
785
786   for(std::vector<int>::iterator motif_start_i = motif_starts.begin();
787       motif_start_i != motif_starts.end();
788       ++motif_start_i)
789   {
790     motif_list.push_back(motif(*motif_start_i, a_motif));
791   }
792 }
793
794 void Sequence::clear_motifs()
795 {
796   motif_list.clear();
797 }
798
799 const std::list<motif>& Sequence::motifs() const
800 {
801   return motif_list;
802 }
803
804 std::vector<int>
805 Sequence::find_motif(std::string a_motif)
806 {
807   std::vector<int> motif_match_starts;
808   std::string a_motif_rc;
809
810   motif_match_starts.clear();
811
812   //std::cout << "motif is: " << a_motif << std::endl;
813   a_motif = motif_normalize(a_motif);
814   //std::cout << "motif is: " << a_motif << std::endl;
815
816   if (a_motif != "")
817   {
818     //std::cout << "Sequence: none blank motif\n";
819     motif_scan(a_motif, &motif_match_starts);
820
821     a_motif_rc = rc_motif(a_motif);
822     // make sure not to do search again if it is a palindrome
823     if (a_motif_rc != a_motif)
824       motif_scan(a_motif_rc, &motif_match_starts);
825   }
826   return motif_match_starts;
827 }
828
829 void
830 Sequence::motif_scan(std::string a_motif, std::vector<int> * motif_match_starts)
831 {
832   char * seq_c;
833   std::string::size_type seq_i;
834   int motif_i, motif_len;
835
836   // faster to loop thru the sequence as a old c std::string (ie char array)
837   seq_c = (char*)sequence.c_str();
838   //std::cout << "Sequence: motif, seq len = " << sequence.length() << std::endl; 
839   motif_len = a_motif.length();
840
841   //std::cout << "motif_length: " << motif_len << std::endl;
842   //std::cout << "RAAARRRRR\n";
843
844   motif_i = 0;
845
846   //std::cout << "motif: " << a_motif << std::endl;
847
848   //std::cout << "Sequence: motif, length= " << length << std::endl;
849   seq_i = 0;
850   while (seq_i < sequence.length())
851   {
852     //std::cout << seq_c[seq_i];
853     //std::cout << seq_c[seq_i] << "?" << a_motif[motif_i] << ":" << motif_i << " ";
854     // this is pretty much a straight translation of Nora's python code
855     // to match iupac letter codes
856     if (a_motif[motif_i] =='N')
857       motif_i++;
858     else if (a_motif[motif_i] == seq_c[seq_i])
859       motif_i++;
860     else if ((a_motif[motif_i] =='M') && 
861              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C')))
862       motif_i++;
863     else if ((a_motif[motif_i] =='R') && 
864              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G')))
865       motif_i++;
866     else if ((a_motif[motif_i] =='W') && 
867              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='T')))
868       motif_i++;
869     else if ((a_motif[motif_i] =='S') && 
870              ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G')))
871       motif_i++;
872     else if ((a_motif[motif_i] =='Y') && 
873              ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='T')))
874       motif_i++;
875     else if ((a_motif[motif_i] =='K') && 
876              ((seq_c[seq_i]=='G') || (seq_c[seq_i]=='T')))
877       motif_i++;
878     else if ((a_motif[motif_i] =='V') && 
879              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
880               (seq_c[seq_i]=='G')))
881       motif_i++;
882     else if ((a_motif[seq_i] =='H') && 
883              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
884               (seq_c[seq_i]=='T')))
885       motif_i++;
886     else if ((a_motif[motif_i] =='D') &&
887              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G') ||
888               (seq_c[seq_i]=='T')))
889       motif_i++;
890     else if ((a_motif[motif_i] =='B') &&
891              ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G') ||
892               (seq_c[seq_i]=='T')))
893       motif_i++;
894
895     else
896     {
897       seq_i -= motif_i;
898       motif_i = 0;
899     }
900
901     // end Nora stuff, now we see if a match is found this pass
902     if (motif_i == motif_len)
903     {
904       //std::cout << "!!";
905       annot new_motif;
906       motif_match_starts->push_back(seq_i - motif_len + 1);
907       motif_i = 0;
908     }
909
910     seq_i++;
911   }
912   //std::cout << std::endl;
913 }
914
915 void Sequence::add_string_annotation(std::string a_seq, 
916                                      std::string name)
917 {
918   std::vector<int> seq_starts = find_motif(a_seq);
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->get_seq(), start->get_header());
936     ++start;
937   }
938 }
939