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