catch possible segfault with get_sequence()
[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   if (seq) 
607     return *seq;
608   else
609     return std::string();
610 }
611
612 Sequence::const_reference Sequence::operator[](Sequence::size_type i) const
613 {
614   return at(i);
615 }
616
617 Sequence::const_reference Sequence::at(Sequence::size_type i) const
618 {
619   if (!seq) throw std::out_of_range("empty sequence");
620   return seq->at(i+seq_start);
621 }
622
623 void
624 Sequence::clear()
625 {
626   parent = 0;
627   seq.reset();
628   seq_start = 0;
629   seq_count = 0;
630   strand = UnknownStrand;
631   header.clear();
632   species.clear();
633   annots.clear();
634   motif_list.clear();
635 }
636
637 const char *Sequence::c_str() const
638 {
639   if (seq) 
640     return seq->c_str()+seq_start;
641   else 
642     return 0;
643 }
644
645 Sequence::const_iterator Sequence::begin() const
646 {
647   if (seq and seq_count != 0)
648     return seq->begin()+seq_start;
649   else 
650     return Sequence::const_iterator(0);
651 }
652
653 Sequence::const_iterator Sequence::end() const
654 {
655   if (seq and seq_count != 0) {
656     return seq->begin() + seq_start + seq_count;
657   } else {
658     return Sequence::const_iterator(0);
659   }
660 }
661
662 bool Sequence::empty() const
663 {
664   return (seq_count == 0) ? true : false;
665 }
666
667 Sequence::size_type Sequence::start() const
668 {
669   if (parent)
670     return seq_start - parent->start();
671   else
672     return seq_start;
673 }
674
675 Sequence::size_type Sequence::stop() const
676 {
677   return start() + seq_count;
678 }
679
680 Sequence::size_type Sequence::size() const
681 {
682   return seq_count;
683 }
684
685 Sequence::size_type Sequence::length() const
686 {
687   return size();
688 }
689
690 void
691 Sequence::save(fs::fstream &save_file)
692 {
693   //fstream save_file;
694   std::list<annot>::iterator annots_i;
695
696   // not sure why, or if i'm doing something wrong, but can't seem to pass
697   // file pointers down to this method from the mussa control class
698   // so each call to save a sequence appends to the file started by mussa_class
699   //save_file.open(save_file_path.c_str(), std::ios::app);
700
701   save_file << "<Sequence>" << std::endl;
702   save_file << *this << std::endl;
703   save_file << "</Sequence>" << std::endl;
704
705   save_file << "<Annotations>" << std::endl;
706   save_file << species << std::endl;
707   for (annots_i = annots.begin(); annots_i != annots.end(); ++annots_i)
708   {
709     save_file << annots_i->begin << " " << annots_i->end << " " ;
710     save_file << annots_i->name << " " << annots_i->type << std::endl;
711   }
712   save_file << "</Annotations>" << std::endl;
713   //save_file.close();
714 }
715
716 void
717 Sequence::load_museq(fs::path load_file_path, int seq_num)
718 {
719   fs::fstream load_file;
720   std::string file_data_line;
721   int seq_counter;
722   annot an_annot;
723   std::string::size_type space_split_i;
724   std::string annot_value;
725
726   annots.clear();
727   load_file.open(load_file_path, std::ios::in);
728
729   seq_counter = 0;
730   // search for the seq_num-th sequence 
731   while ( (!load_file.eof()) && (seq_counter < seq_num) )
732   {
733     getline(load_file,file_data_line);
734     if (file_data_line == "<Sequence>")
735       seq_counter++;
736   }
737   getline(load_file, file_data_line);
738   // looks like the sequence is written as a single line
739   set_filtered_sequence(file_data_line);
740   getline(load_file, file_data_line);
741   getline(load_file, file_data_line);
742   if (file_data_line == "<Annotations>")
743   {
744     getline(load_file, file_data_line);
745     species = file_data_line;
746     while ( (!load_file.eof())  && (file_data_line != "</Annotations>") )
747     {
748       getline(load_file,file_data_line);
749       if ((file_data_line != "") && (file_data_line != "</Annotations>"))  
750       {
751         // need to get 4 values...almost same code 4 times...
752         // get annot start index
753         space_split_i = file_data_line.find(" ");
754         annot_value = file_data_line.substr(0,space_split_i);
755         an_annot.begin = atoi (annot_value.c_str());
756         file_data_line = file_data_line.substr(space_split_i+1);
757         // get annot end index
758         space_split_i = file_data_line.find(" ");
759         annot_value = file_data_line.substr(0,space_split_i);
760         an_annot.end = atoi (annot_value.c_str());
761
762         if (space_split_i == std::string::npos)  // no entry for type or name
763         {
764           std::cout << "seq, annots - no type or name\n";
765           an_annot.type = "";
766           an_annot.name = "";
767         }
768         else   // else get annot type
769         {
770           file_data_line = file_data_line.substr(space_split_i+1);
771           space_split_i = file_data_line.find(" ");
772           annot_value = file_data_line.substr(0,space_split_i);
773           an_annot.type = annot_value;
774           if (space_split_i == std::string::npos)  // no entry for name
775           {
776             std::cout << "seq, annots - no name\n";
777             an_annot.name = "";
778           }
779           else          // get annot name
780           {
781             file_data_line = file_data_line.substr(space_split_i+1);
782             space_split_i = file_data_line.find(" ");
783             annot_value = file_data_line.substr(0,space_split_i);
784             an_annot.type = annot_value;
785           }
786         }
787         annots.push_back(an_annot);  // don't forget to actually add the annot
788       }
789       //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
790       //     << "-->" << an_annot.type << "::" << an_annot.name << std::endl;
791     }
792   }
793   load_file.close();
794 }
795
796 std::string
797 Sequence::rc_motif(std::string a_motif) const
798 {
799   std::string rev_comp;
800   char conversionTable[257];
801   int seq_i, table_i, len;
802
803   len = a_motif.length();
804   rev_comp.reserve(len);
805
806   for(table_i=0; table_i < 256; table_i++)
807   {
808     conversionTable[table_i] = '~';
809   }
810   // add end of std::string character for printing out table for testing purposes
811   conversionTable[256] = '\0';
812
813   // add in the characters for the bases we want to convert (IUPAC)
814   conversionTable[(int)'A'] = 'T';
815   conversionTable[(int)'T'] = 'A';
816   conversionTable[(int)'G'] = 'C';
817   conversionTable[(int)'C'] = 'G';
818   conversionTable[(int)'N'] = 'N';
819   conversionTable[(int)'M'] = 'K';
820   conversionTable[(int)'R'] = 'Y';
821   conversionTable[(int)'W'] = 'W';
822   conversionTable[(int)'S'] = 'S';
823   conversionTable[(int)'Y'] = 'R';
824   conversionTable[(int)'K'] = 'M';
825   conversionTable[(int)'V'] = 'B';
826   conversionTable[(int)'H'] = 'D';
827   conversionTable[(int)'D'] = 'H';
828   conversionTable[(int)'B'] = 'V';
829
830   // finally, the actual conversion loop
831   for(seq_i = len - 1; seq_i >= 0; seq_i--)
832   {
833     //std::cout << "** i = " << seq_i << " bp = " << 
834     table_i = (int) a_motif[seq_i];
835     rev_comp += conversionTable[table_i];
836   }
837
838   //std::cout << "seq: " << a_motif << std::endl;
839   //std::cout << "rc:  " << rev_comp << std::endl;
840
841   return rev_comp;
842 }
843
844 std::string
845 Sequence::motif_normalize(const std::string& a_motif)
846 {
847   std::string valid_motif;
848   int seq_i, len;
849
850   len = a_motif.length();
851   valid_motif.reserve(len);
852
853   // this just upcases IUPAC symbols.  Eventually should return an error if non IUPAC is present.
854   // current nonIUPAC symbols are omitted, which is not reported atm
855   for(seq_i = 0; seq_i < len; seq_i++)
856   {
857     if ((a_motif[seq_i] == 'a') || (a_motif[seq_i] == 'A'))
858       valid_motif += 'A';
859     else if ((a_motif[seq_i] == 't') || (a_motif[seq_i] == 'T'))
860       valid_motif += 'T';
861     else if ((a_motif[seq_i] == 'g') || (a_motif[seq_i] == 'G'))
862       valid_motif += 'G';
863     else if ((a_motif[seq_i] == 'c') || (a_motif[seq_i] == 'C'))
864       valid_motif += 'C';
865     else if ((a_motif[seq_i] == 'n') || (a_motif[seq_i] == 'N'))
866       valid_motif += 'N';
867     else if ((a_motif[seq_i] == 'm') || (a_motif[seq_i] == 'M'))
868       valid_motif += 'M';
869     else if ((a_motif[seq_i] == 'r') || (a_motif[seq_i] == 'R'))
870       valid_motif += 'R';
871     else if ((a_motif[seq_i] == 'w') || (a_motif[seq_i] == 'W'))
872       valid_motif += 'W';
873     else if ((a_motif[seq_i] == 's') || (a_motif[seq_i] == 'S'))
874       valid_motif += 'S';
875     else if ((a_motif[seq_i] == 'y') || (a_motif[seq_i] == 'Y'))
876       valid_motif += 'Y';
877     else if ((a_motif[seq_i] == 'k') || (a_motif[seq_i] == 'K'))
878       valid_motif += 'G';
879     else if ((a_motif[seq_i] == 'v') || (a_motif[seq_i] == 'V'))
880       valid_motif += 'V';
881     else if ((a_motif[seq_i] == 'h') || (a_motif[seq_i] == 'H'))
882       valid_motif += 'H';
883     else if ((a_motif[seq_i] == 'd') || (a_motif[seq_i] == 'D'))
884       valid_motif += 'D';
885     else if ((a_motif[seq_i] == 'b') || (a_motif[seq_i] == 'B'))
886       valid_motif += 'B';
887     else {
888       std::string msg = "Letter ";
889       msg += a_motif[seq_i];
890       msg += " is not a valid IUPAC symbol";
891       throw motif_normalize_error(msg);
892     }
893   }
894   //std::cout << "valid_motif is: " << valid_motif << std::endl;
895   return valid_motif;
896 }
897
898 void Sequence::add_motif(const Sequence& a_motif)
899 {
900   std::vector<int> motif_starts = find_motif(a_motif);
901
902   for(std::vector<int>::iterator motif_start_i = motif_starts.begin();
903       motif_start_i != motif_starts.end();
904       ++motif_start_i)
905   {
906     motif_list.push_back(motif(*motif_start_i, a_motif.get_sequence()));
907   }
908 }
909
910 void Sequence::clear_motifs()
911 {
912   motif_list.clear();
913 }
914
915 const std::list<motif>& Sequence::motifs() const
916 {
917   return motif_list;
918 }
919
920 std::vector<int>
921 Sequence::find_motif(const std::string& a_motif) const
922 {
923   std::vector<int> motif_match_starts;
924   std::string norm_motif_rc;
925
926   motif_match_starts.clear();
927
928   //std::cout << "motif is: " << a_motif << std::endl;
929   std::string norm_motif = motif_normalize(a_motif);
930   //std::cout << "motif is: " << a_motif << std::endl;
931
932   if (norm_motif.size() > 0)
933   {
934     //std::cout << "Sequence: none blank motif\n";
935     motif_scan(norm_motif, &motif_match_starts);
936
937     norm_motif_rc = rc_motif(a_motif);
938     // make sure not to do search again if it is a palindrome
939     if (norm_motif_rc != norm_motif) {
940       motif_scan(norm_motif_rc, &motif_match_starts);
941     }
942   }
943   return motif_match_starts;
944 }
945
946 std::vector<int>
947 Sequence::find_motif(const Sequence& a_motif) const
948 {
949   return find_motif(a_motif.get_sequence());
950 }
951
952 void
953 Sequence::motif_scan(std::string a_motif, std::vector<int> * motif_match_starts) const
954 {
955   // if there's no sequence we can't scan for it?
956   // should this throw an exception?
957   if (!seq) return;
958
959   std::string::const_iterator seq_c = seq->begin();
960   std::string::size_type seq_i;
961   int motif_i, motif_len;
962
963   //std::cout << "Sequence: motif, seq len = " << sequence.length() << std::endl; 
964   motif_len = a_motif.length();
965
966   //std::cout << "motif_length: " << motif_len << std::endl;
967   //std::cout << "RAAARRRRR\n";
968
969   motif_i = 0;
970
971   //std::cout << "motif: " << a_motif << std::endl;
972
973   //std::cout << "Sequence: motif, length= " << length << std::endl;
974   seq_i = 0;
975   while (seq_i < length())
976   {
977     //std::cout << seq_c[seq_i];
978     //std::cout << seq_c[seq_i] << "?" << a_motif[motif_i] << ":" << motif_i << " ";
979     // this is pretty much a straight translation of Nora's python code
980     // to match iupac letter codes
981     if (a_motif[motif_i] =='N')
982       motif_i++;
983     else if (a_motif[motif_i] == seq_c[seq_i])
984       motif_i++;
985     else if ((a_motif[motif_i] =='M') && 
986              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C')))
987       motif_i++;
988     else if ((a_motif[motif_i] =='R') && 
989              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G')))
990       motif_i++;
991     else if ((a_motif[motif_i] =='W') && 
992              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='T')))
993       motif_i++;
994     else if ((a_motif[motif_i] =='S') && 
995              ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G')))
996       motif_i++;
997     else if ((a_motif[motif_i] =='Y') && 
998              ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='T')))
999       motif_i++;
1000     else if ((a_motif[motif_i] =='K') && 
1001              ((seq_c[seq_i]=='G') || (seq_c[seq_i]=='T')))
1002       motif_i++;
1003     else if ((a_motif[motif_i] =='V') && 
1004              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
1005               (seq_c[seq_i]=='G')))
1006       motif_i++;
1007     else if ((a_motif[seq_i] =='H') && 
1008              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
1009               (seq_c[seq_i]=='T')))
1010       motif_i++;
1011     else if ((a_motif[motif_i] =='D') &&
1012              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G') ||
1013               (seq_c[seq_i]=='T')))
1014       motif_i++;
1015     else if ((a_motif[motif_i] =='B') &&
1016              ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G') ||
1017               (seq_c[seq_i]=='T')))
1018       motif_i++;
1019
1020     else
1021     {
1022       seq_i -= motif_i;
1023       motif_i = 0;
1024     }
1025
1026     // end Nora stuff, now we see if a match is found this pass
1027     if (motif_i == motif_len)
1028     {
1029       //std::cout << "!!";
1030       annot new_motif;
1031       motif_match_starts->push_back(seq_i - motif_len + 1);
1032       motif_i = 0;
1033     }
1034
1035     seq_i++;
1036   }
1037   //std::cout << std::endl;
1038 }
1039
1040 void Sequence::add_string_annotation(std::string a_seq, 
1041                                      std::string name)
1042 {
1043   std::vector<int> seq_starts = find_motif(a_seq);
1044   
1045   //std::cout << "searching for " << a_seq << " found " << seq_starts.size() << std::endl;
1046
1047   for(std::vector<int>::iterator seq_start_i = seq_starts.begin();
1048       seq_start_i != seq_starts.end();
1049       ++seq_start_i)
1050   {
1051     annots.push_back(annot(*seq_start_i, 
1052                            *seq_start_i+a_seq.size(),
1053                            "",
1054                            name));
1055   }
1056 }
1057
1058 void Sequence::find_sequences(std::list<Sequence>::iterator start, 
1059                               std::list<Sequence>::iterator end)
1060 {
1061   while (start != end) {
1062     add_string_annotation(start->get_sequence(), start->get_fasta_header());
1063     ++start;
1064   }
1065 }
1066
1067
1068 std::ostream& operator<<(std::ostream& out, const Sequence& s)
1069 {
1070   for(Sequence::const_iterator s_i = s.begin(); s_i != s.end(); ++s_i) {
1071     out << *s_i;
1072   }
1073   return out;
1074 }
1075
1076 bool operator<(const Sequence& x, const Sequence& y)
1077 {
1078   Sequence::const_iterator x_i = x.begin();
1079   Sequence::const_iterator y_i = y.begin();
1080   // for sequences there's some computation associated with computing .end
1081   // so lets cache it.
1082   Sequence::const_iterator xend = x.end();
1083   Sequence::const_iterator yend = y.end();
1084   while(1) {
1085     if( x_i == xend and y_i == yend ) {
1086       return false;
1087     } else if ( x_i == xend ) {
1088       return true;
1089     } else if ( y_i == yend ) {
1090       return false;
1091     } else if ( (*x_i) < (*y_i)) {
1092       return true;
1093     } else if ( (*x_i) > (*y_i) ) {
1094       return false;
1095     } else {
1096       ++x_i;
1097       ++y_i;
1098     }
1099   }
1100 }
1101
1102 bool operator==(const Sequence& x, const Sequence& y) 
1103 {
1104   if (x.empty() and y.empty()) {
1105     // if there's no sequence in either sequence structure, they're equal
1106     return true;
1107   } else if (x.empty() or y.empty()) {
1108     // if we fail the first test, and we discover one is empty,
1109     // we know they can't be equal. (and we need to do this
1110     // to prevent dereferencing an empty pointer)
1111     return false;
1112   } else if (x.seq_count != y.seq_count) {
1113     // if they're of different lenghts, they're not equal
1114     return false;
1115   }
1116   Sequence::const_iterator xseq_i = x.begin();
1117   Sequence::const_iterator yseq_i = y.begin();
1118   // since the length of the two sequences is equal, we only need to
1119   // test one.
1120   for(; xseq_i != x.end(); ++xseq_i, ++yseq_i) {
1121     if (*xseq_i != *yseq_i) {
1122       return false;
1123     }
1124   }
1125   return true;
1126 }