1 // This file is part of the Mussa source distribution.
2 // http://mussa.caltech.edu/
3 // Contact author: Tristan De Buysscher, tristan@caltech.edu
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.
11 // This file is part of the Mussa source distribution.
12 // http://mussa.caltech.edu/
13 // Contact author: Tristan De Buysscher, tristan@caltech.edu
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.
21 // ----------------------------------------
22 // ---------- sequence.cc -----------
23 // ----------------------------------------
24 #include <boost/filesystem/fstream.hpp>
25 namespace fs = boost::filesystem;
27 #include <boost/spirit/core.hpp>
28 #include <boost/spirit/actor/push_back_actor.hpp>
29 #include <boost/spirit/iterator/file_iterator.hpp>
30 namespace spirit = boost::spirit;
32 #include "alg/sequence.hpp"
33 #include "mussa_exceptions.hpp"
47 annot::annot(int start, int end, std::string type, std::string name)
55 motif::motif(int start, std::string motif)
56 : annot(start, start+motif.size(), "motif", motif),
70 Sequence::Sequence(std::string seq)
72 set_filtered_sequence(seq);
75 Sequence &Sequence::operator=(const Sequence& s)
78 sequence = s.sequence;
86 Sequence &Sequence::operator=(const std::string& s)
88 set_filtered_sequence(s);
92 char Sequence::operator[](int index) const
94 return sequence[index];
97 std::ostream& operator<<(std::ostream& out, const Sequence& seq)
99 out << "Sequence(" << seq.get_seq() << ")";
103 //! load a fasta file into a sequence
105 * \param file_path the location of the fasta file in the filesystem
106 * \param seq_num which sequence in the file to load
107 * \param start_index starting position in the fasta sequence, 0 for beginning
108 * \param end_index ending position in the fasta sequence, 0 for end
109 * \return error message, empty string if no error. (gag!)
112 Sequence::load_fasta(fs::path file_path, int seq_num,
113 int start_index, int end_index)
115 fs::fstream data_file;
116 std::string file_data_line;
117 int header_counter = 0;
118 bool read_seq = true;
119 std::string rev_comp;
120 std::string sequence_raw;
121 std::string seq_tmp; // holds sequence during basic filtering
123 data_file.open(file_path, std::ios::in);
126 throw mussa_load_error("fasta sequence number is 1 based (can't be 0)");
130 throw mussa_load_error("Sequence File: " + file_path.string() + " not found");
132 // if file opened okay, read it
135 // search for the header of the fasta sequence we want
136 while ( (!data_file.eof()) && (header_counter < seq_num) )
138 getline(data_file,file_data_line);
139 if (file_data_line.substr(0,1) == ">")
143 if (header_counter > 0) {
144 header = file_data_line.substr(1);
148 while ( !data_file.eof() && read_seq ) {
149 getline(data_file,file_data_line);
150 if (file_data_line.substr(0,1) == ">")
152 else sequence_raw += file_data_line;
155 // Lastly, if subselection of the sequence was specified we keep cut out
156 // and only keep that part
157 // end_index = 0 means no end was specified, so cut to the end
159 end_index = sequence_raw.size();
161 // sequence filtering for upcasing agctn and convert non AGCTN to N
162 set_filtered_sequence(sequence_raw, start_index, end_index-start_index);
164 std::stringstream errormsg;
165 errormsg << file_path.native_file_string()
166 << " did not have any fasta sequences" << std::endl;
167 throw mussa_load_error(errormsg.str());
173 void Sequence::set_filtered_sequence(const std::string &old_seq,
174 std::string::size_type start,
175 std::string::size_type count)
177 char conversionTable[257];
180 count = old_seq.size() - start;
182 sequence.reserve(count);
184 // Make a conversion table
186 // everything we don't specify below will become 'N'
187 for(int table_i=0; table_i < 256; table_i++)
189 conversionTable[table_i] = 'N';
191 // add end of string character for printing out table for testing purposes
192 conversionTable[256] = '\0';
194 // we want these to map to themselves - ie not to change
195 conversionTable[(int)'A'] = 'A';
196 conversionTable[(int)'T'] = 'T';
197 conversionTable[(int)'G'] = 'G';
198 conversionTable[(int)'C'] = 'C';
200 conversionTable[(int)'a'] = 'A';
201 conversionTable[(int)'t'] = 'T';
202 conversionTable[(int)'g'] = 'G';
203 conversionTable[(int)'c'] = 'C';
205 // finally, the actual conversion loop
206 for(std::string::size_type seq_index = 0; seq_index < count; seq_index++)
208 sequence += conversionTable[ (int)old_seq[seq_index+start]];
212 // this doesn't work properly under gcc 3.x ... it can't recognize toupper
213 //transform(sequence.begin(), sequence.end(), sequence.begin(), toupper);
216 Sequence::load_annot(fs::path file_path, int start_index, int end_index)
218 fs::fstream data_stream(file_path, std::ios::in);
221 throw mussa_load_error("Sequence File: " + file_path.string() + " not found");
224 // so i should probably be passing the parse function some iterators
225 // but the annotations files are (currently) small, so i think i can
226 // get away with loading the whole file into memory
229 while(data_stream.good()) {
235 parse_annot(data, start_index, end_index);
238 /* If this works, yikes, this is some brain hurting code.
240 * what's going on is that when pb_annot is instantiated it stores references
241 * to begin, end, name, type, declared in the parse function, then
242 * when operator() is called it grabs values from those references
243 * and uses that to instantiate an annot object and append that to our
246 * This weirdness is because the spirit library requires that actions
247 * conform to a specific prototype operator()(IteratorT, IteratorT)
248 * which doesn't provide any useful opportunity for me to actually
249 * grab the results of our parsing.
251 * so I instantiate this structure in order to have a place to grab
255 struct push_back_annot {
256 std::list<annot>& annot_list;
262 push_back_annot(std::list<annot>& annot_list_,
267 : annot_list(annot_list_),
275 void operator()(std::string::const_iterator,
276 std::string::const_iterator) const
278 //std::cout << "adding annot: " << begin << " " << end << " " << name << " " << type << std::endl;
279 annot_list.push_back(annot(begin, end, name, type));
283 struct push_back_seq {
284 std::list<Sequence>& seq_list;
288 push_back_seq(std::list<Sequence>& seq_list_,
291 : seq_list(seq_list_),
297 void operator()(std::string::const_iterator,
298 std::string::const_iterator) const
300 // filter out newlines from our sequence
302 for(std::string::const_iterator seq_i = seq.begin();
306 if (*seq_i != '\n') new_seq += *seq_i;
308 //std::cout << "adding seq: " << name << " " << new_seq << std::endl;
312 seq_list.push_back(s);
317 Sequence::parse_annot(std::string data, int start_index, int end_index)
324 std::list<Sequence> query_seqs;
326 bool status = spirit::parse(data.begin(), data.end(),
329 (+(spirit::alpha_p))[spirit::assign_a(species)] >>
330 +(spirit::space_p) >>
332 ( // parse an absolute location name
333 (spirit::uint_p[spirit::assign_a(start)] >>
335 spirit::uint_p[spirit::assign_a(end)] >>
337 (*(spirit::alpha_p|spirit::digit_p))[spirit::assign_a(name)] >>
341 (*(spirit::alpha_p))[spirit::assign_a(type)]
343 // to understand how this group gets set
344 // read the comment above struct push_back_annot
345 )[push_back_annot(annots, start, end, type, name)]
347 (spirit::ch_p('>') >>
348 (*(~spirit::chlit<char>('\n')))[spirit::assign_a(name)] >>
350 (+(spirit::ch_p('A')|
355 spirit::ch_p('\n')))[spirit::assign_a(seq)]
356 )[push_back_seq(query_seqs, name, seq)]
362 spirit::space_p*/).full;
364 // go seearch for query sequences
365 find_sequences(query_seqs.begin(), query_seqs.end());
370 Sequence::load_annot(std::istream& data_stream, int start_index, int end_index)
372 std::string file_data_line;
374 std::string::size_type space_split_i;
375 std::string annot_value;
376 std::list<annot>::iterator list_i;
381 getline(data_stream,file_data_line);
382 species = file_data_line;
384 // end_index = 0 means no end was specified, so cut to the end
386 end_index = sequence.length();
388 //std::cout << "START: " << start_index << " END: " << end_index << std::endl;
390 while ( !data_stream.eof() )
392 getline(data_stream,file_data_line);
393 if (file_data_line != "")
395 // need to get 4 values...almost same code 4 times...
396 // get annot start index
397 space_split_i = file_data_line.find(" ");
398 annot_value = file_data_line.substr(0,space_split_i);
399 an_annot.start = atoi (annot_value.c_str());
400 file_data_line = file_data_line.substr(space_split_i+1);
401 // get annot end index
402 space_split_i = file_data_line.find(" ");
403 annot_value = file_data_line.substr(0,space_split_i);
404 an_annot.end = atoi (annot_value.c_str());
405 file_data_line = file_data_line.substr(space_split_i+1);
407 //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
411 space_split_i = file_data_line.find(" ");
412 if (space_split_i == std::string::npos) // no entries for name & type
414 std::cout << "seq, annots - no name or type\n";
420 annot_value = file_data_line.substr(0,space_split_i);
421 an_annot.name = annot_value;
422 file_data_line = file_data_line.substr(space_split_i+1);
424 space_split_i = file_data_line.find(" ");
425 if (space_split_i == std::string::npos) // no entry for type
429 annot_value = file_data_line.substr(0,space_split_i);
430 an_annot.type = annot_value;
435 // add annot to list if it falls within the range of sequence specified
436 if ((start_index <= an_annot.start) && (end_index >= an_annot.end))
438 an_annot.start -= start_index;
439 an_annot.end -= start_index;
440 annots.push_back(an_annot);
442 // else no (or bogus) annotations
448 const std::string& Sequence::get_species() const
453 bool Sequence::empty() const
455 return (size() == 0);
458 const std::list<annot>& Sequence::annotations() const
463 std::string::size_type Sequence::length() const
468 std::string::size_type Sequence::size() const
470 return sequence.size();
473 Sequence::iterator Sequence::begin()
475 return sequence.begin();
478 Sequence::const_iterator Sequence::begin() const
480 return sequence.begin();
483 Sequence::iterator Sequence::end()
485 return sequence.end();
488 Sequence::const_iterator Sequence::end() const
490 return sequence.end();
495 Sequence::get_seq() const
502 Sequence::subseq(int start, int end) const
504 return sequence.substr(start, end);
509 Sequence::c_seq() const
511 return sequence.c_str();
515 Sequence::rev_comp() const
517 std::string rev_comp;
518 char conversionTable[257];
519 int seq_i, table_i, len;
521 len = sequence.length();
522 rev_comp.reserve(len);
523 // make a conversion table
524 // init all parts of conversion table to '~' character
525 // '~' I doubt will ever appear in a sequence file (jeez, I hope)
526 // and may the fleas of 1000 camels infest the genitals of any biologist (and
527 // seven generations of their progeny) who decides to make it mean
528 // something special!!!
529 // PS - double the curse for any smartass non-biologist who tries it as well
530 for(table_i=0; table_i < 256; table_i++)
532 conversionTable[table_i] = '~';
534 // add end of string character for printing out table for testing purposes
535 conversionTable[256] = '\0';
537 // add in the characters for the bases we want to convert
538 conversionTable[(int)'A'] = 'T';
539 conversionTable[(int)'T'] = 'A';
540 conversionTable[(int)'G'] = 'C';
541 conversionTable[(int)'C'] = 'G';
542 conversionTable[(int)'N'] = 'N';
544 // finally, the actual conversion loop
545 for(seq_i = len - 1; seq_i >= 0; seq_i--)
547 table_i = (int) sequence[seq_i];
548 rev_comp += conversionTable[table_i];
554 void Sequence::set_header(std::string &header_)
560 Sequence::get_header() const
565 //FIXME: i don't think this code is callable
567 Sequence::sp_name() const
574 Sequence::set_seq(const std::string& a_seq)
576 set_filtered_sequence(a_seq);
598 Sequence::save(fs::fstream &save_file)
599 //std::string save_file_path)
602 std::list<annot>::iterator annots_i;
604 // not sure why, or if i'm doing something wrong, but can't seem to pass
605 // file pointers down to this method from the mussa control class
606 // so each call to save a sequence appends to the file started by mussa_class
607 //save_file.open(save_file_path.c_str(), std::ios::app);
609 save_file << "<Sequence>" << std::endl;
610 save_file << sequence << std::endl;
611 save_file << "</Sequence>" << std::endl;
613 save_file << "<Annotations>" << std::endl;
614 save_file << species << std::endl;
615 for (annots_i = annots.begin(); annots_i != annots.end(); ++annots_i)
617 save_file << annots_i->start << " " << annots_i->end << " " ;
618 save_file << annots_i->name << " " << annots_i->type << std::endl;
620 save_file << "</Annotations>" << std::endl;
625 Sequence::load_museq(fs::path load_file_path, int seq_num)
627 fs::fstream load_file;
628 std::string file_data_line;
631 std::string::size_type space_split_i;
632 std::string annot_value;
635 load_file.open(load_file_path, std::ios::in);
638 // search for the seq_num-th sequence
639 while ( (!load_file.eof()) && (seq_counter < seq_num) )
641 getline(load_file,file_data_line);
642 if (file_data_line == "<Sequence>")
645 getline(load_file, file_data_line);
646 sequence = file_data_line;
647 getline(load_file, file_data_line);
648 getline(load_file, file_data_line);
649 if (file_data_line == "<Annotations>")
651 getline(load_file, file_data_line);
652 species = file_data_line;
653 while ( (!load_file.eof()) && (file_data_line != "</Annotations>") )
655 getline(load_file,file_data_line);
656 if ((file_data_line != "") && (file_data_line != "</Annotations>"))
658 // need to get 4 values...almost same code 4 times...
659 // get annot start index
660 space_split_i = file_data_line.find(" ");
661 annot_value = file_data_line.substr(0,space_split_i);
662 an_annot.start = atoi (annot_value.c_str());
663 file_data_line = file_data_line.substr(space_split_i+1);
664 // get annot end index
665 space_split_i = file_data_line.find(" ");
666 annot_value = file_data_line.substr(0,space_split_i);
667 an_annot.end = atoi (annot_value.c_str());
669 if (space_split_i == std::string::npos) // no entry for type or name
671 std::cout << "seq, annots - no type or name\n";
675 else // else get annot type
677 file_data_line = file_data_line.substr(space_split_i+1);
678 space_split_i = file_data_line.find(" ");
679 annot_value = file_data_line.substr(0,space_split_i);
680 an_annot.type = annot_value;
681 if (space_split_i == std::string::npos) // no entry for name
683 std::cout << "seq, annots - no name\n";
686 else // get annot name
688 file_data_line = file_data_line.substr(space_split_i+1);
689 space_split_i = file_data_line.find(" ");
690 annot_value = file_data_line.substr(0,space_split_i);
691 an_annot.type = annot_value;
694 annots.push_back(an_annot); // don't forget to actually add the annot
696 //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
697 // << "-->" << an_annot.type << "::" << an_annot.name << std::endl;
705 Sequence::rc_motif(std::string a_motif)
707 std::string rev_comp;
708 char conversionTable[257];
709 int seq_i, table_i, len;
711 len = a_motif.length();
712 rev_comp.reserve(len);
714 for(table_i=0; table_i < 256; table_i++)
716 conversionTable[table_i] = '~';
718 // add end of std::string character for printing out table for testing purposes
719 conversionTable[256] = '\0';
721 // add in the characters for the bases we want to convert (IUPAC)
722 conversionTable[(int)'A'] = 'T';
723 conversionTable[(int)'T'] = 'A';
724 conversionTable[(int)'G'] = 'C';
725 conversionTable[(int)'C'] = 'G';
726 conversionTable[(int)'N'] = 'N';
727 conversionTable[(int)'M'] = 'K';
728 conversionTable[(int)'R'] = 'Y';
729 conversionTable[(int)'W'] = 'W';
730 conversionTable[(int)'S'] = 'S';
731 conversionTable[(int)'Y'] = 'R';
732 conversionTable[(int)'K'] = 'M';
733 conversionTable[(int)'V'] = 'B';
734 conversionTable[(int)'H'] = 'D';
735 conversionTable[(int)'D'] = 'H';
736 conversionTable[(int)'B'] = 'V';
738 // finally, the actual conversion loop
739 for(seq_i = len - 1; seq_i >= 0; seq_i--)
741 //std::cout << "** i = " << seq_i << " bp = " <<
742 table_i = (int) a_motif[seq_i];
743 rev_comp += conversionTable[table_i];
746 //std::cout << "seq: " << a_motif << std::endl;
747 //std::cout << "rc: " << rev_comp << std::endl;
753 Sequence::motif_normalize(std::string a_motif)
755 std::string valid_motif;
758 len = a_motif.length();
759 valid_motif.reserve(len);
761 // this just upcases IUPAC symbols. Eventually should return an error if non IUPAC is present.
762 // current nonIUPAC symbols are omitted, which is not reported atm
763 for(seq_i = 0; seq_i < len; seq_i++)
765 if ((a_motif[seq_i] == 'a') || (a_motif[seq_i] == 'A'))
767 else if ((a_motif[seq_i] == 't') || (a_motif[seq_i] == 'T'))
769 else if ((a_motif[seq_i] == 'g') || (a_motif[seq_i] == 'G'))
771 else if ((a_motif[seq_i] == 'c') || (a_motif[seq_i] == 'C'))
773 else if ((a_motif[seq_i] == 'n') || (a_motif[seq_i] == 'N'))
775 else if ((a_motif[seq_i] == 'm') || (a_motif[seq_i] == 'M'))
777 else if ((a_motif[seq_i] == 'r') || (a_motif[seq_i] == 'R'))
779 else if ((a_motif[seq_i] == 'w') || (a_motif[seq_i] == 'W'))
781 else if ((a_motif[seq_i] == 's') || (a_motif[seq_i] == 'S'))
783 else if ((a_motif[seq_i] == 'y') || (a_motif[seq_i] == 'Y'))
785 else if ((a_motif[seq_i] == 'k') || (a_motif[seq_i] == 'K'))
787 else if ((a_motif[seq_i] == 'v') || (a_motif[seq_i] == 'V'))
789 else if ((a_motif[seq_i] == 'h') || (a_motif[seq_i] == 'H'))
791 else if ((a_motif[seq_i] == 'd') || (a_motif[seq_i] == 'D'))
793 else if ((a_motif[seq_i] == 'b') || (a_motif[seq_i] == 'B'))
796 std::string msg = "Letter ";
797 msg += a_motif[seq_i];
798 msg += " is not a valid IUPAC symbol";
799 throw motif_normalize_error(msg);
802 //std::cout << "valid_motif is: " << valid_motif << std::endl;
806 void Sequence::add_motif(std::string a_motif)
808 std::vector<int> motif_starts = find_motif(a_motif);
810 for(std::vector<int>::iterator motif_start_i = motif_starts.begin();
811 motif_start_i != motif_starts.end();
814 motif_list.push_back(motif(*motif_start_i, a_motif));
818 void Sequence::clear_motifs()
823 const std::list<motif>& Sequence::motifs() const
829 Sequence::find_motif(std::string a_motif)
831 std::vector<int> motif_match_starts;
832 std::string a_motif_rc;
834 motif_match_starts.clear();
836 //std::cout << "motif is: " << a_motif << std::endl;
837 a_motif = motif_normalize(a_motif);
838 //std::cout << "motif is: " << a_motif << std::endl;
842 //std::cout << "Sequence: none blank motif\n";
843 motif_scan(a_motif, &motif_match_starts);
845 a_motif_rc = rc_motif(a_motif);
846 // make sure not to do search again if it is a palindrome
847 if (a_motif_rc != a_motif)
848 motif_scan(a_motif_rc, &motif_match_starts);
850 return motif_match_starts;
854 Sequence::motif_scan(std::string a_motif, std::vector<int> * motif_match_starts)
857 std::string::size_type seq_i;
858 int motif_i, motif_len;
860 // faster to loop thru the sequence as a old c std::string (ie char array)
861 seq_c = (char*)sequence.c_str();
862 //std::cout << "Sequence: motif, seq len = " << sequence.length() << std::endl;
863 motif_len = a_motif.length();
865 //std::cout << "motif_length: " << motif_len << std::endl;
866 //std::cout << "RAAARRRRR\n";
870 //std::cout << "motif: " << a_motif << std::endl;
872 //std::cout << "Sequence: motif, length= " << length << std::endl;
874 while (seq_i < sequence.length())
876 //std::cout << seq_c[seq_i];
877 //std::cout << seq_c[seq_i] << "?" << a_motif[motif_i] << ":" << motif_i << " ";
878 // this is pretty much a straight translation of Nora's python code
879 // to match iupac letter codes
880 if (a_motif[motif_i] =='N')
882 else if (a_motif[motif_i] == seq_c[seq_i])
884 else if ((a_motif[motif_i] =='M') &&
885 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C')))
887 else if ((a_motif[motif_i] =='R') &&
888 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G')))
890 else if ((a_motif[motif_i] =='W') &&
891 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='T')))
893 else if ((a_motif[motif_i] =='S') &&
894 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G')))
896 else if ((a_motif[motif_i] =='Y') &&
897 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='T')))
899 else if ((a_motif[motif_i] =='K') &&
900 ((seq_c[seq_i]=='G') || (seq_c[seq_i]=='T')))
902 else if ((a_motif[motif_i] =='V') &&
903 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
904 (seq_c[seq_i]=='G')))
906 else if ((a_motif[seq_i] =='H') &&
907 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
908 (seq_c[seq_i]=='T')))
910 else if ((a_motif[motif_i] =='D') &&
911 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G') ||
912 (seq_c[seq_i]=='T')))
914 else if ((a_motif[motif_i] =='B') &&
915 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G') ||
916 (seq_c[seq_i]=='T')))
925 // end Nora stuff, now we see if a match is found this pass
926 if (motif_i == motif_len)
930 motif_match_starts->push_back(seq_i - motif_len + 1);
936 //std::cout << std::endl;
939 void Sequence::add_string_annotation(std::string a_seq,
942 std::vector<int> seq_starts = find_motif(a_seq);
944 //std::cout << "searching for " << a_seq << " found " << seq_starts.size() << std::endl;
946 for(std::vector<int>::iterator seq_start_i = seq_starts.begin();
947 seq_start_i != seq_starts.end();
950 annots.push_back(annot(*seq_start_i,
951 *seq_start_i+a_seq.size(),
957 void Sequence::find_sequences(std::list<Sequence>::iterator start,
958 std::list<Sequence>::iterator end)
960 while (start != end) {
961 add_string_annotation(start->get_seq(), start->get_header());