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"
43 bool operator==(const motif& left, const motif& right)
45 return ((left.begin== right.begin) and
46 (left.end == right.end) and
47 (left.type == right.type) and
48 (left.name == right.name));
60 motif::motif(int begin_, std::string motif)
62 end(begin_+motif.size()),
73 Sequence::Sequence(AlphabetRef alphabet)
74 : seq(new SeqSpan("", alphabet, SeqSpan::PlusStrand)),
75 annotation_list(new SeqSpanRefList),
76 motif_list(new MotifList)
84 Sequence::Sequence(const char *seq, AlphabetRef alphabet_, SeqSpan::strand_type strand_)
87 annotation_list(new SeqSpanRefList),
88 motif_list(new MotifList)
90 set_filtered_sequence(seq, alphabet_, 0, npos, strand_);
93 Sequence::Sequence(const std::string& seq,
94 AlphabetRef alphabet_,
95 SeqSpan::strand_type strand_)
98 annotation_list(new SeqSpanRefList),
99 motif_list(new MotifList)
101 set_filtered_sequence(seq, alphabet_, 0, seq.size(), strand_);
104 Sequence::Sequence(const Sequence& o)
108 annotation_list(o.annotation_list),
109 motif_list(o.motif_list)
113 Sequence::Sequence(const Sequence* o)
117 annotation_list(o->annotation_list),
118 motif_list(o->motif_list)
122 Sequence::Sequence(const SequenceRef o)
123 : seq(new SeqSpan(o->seq)),
126 annotation_list(new SeqSpanRefList),
127 motif_list(o->motif_list)
129 // copy over the annotations in the other sequence ref,
130 // attaching them to our current sequence ref
131 for(SeqSpanRefList::const_iterator annot_i = o->annotation_list->begin();
132 annot_i != o->annotation_list->end();
135 size_type annot_begin= (*annot_i)->start();
136 size_type annot_count = (*annot_i)->size();
138 SeqSpanRef new_annot(seq->subseq(annot_begin, annot_count));
139 new_annot->setAnnotations((*annot_i)->annotations());
140 annotation_list->push_back(new_annot);
144 Sequence::Sequence(const SeqSpanRef& seq_ref)
148 annotation_list(new SeqSpanRefList),
149 motif_list(new MotifList)
153 Sequence &Sequence::operator=(const Sequence& s)
159 annotation_list = s.annotation_list;
160 motif_list = s.motif_list;
165 static void multiplatform_getline(std::istream& in, std::string& line)
170 while(in.good() and !(c == '\012' or c == '\015') ) {
174 // if we have cr-lf eat it
176 if (c=='\012' or c == '\015') {
181 void Sequence::load_fasta(fs::path file_path, int seq_num, int start_index, int end_index)
183 load_fasta(file_path, reduced_nucleic_alphabet, seq_num, start_index, end_index);
186 //! load a fasta file into a sequence
187 void Sequence::load_fasta(fs::path file_path, AlphabetRef a,
188 int seq_num, int start_index, int end_index)
190 fs::fstream data_file;
191 data_file.open(file_path, std::ios::in);
193 if (!data_file.good())
195 throw mussa_load_error("Sequence File: "+file_path.string()+" not found");
198 load_fasta(data_file, a, seq_num, start_index, end_index);
199 } catch(sequence_empty_error e) {
200 // there doesn't appear to be any sequence
201 // catch and rethrow to include the filename
202 std::stringstream msg;
203 msg << "The selected sequence in "
204 << file_path.native_file_string()
205 << " appears to be empty";
206 throw sequence_empty_error(msg.str());
207 } catch(sequence_empty_file_error e) {
208 std::stringstream errormsg;
209 errormsg << file_path.native_file_string()
210 << " did not have any fasta sequences" << std::endl;
211 throw sequence_empty_file_error(errormsg.str());
212 } catch(sequence_invalid_load_error e) {
213 std::ostringstream msg;
214 msg << file_path.native_file_string();
215 msg << " " << e.what();
216 throw sequence_invalid_load_error(msg.str());
221 void Sequence::load_fasta(std::istream& file,
222 int seq_num, int start_index, int end_index)
224 load_fasta(file, reduced_nucleic_alphabet, seq_num, start_index, end_index);
228 Sequence::load_fasta(std::istream& data_file, AlphabetRef a,
230 int start_index, int end_index)
232 std::string file_data_line;
233 int header_counter = 0;
234 size_t line_counter = 0;
235 bool read_seq = true;
236 std::string rev_comp;
237 std::string sequence_raw;
238 std::string seq_tmp; // holds sequence during basic filtering
239 const Alphabet &alpha = Alphabet::get_alphabet(a);
242 throw mussa_load_error("fasta sequence number is 1 based (can't be 0)");
245 // search for the header of the fasta sequence we want
246 while ( (!data_file.eof()) && (header_counter < seq_num) )
248 multiplatform_getline(data_file, file_data_line);
250 if (file_data_line.substr(0,1) == ">")
254 if (header_counter > 0) {
255 header = file_data_line.substr(1);
259 while ( !data_file.eof() && read_seq ) {
260 multiplatform_getline(data_file,file_data_line);
262 if (file_data_line.substr(0,1) == ">")
265 for (std::string::const_iterator line_i = file_data_line.begin();
266 line_i != file_data_line.end();
269 if(alpha.exists(*line_i)) {
270 sequence_raw += *line_i;
272 std::ostringstream msg;
273 msg << "Unrecognized characters in fasta sequence at line ";
275 throw sequence_invalid_load_error(msg.str());
281 // Lastly, if subselection of the sequence was specified we keep cut out
282 // and only keep that part
283 // end_index = 0 means no end was specified, so cut to the end
285 end_index = sequence_raw.size();
287 // sequence filtering for upcasing agctn and convert non AGCTN to N
288 if (end_index-start_index <= 0) {
289 std::string msg("The selected sequence appears to be empty");
290 throw sequence_empty_error(msg);
292 set_filtered_sequence(sequence_raw, a, start_index, end_index-start_index, SeqSpan::PlusStrand);
294 std::string errormsg("There were no fasta sequences");
295 throw sequence_empty_file_error(errormsg);
299 void Sequence::set_filtered_sequence(const std::string &in_seq,
300 AlphabetRef alphabet_,
303 SeqSpan::strand_type strand_)
306 count = in_seq.size() - start;
308 new_seq.reserve(count);
310 // finally, the actual conversion loop
311 const Alphabet& alpha_impl = Alphabet::get_alphabet(alphabet_); // go get one of our actual alphabets
312 std::string::const_iterator seq_i = in_seq.begin()+start;
313 for(size_type i = 0; i != count; ++i, ++seq_i)
315 if (alpha_impl.exists(*seq_i)) {
316 new_seq.append(1, toupper(*seq_i));
318 new_seq.append(1, 'N');
321 SeqSpanRef new_seq_ref(new SeqSpan(new_seq, alphabet_, strand_));
326 Sequence::load_annot(fs::path file_path, int start_index, int end_index)
328 if (not fs::exists(file_path)) {
329 throw mussa_load_error("Annotation File " + file_path.string() + " was not found");
331 if (fs::is_directory(file_path)) {
332 throw mussa_load_error(file_path.string() +
333 " is a directory, please provide a file for annotations."
336 fs::fstream data_stream(file_path, std::ios::in);
339 throw mussa_load_error("Error loading annotation file " + file_path.string());
342 // so i should probably be passing the parse function some iterators
343 // but the annotations files are (currently) small, so i think i can
344 // get away with loading the whole file into memory
347 while(data_stream.good()) {
354 parse_annot(data, start_index, end_index);
355 } catch(annotation_load_error e) {
356 std::ostringstream msg;
357 msg << file_path.native_file_string()
360 throw annotation_load_error(msg.str());
364 /* If this works, yikes, this is some brain hurting code.
366 * what's going on is that when pb_annot is instantiated it stores references
367 * to begin, end, name, type, declared in the parse function, then
368 * when operator() is called it grabs values from those references
369 * and uses that to instantiate an annot object and append that to our
372 * This weirdness is because the spirit library requires that actions
373 * conform to a specific prototype operator()(IteratorT, IteratorT)
374 * which doesn't provide any useful opportunity for me to actually
375 * grab the results of our parsing.
377 * so I instantiate this structure in order to have a place to grab
381 struct push_back_annot {
383 SeqSpanRefListRef children;
390 push_back_annot(Sequence* parent_seq,
391 SeqSpanRefListRef children_list,
397 : parent(parent_seq),
398 children(children_list),
407 void operator()(std::string::const_iterator,
408 std::string::const_iterator) const
410 children->push_back(parent->make_annotation(name, type, begin, end));
415 struct push_back_seq {
416 std::list<Sequence>& seq_list;
421 push_back_seq(std::list<Sequence>& seq_list_,
425 : seq_list(seq_list_),
432 void operator()(std::string::const_iterator,
433 std::string::const_iterator) const
435 // filter out newlines from our sequence
437 for(std::string::const_iterator seq_i = seq.begin();
441 if (*seq_i != '\015' && *seq_i != '\012') new_seq += *seq_i;
443 //std::cout << "adding seq: " << name << " " << new_seq << std::endl;
446 s.set_fasta_header(name);
447 seq_list.push_back(s);
453 Sequence::parse_annot(std::string data, int start_index, int end_index)
460 SeqSpanRefListRef parsed_annots(new SeqSpanRefList);
461 std::list<Sequence> query_seqs;
464 bool ok = spirit::parse(data.begin(), data.end(),
471 )[spirit::assign_a(species)] >>
475 ( // ignore html tags
476 *(spirit::space_p) >>
478 +(~spirit::ch_p('>')) >>
483 ( // parse an absolute location name
484 (spirit::uint_p[spirit::assign_a(start)] >>
486 spirit::uint_p[spirit::assign_a(end)] >>
491 )[spirit::assign_a(name)] >>
498 )[spirit::assign_a(type)]
500 // to understand how this group gets set
501 // read the comment above struct push_back_annot
502 )[push_back_annot(this, parsed_annots, start, end, name, type, parsed)]
504 ((spirit::ch_p('>')|spirit::str_p(">")) >>
505 (*(spirit::print_p))[spirit::assign_a(name)] >>
507 (+(spirit::chset<>(Alphabet::nucleic_cstr)))[spirit::assign_a(seqstr)]
508 )[push_back_seq(query_seqs, name, seqstr, parsed)]
515 std::stringstream msg;
516 msg << "Error parsing annotation #" << parsed;
517 throw annotation_load_error(msg.str());
519 // If everything loaded correctly add the sequences to our annotation list
520 // add newly parsed annotations to our sequence
521 std::copy(parsed_annots->begin(), parsed_annots->end(), std::back_inserter(*annotation_list));
522 // go search for query sequences
523 find_sequences(query_seqs.begin(), query_seqs.end());
526 void Sequence::add_annotation(const SeqSpanRef a)
528 annotation_list->push_back(a);
531 void Sequence::add_annotation(std::string name, std::string type, size_type start, size_type stop)
533 add_annotation(make_annotation(name, type, start, stop));
537 Sequence::make_annotation(std::string name, std::string type, size_type start, size_type stop) const
539 // we want things to be in the positive direction
541 size_type tmp = start;
545 size_type count = stop - start;
546 SeqSpanRef new_annot(seq->subseq(start, count, SeqSpan::UnknownStrand));
547 AnnotationsRef metadata(new Annotations(name));
548 metadata->set("type", type);
549 new_annot->setAnnotations(metadata);
553 const SeqSpanRefList& Sequence::annotations() const
555 return *annotation_list;
558 void Sequence::copy_children(Sequence &new_seq, size_type start, size_type count) const
560 new_seq.motif_list = motif_list;
561 new_seq.annotation_list.reset(new SeqSpanRefList);
563 for(SeqSpanRefList::const_iterator annot_i = annotation_list->begin();
564 annot_i != annotation_list->end();
567 size_type annot_begin= (*annot_i)->start();
568 size_type annot_end = (*annot_i)->stop();
570 if (annot_begin < start+count) {
571 if (annot_begin >= start) {
572 annot_begin -= start;
577 if (annot_end < start+count) {
582 SeqSpanRef new_annot(new_seq.seq->subseq(annot_begin, annot_end));
583 new_annot->setAnnotations((*annot_i)->annotations());
584 new_seq.annotation_list->push_back(new_annot);
590 Sequence::subseq(size_type start, size_type count, SeqSpan::strand_type strand) const
592 // FIXME: should i really allow a subsequence of an empty sequence?
598 Sequence new_seq(*this);
599 new_seq.seq = seq->subseq(start, count, strand);
600 if (seq->annotations()) {
601 AnnotationsRef a(new Annotations(*(seq->annotations())));
602 new_seq.seq->setAnnotations(a);
604 copy_children(new_seq, start, count);
610 // FIXME: This needs to be moved into SeqSpan
611 Sequence Sequence::rev_comp() const
613 // a reverse complement is the whole opposite strand
614 return subseq(0, npos, SeqSpan::OppositeStrand);
617 const Alphabet& Sequence::get_alphabet() const
619 return (seq) ? seq->get_alphabet() : Alphabet::empty_alphabet();
622 void Sequence::set_fasta_header(std::string header_)
627 void Sequence::set_species(const std::string& name)
632 std::string Sequence::get_species() const
639 Sequence::get_fasta_header() const
645 Sequence::get_name() const
647 if (header.size() > 0)
649 else if (species.size() > 0)
655 void Sequence::set_sequence(const std::string& s, AlphabetRef a)
657 set_filtered_sequence(s, a, 0, s.size(), SeqSpan::PlusStrand);
660 std::string Sequence::get_sequence() const
662 return seq->sequence();
665 Sequence::const_reference Sequence::operator[](Sequence::size_type i) const
676 annotation_list.reset(new SeqSpanRefList);
677 motif_list.reset(new MotifList);
681 Sequence::save(fs::fstream &save_file)
683 std::string type("type");
684 std::string empty_str("");
686 SeqSpanRefList::iterator annots_i;
687 AnnotationsRef metadata;
689 // not sure why, or if i'm doing something wrong, but can't seem to pass
690 // file pointers down to this method from the mussa control class
691 // so each call to save a sequence appends to the file started by mussa_class
692 //save_file.open(save_file_path.c_str(), std::ios::app);
694 save_file << "<Sequence>" << std::endl;
695 save_file << *this << std::endl;
696 save_file << "</Sequence>" << std::endl;
698 save_file << "<Annotations>" << std::endl;
699 save_file << species << std::endl;
700 for (annots_i = annotation_list->begin();
701 annots_i != annotation_list->end();
704 metadata = (*annots_i)->annotations();
705 save_file << (*annots_i)->parentStart() << " " << (*annots_i)->parentStop() << " " ;
706 save_file << metadata->name() << " "
707 << metadata->getdefault(type, empty_str) << std::endl;
709 save_file << "</Annotations>" << std::endl;
714 Sequence::load_museq(fs::path load_file_path, int seq_num)
716 fs::fstream load_file;
717 std::string file_data_line;
722 std::string annot_name;
723 std::string annot_type;
725 std::string::size_type space_split_i;
726 std::string annot_value;
728 annotation_list.reset(new SeqSpanRefList);
730 load_file.open(load_file_path, std::ios::in);
733 // search for the seq_num-th sequence
734 while ( (!load_file.eof()) && (seq_counter < seq_num) )
736 getline(load_file,file_data_line);
737 if (file_data_line == "<Sequence>")
740 getline(load_file, file_data_line);
741 // looks like the sequence is written as a single line
742 set_filtered_sequence(file_data_line, reduced_dna_alphabet, 0, file_data_line.size(), SeqSpan::PlusStrand);
743 getline(load_file, file_data_line);
744 getline(load_file, file_data_line);
745 if (file_data_line == "<Annotations>")
747 getline(load_file, file_data_line);
748 species = file_data_line;
749 while ( (!load_file.eof()) && (file_data_line != "</Annotations>") )
751 getline(load_file,file_data_line);
752 if ((file_data_line != "") && (file_data_line != "</Annotations>"))
754 // need to get 4 values...almost same code 4 times...
755 // get annot start index
756 space_split_i = file_data_line.find(" ");
757 annot_value = file_data_line.substr(0,space_split_i);
758 annot_begin = atoi (annot_value.c_str());
759 file_data_line = file_data_line.substr(space_split_i+1);
760 // get annot end index
761 space_split_i = file_data_line.find(" ");
762 annot_value = file_data_line.substr(0,space_split_i);
763 annot_end = atoi (annot_value.c_str());
765 if (space_split_i == std::string::npos) // no entry for type or name
767 std::cout << "seq, annots - no type or name\n";
771 else // else get annot type
773 file_data_line = file_data_line.substr(space_split_i+1);
774 space_split_i = file_data_line.find(" ");
775 annot_value = file_data_line.substr(0,space_split_i);
776 //an_annot.type = annot_value;
777 annot_type = annot_value;
778 if (space_split_i == std::string::npos) // no entry for name
780 std::cout << "seq, annots - no name\n";
783 else // get annot name
785 file_data_line = file_data_line.substr(space_split_i+1);
786 space_split_i = file_data_line.find(" ");
787 annot_value = file_data_line.substr(0,space_split_i);
788 // this seems like its wrong?
789 annot_type = annot_value;
792 add_annotation(annot_name, annot_type, annot_begin, annot_end);
794 //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
795 // << "-->" << an_annot.type << "::" << an_annot.name << std::endl;
802 void Sequence::add_motif(const Sequence& a_motif)
804 std::vector<int> motif_starts = find_motif(a_motif);
806 for(std::vector<int>::iterator motif_start_i = motif_starts.begin();
807 motif_start_i != motif_starts.end();
810 motif_list->push_back(motif(*motif_start_i, a_motif.get_sequence()));
814 void Sequence::clear_motifs()
819 motif_list.reset(new MotifList);
822 const Sequence::MotifList& Sequence::motifs() const
828 Sequence::find_motif(const Sequence& a_motif) const
830 std::vector<int> motif_match_starts;
831 Sequence norm_motif_rc;
833 motif_match_starts.clear();
834 // std::cout << "motif is: " << norm_motif << std::endl;
836 if (a_motif.size() > 0)
838 //std::cout << "Sequence: none blank motif\n";
839 motif_scan(a_motif, &motif_match_starts);
841 norm_motif_rc = a_motif.rev_comp();;
842 // make sure not to do search again if it is a palindrome
843 if (norm_motif_rc != a_motif) {
844 motif_scan(norm_motif_rc, &motif_match_starts);
847 return motif_match_starts;
851 Sequence::motif_scan(const Sequence& a_motif, std::vector<int> * motif_match_starts) const
853 // if there's no sequence we can't scan for it?
854 // should this throw an exception?
857 std::string::size_type seq_i = 0;
858 Sequence::size_type motif_i = 0;
859 Sequence::size_type motif_len = a_motif.length();
860 Sequence::value_type motif_char;
861 Sequence::value_type seq_char;
863 while (seq_i < size())
865 // this is pretty much a straight translation of Nora's python code
866 // to match iupac letter codes
867 motif_char = toupper(a_motif[motif_i]);
868 seq_char = toupper(seq->at(seq_i));
869 if (motif_char =='N')
871 else if (motif_char == seq_char)
873 else if ((motif_char =='M') && ((seq_char=='A') || (seq_char=='C')))
875 else if ((motif_char =='R') && ((seq_char=='A') || (seq_char=='G')))
877 else if ((motif_char =='W') && ((seq_char=='A') || (seq_char=='T')))
879 else if ((motif_char =='S') && ((seq_char=='C') || (seq_char=='G')))
881 else if ((motif_char =='Y') && ((seq_char=='C') || (seq_char=='T')))
883 else if ((motif_char =='K') && ((seq_char=='G') || (seq_char=='T')))
885 else if ((motif_char =='V') &&
886 ((seq_char=='A') || (seq_char=='C') || (seq_char=='G')))
888 else if ((motif_char =='H') &&
889 ((seq_char=='A') || (seq_char=='C') || (seq_char=='T')))
891 else if ((motif_char =='D') &&
892 ((seq_char=='A') || (seq_char=='G') || (seq_char=='T')))
894 else if ((motif_char =='B') &&
895 ((seq_char=='C') || (seq_char=='G') || (seq_char=='T')))
899 // if a motif doesn't match, erase our current trial and try again
904 // end Nora stuff, now we see if a match is found this pass
905 if (motif_i == motif_len)
907 motif_match_starts->push_back(seq_i - motif_len + 1);
913 //std::cout << std::endl;
916 void Sequence::add_string_annotation(std::string a_seq,
919 std::vector<int> seq_starts = find_motif(a_seq);
921 for(std::vector<int>::iterator seq_start_i = seq_starts.begin();
922 seq_start_i != seq_starts.end();
925 add_annotation(name, "", *seq_start_i, *seq_start_i+a_seq.size());
929 void Sequence::find_sequences(std::list<Sequence>::iterator start,
930 std::list<Sequence>::iterator end)
932 while (start != end) {
933 add_string_annotation(start->get_sequence(), start->get_fasta_header());
939 std::ostream& operator<<(std::ostream& out, const Sequence& s)
942 for(Sequence::const_iterator s_i = s.begin(); s_i != s.end(); ++s_i) {
949 bool operator<(const Sequence& x, const Sequence& y)
951 Sequence::const_iterator x_i = x.begin();
952 Sequence::const_iterator y_i = y.begin();
953 // for sequences there's some computation associated with computing .end
955 Sequence::const_iterator xend = x.end();
956 Sequence::const_iterator yend = y.end();
958 if( x_i == xend and y_i == yend ) {
960 } else if ( x_i == xend ) {
962 } else if ( y_i == yend ) {
964 } else if ( (*x_i) < (*y_i)) {
966 } else if ( (*x_i) > (*y_i) ) {
975 template <typename Iter1, typename Iter2>
977 bool sequence_insensitive_equality(Iter1 abegin, Iter1 aend, Iter2 bbegin, Iter2 bend)
979 Iter1 aseq_i = abegin;
980 Iter2 bseq_i = bbegin;
981 if (aend-abegin == bend-bbegin) {
982 // since the length of the two sequences is equal, we only need to
984 for(; aseq_i != aend; ++aseq_i, ++bseq_i) {
985 if (toupper(*aseq_i) != toupper(*bseq_i)) {
995 bool operator==(const Sequence& x, const Sequence& y)
997 if (x.seq and y.seq) {
998 // both x and y are defined
999 if (SeqSpan::isFamily(x.seq, y.seq)) {
1000 // both are part of the same SeqSpan tree
1001 return *(x.seq) == *(y.seq);
1003 // we'll have to do a real comparison
1004 return sequence_insensitive_equality<SeqSpan::const_iterator, SeqSpan::const_iterator>(
1010 // true if they're both empty (with either a null SeqSpanRef or
1011 // a zero length string
1012 return (x.size() == y.size());
1016 bool operator!=(const Sequence& x, const Sequence& y)
1018 return not operator==(x, y);