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"
50 annot::annot(int begin, int end, std::string type, std::string name)
62 bool operator==(const annot& left, const annot& right)
64 return ((left.begin== right.begin) and
65 (left.end == right.end) and
66 (left.type == right.type) and
67 (left.name == right.name));
70 motif::motif(int begin, std::string motif)
71 : annot(begin, begin+motif.size(), "motif", motif),
81 Sequence::Sequence(alphabet_ref alphabet_)
94 Sequence::Sequence(const char *seq, alphabet_ref alphabet_)
99 strand(UnknownStrand),
103 set_filtered_sequence(seq, alphabet);
106 Sequence::Sequence(const std::string& seq, alphabet_ref alphabet_)
111 strand(UnknownStrand),
115 set_filtered_sequence(seq, alphabet);
118 Sequence::Sequence(const Sequence& o)
121 alphabet(o.alphabet),
122 seq_start(o.seq_start),
123 seq_count(o.seq_count),
128 motif_list(o.motif_list)
132 Sequence &Sequence::operator=(const Sequence& s)
137 alphabet = s.alphabet;
138 seq_start = s.seq_start;
139 seq_count = s.seq_count;
144 motif_list = s.motif_list;
149 static void multiplatform_getline(std::istream& in, std::string& line)
154 while(in.good() and !(c == '\012' or c == '\015') ) {
158 // if we have cr-lf eat it
160 if (c=='\012' or c == '\015') {
165 void Sequence::load_fasta(fs::path file_path, int seq_num, int start_index, int end_index)
167 load_fasta(file_path, alphabet, seq_num, start_index, end_index);
170 //! load a fasta file into a sequence
171 void Sequence::load_fasta(fs::path file_path, alphabet_ref a,
172 int seq_num, int start_index, int end_index)
174 fs::fstream data_file;
175 data_file.open(file_path, std::ios::in);
177 if (!data_file.good())
179 throw mussa_load_error("Sequence File: "+file_path.string()+" not found");
182 load_fasta(data_file, a, seq_num, start_index, end_index);
183 } catch(sequence_empty_error e) {
184 // there doesn't appear to be any sequence
185 // catch and rethrow to include the filename
186 std::stringstream msg;
187 msg << "The selected sequence in "
188 << file_path.native_file_string()
189 << " appears to be empty";
190 throw sequence_empty_error(msg.str());
191 } catch(sequence_empty_file_error e) {
192 std::stringstream errormsg;
193 errormsg << file_path.native_file_string()
194 << " did not have any fasta sequences" << std::endl;
195 throw sequence_empty_file_error(errormsg.str());
196 } catch(sequence_invalid_load_error e) {
197 std::ostringstream msg;
198 msg << file_path.native_file_string();
199 msg << " " << e.what();
200 throw sequence_invalid_load_error(msg.str());
205 void Sequence::load_fasta(std::istream& file,
206 int seq_num, int start_index, int end_index)
208 load_fasta(file, alphabet, seq_num, start_index, end_index);
212 Sequence::load_fasta(std::istream& data_file, alphabet_ref a,
214 int start_index, int end_index)
216 std::string file_data_line;
217 int header_counter = 0;
218 size_t line_counter = 0;
219 bool read_seq = true;
220 std::string rev_comp;
221 std::string sequence_raw;
222 std::string seq_tmp; // holds sequence during basic filtering
223 const Alphabet &alpha = get_alphabet(a);
226 throw mussa_load_error("fasta sequence number is 1 based (can't be 0)");
229 // search for the header of the fasta sequence we want
230 while ( (!data_file.eof()) && (header_counter < seq_num) )
232 multiplatform_getline(data_file, file_data_line);
234 if (file_data_line.substr(0,1) == ">")
238 if (header_counter > 0) {
239 header = file_data_line.substr(1);
243 while ( !data_file.eof() && read_seq ) {
244 multiplatform_getline(data_file,file_data_line);
246 if (file_data_line.substr(0,1) == ">")
249 for (std::string::const_iterator line_i = file_data_line.begin();
250 line_i != file_data_line.end();
253 if(alpha.exists(*line_i)) {
254 sequence_raw += *line_i;
256 std::ostringstream msg;
257 msg << "Unrecognized characters in fasta sequence at line ";
259 throw sequence_invalid_load_error(msg.str());
265 // Lastly, if subselection of the sequence was specified we keep cut out
266 // and only keep that part
267 // end_index = 0 means no end was specified, so cut to the end
269 end_index = sequence_raw.size();
271 // sequence filtering for upcasing agctn and convert non AGCTN to N
272 if (end_index-start_index <= 0) {
273 std::string msg("The selected sequence appears to be empty");
274 throw sequence_empty_error(msg);
276 set_filtered_sequence(sequence_raw, a, start_index, end_index-start_index);
278 std::string errormsg("There were no fasta sequences");
279 throw sequence_empty_file_error(errormsg);
283 void Sequence::set_filtered_sequence(const std::string &in_seq,
284 alphabet_ref alphabet_,
289 alphabet = alphabet_;
291 count = in_seq.size() - start;
292 boost::shared_ptr<seq_string> new_seq(new seq_string);
293 new_seq->reserve(count);
295 // finally, the actual conversion loop
296 const Alphabet& alpha_impl = get_alphabet(); // go get one of our actual alphabets
297 std::string::const_iterator seq_i = in_seq.begin()+start;
298 for(size_type i = 0; i != count; ++i, ++seq_i)
300 if (alpha_impl.exists(*seq_i)) {
301 new_seq->append(1, toupper(*seq_i));
303 new_seq->append(1, 'N');
314 Sequence::load_annot(fs::path file_path, int start_index, int end_index)
316 fs::fstream data_stream(file_path, std::ios::in);
319 throw mussa_load_error("Sequence File: " + file_path.string() + " not found");
322 // so i should probably be passing the parse function some iterators
323 // but the annotations files are (currently) small, so i think i can
324 // get away with loading the whole file into memory
327 while(data_stream.good()) {
333 parse_annot(data, start_index, end_index);
336 /* If this works, yikes, this is some brain hurting code.
338 * what's going on is that when pb_annot is instantiated it stores references
339 * to begin, end, name, type, declared in the parse function, then
340 * when operator() is called it grabs values from those references
341 * and uses that to instantiate an annot object and append that to our
344 * This weirdness is because the spirit library requires that actions
345 * conform to a specific prototype operator()(IteratorT, IteratorT)
346 * which doesn't provide any useful opportunity for me to actually
347 * grab the results of our parsing.
349 * so I instantiate this structure in order to have a place to grab
353 struct push_back_annot {
354 std::list<annot>& annot_list;
361 push_back_annot(std::list<annot>& annot_list_,
367 : annot_list(annot_list_),
376 void operator()(std::string::const_iterator,
377 std::string::const_iterator) const
379 //std::cout << "adding annot: " << begin << "|" << end << "|" << name << "|" << type << std::endl;
380 annot_list.push_back(annot(begin, end, name, type));
385 struct push_back_seq {
386 std::list<Sequence>& seq_list;
391 push_back_seq(std::list<Sequence>& seq_list_,
395 : seq_list(seq_list_),
402 void operator()(std::string::const_iterator,
403 std::string::const_iterator) const
405 // filter out newlines from our sequence
407 for(std::string::const_iterator seq_i = seq.begin();
411 if (*seq_i != '\015' && *seq_i != '\012') new_seq += *seq_i;
413 //std::cout << "adding seq: " << name << " " << new_seq << std::endl;
416 s.set_fasta_header(name);
417 seq_list.push_back(s);
423 Sequence::parse_annot(std::string data, int start_index, int end_index)
430 std::list<annot> parsed_annots;
431 std::list<Sequence> query_seqs;
434 bool ok = spirit::parse(data.begin(), data.end(),
441 )[spirit::assign_a(species)] >>
445 ( // ignore html tags
446 *(spirit::space_p) >>
448 +(~spirit::ch_p('>')) >>
453 ( // parse an absolute location name
454 (spirit::uint_p[spirit::assign_a(start)] >>
456 spirit::uint_p[spirit::assign_a(end)] >>
461 )[spirit::assign_a(name)] >>
468 )[spirit::assign_a(type)]
470 // to understand how this group gets set
471 // read the comment above struct push_back_annot
472 )[push_back_annot(parsed_annots, start, end, type, name, parsed)]
474 ((spirit::ch_p('>')|spirit::str_p(">")) >>
475 (*(spirit::print_p))[spirit::assign_a(name)] >>
477 (+(spirit::chset<>(Alphabet::nucleic_cstr)))[spirit::assign_a(seq)]
478 )[push_back_seq(query_seqs, name, seq, parsed)]
485 std::stringstream msg;
486 msg << "Error parsing annotation #" << parsed;
487 throw annotation_load_error(msg.str());
489 // add newly parsed annotations to our sequence
490 std::copy(parsed_annots.begin(), parsed_annots.end(), std::back_inserter(annots));
491 // go seearch for query sequences
492 find_sequences(query_seqs.begin(), query_seqs.end());
495 void Sequence::add_annotation(const annot& a)
500 const std::list<annot>& Sequence::annotations() const
506 Sequence::subseq(int start, int count)
513 // there might be an off by one error with start+count > size()
514 if ( count == npos || start+count > size()) {
515 count = size()-start;
517 Sequence new_seq(*this);
518 new_seq.parent = this;
519 new_seq.seq_start = seq_start+start;
520 new_seq.seq_count = count;
522 new_seq.motif_list = motif_list;
523 new_seq.annots.clear();
524 // attempt to copy & reannotate position based annotations
525 int end = start+count;
527 for(std::list<annot>::const_iterator annot_i = annots.begin();
528 annot_i != annots.end();
531 int annot_begin= annot_i->begin;
532 int annot_end = annot_i->end;
534 if (annot_begin < end) {
535 if (annot_begin >= start) {
536 annot_begin -= start;
541 if (annot_end < end) {
547 annot new_annot(annot_begin, annot_end, annot_i->type, annot_i->name);
548 new_seq.annots.push_back(new_annot);
555 std::string Sequence::create_reverse_map() const
557 std::string rc_map(256, '~');
558 // if we're rna, use U instead of T
559 // we might want to add an "is_rna" to sequence at somepoint
560 char TU = (alphabet == reduced_rna_alphabet) ? 'U' : 'T';
561 char tu = (alphabet == reduced_rna_alphabet) ? 'u' : 't';
562 rc_map['A'] = TU ; rc_map['a'] = tu ;
563 rc_map['T'] = 'A'; rc_map['t'] = 'a';
564 rc_map['U'] = 'A'; rc_map['u'] = 'a';
565 rc_map['G'] = 'C'; rc_map['g'] = 'c';
566 rc_map['C'] = 'G'; rc_map['c'] = 'g';
567 rc_map['M'] = 'K'; rc_map['m'] = 'k';
568 rc_map['R'] = 'Y'; rc_map['r'] = 'y';
569 rc_map['W'] = 'W'; rc_map['w'] = 'w';
570 rc_map['S'] = 'S'; rc_map['s'] = 's';
571 rc_map['Y'] = 'R'; rc_map['y'] = 'r';
572 rc_map['K'] = 'M'; rc_map['k'] = 'm';
573 rc_map['V'] = 'B'; rc_map['v'] = 'b';
574 rc_map['H'] = 'D'; rc_map['h'] = 'd';
575 rc_map['D'] = 'H'; rc_map['d'] = 'h';
576 rc_map['B'] = 'V'; rc_map['b'] = 'v';
577 rc_map['N'] = 'N'; rc_map['n'] = 'n';
578 rc_map['X'] = 'X'; rc_map['x'] = 'x';
582 rc_map['~'] = '~'; // not really needed, but perhaps it's clearer.
586 Sequence Sequence::rev_comp() const
588 std::string rev_comp;
589 rev_comp.reserve(length());
591 std::string rc_map = create_reverse_map();
593 // reverse and convert
594 Sequence::const_reverse_iterator seq_i;
595 Sequence::const_reverse_iterator seq_end = rend();
596 for(seq_i = rbegin();
600 rev_comp.append(1, rc_map[*seq_i]);
602 return Sequence(rev_comp, alphabet);
605 void Sequence::set_fasta_header(std::string header_)
610 void Sequence::set_species(const std::string& name)
615 std::string Sequence::get_species() const
622 Sequence::get_fasta_header() const
628 Sequence::get_name() const
630 if (header.size() > 0)
632 else if (species.size() > 0)
638 const Alphabet& Sequence::get_alphabet() const
640 return get_alphabet(alphabet);
643 const Alphabet& Sequence::get_alphabet(alphabet_ref alpha) const
646 case reduced_dna_alphabet:
647 return Alphabet::reduced_dna_alphabet();
648 case reduced_rna_alphabet:
649 return Alphabet::reduced_rna_alphabet();
650 case reduced_nucleic_alphabet:
651 return Alphabet::reduced_nucleic_alphabet();
652 case nucleic_alphabet:
653 return Alphabet::nucleic_alphabet();
654 case protein_alphabet:
655 return Alphabet::protein_alphabet();
657 throw std::runtime_error("unrecognized alphabet type");
662 void Sequence::set_sequence(const std::string& s, alphabet_ref a)
664 set_filtered_sequence(s, a);
667 std::string Sequence::get_sequence() const
672 return std::string();
675 Sequence::const_reference Sequence::operator[](Sequence::size_type i) const
680 Sequence::const_reference Sequence::at(Sequence::size_type i) const
682 if (!seq) throw std::out_of_range("empty sequence");
683 return seq->at(i+seq_start);
693 strand = UnknownStrand;
700 const char *Sequence::c_str() const
703 return seq->c_str()+seq_start;
708 Sequence::const_iterator Sequence::begin() const
710 if (seq and seq_count != 0)
711 return seq->begin()+seq_start;
713 return Sequence::const_iterator(0);
716 Sequence::const_iterator Sequence::end() const
718 if (seq and seq_count != 0) {
719 return seq->begin() + seq_start + seq_count;
721 return Sequence::const_iterator(0);
725 Sequence::const_reverse_iterator Sequence::rbegin() const
727 if (seq and seq_count != 0)
728 return seq->rbegin()+(seq->size()-(seq_start+seq_count));
730 return Sequence::const_reverse_iterator();
733 Sequence::const_reverse_iterator Sequence::rend() const
735 if (seq and seq_count != 0) {
736 return rbegin() + seq_count;
738 return Sequence::const_reverse_iterator();
742 bool Sequence::empty() const
744 return (seq_count == 0) ? true : false;
747 Sequence::size_type Sequence::start() const
750 return seq_start - parent->start();
755 Sequence::size_type Sequence::stop() const
757 return start() + seq_count;
760 Sequence::size_type Sequence::size() const
765 Sequence::size_type Sequence::length() const
771 Sequence::save(fs::fstream &save_file)
774 std::list<annot>::iterator annots_i;
776 // not sure why, or if i'm doing something wrong, but can't seem to pass
777 // file pointers down to this method from the mussa control class
778 // so each call to save a sequence appends to the file started by mussa_class
779 //save_file.open(save_file_path.c_str(), std::ios::app);
781 save_file << "<Sequence>" << std::endl;
782 save_file << *this << std::endl;
783 save_file << "</Sequence>" << std::endl;
785 save_file << "<Annotations>" << std::endl;
786 save_file << species << std::endl;
787 for (annots_i = annots.begin(); annots_i != annots.end(); ++annots_i)
789 save_file << annots_i->begin << " " << annots_i->end << " " ;
790 save_file << annots_i->name << " " << annots_i->type << std::endl;
792 save_file << "</Annotations>" << std::endl;
797 Sequence::load_museq(fs::path load_file_path, int seq_num)
799 fs::fstream load_file;
800 std::string file_data_line;
803 std::string::size_type space_split_i;
804 std::string annot_value;
807 load_file.open(load_file_path, std::ios::in);
810 // search for the seq_num-th sequence
811 while ( (!load_file.eof()) && (seq_counter < seq_num) )
813 getline(load_file,file_data_line);
814 if (file_data_line == "<Sequence>")
817 getline(load_file, file_data_line);
818 // looks like the sequence is written as a single line
819 set_filtered_sequence(file_data_line, reduced_dna_alphabet);
820 getline(load_file, file_data_line);
821 getline(load_file, file_data_line);
822 if (file_data_line == "<Annotations>")
824 getline(load_file, file_data_line);
825 species = file_data_line;
826 while ( (!load_file.eof()) && (file_data_line != "</Annotations>") )
828 getline(load_file,file_data_line);
829 if ((file_data_line != "") && (file_data_line != "</Annotations>"))
831 // need to get 4 values...almost same code 4 times...
832 // get annot start index
833 space_split_i = file_data_line.find(" ");
834 annot_value = file_data_line.substr(0,space_split_i);
835 an_annot.begin = atoi (annot_value.c_str());
836 file_data_line = file_data_line.substr(space_split_i+1);
837 // get annot end index
838 space_split_i = file_data_line.find(" ");
839 annot_value = file_data_line.substr(0,space_split_i);
840 an_annot.end = atoi (annot_value.c_str());
842 if (space_split_i == std::string::npos) // no entry for type or name
844 std::cout << "seq, annots - no type or name\n";
848 else // else get annot type
850 file_data_line = file_data_line.substr(space_split_i+1);
851 space_split_i = file_data_line.find(" ");
852 annot_value = file_data_line.substr(0,space_split_i);
853 an_annot.type = annot_value;
854 if (space_split_i == std::string::npos) // no entry for name
856 std::cout << "seq, annots - no name\n";
859 else // get annot name
861 file_data_line = file_data_line.substr(space_split_i+1);
862 space_split_i = file_data_line.find(" ");
863 annot_value = file_data_line.substr(0,space_split_i);
864 an_annot.type = annot_value;
867 annots.push_back(an_annot); // don't forget to actually add the annot
869 //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
870 // << "-->" << an_annot.type << "::" << an_annot.name << std::endl;
877 void Sequence::add_motif(const Sequence& a_motif)
879 std::vector<int> motif_starts = find_motif(a_motif);
881 for(std::vector<int>::iterator motif_start_i = motif_starts.begin();
882 motif_start_i != motif_starts.end();
885 motif_list.push_back(motif(*motif_start_i, a_motif.get_sequence()));
889 void Sequence::clear_motifs()
894 const std::list<motif>& Sequence::motifs() const
900 Sequence::find_motif(const Sequence& a_motif) const
902 std::vector<int> motif_match_starts;
903 Sequence norm_motif_rc;
905 motif_match_starts.clear();
906 // std::cout << "motif is: " << norm_motif << std::endl;
908 if (a_motif.size() > 0)
910 //std::cout << "Sequence: none blank motif\n";
911 motif_scan(a_motif, &motif_match_starts);
913 norm_motif_rc = a_motif.rev_comp();;
914 // make sure not to do search again if it is a palindrome
915 if (norm_motif_rc != a_motif) {
916 motif_scan(norm_motif_rc, &motif_match_starts);
919 return motif_match_starts;
923 Sequence::motif_scan(const Sequence& a_motif, std::vector<int> * motif_match_starts) const
925 // if there's no sequence we can't scan for it?
926 // should this throw an exception?
929 std::string::size_type seq_i = 0;
930 Sequence::size_type motif_i = 0;
931 Sequence::size_type motif_len = a_motif.length();
932 Sequence::value_type motif_char;
933 Sequence::value_type seq_char;
935 while (seq_i < size())
937 // this is pretty much a straight translation of Nora's python code
938 // to match iupac letter codes
939 motif_char = toupper(a_motif[motif_i]);
940 seq_char = toupper(seq->at(seq_start+seq_i));
941 if (motif_char =='N')
943 else if (motif_char == seq_char)
945 else if ((motif_char =='M') && ((seq_char=='A') || (seq_char=='C')))
947 else if ((motif_char =='R') && ((seq_char=='A') || (seq_char=='G')))
949 else if ((motif_char =='W') && ((seq_char=='A') || (seq_char=='T')))
951 else if ((motif_char =='S') && ((seq_char=='C') || (seq_char=='G')))
953 else if ((motif_char =='Y') && ((seq_char=='C') || (seq_char=='T')))
955 else if ((motif_char =='K') && ((seq_char=='G') || (seq_char=='T')))
957 else if ((motif_char =='V') &&
958 ((seq_char=='A') || (seq_char=='C') || (seq_char=='G')))
960 else if ((motif_char =='H') &&
961 ((seq_char=='A') || (seq_char=='C') || (seq_char=='T')))
963 else if ((motif_char =='D') &&
964 ((seq_char=='A') || (seq_char=='G') || (seq_char=='T')))
966 else if ((motif_char =='B') &&
967 ((seq_char=='C') || (seq_char=='G') || (seq_char=='T')))
971 // if a motif doesn't match, erase our current trial and try again
976 // end Nora stuff, now we see if a match is found this pass
977 if (motif_i == motif_len)
980 motif_match_starts->push_back(seq_i - motif_len + 1);
986 //std::cout << std::endl;
989 void Sequence::add_string_annotation(std::string a_seq,
992 std::vector<int> seq_starts = find_motif(a_seq);
994 //std::cout << "searching for " << a_seq << " found " << seq_starts.size() << std::endl;
996 for(std::vector<int>::iterator seq_start_i = seq_starts.begin();
997 seq_start_i != seq_starts.end();
1000 annots.push_back(annot(*seq_start_i,
1001 *seq_start_i+a_seq.size(),
1007 void Sequence::find_sequences(std::list<Sequence>::iterator start,
1008 std::list<Sequence>::iterator end)
1010 while (start != end) {
1011 add_string_annotation(start->get_sequence(), start->get_fasta_header());
1017 std::ostream& operator<<(std::ostream& out, const Sequence& s)
1019 for(Sequence::const_iterator s_i = s.begin(); s_i != s.end(); ++s_i) {
1025 bool operator<(const Sequence& x, const Sequence& y)
1027 Sequence::const_iterator x_i = x.begin();
1028 Sequence::const_iterator y_i = y.begin();
1029 // for sequences there's some computation associated with computing .end
1030 // so lets cache it.
1031 Sequence::const_iterator xend = x.end();
1032 Sequence::const_iterator yend = y.end();
1034 if( x_i == xend and y_i == yend ) {
1036 } else if ( x_i == xend ) {
1038 } else if ( y_i == yend ) {
1040 } else if ( (*x_i) < (*y_i)) {
1042 } else if ( (*x_i) > (*y_i) ) {
1051 bool operator==(const Sequence& x, const Sequence& y)
1053 if (x.empty() and y.empty()) {
1054 // if there's no sequence in either sequence structure, they're equal
1056 } else if (x.empty() or y.empty()) {
1057 // if we fail the first test, and we discover one is empty,
1058 // we know they can't be equal. (and we need to do this
1059 // to prevent dereferencing an empty pointer)
1061 } else if (x.seq_count != y.seq_count) {
1062 // if they're of different lenghts, they're not equal
1065 Sequence::const_iterator xseq_i = x.begin();
1066 Sequence::const_iterator yseq_i = y.begin();
1067 // since the length of the two sequences is equal, we only need to
1069 for(; xseq_i != x.end(); ++xseq_i, ++yseq_i) {
1070 if (toupper(*xseq_i) != toupper(*yseq_i)) {
1077 bool operator!=(const Sequence& x, const Sequence& y)
1079 return not operator==(x, y);