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