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