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");
223 // so i should probably be passing the parse function some iterators
224 // but the annotations files are (currently) small, so i think i can
225 // get away with loading the whole file into memory
228 while(data_stream.good()) {
234 parse_annot(data, start_index, end_index);
237 /* If this works, yikes, this is some brain hurting code.
239 * what's going on is that when pb_annot is instantiated it stores references
240 * to begin, end, name, type, declared in the parse function, then
241 * when operator() is called it grabs values from those references
242 * and uses that to instantiate an annot object and append that to our
245 * This weirdness is because the spirit library requires that actions
246 * conform to a specific prototype operator()(IteratorT, IteratorT)
247 * which doesn't provide any useful opportunity for me to actually
248 * grab the results of our parsing.
250 * so I instantiate this structure in order to have a place to grab
254 struct push_back_annot {
255 std::list<annot>& annot_list;
261 push_back_annot(std::list<annot>& annot_list_,
266 : annot_list(annot_list_),
274 void operator()(std::string::const_iterator,
275 std::string::const_iterator) const
277 annot_list.push_back(annot(begin, end, name, type));
283 Sequence::parse_annot(std::string data, int start_index, int end_index)
285 std::string species_name;
292 bool status = spirit::parse(data.begin(), data.end(),
295 (+(spirit::alpha_p))[spirit::assign_a(species_name)] >>
296 *((spirit::uint_p[spirit::assign_a(start)] >>
297 spirit::uint_p[spirit::assign_a(end)] >>
298 (*(spirit::alpha_p))[spirit::assign_a(name)] >>
299 (*(spirit::alpha_p))[spirit::assign_a(type)]
300 // to understand, read the comment above
301 // struct push_back_annot
302 )[push_back_annot(annots, start, end, name, type)])
305 spirit::space_p).full;
310 Sequence::load_annot(std::istream& data_stream, int start_index, int end_index)
312 std::string file_data_line;
314 std::string::size_type space_split_i;
315 std::string annot_value;
316 std::list<annot>::iterator list_i;
321 getline(data_stream,file_data_line);
322 species = file_data_line;
324 // end_index = 0 means no end was specified, so cut to the end
326 end_index = sequence.length();
328 //std::cout << "START: " << start_index << " END: " << end_index << std::endl;
330 while ( !data_stream.eof() )
332 getline(data_stream,file_data_line);
333 if (file_data_line != "")
335 // need to get 4 values...almost same code 4 times...
336 // get annot start index
337 space_split_i = file_data_line.find(" ");
338 annot_value = file_data_line.substr(0,space_split_i);
339 an_annot.start = atoi (annot_value.c_str());
340 file_data_line = file_data_line.substr(space_split_i+1);
341 // get annot end index
342 space_split_i = file_data_line.find(" ");
343 annot_value = file_data_line.substr(0,space_split_i);
344 an_annot.end = atoi (annot_value.c_str());
345 file_data_line = file_data_line.substr(space_split_i+1);
347 //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
351 space_split_i = file_data_line.find(" ");
352 if (space_split_i == std::string::npos) // no entries for name & type
354 std::cout << "seq, annots - no name or type\n";
360 annot_value = file_data_line.substr(0,space_split_i);
361 an_annot.name = annot_value;
362 file_data_line = file_data_line.substr(space_split_i+1);
364 space_split_i = file_data_line.find(" ");
365 if (space_split_i == std::string::npos) // no entry for type
369 annot_value = file_data_line.substr(0,space_split_i);
370 an_annot.type = annot_value;
375 // add annot to list if it falls within the range of sequence specified
376 if ((start_index <= an_annot.start) && (end_index >= an_annot.end))
378 an_annot.start -= start_index;
379 an_annot.end -= start_index;
380 annots.push_back(an_annot);
382 // else no (or bogus) annotations
388 const std::string& Sequence::get_species() const
393 bool Sequence::empty() const
395 return (size() == 0);
398 const std::list<annot>& Sequence::annotations() const
403 std::string::size_type Sequence::length() const
408 std::string::size_type Sequence::size() const
410 return sequence.size();
413 Sequence::iterator Sequence::begin()
415 return sequence.begin();
418 Sequence::const_iterator Sequence::begin() const
420 return sequence.begin();
423 Sequence::iterator Sequence::end()
425 return sequence.end();
428 Sequence::const_iterator Sequence::end() const
430 return sequence.end();
435 Sequence::get_seq() const
442 Sequence::subseq(int start, int end) const
444 return sequence.substr(start, end);
449 Sequence::c_seq() const
451 return sequence.c_str();
455 Sequence::rev_comp() const
457 std::string rev_comp;
458 char conversionTable[257];
459 int seq_i, table_i, len;
461 len = sequence.length();
462 rev_comp.reserve(len);
463 // make a conversion table
464 // init all parts of conversion table to '~' character
465 // '~' I doubt will ever appear in a sequence file (jeez, I hope)
466 // and may the fleas of 1000 camels infest the genitals of any biologist (and
467 // seven generations of their progeny) who decides to make it mean
468 // something special!!!
469 // PS - double the curse for any smartass non-biologist who tries it as well
470 for(table_i=0; table_i < 256; table_i++)
472 conversionTable[table_i] = '~';
474 // add end of string character for printing out table for testing purposes
475 conversionTable[256] = '\0';
477 // add in the characters for the bases we want to convert
478 conversionTable[(int)'A'] = 'T';
479 conversionTable[(int)'T'] = 'A';
480 conversionTable[(int)'G'] = 'C';
481 conversionTable[(int)'C'] = 'G';
482 conversionTable[(int)'N'] = 'N';
484 // finally, the actual conversion loop
485 for(seq_i = len - 1; seq_i >= 0; seq_i--)
487 table_i = (int) sequence[seq_i];
488 rev_comp += conversionTable[table_i];
496 Sequence::get_header() const
501 //FIXME: i don't think this code is callable
503 Sequence::sp_name() const
510 Sequence::set_seq(const std::string& a_seq)
512 set_filtered_sequence(a_seq);
534 Sequence::save(fs::fstream &save_file)
535 //std::string save_file_path)
538 std::list<annot>::iterator annots_i;
540 // not sure why, or if i'm doing something wrong, but can't seem to pass
541 // file pointers down to this method from the mussa control class
542 // so each call to save a sequence appends to the file started by mussa_class
543 //save_file.open(save_file_path.c_str(), std::ios::app);
545 save_file << "<Sequence>" << std::endl;
546 save_file << sequence << std::endl;
547 save_file << "</Sequence>" << std::endl;
549 save_file << "<Annotations>" << std::endl;
550 save_file << species << std::endl;
551 for (annots_i = annots.begin(); annots_i != annots.end(); ++annots_i)
553 save_file << annots_i->start << " " << annots_i->end << " " ;
554 save_file << annots_i->name << " " << annots_i->type << std::endl;
556 save_file << "</Annotations>" << std::endl;
561 Sequence::load_museq(fs::path load_file_path, int seq_num)
563 fs::fstream load_file;
564 std::string file_data_line;
567 std::string::size_type space_split_i;
568 std::string annot_value;
571 load_file.open(load_file_path, std::ios::in);
574 // search for the seq_num-th sequence
575 while ( (!load_file.eof()) && (seq_counter < seq_num) )
577 getline(load_file,file_data_line);
578 if (file_data_line == "<Sequence>")
581 getline(load_file, file_data_line);
582 sequence = file_data_line;
583 getline(load_file, file_data_line);
584 getline(load_file, file_data_line);
585 if (file_data_line == "<Annotations>")
587 getline(load_file, file_data_line);
588 species = file_data_line;
589 while ( (!load_file.eof()) && (file_data_line != "</Annotations>") )
591 getline(load_file,file_data_line);
592 if ((file_data_line != "") && (file_data_line != "</Annotations>"))
594 // need to get 4 values...almost same code 4 times...
595 // get annot start index
596 space_split_i = file_data_line.find(" ");
597 annot_value = file_data_line.substr(0,space_split_i);
598 an_annot.start = atoi (annot_value.c_str());
599 file_data_line = file_data_line.substr(space_split_i+1);
600 // get annot end index
601 space_split_i = file_data_line.find(" ");
602 annot_value = file_data_line.substr(0,space_split_i);
603 an_annot.end = atoi (annot_value.c_str());
605 if (space_split_i == std::string::npos) // no entry for type or name
607 std::cout << "seq, annots - no type or name\n";
611 else // else get annot type
613 file_data_line = file_data_line.substr(space_split_i+1);
614 space_split_i = file_data_line.find(" ");
615 annot_value = file_data_line.substr(0,space_split_i);
616 an_annot.type = annot_value;
617 if (space_split_i == std::string::npos) // no entry for name
619 std::cout << "seq, annots - no name\n";
622 else // get annot name
624 file_data_line = file_data_line.substr(space_split_i+1);
625 space_split_i = file_data_line.find(" ");
626 annot_value = file_data_line.substr(0,space_split_i);
627 an_annot.type = annot_value;
630 annots.push_back(an_annot); // don't forget to actually add the annot
632 //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
633 // << "-->" << an_annot.type << "::" << an_annot.name << std::endl;
641 Sequence::rc_motif(std::string a_motif)
643 std::string rev_comp;
644 char conversionTable[257];
645 int seq_i, table_i, len;
647 len = a_motif.length();
648 rev_comp.reserve(len);
650 for(table_i=0; table_i < 256; table_i++)
652 conversionTable[table_i] = '~';
654 // add end of std::string character for printing out table for testing purposes
655 conversionTable[256] = '\0';
657 // add in the characters for the bases we want to convert (IUPAC)
658 conversionTable[(int)'A'] = 'T';
659 conversionTable[(int)'T'] = 'A';
660 conversionTable[(int)'G'] = 'C';
661 conversionTable[(int)'C'] = 'G';
662 conversionTable[(int)'N'] = 'N';
663 conversionTable[(int)'M'] = 'K';
664 conversionTable[(int)'R'] = 'Y';
665 conversionTable[(int)'W'] = 'W';
666 conversionTable[(int)'S'] = 'S';
667 conversionTable[(int)'Y'] = 'R';
668 conversionTable[(int)'K'] = 'M';
669 conversionTable[(int)'V'] = 'B';
670 conversionTable[(int)'H'] = 'D';
671 conversionTable[(int)'D'] = 'H';
672 conversionTable[(int)'B'] = 'V';
674 // finally, the actual conversion loop
675 for(seq_i = len - 1; seq_i >= 0; seq_i--)
677 //std::cout << "** i = " << seq_i << " bp = " <<
678 table_i = (int) a_motif[seq_i];
679 rev_comp += conversionTable[table_i];
682 //std::cout << "seq: " << a_motif << std::endl;
683 //std::cout << "rc: " << rev_comp << std::endl;
689 Sequence::motif_normalize(std::string a_motif)
691 std::string valid_motif;
694 len = a_motif.length();
695 valid_motif.reserve(len);
697 // this just upcases IUPAC symbols. Eventually should return an error if non IUPAC is present.
698 // current nonIUPAC symbols are omitted, which is not reported atm
699 for(seq_i = 0; seq_i < len; seq_i++)
701 if ((a_motif[seq_i] == 'a') || (a_motif[seq_i] == 'A'))
703 else if ((a_motif[seq_i] == 't') || (a_motif[seq_i] == 'T'))
705 else if ((a_motif[seq_i] == 'g') || (a_motif[seq_i] == 'G'))
707 else if ((a_motif[seq_i] == 'c') || (a_motif[seq_i] == 'C'))
709 else if ((a_motif[seq_i] == 'n') || (a_motif[seq_i] == 'N'))
711 else if ((a_motif[seq_i] == 'm') || (a_motif[seq_i] == 'M'))
713 else if ((a_motif[seq_i] == 'r') || (a_motif[seq_i] == 'R'))
715 else if ((a_motif[seq_i] == 'w') || (a_motif[seq_i] == 'W'))
717 else if ((a_motif[seq_i] == 's') || (a_motif[seq_i] == 'S'))
719 else if ((a_motif[seq_i] == 'y') || (a_motif[seq_i] == 'Y'))
721 else if ((a_motif[seq_i] == 'k') || (a_motif[seq_i] == 'K'))
723 else if ((a_motif[seq_i] == 'v') || (a_motif[seq_i] == 'V'))
725 else if ((a_motif[seq_i] == 'h') || (a_motif[seq_i] == 'H'))
727 else if ((a_motif[seq_i] == 'd') || (a_motif[seq_i] == 'D'))
729 else if ((a_motif[seq_i] == 'b') || (a_motif[seq_i] == 'B'))
732 std::string msg = "Letter ";
733 msg += a_motif[seq_i];
734 msg += " is not a valid IUPAC symbol";
735 throw motif_normalize_error(msg);
738 //std::cout << "valid_motif is: " << valid_motif << std::endl;
742 void Sequence::add_motif(std::string a_motif)
744 std::vector<int> motif_starts = find_motif(a_motif);
746 for(std::vector<int>::iterator motif_start_i = motif_starts.begin();
747 motif_start_i != motif_starts.end();
750 motif_list.push_back(motif(*motif_start_i, a_motif));
754 void Sequence::clear_motifs()
759 const std::list<motif>& Sequence::motifs() const
765 Sequence::find_motif(std::string a_motif)
767 std::vector<int> motif_match_starts;
768 std::string a_motif_rc;
770 motif_match_starts.clear();
772 //std::cout << "motif is: " << a_motif << std::endl;
773 a_motif = motif_normalize(a_motif);
774 //std::cout << "motif is: " << a_motif << std::endl;
778 //std::cout << "Sequence: none blank motif\n";
779 motif_scan(a_motif, &motif_match_starts);
781 a_motif_rc = rc_motif(a_motif);
782 // make sure not to do search again if it is a palindrome
783 if (a_motif_rc != a_motif)
784 motif_scan(a_motif_rc, &motif_match_starts);
786 return motif_match_starts;
790 Sequence::motif_scan(std::string a_motif, std::vector<int> * motif_match_starts)
793 std::string::size_type seq_i;
794 int motif_i, motif_len;
796 // faster to loop thru the sequence as a old c std::string (ie char array)
797 seq_c = (char*)sequence.c_str();
798 //std::cout << "Sequence: motif, seq len = " << sequence.length() << std::endl;
799 motif_len = a_motif.length();
801 //std::cout << "motif_length: " << motif_len << std::endl;
802 //std::cout << "RAAARRRRR\n";
806 //std::cout << "motif: " << a_motif << std::endl;
808 //std::cout << "Sequence: motif, length= " << length << std::endl;
810 while (seq_i < sequence.length())
812 //std::cout << seq_c[seq_i];
813 //std::cout << seq_c[seq_i] << "?" << a_motif[motif_i] << ":" << motif_i << " ";
814 // this is pretty much a straight translation of Nora's python code
815 // to match iupac letter codes
816 if (a_motif[motif_i] =='N')
818 else if (a_motif[motif_i] == seq_c[seq_i])
820 else if ((a_motif[motif_i] =='M') &&
821 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C')))
823 else if ((a_motif[motif_i] =='R') &&
824 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G')))
826 else if ((a_motif[motif_i] =='W') &&
827 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='T')))
829 else if ((a_motif[motif_i] =='S') &&
830 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G')))
832 else if ((a_motif[motif_i] =='Y') &&
833 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='T')))
835 else if ((a_motif[motif_i] =='K') &&
836 ((seq_c[seq_i]=='G') || (seq_c[seq_i]=='T')))
838 else if ((a_motif[motif_i] =='V') &&
839 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
840 (seq_c[seq_i]=='G')))
842 else if ((a_motif[seq_i] =='H') &&
843 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
844 (seq_c[seq_i]=='T')))
846 else if ((a_motif[motif_i] =='D') &&
847 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G') ||
848 (seq_c[seq_i]=='T')))
850 else if ((a_motif[motif_i] =='B') &&
851 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G') ||
852 (seq_c[seq_i]=='T')))
861 // end Nora stuff, now we see if a match is found this pass
862 if (motif_i == motif_len)
866 motif_match_starts->push_back(seq_i - motif_len + 1);
872 //std::cout << std::endl;
875 void Sequence::add_string_annotation(std::string a_seq,
878 std::vector<int> seq_starts = find_motif(a_seq);
880 for(std::vector<int>::iterator seq_start_i = seq_starts.begin();
881 seq_start_i != seq_starts.end();
884 annots.push_back(annot(*seq_start_i,
885 *seq_start_i+a_seq.size(),
891 void Sequence::find_sequences(std::list<Sequence>::iterator start,
892 std::list<Sequence>::iterator end)
894 while (start != end) {
895 add_string_annotation(start->get_seq(), start->get_header());