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