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)),
92 Sequence::Sequence(const char *seq, AlphabetRef alphabet_)
93 : strand(UnknownStrand),
97 set_filtered_sequence(seq, alphabet_);
100 Sequence::Sequence(const std::string& seq, AlphabetRef alphabet_)
101 : strand(UnknownStrand),
105 set_filtered_sequence(seq, alphabet_);
108 Sequence::Sequence(const Sequence& o)
114 motif_list(o.motif_list)
118 Sequence::Sequence(const Sequence* o)
124 motif_list(o->motif_list)
128 Sequence::Sequence(const SeqSpanRef& seq_ref)
130 strand(UnknownStrand),
136 Sequence &Sequence::operator=(const Sequence& s)
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, reduced_nucleic_alphabet, seq_num, start_index, end_index);
170 //! load a fasta file into a sequence
171 void Sequence::load_fasta(fs::path file_path, AlphabetRef 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, reduced_nucleic_alphabet, seq_num, start_index, end_index);
212 Sequence::load_fasta(std::istream& data_file, AlphabetRef 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();
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 AlphabetRef alphabet_,
290 count = in_seq.size() - start;
292 new_seq.reserve(count);
294 // finally, the actual conversion loop
295 const Alphabet& alpha_impl = Alphabet::get_alphabet(alphabet_); // go get one of our actual alphabets
296 std::string::const_iterator seq_i = in_seq.begin()+start;
297 for(size_type i = 0; i != count; ++i, ++seq_i)
299 if (alpha_impl.exists(*seq_i)) {
300 new_seq.append(1, toupper(*seq_i));
302 new_seq.append(1, 'N');
305 SeqSpanRef new_seq_ref(new SeqSpan(new_seq, alphabet_));
311 Sequence::load_annot(fs::path file_path, int start_index, int end_index)
313 if (not fs::exists(file_path)) {
314 throw mussa_load_error("Annotation File " + file_path.string() + " was not found");
316 if (fs::is_directory(file_path)) {
317 throw mussa_load_error(file_path.string() +
318 " is a directory, please provide a file for annotations."
321 fs::fstream data_stream(file_path, std::ios::in);
324 throw mussa_load_error("Error loading annotation file " + file_path.string());
327 // so i should probably be passing the parse function some iterators
328 // but the annotations files are (currently) small, so i think i can
329 // get away with loading the whole file into memory
332 while(data_stream.good()) {
339 parse_annot(data, start_index, end_index);
340 } catch(annotation_load_error e) {
341 std::ostringstream msg;
342 msg << file_path.native_file_string()
345 throw annotation_load_error(msg.str());
349 /* If this works, yikes, this is some brain hurting code.
351 * what's going on is that when pb_annot is instantiated it stores references
352 * to begin, end, name, type, declared in the parse function, then
353 * when operator() is called it grabs values from those references
354 * and uses that to instantiate an annot object and append that to our
357 * This weirdness is because the spirit library requires that actions
358 * conform to a specific prototype operator()(IteratorT, IteratorT)
359 * which doesn't provide any useful opportunity for me to actually
360 * grab the results of our parsing.
362 * so I instantiate this structure in order to have a place to grab
366 struct push_back_annot {
367 std::list<annot>& annot_list;
374 push_back_annot(std::list<annot>& annot_list_,
380 : annot_list(annot_list_),
389 void operator()(std::string::const_iterator,
390 std::string::const_iterator) const
392 //std::cout << "adding annot: " << begin << "|" << end << "|" << name << "|" << type << std::endl;
393 annot_list.push_back(annot(begin, end, name, type));
398 struct push_back_seq {
399 std::list<Sequence>& seq_list;
404 push_back_seq(std::list<Sequence>& seq_list_,
408 : seq_list(seq_list_),
415 void operator()(std::string::const_iterator,
416 std::string::const_iterator) const
418 // filter out newlines from our sequence
420 for(std::string::const_iterator seq_i = seq.begin();
424 if (*seq_i != '\015' && *seq_i != '\012') new_seq += *seq_i;
426 //std::cout << "adding seq: " << name << " " << new_seq << std::endl;
429 s.set_fasta_header(name);
430 seq_list.push_back(s);
436 Sequence::parse_annot(std::string data, int start_index, int end_index)
443 std::list<annot> parsed_annots;
444 std::list<Sequence> query_seqs;
447 bool ok = spirit::parse(data.begin(), data.end(),
454 )[spirit::assign_a(species)] >>
458 ( // ignore html tags
459 *(spirit::space_p) >>
461 +(~spirit::ch_p('>')) >>
466 ( // parse an absolute location name
467 (spirit::uint_p[spirit::assign_a(start)] >>
469 spirit::uint_p[spirit::assign_a(end)] >>
474 )[spirit::assign_a(name)] >>
481 )[spirit::assign_a(type)]
483 // to understand how this group gets set
484 // read the comment above struct push_back_annot
485 )[push_back_annot(parsed_annots, start, end, type, name, parsed)]
487 ((spirit::ch_p('>')|spirit::str_p(">")) >>
488 (*(spirit::print_p))[spirit::assign_a(name)] >>
490 (+(spirit::chset<>(Alphabet::nucleic_cstr)))[spirit::assign_a(seq)]
491 )[push_back_seq(query_seqs, name, seq, parsed)]
498 std::stringstream msg;
499 msg << "Error parsing annotation #" << parsed;
500 throw annotation_load_error(msg.str());
502 // add newly parsed annotations to our sequence
503 std::copy(parsed_annots.begin(), parsed_annots.end(), std::back_inserter(annots));
504 // go seearch for query sequences
505 find_sequences(query_seqs.begin(), query_seqs.end());
508 void Sequence::add_annotation(const annot& a)
513 const std::list<annot>& Sequence::annotations() const
518 void Sequence::copy_children(Sequence &new_seq, size_type start, size_type count) const
520 new_seq.motif_list = motif_list;
521 new_seq.annots.clear();
523 for(std::list<annot>::const_iterator annot_i = annots.begin();
524 annot_i != annots.end();
527 size_type annot_begin= annot_i->begin;
528 size_type annot_end = annot_i->end;
530 if (annot_begin < start+count) {
531 if (annot_begin >= start) {
532 annot_begin -= start;
537 if (annot_end < start+count) {
543 annot new_annot(annot_begin, annot_end, annot_i->type, annot_i->name);
544 new_seq.annots.push_back(new_annot);
550 Sequence::subseq(size_type start, size_type count) const
557 Sequence new_seq = *this;
558 new_seq.seq = seq->subseq(start, count);
560 copy_children(new_seq, start, count);
566 // FIXME: This needs to be moved into SeqSpan
567 Sequence Sequence::rev_comp() const
569 std::string rev_comp;
570 rev_comp.reserve(length());
572 std::string rc_map = seq->seq->create_reverse_complement_map();
574 // reverse and convert
575 Sequence::const_reverse_iterator seq_i;
576 Sequence::const_reverse_iterator seq_end = rend();
577 for(seq_i = rbegin();
581 rev_comp.append(1, rc_map[*seq_i]);
583 return Sequence(rev_comp, seq->seq->get_alphabet_ref());
586 const Alphabet& Sequence::get_alphabet() const
588 return (seq) ? seq->get_alphabet() : Alphabet::empty_alphabet();
591 void Sequence::set_fasta_header(std::string header_)
596 void Sequence::set_species(const std::string& name)
601 std::string Sequence::get_species() const
608 Sequence::get_fasta_header() const
614 Sequence::get_name() const
616 if (header.size() > 0)
618 else if (species.size() > 0)
624 void Sequence::set_sequence(const std::string& s, AlphabetRef a)
626 set_filtered_sequence(s, a);
629 std::string Sequence::get_sequence() const
631 return seq->sequence();
634 Sequence::const_reference Sequence::operator[](Sequence::size_type i) const
643 strand = UnknownStrand;
651 Sequence::save(fs::fstream &save_file)
654 std::list<annot>::iterator annots_i;
656 // not sure why, or if i'm doing something wrong, but can't seem to pass
657 // file pointers down to this method from the mussa control class
658 // so each call to save a sequence appends to the file started by mussa_class
659 //save_file.open(save_file_path.c_str(), std::ios::app);
661 save_file << "<Sequence>" << std::endl;
662 save_file << *this << std::endl;
663 save_file << "</Sequence>" << std::endl;
665 save_file << "<Annotations>" << std::endl;
666 save_file << species << std::endl;
667 for (annots_i = annots.begin(); annots_i != annots.end(); ++annots_i)
669 save_file << annots_i->begin << " " << annots_i->end << " " ;
670 save_file << annots_i->name << " " << annots_i->type << std::endl;
672 save_file << "</Annotations>" << std::endl;
677 Sequence::load_museq(fs::path load_file_path, int seq_num)
679 fs::fstream load_file;
680 std::string file_data_line;
683 std::string::size_type space_split_i;
684 std::string annot_value;
687 load_file.open(load_file_path, std::ios::in);
690 // search for the seq_num-th sequence
691 while ( (!load_file.eof()) && (seq_counter < seq_num) )
693 getline(load_file,file_data_line);
694 if (file_data_line == "<Sequence>")
697 getline(load_file, file_data_line);
698 // looks like the sequence is written as a single line
699 set_filtered_sequence(file_data_line, reduced_dna_alphabet);
700 getline(load_file, file_data_line);
701 getline(load_file, file_data_line);
702 if (file_data_line == "<Annotations>")
704 getline(load_file, file_data_line);
705 species = file_data_line;
706 while ( (!load_file.eof()) && (file_data_line != "</Annotations>") )
708 getline(load_file,file_data_line);
709 if ((file_data_line != "") && (file_data_line != "</Annotations>"))
711 // need to get 4 values...almost same code 4 times...
712 // get annot start index
713 space_split_i = file_data_line.find(" ");
714 annot_value = file_data_line.substr(0,space_split_i);
715 an_annot.begin = atoi (annot_value.c_str());
716 file_data_line = file_data_line.substr(space_split_i+1);
717 // get annot end index
718 space_split_i = file_data_line.find(" ");
719 annot_value = file_data_line.substr(0,space_split_i);
720 an_annot.end = atoi (annot_value.c_str());
722 if (space_split_i == std::string::npos) // no entry for type or name
724 std::cout << "seq, annots - no type or name\n";
728 else // else get annot type
730 file_data_line = file_data_line.substr(space_split_i+1);
731 space_split_i = file_data_line.find(" ");
732 annot_value = file_data_line.substr(0,space_split_i);
733 an_annot.type = annot_value;
734 if (space_split_i == std::string::npos) // no entry for name
736 std::cout << "seq, annots - no name\n";
739 else // get annot name
741 file_data_line = file_data_line.substr(space_split_i+1);
742 space_split_i = file_data_line.find(" ");
743 annot_value = file_data_line.substr(0,space_split_i);
744 an_annot.type = annot_value;
747 annots.push_back(an_annot); // don't forget to actually add the annot
749 //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
750 // << "-->" << an_annot.type << "::" << an_annot.name << std::endl;
757 void Sequence::add_motif(const Sequence& a_motif)
759 std::vector<int> motif_starts = find_motif(a_motif);
761 for(std::vector<int>::iterator motif_start_i = motif_starts.begin();
762 motif_start_i != motif_starts.end();
765 motif_list.push_back(motif(*motif_start_i, a_motif.get_sequence()));
769 void Sequence::clear_motifs()
774 const std::list<motif>& Sequence::motifs() const
780 Sequence::find_motif(const Sequence& a_motif) const
782 std::vector<int> motif_match_starts;
783 Sequence norm_motif_rc;
785 motif_match_starts.clear();
786 // std::cout << "motif is: " << norm_motif << std::endl;
788 if (a_motif.size() > 0)
790 //std::cout << "Sequence: none blank motif\n";
791 motif_scan(a_motif, &motif_match_starts);
793 norm_motif_rc = a_motif.rev_comp();;
794 // make sure not to do search again if it is a palindrome
795 if (norm_motif_rc != a_motif) {
796 motif_scan(norm_motif_rc, &motif_match_starts);
799 return motif_match_starts;
803 Sequence::motif_scan(const Sequence& a_motif, std::vector<int> * motif_match_starts) const
805 // if there's no sequence we can't scan for it?
806 // should this throw an exception?
809 std::string::size_type seq_i = 0;
810 Sequence::size_type motif_i = 0;
811 Sequence::size_type motif_len = a_motif.length();
812 Sequence::value_type motif_char;
813 Sequence::value_type seq_char;
815 while (seq_i < size())
817 // this is pretty much a straight translation of Nora's python code
818 // to match iupac letter codes
819 motif_char = toupper(a_motif[motif_i]);
820 seq_char = toupper(seq->at(seq_i));
821 if (motif_char =='N')
823 else if (motif_char == seq_char)
825 else if ((motif_char =='M') && ((seq_char=='A') || (seq_char=='C')))
827 else if ((motif_char =='R') && ((seq_char=='A') || (seq_char=='G')))
829 else if ((motif_char =='W') && ((seq_char=='A') || (seq_char=='T')))
831 else if ((motif_char =='S') && ((seq_char=='C') || (seq_char=='G')))
833 else if ((motif_char =='Y') && ((seq_char=='C') || (seq_char=='T')))
835 else if ((motif_char =='K') && ((seq_char=='G') || (seq_char=='T')))
837 else if ((motif_char =='V') &&
838 ((seq_char=='A') || (seq_char=='C') || (seq_char=='G')))
840 else if ((motif_char =='H') &&
841 ((seq_char=='A') || (seq_char=='C') || (seq_char=='T')))
843 else if ((motif_char =='D') &&
844 ((seq_char=='A') || (seq_char=='G') || (seq_char=='T')))
846 else if ((motif_char =='B') &&
847 ((seq_char=='C') || (seq_char=='G') || (seq_char=='T')))
851 // if a motif doesn't match, erase our current trial and try again
856 // end Nora stuff, now we see if a match is found this pass
857 if (motif_i == motif_len)
860 motif_match_starts->push_back(seq_i - motif_len + 1);
866 //std::cout << std::endl;
869 void Sequence::add_string_annotation(std::string a_seq,
872 std::vector<int> seq_starts = find_motif(a_seq);
874 //std::cout << "searching for " << a_seq << " found " << seq_starts.size() << std::endl;
876 for(std::vector<int>::iterator seq_start_i = seq_starts.begin();
877 seq_start_i != seq_starts.end();
880 annots.push_back(annot(*seq_start_i,
881 *seq_start_i+a_seq.size(),
887 void Sequence::find_sequences(std::list<Sequence>::iterator start,
888 std::list<Sequence>::iterator end)
890 while (start != end) {
891 add_string_annotation(start->get_sequence(), start->get_fasta_header());
897 std::ostream& operator<<(std::ostream& out, const Sequence& s)
900 for(Sequence::const_iterator s_i = s.begin(); s_i != s.end(); ++s_i) {
907 bool operator<(const Sequence& x, const Sequence& y)
909 Sequence::const_iterator x_i = x.begin();
910 Sequence::const_iterator y_i = y.begin();
911 // for sequences there's some computation associated with computing .end
913 Sequence::const_iterator xend = x.end();
914 Sequence::const_iterator yend = y.end();
916 if( x_i == xend and y_i == yend ) {
918 } else if ( x_i == xend ) {
920 } else if ( y_i == yend ) {
922 } else if ( (*x_i) < (*y_i)) {
924 } else if ( (*x_i) > (*y_i) ) {
933 template <typename Iter1, typename Iter2>
935 bool sequence_insensitive_equality(Iter1 abegin, Iter1 aend, Iter2 bbegin, Iter2 bend)
937 Iter1 aseq_i = abegin;
938 Iter2 bseq_i = bbegin;
939 if (aend-abegin == bend-bbegin) {
940 // since the length of the two sequences is equal, we only need to
942 for(; aseq_i != aend; ++aseq_i, ++bseq_i) {
943 if (toupper(*aseq_i) != toupper(*bseq_i)) {
953 bool operator==(const Sequence& x, const Sequence& y)
955 if (x.seq and y.seq) {
956 // both x and y are defined
957 if (SeqSpan::isFamily(x.seq, y.seq)) {
958 // both are part of the same SeqSpan tree
959 return *(x.seq) == *(y.seq);
961 // we'll have to do a real comparison
962 return sequence_insensitive_equality<SeqSpan::const_iterator, SeqSpan::const_iterator>(
968 // true if they're both empty (with either a null SeqSpanRef or
969 // a zero length string
970 return (x.size() == y.size());
974 bool operator!=(const Sequence& x, const Sequence& y)
976 return not operator==(x, y);