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(o->annotation_list),
127 motif_list(o->motif_list)
131 Sequence::Sequence(const SeqSpanRef& seq_ref)
135 annotation_list(new SeqSpanRefList),
136 motif_list(new MotifList)
140 Sequence &Sequence::operator=(const Sequence& s)
146 annotation_list = s.annotation_list;
147 motif_list = s.motif_list;
152 static void multiplatform_getline(std::istream& in, std::string& line)
157 while(in.good() and !(c == '\012' or c == '\015') ) {
161 // if we have cr-lf eat it
163 if (c=='\012' or c == '\015') {
168 void Sequence::load_fasta(fs::path file_path, int seq_num, int start_index, int end_index)
170 load_fasta(file_path, reduced_nucleic_alphabet, seq_num, start_index, end_index);
173 //! load a fasta file into a sequence
174 void Sequence::load_fasta(fs::path file_path, AlphabetRef a,
175 int seq_num, int start_index, int end_index)
177 fs::fstream data_file;
178 data_file.open(file_path, std::ios::in);
180 if (!data_file.good())
182 throw mussa_load_error("Sequence File: "+file_path.string()+" not found");
185 load_fasta(data_file, a, seq_num, start_index, end_index);
186 } catch(sequence_empty_error e) {
187 // there doesn't appear to be any sequence
188 // catch and rethrow to include the filename
189 std::stringstream msg;
190 msg << "The selected sequence in "
191 << file_path.native_file_string()
192 << " appears to be empty";
193 throw sequence_empty_error(msg.str());
194 } catch(sequence_empty_file_error e) {
195 std::stringstream errormsg;
196 errormsg << file_path.native_file_string()
197 << " did not have any fasta sequences" << std::endl;
198 throw sequence_empty_file_error(errormsg.str());
199 } catch(sequence_invalid_load_error e) {
200 std::ostringstream msg;
201 msg << file_path.native_file_string();
202 msg << " " << e.what();
203 throw sequence_invalid_load_error(msg.str());
208 void Sequence::load_fasta(std::istream& file,
209 int seq_num, int start_index, int end_index)
211 load_fasta(file, reduced_nucleic_alphabet, seq_num, start_index, end_index);
215 Sequence::load_fasta(std::istream& data_file, AlphabetRef a,
217 int start_index, int end_index)
219 std::string file_data_line;
220 int header_counter = 0;
221 size_t line_counter = 0;
222 bool read_seq = true;
223 std::string rev_comp;
224 std::string sequence_raw;
225 std::string seq_tmp; // holds sequence during basic filtering
226 const Alphabet &alpha = Alphabet::get_alphabet(a);
229 throw mussa_load_error("fasta sequence number is 1 based (can't be 0)");
232 // search for the header of the fasta sequence we want
233 while ( (!data_file.eof()) && (header_counter < seq_num) )
235 multiplatform_getline(data_file, file_data_line);
237 if (file_data_line.substr(0,1) == ">")
241 if (header_counter > 0) {
242 header = file_data_line.substr(1);
246 while ( !data_file.eof() && read_seq ) {
247 multiplatform_getline(data_file,file_data_line);
249 if (file_data_line.substr(0,1) == ">")
252 for (std::string::const_iterator line_i = file_data_line.begin();
253 line_i != file_data_line.end();
256 if(alpha.exists(*line_i)) {
257 sequence_raw += *line_i;
259 std::ostringstream msg;
260 msg << "Unrecognized characters in fasta sequence at line ";
262 throw sequence_invalid_load_error(msg.str());
268 // Lastly, if subselection of the sequence was specified we keep cut out
269 // and only keep that part
270 // end_index = 0 means no end was specified, so cut to the end
272 end_index = sequence_raw.size();
274 // sequence filtering for upcasing agctn and convert non AGCTN to N
275 if (end_index-start_index <= 0) {
276 std::string msg("The selected sequence appears to be empty");
277 throw sequence_empty_error(msg);
279 set_filtered_sequence(sequence_raw, a, start_index, end_index-start_index, SeqSpan::PlusStrand);
281 std::string errormsg("There were no fasta sequences");
282 throw sequence_empty_file_error(errormsg);
286 void Sequence::set_filtered_sequence(const std::string &in_seq,
287 AlphabetRef alphabet_,
290 SeqSpan::strand_type strand_)
293 count = in_seq.size() - start;
295 new_seq.reserve(count);
297 // finally, the actual conversion loop
298 const Alphabet& alpha_impl = Alphabet::get_alphabet(alphabet_); // go get one of our actual alphabets
299 std::string::const_iterator seq_i = in_seq.begin()+start;
300 for(size_type i = 0; i != count; ++i, ++seq_i)
302 if (alpha_impl.exists(*seq_i)) {
303 new_seq.append(1, toupper(*seq_i));
305 new_seq.append(1, 'N');
308 SeqSpanRef new_seq_ref(new SeqSpan(new_seq, alphabet_, strand_));
313 Sequence::load_annot(fs::path file_path, int start_index, int end_index)
315 if (not fs::exists(file_path)) {
316 throw mussa_load_error("Annotation File " + file_path.string() + " was not found");
318 if (fs::is_directory(file_path)) {
319 throw mussa_load_error(file_path.string() +
320 " is a directory, please provide a file for annotations."
323 fs::fstream data_stream(file_path, std::ios::in);
326 throw mussa_load_error("Error loading annotation file " + file_path.string());
329 // so i should probably be passing the parse function some iterators
330 // but the annotations files are (currently) small, so i think i can
331 // get away with loading the whole file into memory
334 while(data_stream.good()) {
341 parse_annot(data, start_index, end_index);
342 } catch(annotation_load_error e) {
343 std::ostringstream msg;
344 msg << file_path.native_file_string()
347 throw annotation_load_error(msg.str());
351 /* If this works, yikes, this is some brain hurting code.
353 * what's going on is that when pb_annot is instantiated it stores references
354 * to begin, end, name, type, declared in the parse function, then
355 * when operator() is called it grabs values from those references
356 * and uses that to instantiate an annot object and append that to our
359 * This weirdness is because the spirit library requires that actions
360 * conform to a specific prototype operator()(IteratorT, IteratorT)
361 * which doesn't provide any useful opportunity for me to actually
362 * grab the results of our parsing.
364 * so I instantiate this structure in order to have a place to grab
368 struct push_back_annot {
370 SeqSpanRefListRef children;
377 push_back_annot(Sequence* parent_seq,
378 SeqSpanRefListRef children_list,
384 : parent(parent_seq),
385 children(children_list),
394 void operator()(std::string::const_iterator,
395 std::string::const_iterator) const
397 children->push_back(parent->make_annotation(name, type, begin, end));
402 struct push_back_seq {
403 std::list<Sequence>& seq_list;
408 push_back_seq(std::list<Sequence>& seq_list_,
412 : seq_list(seq_list_),
419 void operator()(std::string::const_iterator,
420 std::string::const_iterator) const
422 // filter out newlines from our sequence
424 for(std::string::const_iterator seq_i = seq.begin();
428 if (*seq_i != '\015' && *seq_i != '\012') new_seq += *seq_i;
430 //std::cout << "adding seq: " << name << " " << new_seq << std::endl;
433 s.set_fasta_header(name);
434 seq_list.push_back(s);
440 Sequence::parse_annot(std::string data, int start_index, int end_index)
447 SeqSpanRefListRef parsed_annots(new SeqSpanRefList);
448 std::list<Sequence> query_seqs;
451 bool ok = spirit::parse(data.begin(), data.end(),
458 )[spirit::assign_a(species)] >>
462 ( // ignore html tags
463 *(spirit::space_p) >>
465 +(~spirit::ch_p('>')) >>
470 ( // parse an absolute location name
471 (spirit::uint_p[spirit::assign_a(start)] >>
473 spirit::uint_p[spirit::assign_a(end)] >>
478 )[spirit::assign_a(name)] >>
485 )[spirit::assign_a(type)]
487 // to understand how this group gets set
488 // read the comment above struct push_back_annot
489 )[push_back_annot(this, parsed_annots, start, end, name, type, parsed)]
491 ((spirit::ch_p('>')|spirit::str_p(">")) >>
492 (*(spirit::print_p))[spirit::assign_a(name)] >>
494 (+(spirit::chset<>(Alphabet::nucleic_cstr)))[spirit::assign_a(seqstr)]
495 )[push_back_seq(query_seqs, name, seqstr, parsed)]
502 std::stringstream msg;
503 msg << "Error parsing annotation #" << parsed;
504 throw annotation_load_error(msg.str());
506 // If everything loaded correctly add the sequences to our annotation list
507 // add newly parsed annotations to our sequence
508 std::copy(parsed_annots->begin(), parsed_annots->end(), std::back_inserter(*annotation_list));
509 // go search for query sequences
510 find_sequences(query_seqs.begin(), query_seqs.end());
513 void Sequence::add_annotation(const SeqSpanRef a)
515 annotation_list->push_back(a);
518 void Sequence::add_annotation(std::string name, std::string type, size_type start, size_type stop)
520 add_annotation(make_annotation(name, type, start, stop));
524 Sequence::make_annotation(std::string name, std::string type, size_type start, size_type stop) const
526 // we want things to be in the positive direction
528 size_type tmp = start;
532 size_type count = stop - start;
533 SeqSpanRef new_annot(seq->subseq(start, count, SeqSpan::UnknownStrand));
534 AnnotationsRef metadata(new Annotations(name));
535 metadata->set("type", type);
536 new_annot->setAnnotations(metadata);
540 const SeqSpanRefList& Sequence::annotations() const
542 return *annotation_list;
545 void Sequence::copy_children(Sequence &new_seq, size_type start, size_type count) const
547 new_seq.motif_list = motif_list;
548 new_seq.annotation_list.reset(new SeqSpanRefList);
550 for(SeqSpanRefList::const_iterator annot_i = annotation_list->begin();
551 annot_i != annotation_list->end();
554 size_type annot_begin= (*annot_i)->start();
555 size_type annot_end = (*annot_i)->stop();
557 if (annot_begin < start+count) {
558 if (annot_begin >= start) {
559 annot_begin -= start;
564 if (annot_end < start+count) {
570 SeqSpanRef new_annot(seq->subseq(annot_begin, annot_end));
571 new_annot->setAnnotations((*annot_i)->annotations());
572 new_seq.annotation_list->push_back(new_annot);
578 Sequence::subseq(size_type start, size_type count, SeqSpan::strand_type strand) const
580 // FIXME: should i really allow a subsequence of an empty sequence?
586 Sequence new_seq(*this);
587 new_seq.seq = seq->subseq(start, count, strand);
588 if (seq->annotations()) {
589 AnnotationsRef a(new Annotations(*(seq->annotations())));
590 new_seq.seq->setAnnotations(a);
592 copy_children(new_seq, start, count);
598 // FIXME: This needs to be moved into SeqSpan
599 Sequence Sequence::rev_comp() const
601 // a reverse complement is the whole opposite strand
602 return subseq(0, npos, SeqSpan::OppositeStrand);
605 const Alphabet& Sequence::get_alphabet() const
607 return (seq) ? seq->get_alphabet() : Alphabet::empty_alphabet();
610 void Sequence::set_fasta_header(std::string header_)
615 void Sequence::set_species(const std::string& name)
620 std::string Sequence::get_species() const
627 Sequence::get_fasta_header() const
633 Sequence::get_name() const
635 if (header.size() > 0)
637 else if (species.size() > 0)
643 void Sequence::set_sequence(const std::string& s, AlphabetRef a)
645 set_filtered_sequence(s, a, 0, s.size(), SeqSpan::PlusStrand);
648 std::string Sequence::get_sequence() const
650 return seq->sequence();
653 Sequence::const_reference Sequence::operator[](Sequence::size_type i) const
664 annotation_list.reset(new SeqSpanRefList);
665 motif_list.reset(new MotifList);
669 Sequence::save(fs::fstream &save_file)
671 std::string type("type");
672 std::string empty_str("");
674 SeqSpanRefList::iterator annots_i;
675 AnnotationsRef metadata;
677 // not sure why, or if i'm doing something wrong, but can't seem to pass
678 // file pointers down to this method from the mussa control class
679 // so each call to save a sequence appends to the file started by mussa_class
680 //save_file.open(save_file_path.c_str(), std::ios::app);
682 save_file << "<Sequence>" << std::endl;
683 save_file << *this << std::endl;
684 save_file << "</Sequence>" << std::endl;
686 save_file << "<Annotations>" << std::endl;
687 save_file << species << std::endl;
688 for (annots_i = annotation_list->begin();
689 annots_i != annotation_list->end();
692 metadata = (*annots_i)->annotations();
693 save_file << (*annots_i)->parentStart() << " " << (*annots_i)->parentStop() << " " ;
694 save_file << metadata->name() << " "
695 << metadata->getdefault(type, empty_str) << std::endl;
697 save_file << "</Annotations>" << std::endl;
702 Sequence::load_museq(fs::path load_file_path, int seq_num)
704 fs::fstream load_file;
705 std::string file_data_line;
710 std::string annot_name;
711 std::string annot_type;
713 std::string::size_type space_split_i;
714 std::string annot_value;
716 annotation_list.reset(new SeqSpanRefList);
718 load_file.open(load_file_path, std::ios::in);
721 // search for the seq_num-th sequence
722 while ( (!load_file.eof()) && (seq_counter < seq_num) )
724 getline(load_file,file_data_line);
725 if (file_data_line == "<Sequence>")
728 getline(load_file, file_data_line);
729 // looks like the sequence is written as a single line
730 set_filtered_sequence(file_data_line, reduced_dna_alphabet, 0, file_data_line.size(), SeqSpan::PlusStrand);
731 getline(load_file, file_data_line);
732 getline(load_file, file_data_line);
733 if (file_data_line == "<Annotations>")
735 getline(load_file, file_data_line);
736 species = file_data_line;
737 while ( (!load_file.eof()) && (file_data_line != "</Annotations>") )
739 getline(load_file,file_data_line);
740 if ((file_data_line != "") && (file_data_line != "</Annotations>"))
742 // need to get 4 values...almost same code 4 times...
743 // get annot start index
744 space_split_i = file_data_line.find(" ");
745 annot_value = file_data_line.substr(0,space_split_i);
746 annot_begin = atoi (annot_value.c_str());
747 file_data_line = file_data_line.substr(space_split_i+1);
748 // get annot end index
749 space_split_i = file_data_line.find(" ");
750 annot_value = file_data_line.substr(0,space_split_i);
751 annot_end = atoi (annot_value.c_str());
753 if (space_split_i == std::string::npos) // no entry for type or name
755 std::cout << "seq, annots - no type or name\n";
759 else // else get annot type
761 file_data_line = file_data_line.substr(space_split_i+1);
762 space_split_i = file_data_line.find(" ");
763 annot_value = file_data_line.substr(0,space_split_i);
764 //an_annot.type = annot_value;
765 annot_type = annot_value;
766 if (space_split_i == std::string::npos) // no entry for name
768 std::cout << "seq, annots - no name\n";
771 else // get annot name
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 // this seems like its wrong?
777 annot_type = annot_value;
780 add_annotation(annot_name, annot_type, annot_begin, annot_end);
782 //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
783 // << "-->" << an_annot.type << "::" << an_annot.name << std::endl;
790 void Sequence::add_motif(const Sequence& a_motif)
792 std::vector<int> motif_starts = find_motif(a_motif);
794 for(std::vector<int>::iterator motif_start_i = motif_starts.begin();
795 motif_start_i != motif_starts.end();
798 motif_list->push_back(motif(*motif_start_i, a_motif.get_sequence()));
802 void Sequence::clear_motifs()
807 motif_list.reset(new MotifList);
810 const Sequence::MotifList& Sequence::motifs() const
816 Sequence::find_motif(const Sequence& a_motif) const
818 std::vector<int> motif_match_starts;
819 Sequence norm_motif_rc;
821 motif_match_starts.clear();
822 // std::cout << "motif is: " << norm_motif << std::endl;
824 if (a_motif.size() > 0)
826 //std::cout << "Sequence: none blank motif\n";
827 motif_scan(a_motif, &motif_match_starts);
829 norm_motif_rc = a_motif.rev_comp();;
830 // make sure not to do search again if it is a palindrome
831 if (norm_motif_rc != a_motif) {
832 motif_scan(norm_motif_rc, &motif_match_starts);
835 return motif_match_starts;
839 Sequence::motif_scan(const Sequence& a_motif, std::vector<int> * motif_match_starts) const
841 // if there's no sequence we can't scan for it?
842 // should this throw an exception?
845 std::string::size_type seq_i = 0;
846 Sequence::size_type motif_i = 0;
847 Sequence::size_type motif_len = a_motif.length();
848 Sequence::value_type motif_char;
849 Sequence::value_type seq_char;
851 while (seq_i < size())
853 // this is pretty much a straight translation of Nora's python code
854 // to match iupac letter codes
855 motif_char = toupper(a_motif[motif_i]);
856 seq_char = toupper(seq->at(seq_i));
857 if (motif_char =='N')
859 else if (motif_char == seq_char)
861 else if ((motif_char =='M') && ((seq_char=='A') || (seq_char=='C')))
863 else if ((motif_char =='R') && ((seq_char=='A') || (seq_char=='G')))
865 else if ((motif_char =='W') && ((seq_char=='A') || (seq_char=='T')))
867 else if ((motif_char =='S') && ((seq_char=='C') || (seq_char=='G')))
869 else if ((motif_char =='Y') && ((seq_char=='C') || (seq_char=='T')))
871 else if ((motif_char =='K') && ((seq_char=='G') || (seq_char=='T')))
873 else if ((motif_char =='V') &&
874 ((seq_char=='A') || (seq_char=='C') || (seq_char=='G')))
876 else if ((motif_char =='H') &&
877 ((seq_char=='A') || (seq_char=='C') || (seq_char=='T')))
879 else if ((motif_char =='D') &&
880 ((seq_char=='A') || (seq_char=='G') || (seq_char=='T')))
882 else if ((motif_char =='B') &&
883 ((seq_char=='C') || (seq_char=='G') || (seq_char=='T')))
887 // if a motif doesn't match, erase our current trial and try again
892 // end Nora stuff, now we see if a match is found this pass
893 if (motif_i == motif_len)
895 motif_match_starts->push_back(seq_i - motif_len + 1);
901 //std::cout << std::endl;
904 void Sequence::add_string_annotation(std::string a_seq,
907 std::vector<int> seq_starts = find_motif(a_seq);
909 for(std::vector<int>::iterator seq_start_i = seq_starts.begin();
910 seq_start_i != seq_starts.end();
913 add_annotation(name, "", *seq_start_i, *seq_start_i+a_seq.size());
917 void Sequence::find_sequences(std::list<Sequence>::iterator start,
918 std::list<Sequence>::iterator end)
920 while (start != end) {
921 add_string_annotation(start->get_sequence(), start->get_fasta_header());
927 std::ostream& operator<<(std::ostream& out, const Sequence& s)
930 for(Sequence::const_iterator s_i = s.begin(); s_i != s.end(); ++s_i) {
937 bool operator<(const Sequence& x, const Sequence& y)
939 Sequence::const_iterator x_i = x.begin();
940 Sequence::const_iterator y_i = y.begin();
941 // for sequences there's some computation associated with computing .end
943 Sequence::const_iterator xend = x.end();
944 Sequence::const_iterator yend = y.end();
946 if( x_i == xend and y_i == yend ) {
948 } else if ( x_i == xend ) {
950 } else if ( y_i == yend ) {
952 } else if ( (*x_i) < (*y_i)) {
954 } else if ( (*x_i) > (*y_i) ) {
963 template <typename Iter1, typename Iter2>
965 bool sequence_insensitive_equality(Iter1 abegin, Iter1 aend, Iter2 bbegin, Iter2 bend)
967 Iter1 aseq_i = abegin;
968 Iter2 bseq_i = bbegin;
969 if (aend-abegin == bend-bbegin) {
970 // since the length of the two sequences is equal, we only need to
972 for(; aseq_i != aend; ++aseq_i, ++bseq_i) {
973 if (toupper(*aseq_i) != toupper(*bseq_i)) {
983 bool operator==(const Sequence& x, const Sequence& y)
985 if (x.seq and y.seq) {
986 // both x and y are defined
987 if (SeqSpan::isFamily(x.seq, y.seq)) {
988 // both are part of the same SeqSpan tree
989 return *(x.seq) == *(y.seq);
991 // we'll have to do a real comparison
992 return sequence_insensitive_equality<SeqSpan::const_iterator, SeqSpan::const_iterator>(
998 // true if they're both empty (with either a null SeqSpanRef or
999 // a zero length string
1000 return (x.size() == y.size());
1004 bool operator!=(const Sequence& x, const Sequence& y)
1006 return not operator==(x, y);