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 #include <boost/spirit/utility/chset.hpp>
31 namespace spirit = boost::spirit;
33 #include "alg/sequence.hpp"
34 #include "mussa_exceptions.hpp"
40 // some standard dna alphabets
43 // this should make our sequence parsing end-of-line convention
45 static const char* dna_alphabet = "AaCcGgTtNn\012\015";
46 static const char* rna_alphabet = "AaCcGgNnUu\012\015";
47 static const char* iupac_alphabet = "AaCcGgTtUuRrYyMmKkSsWwBbDdHhVvNn\012\015";
57 annot::annot(int start, int end, std::string type, std::string name)
65 motif::motif(int start, std::string motif)
66 : annot(start, start+motif.size(), "motif", motif),
80 Sequence::Sequence(std::string seq)
84 set_filtered_sequence(seq);
87 Sequence &Sequence::operator=(const Sequence& s)
90 sequence = s.sequence;
98 Sequence &Sequence::operator=(const std::string& s)
100 set_filtered_sequence(s);
104 char Sequence::operator[](int index) const
106 return sequence[index];
109 std::ostream& operator<<(std::ostream& out, const Sequence& seq)
111 out << "Sequence(" << seq.get_seq() << ")";
115 //! load a fasta file into a sequence
117 * \param file_path the location of the fasta file in the filesystem
118 * \param seq_num which sequence in the file to load
119 * \param start_index starting position in the fasta sequence, 0 for beginning
120 * \param end_index ending position in the fasta sequence, 0 for end
121 * \return error message, empty string if no error. (gag!)
124 Sequence::load_fasta(fs::path file_path, int seq_num,
125 int start_index, int end_index)
127 fs::fstream data_file;
128 std::string file_data_line;
129 int header_counter = 0;
130 bool read_seq = true;
131 std::string rev_comp;
132 std::string sequence_raw;
133 std::string seq_tmp; // holds sequence during basic filtering
135 data_file.open(file_path, std::ios::in);
138 throw mussa_load_error("fasta sequence number is 1 based (can't be 0)");
142 throw mussa_load_error("Sequence File: " + file_path.string() + " not found");
144 // if file opened okay, read it
147 // search for the header of the fasta sequence we want
148 while ( (!data_file.eof()) && (header_counter < seq_num) )
150 getline(data_file,file_data_line);
151 if (file_data_line.substr(0,1) == ">")
155 if (header_counter > 0) {
156 header = file_data_line.substr(1);
160 while ( !data_file.eof() && read_seq ) {
161 getline(data_file,file_data_line);
162 if (file_data_line.substr(0,1) == ">")
164 else sequence_raw += file_data_line;
167 // Lastly, if subselection of the sequence was specified we keep cut out
168 // and only keep that part
169 // end_index = 0 means no end was specified, so cut to the end
171 end_index = sequence_raw.size();
173 // sequence filtering for upcasing agctn and convert non AGCTN to N
174 if (end_index-start_index <= 0) {
175 // there doesn't appear to be any sequence
176 std::stringstream msg;
177 msg << "The selected sequence in "
178 << file_path.native_file_string()
179 << " appears to be empty";
180 throw mussa_load_error(msg.str());
182 set_filtered_sequence(sequence_raw, start_index, end_index-start_index);
184 std::stringstream errormsg;
185 errormsg << file_path.native_file_string()
186 << " did not have any fasta sequences" << std::endl;
187 throw mussa_load_error(errormsg.str());
193 void Sequence::set_filtered_sequence(const std::string &old_seq,
194 std::string::size_type start,
195 std::string::size_type count)
197 char conversionTable[257];
200 count = old_seq.size() - start;
202 sequence.reserve(count);
204 // Make a conversion table
206 // everything we don't specify below will become 'N'
207 for(int table_i=0; table_i < 256; table_i++)
209 conversionTable[table_i] = 'N';
211 // add end of string character for printing out table for testing purposes
212 conversionTable[256] = '\0';
214 // we want these to map to themselves - ie not to change
215 conversionTable[(int)'A'] = 'A';
216 conversionTable[(int)'T'] = 'T';
217 conversionTable[(int)'G'] = 'G';
218 conversionTable[(int)'C'] = 'C';
220 conversionTable[(int)'a'] = 'A';
221 conversionTable[(int)'t'] = 'T';
222 conversionTable[(int)'g'] = 'G';
223 conversionTable[(int)'c'] = 'C';
225 // finally, the actual conversion loop
226 for(std::string::size_type seq_index = 0; seq_index < count; seq_index++)
228 sequence += conversionTable[ (int)old_seq[seq_index+start]];
232 // this doesn't work properly under gcc 3.x ... it can't recognize toupper
233 //transform(sequence.begin(), sequence.end(), sequence.begin(), toupper);
236 Sequence::load_annot(fs::path file_path, int start_index, int end_index)
238 fs::fstream data_stream(file_path, std::ios::in);
241 throw mussa_load_error("Sequence File: " + file_path.string() + " not found");
244 // so i should probably be passing the parse function some iterators
245 // but the annotations files are (currently) small, so i think i can
246 // get away with loading the whole file into memory
249 while(data_stream.good()) {
255 parse_annot(data, start_index, end_index);
258 /* If this works, yikes, this is some brain hurting code.
260 * what's going on is that when pb_annot is instantiated it stores references
261 * to begin, end, name, type, declared in the parse function, then
262 * when operator() is called it grabs values from those references
263 * and uses that to instantiate an annot object and append that to our
266 * This weirdness is because the spirit library requires that actions
267 * conform to a specific prototype operator()(IteratorT, IteratorT)
268 * which doesn't provide any useful opportunity for me to actually
269 * grab the results of our parsing.
271 * so I instantiate this structure in order to have a place to grab
275 struct push_back_annot {
276 std::list<annot>& annot_list;
282 push_back_annot(std::list<annot>& annot_list_,
287 : annot_list(annot_list_),
295 void operator()(std::string::const_iterator,
296 std::string::const_iterator) const
298 //std::cout << "adding annot: " << begin << " " << end << " " << name << " " << type << std::endl;
299 annot_list.push_back(annot(begin, end, name, type));
303 struct push_back_seq {
304 std::list<Sequence>& seq_list;
308 push_back_seq(std::list<Sequence>& seq_list_,
311 : seq_list(seq_list_),
317 void operator()(std::string::const_iterator,
318 std::string::const_iterator) const
320 // filter out newlines from our sequence
322 for(std::string::const_iterator seq_i = seq.begin();
326 if (*seq_i != '\015' && *seq_i != '\012') new_seq += *seq_i;
328 //std::cout << "adding seq: " << name << " " << new_seq << std::endl;
332 seq_list.push_back(s);
337 Sequence::parse_annot(std::string data, int start_index, int end_index)
344 std::list<Sequence> query_seqs;
346 bool status = spirit::parse(data.begin(), data.end(),
349 (+(spirit::alpha_p))[spirit::assign_a(species)] >>
350 +(spirit::space_p) >>
352 ( // parse an absolute location name
353 (spirit::uint_p[spirit::assign_a(start)] >>
355 spirit::uint_p[spirit::assign_a(end)] >>
357 (*(spirit::alpha_p|spirit::digit_p))[spirit::assign_a(name)] >>
361 (*(spirit::alpha_p))[spirit::assign_a(type)]
363 // to understand how this group gets set
364 // read the comment above struct push_back_annot
365 )[push_back_annot(annots, start, end, type, name)]
367 (spirit::ch_p('>') >>
368 (*(spirit::print_p))[spirit::assign_a(name)] >>
370 (+(spirit::chset<>(iupac_alphabet)))[spirit::assign_a(seq)]
371 )[push_back_seq(query_seqs, name, seq)]
377 spirit::space_p*/).full;
379 // go seearch for query sequences
380 find_sequences(query_seqs.begin(), query_seqs.end());
385 Sequence::load_annot(std::istream& data_stream, int start_index, int end_index)
387 std::string file_data_line;
389 std::string::size_type space_split_i;
390 std::string annot_value;
391 std::list<annot>::iterator list_i;
396 getline(data_stream,file_data_line);
397 species = file_data_line;
399 // end_index = 0 means no end was specified, so cut to the end
401 end_index = sequence.length();
403 //std::cout << "START: " << start_index << " END: " << end_index << std::endl;
405 while ( !data_stream.eof() )
407 getline(data_stream,file_data_line);
408 if (file_data_line != "")
410 // need to get 4 values...almost same code 4 times...
411 // get annot start index
412 space_split_i = file_data_line.find(" ");
413 annot_value = file_data_line.substr(0,space_split_i);
414 an_annot.start = atoi (annot_value.c_str());
415 file_data_line = file_data_line.substr(space_split_i+1);
416 // get annot end index
417 space_split_i = file_data_line.find(" ");
418 annot_value = file_data_line.substr(0,space_split_i);
419 an_annot.end = atoi (annot_value.c_str());
420 file_data_line = file_data_line.substr(space_split_i+1);
422 //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
426 space_split_i = file_data_line.find(" ");
427 if (space_split_i == std::string::npos) // no entries for name & type
429 std::cout << "seq, annots - no name or type\n";
435 annot_value = file_data_line.substr(0,space_split_i);
436 an_annot.name = annot_value;
437 file_data_line = file_data_line.substr(space_split_i+1);
439 space_split_i = file_data_line.find(" ");
440 if (space_split_i == std::string::npos) // no entry for type
444 annot_value = file_data_line.substr(0,space_split_i);
445 an_annot.type = annot_value;
450 // add annot to list if it falls within the range of sequence specified
451 if ((start_index <= an_annot.start) && (end_index >= an_annot.end))
453 an_annot.start -= start_index;
454 an_annot.end -= start_index;
455 annots.push_back(an_annot);
457 // else no (or bogus) annotations
463 const std::string& Sequence::get_species() const
468 bool Sequence::empty() const
470 return (size() == 0);
473 const std::list<annot>& Sequence::annotations() const
478 std::string::size_type Sequence::length() const
483 std::string::size_type Sequence::size() const
485 return sequence.size();
488 Sequence::iterator Sequence::begin()
490 return sequence.begin();
493 Sequence::const_iterator Sequence::begin() const
495 return sequence.begin();
498 Sequence::iterator Sequence::end()
500 return sequence.end();
503 Sequence::const_iterator Sequence::end() const
505 return sequence.end();
510 Sequence::get_seq() const
517 Sequence::subseq(int start, int end) const
519 return sequence.substr(start, end);
524 Sequence::c_seq() const
526 return sequence.c_str();
530 Sequence::rev_comp() const
532 std::string rev_comp;
533 char conversionTable[257];
534 int seq_i, table_i, len;
536 len = sequence.length();
537 rev_comp.reserve(len);
538 // make a conversion table
539 // init all parts of conversion table to '~' character
540 // '~' I doubt will ever appear in a sequence file (jeez, I hope)
541 // and may the fleas of 1000 camels infest the genitals of any biologist (and
542 // seven generations of their progeny) who decides to make it mean
543 // something special!!!
544 // PS - double the curse for any smartass non-biologist who tries it as well
545 for(table_i=0; table_i < 256; table_i++)
547 conversionTable[table_i] = '~';
549 // add end of string character for printing out table for testing purposes
550 conversionTable[256] = '\0';
552 // add in the characters for the bases we want to convert
553 conversionTable[(int)'A'] = 'T';
554 conversionTable[(int)'T'] = 'A';
555 conversionTable[(int)'G'] = 'C';
556 conversionTable[(int)'C'] = 'G';
557 conversionTable[(int)'N'] = 'N';
559 // finally, the actual conversion loop
560 for(seq_i = len - 1; seq_i >= 0; seq_i--)
562 table_i = (int) sequence[seq_i];
563 rev_comp += conversionTable[table_i];
569 void Sequence::set_header(std::string header_)
575 Sequence::get_header() const
580 //FIXME: i don't think this code is callable
582 Sequence::sp_name() const
589 Sequence::set_seq(const std::string& a_seq)
591 set_filtered_sequence(a_seq);
613 Sequence::save(fs::fstream &save_file)
614 //std::string save_file_path)
617 std::list<annot>::iterator annots_i;
619 // not sure why, or if i'm doing something wrong, but can't seem to pass
620 // file pointers down to this method from the mussa control class
621 // so each call to save a sequence appends to the file started by mussa_class
622 //save_file.open(save_file_path.c_str(), std::ios::app);
624 save_file << "<Sequence>" << std::endl;
625 save_file << sequence << std::endl;
626 save_file << "</Sequence>" << std::endl;
628 save_file << "<Annotations>" << std::endl;
629 save_file << species << std::endl;
630 for (annots_i = annots.begin(); annots_i != annots.end(); ++annots_i)
632 save_file << annots_i->start << " " << annots_i->end << " " ;
633 save_file << annots_i->name << " " << annots_i->type << std::endl;
635 save_file << "</Annotations>" << std::endl;
640 Sequence::load_museq(fs::path load_file_path, int seq_num)
642 fs::fstream load_file;
643 std::string file_data_line;
646 std::string::size_type space_split_i;
647 std::string annot_value;
650 load_file.open(load_file_path, std::ios::in);
653 // search for the seq_num-th sequence
654 while ( (!load_file.eof()) && (seq_counter < seq_num) )
656 getline(load_file,file_data_line);
657 if (file_data_line == "<Sequence>")
660 getline(load_file, file_data_line);
661 sequence = file_data_line;
662 getline(load_file, file_data_line);
663 getline(load_file, file_data_line);
664 if (file_data_line == "<Annotations>")
666 getline(load_file, file_data_line);
667 species = file_data_line;
668 while ( (!load_file.eof()) && (file_data_line != "</Annotations>") )
670 getline(load_file,file_data_line);
671 if ((file_data_line != "") && (file_data_line != "</Annotations>"))
673 // need to get 4 values...almost same code 4 times...
674 // get annot start index
675 space_split_i = file_data_line.find(" ");
676 annot_value = file_data_line.substr(0,space_split_i);
677 an_annot.start = atoi (annot_value.c_str());
678 file_data_line = file_data_line.substr(space_split_i+1);
679 // get annot end index
680 space_split_i = file_data_line.find(" ");
681 annot_value = file_data_line.substr(0,space_split_i);
682 an_annot.end = atoi (annot_value.c_str());
684 if (space_split_i == std::string::npos) // no entry for type or name
686 std::cout << "seq, annots - no type or name\n";
690 else // else get annot type
692 file_data_line = file_data_line.substr(space_split_i+1);
693 space_split_i = file_data_line.find(" ");
694 annot_value = file_data_line.substr(0,space_split_i);
695 an_annot.type = annot_value;
696 if (space_split_i == std::string::npos) // no entry for name
698 std::cout << "seq, annots - no name\n";
701 else // get annot name
703 file_data_line = file_data_line.substr(space_split_i+1);
704 space_split_i = file_data_line.find(" ");
705 annot_value = file_data_line.substr(0,space_split_i);
706 an_annot.type = annot_value;
709 annots.push_back(an_annot); // don't forget to actually add the annot
711 //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
712 // << "-->" << an_annot.type << "::" << an_annot.name << std::endl;
720 Sequence::rc_motif(std::string a_motif)
722 std::string rev_comp;
723 char conversionTable[257];
724 int seq_i, table_i, len;
726 len = a_motif.length();
727 rev_comp.reserve(len);
729 for(table_i=0; table_i < 256; table_i++)
731 conversionTable[table_i] = '~';
733 // add end of std::string character for printing out table for testing purposes
734 conversionTable[256] = '\0';
736 // add in the characters for the bases we want to convert (IUPAC)
737 conversionTable[(int)'A'] = 'T';
738 conversionTable[(int)'T'] = 'A';
739 conversionTable[(int)'G'] = 'C';
740 conversionTable[(int)'C'] = 'G';
741 conversionTable[(int)'N'] = 'N';
742 conversionTable[(int)'M'] = 'K';
743 conversionTable[(int)'R'] = 'Y';
744 conversionTable[(int)'W'] = 'W';
745 conversionTable[(int)'S'] = 'S';
746 conversionTable[(int)'Y'] = 'R';
747 conversionTable[(int)'K'] = 'M';
748 conversionTable[(int)'V'] = 'B';
749 conversionTable[(int)'H'] = 'D';
750 conversionTable[(int)'D'] = 'H';
751 conversionTable[(int)'B'] = 'V';
753 // finally, the actual conversion loop
754 for(seq_i = len - 1; seq_i >= 0; seq_i--)
756 //std::cout << "** i = " << seq_i << " bp = " <<
757 table_i = (int) a_motif[seq_i];
758 rev_comp += conversionTable[table_i];
761 //std::cout << "seq: " << a_motif << std::endl;
762 //std::cout << "rc: " << rev_comp << std::endl;
768 Sequence::motif_normalize(std::string a_motif)
770 std::string valid_motif;
773 len = a_motif.length();
774 valid_motif.reserve(len);
776 // this just upcases IUPAC symbols. Eventually should return an error if non IUPAC is present.
777 // current nonIUPAC symbols are omitted, which is not reported atm
778 for(seq_i = 0; seq_i < len; seq_i++)
780 if ((a_motif[seq_i] == 'a') || (a_motif[seq_i] == 'A'))
782 else if ((a_motif[seq_i] == 't') || (a_motif[seq_i] == 'T'))
784 else if ((a_motif[seq_i] == 'g') || (a_motif[seq_i] == 'G'))
786 else if ((a_motif[seq_i] == 'c') || (a_motif[seq_i] == 'C'))
788 else if ((a_motif[seq_i] == 'n') || (a_motif[seq_i] == 'N'))
790 else if ((a_motif[seq_i] == 'm') || (a_motif[seq_i] == 'M'))
792 else if ((a_motif[seq_i] == 'r') || (a_motif[seq_i] == 'R'))
794 else if ((a_motif[seq_i] == 'w') || (a_motif[seq_i] == 'W'))
796 else if ((a_motif[seq_i] == 's') || (a_motif[seq_i] == 'S'))
798 else if ((a_motif[seq_i] == 'y') || (a_motif[seq_i] == 'Y'))
800 else if ((a_motif[seq_i] == 'k') || (a_motif[seq_i] == 'K'))
802 else if ((a_motif[seq_i] == 'v') || (a_motif[seq_i] == 'V'))
804 else if ((a_motif[seq_i] == 'h') || (a_motif[seq_i] == 'H'))
806 else if ((a_motif[seq_i] == 'd') || (a_motif[seq_i] == 'D'))
808 else if ((a_motif[seq_i] == 'b') || (a_motif[seq_i] == 'B'))
811 std::string msg = "Letter ";
812 msg += a_motif[seq_i];
813 msg += " is not a valid IUPAC symbol";
814 throw motif_normalize_error(msg);
817 //std::cout << "valid_motif is: " << valid_motif << std::endl;
821 void Sequence::add_motif(std::string a_motif)
823 std::vector<int> motif_starts = find_motif(a_motif);
825 for(std::vector<int>::iterator motif_start_i = motif_starts.begin();
826 motif_start_i != motif_starts.end();
829 motif_list.push_back(motif(*motif_start_i, a_motif));
833 void Sequence::clear_motifs()
838 const std::list<motif>& Sequence::motifs() const
844 Sequence::find_motif(std::string a_motif)
846 std::vector<int> motif_match_starts;
847 std::string a_motif_rc;
849 motif_match_starts.clear();
851 //std::cout << "motif is: " << a_motif << std::endl;
852 a_motif = motif_normalize(a_motif);
853 //std::cout << "motif is: " << a_motif << std::endl;
857 //std::cout << "Sequence: none blank motif\n";
858 motif_scan(a_motif, &motif_match_starts);
860 a_motif_rc = rc_motif(a_motif);
861 // make sure not to do search again if it is a palindrome
862 if (a_motif_rc != a_motif)
863 motif_scan(a_motif_rc, &motif_match_starts);
865 return motif_match_starts;
869 Sequence::motif_scan(std::string a_motif, std::vector<int> * motif_match_starts)
872 std::string::size_type seq_i;
873 int motif_i, motif_len;
875 // faster to loop thru the sequence as a old c std::string (ie char array)
876 seq_c = (char*)sequence.c_str();
877 //std::cout << "Sequence: motif, seq len = " << sequence.length() << std::endl;
878 motif_len = a_motif.length();
880 //std::cout << "motif_length: " << motif_len << std::endl;
881 //std::cout << "RAAARRRRR\n";
885 //std::cout << "motif: " << a_motif << std::endl;
887 //std::cout << "Sequence: motif, length= " << length << std::endl;
889 while (seq_i < sequence.length())
891 //std::cout << seq_c[seq_i];
892 //std::cout << seq_c[seq_i] << "?" << a_motif[motif_i] << ":" << motif_i << " ";
893 // this is pretty much a straight translation of Nora's python code
894 // to match iupac letter codes
895 if (a_motif[motif_i] =='N')
897 else if (a_motif[motif_i] == seq_c[seq_i])
899 else if ((a_motif[motif_i] =='M') &&
900 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C')))
902 else if ((a_motif[motif_i] =='R') &&
903 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G')))
905 else if ((a_motif[motif_i] =='W') &&
906 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='T')))
908 else if ((a_motif[motif_i] =='S') &&
909 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G')))
911 else if ((a_motif[motif_i] =='Y') &&
912 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='T')))
914 else if ((a_motif[motif_i] =='K') &&
915 ((seq_c[seq_i]=='G') || (seq_c[seq_i]=='T')))
917 else if ((a_motif[motif_i] =='V') &&
918 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
919 (seq_c[seq_i]=='G')))
921 else if ((a_motif[seq_i] =='H') &&
922 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
923 (seq_c[seq_i]=='T')))
925 else if ((a_motif[motif_i] =='D') &&
926 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G') ||
927 (seq_c[seq_i]=='T')))
929 else if ((a_motif[motif_i] =='B') &&
930 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G') ||
931 (seq_c[seq_i]=='T')))
940 // end Nora stuff, now we see if a match is found this pass
941 if (motif_i == motif_len)
945 motif_match_starts->push_back(seq_i - motif_len + 1);
951 //std::cout << std::endl;
954 void Sequence::add_string_annotation(std::string a_seq,
957 std::vector<int> seq_starts = find_motif(a_seq);
959 //std::cout << "searching for " << a_seq << " found " << seq_starts.size() << std::endl;
961 for(std::vector<int>::iterator seq_start_i = seq_starts.begin();
962 seq_start_i != seq_starts.end();
965 annots.push_back(annot(*seq_start_i,
966 *seq_start_i+a_seq.size(),
972 void Sequence::find_sequences(std::list<Sequence>::iterator start,
973 std::list<Sequence>::iterator end)
975 while (start != end) {
976 add_string_annotation(start->get_seq(), start->get_header());