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(AlphabetRef alphabet)
83 : seq(new SeqSpan("", alphabet, SeqSpan::PlusStrand))
91 Sequence::Sequence(const char *seq, AlphabetRef alphabet_, SeqSpan::strand_type strand_)
95 set_filtered_sequence(seq, alphabet_, 0, npos, strand_);
98 Sequence::Sequence(const std::string& seq,
99 AlphabetRef alphabet_,
100 SeqSpan::strand_type strand_)
104 set_filtered_sequence(seq, alphabet_, 0, seq.size(), strand_);
107 Sequence::Sequence(const Sequence& o)
112 motif_list(o.motif_list)
116 Sequence::Sequence(const Sequence* o)
121 motif_list(o->motif_list)
125 Sequence::Sequence(const SequenceRef o)
126 : seq(new SeqSpan(o->seq)),
130 motif_list(o->motif_list)
134 Sequence::Sequence(const SeqSpanRef& seq_ref)
141 Sequence &Sequence::operator=(const Sequence& s)
148 motif_list = s.motif_list;
153 static void multiplatform_getline(std::istream& in, std::string& line)
158 while(in.good() and !(c == '\012' or c == '\015') ) {
162 // if we have cr-lf eat it
164 if (c=='\012' or c == '\015') {
169 void Sequence::load_fasta(fs::path file_path, int seq_num, int start_index, int end_index)
171 load_fasta(file_path, reduced_nucleic_alphabet, seq_num, start_index, end_index);
174 //! load a fasta file into a sequence
175 void Sequence::load_fasta(fs::path file_path, AlphabetRef a,
176 int seq_num, int start_index, int end_index)
178 fs::fstream data_file;
179 data_file.open(file_path, std::ios::in);
181 if (!data_file.good())
183 throw mussa_load_error("Sequence File: "+file_path.string()+" not found");
186 load_fasta(data_file, a, seq_num, start_index, end_index);
187 } catch(sequence_empty_error e) {
188 // there doesn't appear to be any sequence
189 // catch and rethrow to include the filename
190 std::stringstream msg;
191 msg << "The selected sequence in "
192 << file_path.native_file_string()
193 << " appears to be empty";
194 throw sequence_empty_error(msg.str());
195 } catch(sequence_empty_file_error e) {
196 std::stringstream errormsg;
197 errormsg << file_path.native_file_string()
198 << " did not have any fasta sequences" << std::endl;
199 throw sequence_empty_file_error(errormsg.str());
200 } catch(sequence_invalid_load_error e) {
201 std::ostringstream msg;
202 msg << file_path.native_file_string();
203 msg << " " << e.what();
204 throw sequence_invalid_load_error(msg.str());
209 void Sequence::load_fasta(std::istream& file,
210 int seq_num, int start_index, int end_index)
212 load_fasta(file, reduced_nucleic_alphabet, seq_num, start_index, end_index);
216 Sequence::load_fasta(std::istream& data_file, AlphabetRef a,
218 int start_index, int end_index)
220 std::string file_data_line;
221 int header_counter = 0;
222 size_t line_counter = 0;
223 bool read_seq = true;
224 std::string rev_comp;
225 std::string sequence_raw;
226 std::string seq_tmp; // holds sequence during basic filtering
227 const Alphabet &alpha = Alphabet::get_alphabet(a);
230 throw mussa_load_error("fasta sequence number is 1 based (can't be 0)");
233 // search for the header of the fasta sequence we want
234 while ( (!data_file.eof()) && (header_counter < seq_num) )
236 multiplatform_getline(data_file, file_data_line);
238 if (file_data_line.substr(0,1) == ">")
242 if (header_counter > 0) {
243 header = file_data_line.substr(1);
247 while ( !data_file.eof() && read_seq ) {
248 multiplatform_getline(data_file,file_data_line);
250 if (file_data_line.substr(0,1) == ">")
253 for (std::string::const_iterator line_i = file_data_line.begin();
254 line_i != file_data_line.end();
257 if(alpha.exists(*line_i)) {
258 sequence_raw += *line_i;
260 std::ostringstream msg;
261 msg << "Unrecognized characters in fasta sequence at line ";
263 throw sequence_invalid_load_error(msg.str());
269 // Lastly, if subselection of the sequence was specified we keep cut out
270 // and only keep that part
271 // end_index = 0 means no end was specified, so cut to the end
273 end_index = sequence_raw.size();
275 // sequence filtering for upcasing agctn and convert non AGCTN to N
276 if (end_index-start_index <= 0) {
277 std::string msg("The selected sequence appears to be empty");
278 throw sequence_empty_error(msg);
280 set_filtered_sequence(sequence_raw, a, start_index, end_index-start_index, SeqSpan::PlusStrand);
282 std::string errormsg("There were no fasta sequences");
283 throw sequence_empty_file_error(errormsg);
287 void Sequence::set_filtered_sequence(const std::string &in_seq,
288 AlphabetRef alphabet_,
291 SeqSpan::strand_type strand_)
294 count = in_seq.size() - start;
296 new_seq.reserve(count);
298 // finally, the actual conversion loop
299 const Alphabet& alpha_impl = Alphabet::get_alphabet(alphabet_); // go get one of our actual alphabets
300 std::string::const_iterator seq_i = in_seq.begin()+start;
301 for(size_type i = 0; i != count; ++i, ++seq_i)
303 if (alpha_impl.exists(*seq_i)) {
304 new_seq.append(1, toupper(*seq_i));
306 new_seq.append(1, 'N');
309 SeqSpanRef new_seq_ref(new SeqSpan(new_seq, alphabet_, strand_));
314 Sequence::load_annot(fs::path file_path, int start_index, int end_index)
316 if (not fs::exists(file_path)) {
317 throw mussa_load_error("Annotation File " + file_path.string() + " was not found");
319 if (fs::is_directory(file_path)) {
320 throw mussa_load_error(file_path.string() +
321 " is a directory, please provide a file for annotations."
324 fs::fstream data_stream(file_path, std::ios::in);
327 throw mussa_load_error("Error loading annotation file " + file_path.string());
330 // so i should probably be passing the parse function some iterators
331 // but the annotations files are (currently) small, so i think i can
332 // get away with loading the whole file into memory
335 while(data_stream.good()) {
342 parse_annot(data, start_index, end_index);
343 } catch(annotation_load_error e) {
344 std::ostringstream msg;
345 msg << file_path.native_file_string()
348 throw annotation_load_error(msg.str());
352 /* If this works, yikes, this is some brain hurting code.
354 * what's going on is that when pb_annot is instantiated it stores references
355 * to begin, end, name, type, declared in the parse function, then
356 * when operator() is called it grabs values from those references
357 * and uses that to instantiate an annot object and append that to our
360 * This weirdness is because the spirit library requires that actions
361 * conform to a specific prototype operator()(IteratorT, IteratorT)
362 * which doesn't provide any useful opportunity for me to actually
363 * grab the results of our parsing.
365 * so I instantiate this structure in order to have a place to grab
369 struct push_back_annot {
370 std::list<annot>& annot_list;
377 push_back_annot(std::list<annot>& annot_list_,
383 : annot_list(annot_list_),
392 void operator()(std::string::const_iterator,
393 std::string::const_iterator) const
395 //std::cout << "adding annot: " << begin << "|" << end << "|" << name << "|" << type << std::endl;
396 annot_list.push_back(annot(begin, end, name, type));
401 struct push_back_seq {
402 std::list<Sequence>& seq_list;
407 push_back_seq(std::list<Sequence>& seq_list_,
411 : seq_list(seq_list_),
418 void operator()(std::string::const_iterator,
419 std::string::const_iterator) const
421 // filter out newlines from our sequence
423 for(std::string::const_iterator seq_i = seq.begin();
427 if (*seq_i != '\015' && *seq_i != '\012') new_seq += *seq_i;
429 //std::cout << "adding seq: " << name << " " << new_seq << std::endl;
432 s.set_fasta_header(name);
433 seq_list.push_back(s);
439 Sequence::parse_annot(std::string data, int start_index, int end_index)
446 std::list<annot> parsed_annots;
447 std::list<Sequence> query_seqs;
450 bool ok = spirit::parse(data.begin(), data.end(),
457 )[spirit::assign_a(species)] >>
461 ( // ignore html tags
462 *(spirit::space_p) >>
464 +(~spirit::ch_p('>')) >>
469 ( // parse an absolute location name
470 (spirit::uint_p[spirit::assign_a(start)] >>
472 spirit::uint_p[spirit::assign_a(end)] >>
477 )[spirit::assign_a(name)] >>
484 )[spirit::assign_a(type)]
486 // to understand how this group gets set
487 // read the comment above struct push_back_annot
488 )[push_back_annot(parsed_annots, start, end, type, name, parsed)]
490 ((spirit::ch_p('>')|spirit::str_p(">")) >>
491 (*(spirit::print_p))[spirit::assign_a(name)] >>
493 (+(spirit::chset<>(Alphabet::nucleic_cstr)))[spirit::assign_a(seq)]
494 )[push_back_seq(query_seqs, name, seq, parsed)]
501 std::stringstream msg;
502 msg << "Error parsing annotation #" << parsed;
503 throw annotation_load_error(msg.str());
505 // add newly parsed annotations to our sequence
506 std::copy(parsed_annots.begin(), parsed_annots.end(), std::back_inserter(annots));
507 // go seearch for query sequences
508 find_sequences(query_seqs.begin(), query_seqs.end());
511 void Sequence::add_annotation(const annot& a)
516 const std::list<annot>& Sequence::annotations() const
521 void Sequence::copy_children(Sequence &new_seq, size_type start, size_type count) const
523 new_seq.motif_list = motif_list;
524 new_seq.annots.clear();
526 for(std::list<annot>::const_iterator annot_i = annots.begin();
527 annot_i != annots.end();
530 size_type annot_begin= annot_i->begin;
531 size_type annot_end = annot_i->end;
533 if (annot_begin < start+count) {
534 if (annot_begin >= start) {
535 annot_begin -= start;
540 if (annot_end < start+count) {
546 annot new_annot(annot_begin, annot_end, annot_i->type, annot_i->name);
547 new_seq.annots.push_back(new_annot);
553 Sequence::subseq(size_type start, size_type count, SeqSpan::strand_type strand) const
555 // FIXME: should i really allow a subsequence of an empty sequence?
561 Sequence new_seq = *this;
562 new_seq.seq = seq->subseq(start, count, strand);
563 if (seq->annotations()) {
564 AnnotationsRef a(new Annotations(*(seq->annotations())));
565 new_seq.seq->setAnnotations(a);
567 copy_children(new_seq, start, count);
573 // FIXME: This needs to be moved into SeqSpan
574 Sequence Sequence::rev_comp() const
576 // a reverse complement is the whole opposite strand
577 return subseq(0, npos, SeqSpan::OppositeStrand);
580 const Alphabet& Sequence::get_alphabet() const
582 return (seq) ? seq->get_alphabet() : Alphabet::empty_alphabet();
585 void Sequence::set_fasta_header(std::string header_)
590 void Sequence::set_species(const std::string& name)
595 std::string Sequence::get_species() const
602 Sequence::get_fasta_header() const
608 Sequence::get_name() const
610 if (header.size() > 0)
612 else if (species.size() > 0)
618 void Sequence::set_sequence(const std::string& s, AlphabetRef a)
620 set_filtered_sequence(s, a, 0, s.size(), SeqSpan::PlusStrand);
623 std::string Sequence::get_sequence() const
625 return seq->sequence();
628 Sequence::const_reference Sequence::operator[](Sequence::size_type i) const
644 Sequence::save(fs::fstream &save_file)
647 std::list<annot>::iterator annots_i;
649 // not sure why, or if i'm doing something wrong, but can't seem to pass
650 // file pointers down to this method from the mussa control class
651 // so each call to save a sequence appends to the file started by mussa_class
652 //save_file.open(save_file_path.c_str(), std::ios::app);
654 save_file << "<Sequence>" << std::endl;
655 save_file << *this << std::endl;
656 save_file << "</Sequence>" << std::endl;
658 save_file << "<Annotations>" << std::endl;
659 save_file << species << std::endl;
660 for (annots_i = annots.begin(); annots_i != annots.end(); ++annots_i)
662 save_file << annots_i->begin << " " << annots_i->end << " " ;
663 save_file << annots_i->name << " " << annots_i->type << std::endl;
665 save_file << "</Annotations>" << std::endl;
670 Sequence::load_museq(fs::path load_file_path, int seq_num)
672 fs::fstream load_file;
673 std::string file_data_line;
676 std::string::size_type space_split_i;
677 std::string annot_value;
680 load_file.open(load_file_path, std::ios::in);
683 // search for the seq_num-th sequence
684 while ( (!load_file.eof()) && (seq_counter < seq_num) )
686 getline(load_file,file_data_line);
687 if (file_data_line == "<Sequence>")
690 getline(load_file, file_data_line);
691 // looks like the sequence is written as a single line
692 set_filtered_sequence(file_data_line, reduced_dna_alphabet, 0, file_data_line.size(), SeqSpan::PlusStrand);
693 getline(load_file, file_data_line);
694 getline(load_file, file_data_line);
695 if (file_data_line == "<Annotations>")
697 getline(load_file, file_data_line);
698 species = file_data_line;
699 while ( (!load_file.eof()) && (file_data_line != "</Annotations>") )
701 getline(load_file,file_data_line);
702 if ((file_data_line != "") && (file_data_line != "</Annotations>"))
704 // need to get 4 values...almost same code 4 times...
705 // get annot start index
706 space_split_i = file_data_line.find(" ");
707 annot_value = file_data_line.substr(0,space_split_i);
708 an_annot.begin = atoi (annot_value.c_str());
709 file_data_line = file_data_line.substr(space_split_i+1);
710 // get annot end index
711 space_split_i = file_data_line.find(" ");
712 annot_value = file_data_line.substr(0,space_split_i);
713 an_annot.end = atoi (annot_value.c_str());
715 if (space_split_i == std::string::npos) // no entry for type or name
717 std::cout << "seq, annots - no type or name\n";
721 else // else get annot type
723 file_data_line = file_data_line.substr(space_split_i+1);
724 space_split_i = file_data_line.find(" ");
725 annot_value = file_data_line.substr(0,space_split_i);
726 an_annot.type = annot_value;
727 if (space_split_i == std::string::npos) // no entry for name
729 std::cout << "seq, annots - no name\n";
732 else // get annot name
734 file_data_line = file_data_line.substr(space_split_i+1);
735 space_split_i = file_data_line.find(" ");
736 annot_value = file_data_line.substr(0,space_split_i);
737 an_annot.type = annot_value;
740 annots.push_back(an_annot); // don't forget to actually add the annot
742 //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
743 // << "-->" << an_annot.type << "::" << an_annot.name << std::endl;
750 void Sequence::add_motif(const Sequence& a_motif)
752 std::vector<int> motif_starts = find_motif(a_motif);
754 for(std::vector<int>::iterator motif_start_i = motif_starts.begin();
755 motif_start_i != motif_starts.end();
758 motif_list.push_back(motif(*motif_start_i, a_motif.get_sequence()));
762 void Sequence::clear_motifs()
767 const std::list<motif>& Sequence::motifs() const
773 Sequence::find_motif(const Sequence& a_motif) const
775 std::vector<int> motif_match_starts;
776 Sequence norm_motif_rc;
778 motif_match_starts.clear();
779 // std::cout << "motif is: " << norm_motif << std::endl;
781 if (a_motif.size() > 0)
783 //std::cout << "Sequence: none blank motif\n";
784 motif_scan(a_motif, &motif_match_starts);
786 norm_motif_rc = a_motif.rev_comp();;
787 // make sure not to do search again if it is a palindrome
788 if (norm_motif_rc != a_motif) {
789 motif_scan(norm_motif_rc, &motif_match_starts);
792 return motif_match_starts;
796 Sequence::motif_scan(const Sequence& a_motif, std::vector<int> * motif_match_starts) const
798 // if there's no sequence we can't scan for it?
799 // should this throw an exception?
802 std::string::size_type seq_i = 0;
803 Sequence::size_type motif_i = 0;
804 Sequence::size_type motif_len = a_motif.length();
805 Sequence::value_type motif_char;
806 Sequence::value_type seq_char;
808 while (seq_i < size())
810 // this is pretty much a straight translation of Nora's python code
811 // to match iupac letter codes
812 motif_char = toupper(a_motif[motif_i]);
813 seq_char = toupper(seq->at(seq_i));
814 if (motif_char =='N')
816 else if (motif_char == seq_char)
818 else if ((motif_char =='M') && ((seq_char=='A') || (seq_char=='C')))
820 else if ((motif_char =='R') && ((seq_char=='A') || (seq_char=='G')))
822 else if ((motif_char =='W') && ((seq_char=='A') || (seq_char=='T')))
824 else if ((motif_char =='S') && ((seq_char=='C') || (seq_char=='G')))
826 else if ((motif_char =='Y') && ((seq_char=='C') || (seq_char=='T')))
828 else if ((motif_char =='K') && ((seq_char=='G') || (seq_char=='T')))
830 else if ((motif_char =='V') &&
831 ((seq_char=='A') || (seq_char=='C') || (seq_char=='G')))
833 else if ((motif_char =='H') &&
834 ((seq_char=='A') || (seq_char=='C') || (seq_char=='T')))
836 else if ((motif_char =='D') &&
837 ((seq_char=='A') || (seq_char=='G') || (seq_char=='T')))
839 else if ((motif_char =='B') &&
840 ((seq_char=='C') || (seq_char=='G') || (seq_char=='T')))
844 // if a motif doesn't match, erase our current trial and try again
849 // end Nora stuff, now we see if a match is found this pass
850 if (motif_i == motif_len)
853 motif_match_starts->push_back(seq_i - motif_len + 1);
859 //std::cout << std::endl;
862 void Sequence::add_string_annotation(std::string a_seq,
865 std::vector<int> seq_starts = find_motif(a_seq);
867 //std::cout << "searching for " << a_seq << " found " << seq_starts.size() << std::endl;
869 for(std::vector<int>::iterator seq_start_i = seq_starts.begin();
870 seq_start_i != seq_starts.end();
873 annots.push_back(annot(*seq_start_i,
874 *seq_start_i+a_seq.size(),
880 void Sequence::find_sequences(std::list<Sequence>::iterator start,
881 std::list<Sequence>::iterator end)
883 while (start != end) {
884 add_string_annotation(start->get_sequence(), start->get_fasta_header());
890 std::ostream& operator<<(std::ostream& out, const Sequence& s)
893 for(Sequence::const_iterator s_i = s.begin(); s_i != s.end(); ++s_i) {
900 bool operator<(const Sequence& x, const Sequence& y)
902 Sequence::const_iterator x_i = x.begin();
903 Sequence::const_iterator y_i = y.begin();
904 // for sequences there's some computation associated with computing .end
906 Sequence::const_iterator xend = x.end();
907 Sequence::const_iterator yend = y.end();
909 if( x_i == xend and y_i == yend ) {
911 } else if ( x_i == xend ) {
913 } else if ( y_i == yend ) {
915 } else if ( (*x_i) < (*y_i)) {
917 } else if ( (*x_i) > (*y_i) ) {
926 template <typename Iter1, typename Iter2>
928 bool sequence_insensitive_equality(Iter1 abegin, Iter1 aend, Iter2 bbegin, Iter2 bend)
930 Iter1 aseq_i = abegin;
931 Iter2 bseq_i = bbegin;
932 if (aend-abegin == bend-bbegin) {
933 // since the length of the two sequences is equal, we only need to
935 for(; aseq_i != aend; ++aseq_i, ++bseq_i) {
936 if (toupper(*aseq_i) != toupper(*bseq_i)) {
946 bool operator==(const Sequence& x, const Sequence& y)
948 if (x.seq and y.seq) {
949 // both x and y are defined
950 if (SeqSpan::isFamily(x.seq, y.seq)) {
951 // both are part of the same SeqSpan tree
952 return *(x.seq) == *(y.seq);
954 // we'll have to do a real comparison
955 return sequence_insensitive_equality<SeqSpan::const_iterator, SeqSpan::const_iterator>(
961 // true if they're both empty (with either a null SeqSpanRef or
962 // a zero length string
963 return (x.size() == y.size());
967 bool operator!=(const Sequence& x, const Sequence& y)
969 return not operator==(x, y);