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 #include <boost/filesystem/operations.hpp>
26 namespace fs = boost::filesystem;
28 #include <boost/spirit/core.hpp>
29 #include <boost/spirit/actor/push_back_actor.hpp>
30 #include <boost/spirit/iterator/file_iterator.hpp>
31 #include <boost/spirit/utility/chset.hpp>
32 namespace spirit = boost::spirit;
34 #include "alg/sequence.hpp"
35 #include "mussa_exceptions.hpp"
51 annot::annot(int begin, int end, std::string type, std::string name)
63 bool operator==(const annot& left, const annot& right)
65 return ((left.begin== right.begin) and
66 (left.end == right.end) and
67 (left.type == right.type) and
68 (left.name == right.name));
71 motif::motif(int begin, std::string motif)
72 : annot(begin, begin+motif.size(), "motif", motif),
82 Sequence::Sequence(alphabet_ref alphabet_)
83 : seq(new SeqSpan("")),
93 Sequence::Sequence(const char *seq, alphabet_ref alphabet_)
94 : alphabet(alphabet_),
95 strand(UnknownStrand),
99 set_filtered_sequence(seq, alphabet);
102 Sequence::Sequence(const std::string& seq, alphabet_ref alphabet_)
103 : alphabet(alphabet_),
104 strand(UnknownStrand),
108 set_filtered_sequence(seq, alphabet);
111 Sequence::Sequence(const Sequence& o)
113 alphabet(o.alphabet),
118 motif_list(o.motif_list)
122 Sequence::Sequence(const Sequence* o)
124 alphabet(o->alphabet),
129 motif_list(o->motif_list)
133 Sequence::Sequence(const SeqSpanRef& seq_ref, alphabet_ref alphabet_)
136 strand(UnknownStrand),
142 Sequence &Sequence::operator=(const Sequence& s)
146 alphabet = s.alphabet;
151 motif_list = s.motif_list;
156 static void multiplatform_getline(std::istream& in, std::string& line)
161 while(in.good() and !(c == '\012' or c == '\015') ) {
165 // if we have cr-lf eat it
167 if (c=='\012' or c == '\015') {
172 void Sequence::load_fasta(fs::path file_path, int seq_num, int start_index, int end_index)
174 load_fasta(file_path, alphabet, seq_num, start_index, end_index);
177 //! load a fasta file into a sequence
178 void Sequence::load_fasta(fs::path file_path, alphabet_ref a,
179 int seq_num, int start_index, int end_index)
181 fs::fstream data_file;
182 data_file.open(file_path, std::ios::in);
184 if (!data_file.good())
186 throw mussa_load_error("Sequence File: "+file_path.string()+" not found");
189 load_fasta(data_file, a, seq_num, start_index, end_index);
190 } catch(sequence_empty_error e) {
191 // there doesn't appear to be any sequence
192 // catch and rethrow to include the filename
193 std::stringstream msg;
194 msg << "The selected sequence in "
195 << file_path.native_file_string()
196 << " appears to be empty";
197 throw sequence_empty_error(msg.str());
198 } catch(sequence_empty_file_error e) {
199 std::stringstream errormsg;
200 errormsg << file_path.native_file_string()
201 << " did not have any fasta sequences" << std::endl;
202 throw sequence_empty_file_error(errormsg.str());
203 } catch(sequence_invalid_load_error e) {
204 std::ostringstream msg;
205 msg << file_path.native_file_string();
206 msg << " " << e.what();
207 throw sequence_invalid_load_error(msg.str());
212 void Sequence::load_fasta(std::istream& file,
213 int seq_num, int start_index, int end_index)
215 load_fasta(file, alphabet, seq_num, start_index, end_index);
219 Sequence::load_fasta(std::istream& data_file, alphabet_ref a,
221 int start_index, int end_index)
223 std::string file_data_line;
224 int header_counter = 0;
225 size_t line_counter = 0;
226 bool read_seq = true;
227 std::string rev_comp;
228 std::string sequence_raw;
229 std::string seq_tmp; // holds sequence during basic filtering
230 const Alphabet &alpha = get_alphabet(a);
233 throw mussa_load_error("fasta sequence number is 1 based (can't be 0)");
236 // search for the header of the fasta sequence we want
237 while ( (!data_file.eof()) && (header_counter < seq_num) )
239 multiplatform_getline(data_file, file_data_line);
241 if (file_data_line.substr(0,1) == ">")
245 if (header_counter > 0) {
246 header = file_data_line.substr(1);
250 while ( !data_file.eof() && read_seq ) {
251 multiplatform_getline(data_file,file_data_line);
253 if (file_data_line.substr(0,1) == ">")
256 for (std::string::const_iterator line_i = file_data_line.begin();
257 line_i != file_data_line.end();
260 if(alpha.exists(*line_i)) {
261 sequence_raw += *line_i;
263 std::ostringstream msg;
264 msg << "Unrecognized characters in fasta sequence at line ";
266 throw sequence_invalid_load_error(msg.str());
272 // Lastly, if subselection of the sequence was specified we keep cut out
273 // and only keep that part
274 // end_index = 0 means no end was specified, so cut to the end
276 end_index = sequence_raw.size();
278 // sequence filtering for upcasing agctn and convert non AGCTN to N
279 if (end_index-start_index <= 0) {
280 std::string msg("The selected sequence appears to be empty");
281 throw sequence_empty_error(msg);
283 set_filtered_sequence(sequence_raw, a, start_index, end_index-start_index);
285 std::string errormsg("There were no fasta sequences");
286 throw sequence_empty_file_error(errormsg);
290 void Sequence::set_filtered_sequence(const std::string &in_seq,
291 alphabet_ref alphabet_,
296 alphabet = alphabet_;
298 count = in_seq.size() - start;
300 new_seq.reserve(count);
302 // finally, the actual conversion loop
303 const Alphabet& alpha_impl = get_alphabet(); // go get one of our actual alphabets
304 std::string::const_iterator seq_i = in_seq.begin()+start;
305 for(size_type i = 0; i != count; ++i, ++seq_i)
307 if (alpha_impl.exists(*seq_i)) {
308 new_seq.append(1, toupper(*seq_i));
310 new_seq.append(1, 'N');
313 SeqSpanRef new_seq_ref(new SeqSpan(new_seq));
319 Sequence::load_annot(fs::path file_path, int start_index, int end_index)
321 if (not fs::exists(file_path)) {
322 throw mussa_load_error("Annotation File " + file_path.string() + " was not found");
324 if (fs::is_directory(file_path)) {
325 throw mussa_load_error(file_path.string() +
326 " is a directory, please provide a file for annotations."
329 fs::fstream data_stream(file_path, std::ios::in);
332 throw mussa_load_error("Error loading annotation file " + file_path.string());
335 // so i should probably be passing the parse function some iterators
336 // but the annotations files are (currently) small, so i think i can
337 // get away with loading the whole file into memory
340 while(data_stream.good()) {
347 parse_annot(data, start_index, end_index);
348 } catch(annotation_load_error e) {
349 std::ostringstream msg;
350 msg << file_path.native_file_string()
353 throw annotation_load_error(msg.str());
357 /* If this works, yikes, this is some brain hurting code.
359 * what's going on is that when pb_annot is instantiated it stores references
360 * to begin, end, name, type, declared in the parse function, then
361 * when operator() is called it grabs values from those references
362 * and uses that to instantiate an annot object and append that to our
365 * This weirdness is because the spirit library requires that actions
366 * conform to a specific prototype operator()(IteratorT, IteratorT)
367 * which doesn't provide any useful opportunity for me to actually
368 * grab the results of our parsing.
370 * so I instantiate this structure in order to have a place to grab
374 struct push_back_annot {
375 std::list<annot>& annot_list;
382 push_back_annot(std::list<annot>& annot_list_,
388 : annot_list(annot_list_),
397 void operator()(std::string::const_iterator,
398 std::string::const_iterator) const
400 //std::cout << "adding annot: " << begin << "|" << end << "|" << name << "|" << type << std::endl;
401 annot_list.push_back(annot(begin, end, name, type));
406 struct push_back_seq {
407 std::list<Sequence>& seq_list;
412 push_back_seq(std::list<Sequence>& seq_list_,
416 : seq_list(seq_list_),
423 void operator()(std::string::const_iterator,
424 std::string::const_iterator) const
426 // filter out newlines from our sequence
428 for(std::string::const_iterator seq_i = seq.begin();
432 if (*seq_i != '\015' && *seq_i != '\012') new_seq += *seq_i;
434 //std::cout << "adding seq: " << name << " " << new_seq << std::endl;
437 s.set_fasta_header(name);
438 seq_list.push_back(s);
444 Sequence::parse_annot(std::string data, int start_index, int end_index)
451 std::list<annot> parsed_annots;
452 std::list<Sequence> query_seqs;
455 bool ok = spirit::parse(data.begin(), data.end(),
462 )[spirit::assign_a(species)] >>
466 ( // ignore html tags
467 *(spirit::space_p) >>
469 +(~spirit::ch_p('>')) >>
474 ( // parse an absolute location name
475 (spirit::uint_p[spirit::assign_a(start)] >>
477 spirit::uint_p[spirit::assign_a(end)] >>
482 )[spirit::assign_a(name)] >>
489 )[spirit::assign_a(type)]
491 // to understand how this group gets set
492 // read the comment above struct push_back_annot
493 )[push_back_annot(parsed_annots, start, end, type, name, parsed)]
495 ((spirit::ch_p('>')|spirit::str_p(">")) >>
496 (*(spirit::print_p))[spirit::assign_a(name)] >>
498 (+(spirit::chset<>(Alphabet::nucleic_cstr)))[spirit::assign_a(seq)]
499 )[push_back_seq(query_seqs, name, seq, parsed)]
506 std::stringstream msg;
507 msg << "Error parsing annotation #" << parsed;
508 throw annotation_load_error(msg.str());
510 // add newly parsed annotations to our sequence
511 std::copy(parsed_annots.begin(), parsed_annots.end(), std::back_inserter(annots));
512 // go seearch for query sequences
513 find_sequences(query_seqs.begin(), query_seqs.end());
516 void Sequence::add_annotation(const annot& a)
521 const std::list<annot>& Sequence::annotations() const
526 void Sequence::copy_children(Sequence &new_seq, size_type start, size_type count) const
528 new_seq.motif_list = motif_list;
529 new_seq.annots.clear();
531 for(std::list<annot>::const_iterator annot_i = annots.begin();
532 annot_i != annots.end();
535 size_type annot_begin= annot_i->begin;
536 size_type annot_end = annot_i->end;
538 if (annot_begin < start+count) {
539 if (annot_begin >= start) {
540 annot_begin -= start;
545 if (annot_end < start+count) {
551 annot new_annot(annot_begin, annot_end, annot_i->type, annot_i->name);
552 new_seq.annots.push_back(new_annot);
558 Sequence::subseq(size_type start, size_type count) const
565 Sequence new_seq = *this;
566 new_seq.seq = seq->subseq(start, count);
568 copy_children(new_seq, start, count);
573 std::string Sequence::create_reverse_map() const
575 std::string rc_map(256, '~');
576 // if we're rna, use U instead of T
577 // we might want to add an "is_rna" to sequence at somepoint
578 char TU = (alphabet == reduced_rna_alphabet) ? 'U' : 'T';
579 char tu = (alphabet == reduced_rna_alphabet) ? 'u' : 't';
580 rc_map['A'] = TU ; rc_map['a'] = tu ;
581 rc_map['T'] = 'A'; rc_map['t'] = 'a';
582 rc_map['U'] = 'A'; rc_map['u'] = 'a';
583 rc_map['G'] = 'C'; rc_map['g'] = 'c';
584 rc_map['C'] = 'G'; rc_map['c'] = 'g';
585 rc_map['M'] = 'K'; rc_map['m'] = 'k';
586 rc_map['R'] = 'Y'; rc_map['r'] = 'y';
587 rc_map['W'] = 'W'; rc_map['w'] = 'w';
588 rc_map['S'] = 'S'; rc_map['s'] = 's';
589 rc_map['Y'] = 'R'; rc_map['y'] = 'r';
590 rc_map['K'] = 'M'; rc_map['k'] = 'm';
591 rc_map['V'] = 'B'; rc_map['v'] = 'b';
592 rc_map['H'] = 'D'; rc_map['h'] = 'd';
593 rc_map['D'] = 'H'; rc_map['d'] = 'h';
594 rc_map['B'] = 'V'; rc_map['b'] = 'v';
595 rc_map['N'] = 'N'; rc_map['n'] = 'n';
596 rc_map['X'] = 'X'; rc_map['x'] = 'x';
600 rc_map['~'] = '~'; // not really needed, but perhaps it's clearer.
604 Sequence Sequence::rev_comp() const
606 std::string rev_comp;
607 rev_comp.reserve(length());
609 std::string rc_map = create_reverse_map();
611 // reverse and convert
612 Sequence::const_reverse_iterator seq_i;
613 Sequence::const_reverse_iterator seq_end = rend();
614 for(seq_i = rbegin();
618 rev_comp.append(1, rc_map[*seq_i]);
620 return Sequence(rev_comp, alphabet);
623 void Sequence::set_fasta_header(std::string header_)
628 void Sequence::set_species(const std::string& name)
633 std::string Sequence::get_species() const
640 Sequence::get_fasta_header() const
646 Sequence::get_name() const
648 if (header.size() > 0)
650 else if (species.size() > 0)
656 const Alphabet& Sequence::get_alphabet() const
658 return get_alphabet(alphabet);
661 const Alphabet& Sequence::get_alphabet(alphabet_ref alpha) const
664 case reduced_dna_alphabet:
665 return Alphabet::reduced_dna_alphabet();
666 case reduced_rna_alphabet:
667 return Alphabet::reduced_rna_alphabet();
668 case reduced_nucleic_alphabet:
669 return Alphabet::reduced_nucleic_alphabet();
670 case nucleic_alphabet:
671 return Alphabet::nucleic_alphabet();
672 case protein_alphabet:
673 return Alphabet::protein_alphabet();
675 throw std::runtime_error("unrecognized alphabet type");
680 void Sequence::set_sequence(const std::string& s, alphabet_ref a)
682 set_filtered_sequence(s, a);
685 std::string Sequence::get_sequence() const
687 return seq->sequence();
690 Sequence::const_reference Sequence::operator[](Sequence::size_type i) const
699 strand = UnknownStrand;
707 Sequence::save(fs::fstream &save_file)
710 std::list<annot>::iterator annots_i;
712 // not sure why, or if i'm doing something wrong, but can't seem to pass
713 // file pointers down to this method from the mussa control class
714 // so each call to save a sequence appends to the file started by mussa_class
715 //save_file.open(save_file_path.c_str(), std::ios::app);
717 save_file << "<Sequence>" << std::endl;
718 save_file << *this << std::endl;
719 save_file << "</Sequence>" << std::endl;
721 save_file << "<Annotations>" << std::endl;
722 save_file << species << std::endl;
723 for (annots_i = annots.begin(); annots_i != annots.end(); ++annots_i)
725 save_file << annots_i->begin << " " << annots_i->end << " " ;
726 save_file << annots_i->name << " " << annots_i->type << std::endl;
728 save_file << "</Annotations>" << std::endl;
733 Sequence::load_museq(fs::path load_file_path, int seq_num)
735 fs::fstream load_file;
736 std::string file_data_line;
739 std::string::size_type space_split_i;
740 std::string annot_value;
743 load_file.open(load_file_path, std::ios::in);
746 // search for the seq_num-th sequence
747 while ( (!load_file.eof()) && (seq_counter < seq_num) )
749 getline(load_file,file_data_line);
750 if (file_data_line == "<Sequence>")
753 getline(load_file, file_data_line);
754 // looks like the sequence is written as a single line
755 set_filtered_sequence(file_data_line, reduced_dna_alphabet);
756 getline(load_file, file_data_line);
757 getline(load_file, file_data_line);
758 if (file_data_line == "<Annotations>")
760 getline(load_file, file_data_line);
761 species = file_data_line;
762 while ( (!load_file.eof()) && (file_data_line != "</Annotations>") )
764 getline(load_file,file_data_line);
765 if ((file_data_line != "") && (file_data_line != "</Annotations>"))
767 // need to get 4 values...almost same code 4 times...
768 // get annot start index
769 space_split_i = file_data_line.find(" ");
770 annot_value = file_data_line.substr(0,space_split_i);
771 an_annot.begin = atoi (annot_value.c_str());
772 file_data_line = file_data_line.substr(space_split_i+1);
773 // get annot end index
774 space_split_i = file_data_line.find(" ");
775 annot_value = file_data_line.substr(0,space_split_i);
776 an_annot.end = atoi (annot_value.c_str());
778 if (space_split_i == std::string::npos) // no entry for type or name
780 std::cout << "seq, annots - no type or name\n";
784 else // else get annot type
786 file_data_line = file_data_line.substr(space_split_i+1);
787 space_split_i = file_data_line.find(" ");
788 annot_value = file_data_line.substr(0,space_split_i);
789 an_annot.type = annot_value;
790 if (space_split_i == std::string::npos) // no entry for name
792 std::cout << "seq, annots - no name\n";
795 else // get annot name
797 file_data_line = file_data_line.substr(space_split_i+1);
798 space_split_i = file_data_line.find(" ");
799 annot_value = file_data_line.substr(0,space_split_i);
800 an_annot.type = annot_value;
803 annots.push_back(an_annot); // don't forget to actually add the annot
805 //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
806 // << "-->" << an_annot.type << "::" << an_annot.name << std::endl;
813 void Sequence::add_motif(const Sequence& a_motif)
815 std::vector<int> motif_starts = find_motif(a_motif);
817 for(std::vector<int>::iterator motif_start_i = motif_starts.begin();
818 motif_start_i != motif_starts.end();
821 motif_list.push_back(motif(*motif_start_i, a_motif.get_sequence()));
825 void Sequence::clear_motifs()
830 const std::list<motif>& Sequence::motifs() const
836 Sequence::find_motif(const Sequence& a_motif) const
838 std::vector<int> motif_match_starts;
839 Sequence norm_motif_rc;
841 motif_match_starts.clear();
842 // std::cout << "motif is: " << norm_motif << std::endl;
844 if (a_motif.size() > 0)
846 //std::cout << "Sequence: none blank motif\n";
847 motif_scan(a_motif, &motif_match_starts);
849 norm_motif_rc = a_motif.rev_comp();;
850 // make sure not to do search again if it is a palindrome
851 if (norm_motif_rc != a_motif) {
852 motif_scan(norm_motif_rc, &motif_match_starts);
855 return motif_match_starts;
859 Sequence::motif_scan(const Sequence& a_motif, std::vector<int> * motif_match_starts) const
861 // if there's no sequence we can't scan for it?
862 // should this throw an exception?
865 std::string::size_type seq_i = 0;
866 Sequence::size_type motif_i = 0;
867 Sequence::size_type motif_len = a_motif.length();
868 Sequence::value_type motif_char;
869 Sequence::value_type seq_char;
871 while (seq_i < size())
873 // this is pretty much a straight translation of Nora's python code
874 // to match iupac letter codes
875 motif_char = toupper(a_motif[motif_i]);
876 seq_char = toupper(seq->at(seq_i));
877 if (motif_char =='N')
879 else if (motif_char == seq_char)
881 else if ((motif_char =='M') && ((seq_char=='A') || (seq_char=='C')))
883 else if ((motif_char =='R') && ((seq_char=='A') || (seq_char=='G')))
885 else if ((motif_char =='W') && ((seq_char=='A') || (seq_char=='T')))
887 else if ((motif_char =='S') && ((seq_char=='C') || (seq_char=='G')))
889 else if ((motif_char =='Y') && ((seq_char=='C') || (seq_char=='T')))
891 else if ((motif_char =='K') && ((seq_char=='G') || (seq_char=='T')))
893 else if ((motif_char =='V') &&
894 ((seq_char=='A') || (seq_char=='C') || (seq_char=='G')))
896 else if ((motif_char =='H') &&
897 ((seq_char=='A') || (seq_char=='C') || (seq_char=='T')))
899 else if ((motif_char =='D') &&
900 ((seq_char=='A') || (seq_char=='G') || (seq_char=='T')))
902 else if ((motif_char =='B') &&
903 ((seq_char=='C') || (seq_char=='G') || (seq_char=='T')))
907 // if a motif doesn't match, erase our current trial and try again
912 // end Nora stuff, now we see if a match is found this pass
913 if (motif_i == motif_len)
916 motif_match_starts->push_back(seq_i - motif_len + 1);
922 //std::cout << std::endl;
925 void Sequence::add_string_annotation(std::string a_seq,
928 std::vector<int> seq_starts = find_motif(a_seq);
930 //std::cout << "searching for " << a_seq << " found " << seq_starts.size() << std::endl;
932 for(std::vector<int>::iterator seq_start_i = seq_starts.begin();
933 seq_start_i != seq_starts.end();
936 annots.push_back(annot(*seq_start_i,
937 *seq_start_i+a_seq.size(),
943 void Sequence::find_sequences(std::list<Sequence>::iterator start,
944 std::list<Sequence>::iterator end)
946 while (start != end) {
947 add_string_annotation(start->get_sequence(), start->get_fasta_header());
953 std::ostream& operator<<(std::ostream& out, const Sequence& s)
956 for(Sequence::const_iterator s_i = s.begin(); s_i != s.end(); ++s_i) {
963 bool operator<(const Sequence& x, const Sequence& y)
965 Sequence::const_iterator x_i = x.begin();
966 Sequence::const_iterator y_i = y.begin();
967 // for sequences there's some computation associated with computing .end
969 Sequence::const_iterator xend = x.end();
970 Sequence::const_iterator yend = y.end();
972 if( x_i == xend and y_i == yend ) {
974 } else if ( x_i == xend ) {
976 } else if ( y_i == yend ) {
978 } else if ( (*x_i) < (*y_i)) {
980 } else if ( (*x_i) > (*y_i) ) {
989 template <typename Iter1, typename Iter2>
991 bool sequence_insensitive_equality(Iter1 abegin, Iter1 aend, Iter2 bbegin, Iter2 bend)
993 Iter1 aseq_i = abegin;
994 Iter2 bseq_i = bbegin;
995 if (aend-abegin == bend-bbegin) {
996 // since the length of the two sequences is equal, we only need to
998 for(; aseq_i != aend; ++aseq_i, ++bseq_i) {
999 if (toupper(*aseq_i) != toupper(*bseq_i)) {
1009 bool operator==(const Sequence& x, const Sequence& y)
1011 if (x.seq and y.seq) {
1012 // both x and y are defined
1013 if (SeqSpan::isFamily(x.seq, y.seq)) {
1014 // both are part of the same SeqSpan tree
1015 return *(x.seq) == *(y.seq);
1017 // we'll have to do a real comparison
1018 return sequence_insensitive_equality<SeqSpan::const_iterator, SeqSpan::const_iterator>(
1024 // true if they're both empty (with either a null SeqSpanRef or
1025 // a zero length string
1026 return (x.size() == y.size());
1030 bool operator!=(const Sequence& x, const Sequence& y)
1032 return not operator==(x, y);