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 namespace fs = boost::filesystem;
27 #include <boost/spirit/core.hpp>
28 #include <boost/spirit/actor/push_back_actor.hpp>
29 #include <boost/spirit/iterator/file_iterator.hpp>
30 #include <boost/spirit/utility/chset.hpp>
31 namespace spirit = boost::spirit;
33 #include "alg/sequence.hpp"
34 #include "mussa_exceptions.hpp"
40 // some standard dna alphabets
43 // this should make our sequence parsing end-of-line convention
45 static const char* dna_alphabet = "AaCcGgTtNn\012\015";
46 static const char* rna_alphabet = "AaCcGgNnUu\012\015";
47 static const char* iupac_alphabet = "AaCcGgTtUuRrYyMmKkSsWwBbDdHhVvNn\012\015";
57 annot::annot(int start, int end, std::string type, std::string name)
69 bool operator==(const annot& left, const annot& right)
71 return ((left.start == right.start) and
72 (left.end == right.end) and
73 (left.type == right.type) and
74 (left.name == right.name));
77 motif::motif(int start, std::string motif)
78 : annot(start, start+motif.size(), "motif", motif),
98 Sequence::Sequence(const char *seq)
102 set_filtered_sequence(seq);
105 Sequence::Sequence(const std::string& seq)
109 set_filtered_sequence(seq);
112 Sequence::Sequence(const Sequence& o)
117 motif_list(o.motif_list)
121 Sequence &Sequence::operator=(const Sequence& s)
124 //sequence = s.sequence;
129 motif_list = s.motif_list;
134 static void multiplatform_getline(std::istream& in, std::string& line)
139 while(in.good() and !(c == '\012' or c == '\015') ) {
143 // if we have cr-lf eat it
145 if (c=='\012' or c == '\015') {
150 //! load a fasta file into a sequence
152 * \param file_path the location of the fasta file in the filesystem
153 * \param seq_num which sequence in the file to load
154 * \param start_index starting position in the fasta sequence, 0 for beginning
155 * \param end_index ending position in the fasta sequence, 0 for end
156 * \return error message, empty string if no error. (gag!)
158 void Sequence::load_fasta(fs::path file_path, int seq_num,
159 int start_index, int end_index)
161 fs::fstream data_file;
162 data_file.open(file_path, std::ios::in);
164 if (!data_file.good())
166 throw mussa_load_error("Sequence File: "+file_path.string()+" not found");
169 load_fasta(data_file, seq_num, start_index, end_index);
170 } catch(sequence_empty_error e) {
171 // there doesn't appear to be any sequence
172 // catch and rethrow to include the filename
173 std::stringstream msg;
174 msg << "The selected sequence in "
175 << file_path.native_file_string()
176 << " appears to be empty";
177 throw sequence_empty_error(msg.str());
178 } catch(sequence_empty_file_error e) {
179 std::stringstream errormsg;
180 errormsg << file_path.native_file_string()
181 << " did not have any fasta sequences" << std::endl;
182 throw sequence_empty_file_error(errormsg.str());
188 Sequence::load_fasta(std::iostream& data_file, int seq_num,
189 int start_index, int end_index)
191 std::string file_data_line;
192 int header_counter = 0;
193 bool read_seq = true;
194 std::string rev_comp;
195 std::string sequence_raw;
196 std::string seq_tmp; // holds sequence during basic filtering
199 throw mussa_load_error("fasta sequence number is 1 based (can't be 0)");
202 // search for the header of the fasta sequence we want
203 while ( (!data_file.eof()) && (header_counter < seq_num) )
205 multiplatform_getline(data_file, file_data_line);
206 if (file_data_line.substr(0,1) == ">")
210 if (header_counter > 0) {
211 header = file_data_line.substr(1);
215 while ( !data_file.eof() && read_seq ) {
216 multiplatform_getline(data_file,file_data_line);
217 if (file_data_line.substr(0,1) == ">")
219 else sequence_raw += file_data_line;
222 // Lastly, if subselection of the sequence was specified we keep cut out
223 // and only keep that part
224 // end_index = 0 means no end was specified, so cut to the end
226 end_index = sequence_raw.size();
228 // sequence filtering for upcasing agctn and convert non AGCTN to N
229 if (end_index-start_index <= 0) {
230 std::string msg("The selected sequence appears to be empty");
231 throw sequence_empty_error(msg);
233 set_filtered_sequence(sequence_raw, start_index, end_index-start_index);
235 std::string errormsg("There were no fasta sequences");
236 throw sequence_empty_file_error(errormsg);
240 void Sequence::set_filtered_sequence(const std::string &old_seq,
241 std::string::size_type start,
242 std::string::size_type count)
244 char conversionTable[257];
247 count = old_seq.size() - start;
248 std::string::clear();
251 // Make a conversion table
253 // everything we don't specify below will become 'N'
254 for(int table_i=0; table_i < 256; table_i++)
256 conversionTable[table_i] = 'N';
258 // add end of string character for printing out table for testing purposes
259 conversionTable[256] = '\0';
261 // we want these to map to themselves - ie not to change
262 conversionTable[(int)'A'] = 'A';
263 conversionTable[(int)'T'] = 'T';
264 conversionTable[(int)'G'] = 'G';
265 conversionTable[(int)'C'] = 'C';
267 conversionTable[(int)'a'] = 'A';
268 conversionTable[(int)'t'] = 'T';
269 conversionTable[(int)'g'] = 'G';
270 conversionTable[(int)'c'] = 'C';
272 // finally, the actual conversion loop
273 for(std::string::size_type seq_index = 0; seq_index < count; seq_index++)
275 append(1, conversionTable[ (int)old_seq[seq_index+start]]);
279 // this doesn't work properly under gcc 3.x ... it can't recognize toupper
280 //transform(sequence.begin(), sequence.end(), sequence.begin(), toupper);
283 Sequence::load_annot(fs::path file_path, int start_index, int end_index)
285 fs::fstream data_stream(file_path, std::ios::in);
288 throw mussa_load_error("Sequence File: " + file_path.string() + " not found");
291 // so i should probably be passing the parse function some iterators
292 // but the annotations files are (currently) small, so i think i can
293 // get away with loading the whole file into memory
296 while(data_stream.good()) {
302 parse_annot(data, start_index, end_index);
305 /* If this works, yikes, this is some brain hurting code.
307 * what's going on is that when pb_annot is instantiated it stores references
308 * to begin, end, name, type, declared in the parse function, then
309 * when operator() is called it grabs values from those references
310 * and uses that to instantiate an annot object and append that to our
313 * This weirdness is because the spirit library requires that actions
314 * conform to a specific prototype operator()(IteratorT, IteratorT)
315 * which doesn't provide any useful opportunity for me to actually
316 * grab the results of our parsing.
318 * so I instantiate this structure in order to have a place to grab
322 struct push_back_annot {
323 std::list<annot>& annot_list;
329 push_back_annot(std::list<annot>& annot_list_,
334 : annot_list(annot_list_),
342 void operator()(std::string::const_iterator,
343 std::string::const_iterator) const
345 //std::cout << "adding annot: " << begin << "|" << end << "|" << name << "|" << type << std::endl;
346 annot_list.push_back(annot(begin, end, name, type));
350 struct push_back_seq {
351 std::list<Sequence>& seq_list;
355 push_back_seq(std::list<Sequence>& seq_list_,
358 : seq_list(seq_list_),
364 void operator()(std::string::const_iterator,
365 std::string::const_iterator) const
367 // filter out newlines from our sequence
369 for(std::string::const_iterator seq_i = seq.begin();
373 if (*seq_i != '\015' && *seq_i != '\012') new_seq += *seq_i;
375 //std::cout << "adding seq: " << name << " " << new_seq << std::endl;
379 seq_list.push_back(s);
384 Sequence::parse_annot(std::string data, int start_index, int end_index)
391 std::list<Sequence> query_seqs;
393 bool status = spirit::parse(data.begin(), data.end(),
400 )[spirit::assign_a(species)] >>
404 ( // parse an absolute location name
405 (spirit::uint_p[spirit::assign_a(start)] >>
407 spirit::uint_p[spirit::assign_a(end)] >>
412 )[spirit::assign_a(name)] >>
419 )[spirit::assign_a(type)]
421 // to understand how this group gets set
422 // read the comment above struct push_back_annot
423 )[push_back_annot(annots, start, end, type, name)]
425 (spirit::ch_p('>') >>
426 (*(spirit::print_p))[spirit::assign_a(name)] >>
428 (+(spirit::chset<>(iupac_alphabet)))[spirit::assign_a(seq)]
429 )[push_back_seq(query_seqs, name, seq)]
435 spirit::space_p*/).full;
437 // go seearch for query sequences
438 find_sequences(query_seqs.begin(), query_seqs.end());
441 void Sequence::set_species(const std::string& name)
446 const std::string& Sequence::get_species() const
451 void Sequence::add_annotation(const annot& a)
456 const std::list<annot>& Sequence::annotations() const
462 Sequence::subseq(int start, int count) const
464 // there might be an off by one error with start+count > size()
465 if ( count == npos || start+count > size()) {
466 count = size()-start;
468 Sequence new_seq(std::string::substr(start, count));
469 new_seq.set_header(get_header());
470 //new_seq.set_species(get_species());
472 new_seq.motif_list = motif_list;
473 // attempt to copy & reannotate position based annotations
474 int end = start+count;
476 for(std::list<annot>::const_iterator annot_i = annots.begin();
477 annot_i != annots.end();
480 int annot_start = annot_i->start;
481 int annot_end = annot_i->end;
483 if (annot_start < end) {
484 if (annot_start >=start) {
485 annot_start -= start;
490 if (annot_end < end) {
496 annot new_annot(annot_start, annot_end, annot_i->type, annot_i->name);
497 new_seq.annots.push_back(new_annot);
505 Sequence::rev_comp() const
507 std::string rev_comp;
508 char conversionTable[257];
509 int seq_i, table_i, len;
512 rev_comp.reserve(len);
513 // make a conversion table
514 // init all parts of conversion table to '~' character
515 // '~' I doubt will ever appear in a sequence file (jeez, I hope)
516 // and may the fleas of 1000 camels infest the genitals of any biologist (and
517 // seven generations of their progeny) who decides to make it mean
518 // something special!!!
519 // PS - double the curse for any smartass non-biologist who tries it as well
520 for(table_i=0; table_i < 256; table_i++)
522 conversionTable[table_i] = '~';
524 // add end of string character for printing out table for testing purposes
525 conversionTable[256] = '\0';
527 // add in the characters for the bases we want to convert
528 conversionTable[(int)'A'] = 'T';
529 conversionTable[(int)'T'] = 'A';
530 conversionTable[(int)'G'] = 'C';
531 conversionTable[(int)'C'] = 'G';
532 conversionTable[(int)'N'] = 'N';
534 // finally, the actual conversion loop
535 for(seq_i = len - 1; seq_i >= 0; seq_i--)
537 table_i = (int) at(seq_i);
538 rev_comp += conversionTable[table_i];
544 void Sequence::set_header(std::string header_)
550 Sequence::get_header() const
566 std::string::clear();
573 Sequence::save(fs::fstream &save_file)
574 //std::string save_file_path)
577 std::list<annot>::iterator annots_i;
579 // not sure why, or if i'm doing something wrong, but can't seem to pass
580 // file pointers down to this method from the mussa control class
581 // so each call to save a sequence appends to the file started by mussa_class
582 //save_file.open(save_file_path.c_str(), std::ios::app);
584 save_file << "<Sequence>" << std::endl;
585 save_file << *this << std::endl;
586 save_file << "</Sequence>" << std::endl;
588 save_file << "<Annotations>" << std::endl;
589 save_file << species << std::endl;
590 for (annots_i = annots.begin(); annots_i != annots.end(); ++annots_i)
592 save_file << annots_i->start << " " << annots_i->end << " " ;
593 save_file << annots_i->name << " " << annots_i->type << std::endl;
595 save_file << "</Annotations>" << std::endl;
600 Sequence::load_museq(fs::path load_file_path, int seq_num)
602 fs::fstream load_file;
603 std::string file_data_line;
606 std::string::size_type space_split_i;
607 std::string annot_value;
610 load_file.open(load_file_path, std::ios::in);
613 // search for the seq_num-th sequence
614 while ( (!load_file.eof()) && (seq_counter < seq_num) )
616 getline(load_file,file_data_line);
617 if (file_data_line == "<Sequence>")
620 getline(load_file, file_data_line);
621 assign(file_data_line);
622 getline(load_file, file_data_line);
623 getline(load_file, file_data_line);
624 if (file_data_line == "<Annotations>")
626 getline(load_file, file_data_line);
627 species = file_data_line;
628 while ( (!load_file.eof()) && (file_data_line != "</Annotations>") )
630 getline(load_file,file_data_line);
631 if ((file_data_line != "") && (file_data_line != "</Annotations>"))
633 // need to get 4 values...almost same code 4 times...
634 // get annot start index
635 space_split_i = file_data_line.find(" ");
636 annot_value = file_data_line.substr(0,space_split_i);
637 an_annot.start = atoi (annot_value.c_str());
638 file_data_line = file_data_line.substr(space_split_i+1);
639 // get annot end index
640 space_split_i = file_data_line.find(" ");
641 annot_value = file_data_line.substr(0,space_split_i);
642 an_annot.end = atoi (annot_value.c_str());
644 if (space_split_i == std::string::npos) // no entry for type or name
646 std::cout << "seq, annots - no type or name\n";
650 else // else get annot type
652 file_data_line = file_data_line.substr(space_split_i+1);
653 space_split_i = file_data_line.find(" ");
654 annot_value = file_data_line.substr(0,space_split_i);
655 an_annot.type = annot_value;
656 if (space_split_i == std::string::npos) // no entry for name
658 std::cout << "seq, annots - no name\n";
661 else // get annot name
663 file_data_line = file_data_line.substr(space_split_i+1);
664 space_split_i = file_data_line.find(" ");
665 annot_value = file_data_line.substr(0,space_split_i);
666 an_annot.type = annot_value;
669 annots.push_back(an_annot); // don't forget to actually add the annot
671 //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
672 // << "-->" << an_annot.type << "::" << an_annot.name << std::endl;
680 Sequence::rc_motif(std::string a_motif)
682 std::string rev_comp;
683 char conversionTable[257];
684 int seq_i, table_i, len;
686 len = a_motif.length();
687 rev_comp.reserve(len);
689 for(table_i=0; table_i < 256; table_i++)
691 conversionTable[table_i] = '~';
693 // add end of std::string character for printing out table for testing purposes
694 conversionTable[256] = '\0';
696 // add in the characters for the bases we want to convert (IUPAC)
697 conversionTable[(int)'A'] = 'T';
698 conversionTable[(int)'T'] = 'A';
699 conversionTable[(int)'G'] = 'C';
700 conversionTable[(int)'C'] = 'G';
701 conversionTable[(int)'N'] = 'N';
702 conversionTable[(int)'M'] = 'K';
703 conversionTable[(int)'R'] = 'Y';
704 conversionTable[(int)'W'] = 'W';
705 conversionTable[(int)'S'] = 'S';
706 conversionTable[(int)'Y'] = 'R';
707 conversionTable[(int)'K'] = 'M';
708 conversionTable[(int)'V'] = 'B';
709 conversionTable[(int)'H'] = 'D';
710 conversionTable[(int)'D'] = 'H';
711 conversionTable[(int)'B'] = 'V';
713 // finally, the actual conversion loop
714 for(seq_i = len - 1; seq_i >= 0; seq_i--)
716 //std::cout << "** i = " << seq_i << " bp = " <<
717 table_i = (int) a_motif[seq_i];
718 rev_comp += conversionTable[table_i];
721 //std::cout << "seq: " << a_motif << std::endl;
722 //std::cout << "rc: " << rev_comp << std::endl;
728 Sequence::motif_normalize(std::string a_motif)
730 std::string valid_motif;
733 len = a_motif.length();
734 valid_motif.reserve(len);
736 // this just upcases IUPAC symbols. Eventually should return an error if non IUPAC is present.
737 // current nonIUPAC symbols are omitted, which is not reported atm
738 for(seq_i = 0; seq_i < len; seq_i++)
740 if ((a_motif[seq_i] == 'a') || (a_motif[seq_i] == 'A'))
742 else if ((a_motif[seq_i] == 't') || (a_motif[seq_i] == 'T'))
744 else if ((a_motif[seq_i] == 'g') || (a_motif[seq_i] == 'G'))
746 else if ((a_motif[seq_i] == 'c') || (a_motif[seq_i] == 'C'))
748 else if ((a_motif[seq_i] == 'n') || (a_motif[seq_i] == 'N'))
750 else if ((a_motif[seq_i] == 'm') || (a_motif[seq_i] == 'M'))
752 else if ((a_motif[seq_i] == 'r') || (a_motif[seq_i] == 'R'))
754 else if ((a_motif[seq_i] == 'w') || (a_motif[seq_i] == 'W'))
756 else if ((a_motif[seq_i] == 's') || (a_motif[seq_i] == 'S'))
758 else if ((a_motif[seq_i] == 'y') || (a_motif[seq_i] == 'Y'))
760 else if ((a_motif[seq_i] == 'k') || (a_motif[seq_i] == 'K'))
762 else if ((a_motif[seq_i] == 'v') || (a_motif[seq_i] == 'V'))
764 else if ((a_motif[seq_i] == 'h') || (a_motif[seq_i] == 'H'))
766 else if ((a_motif[seq_i] == 'd') || (a_motif[seq_i] == 'D'))
768 else if ((a_motif[seq_i] == 'b') || (a_motif[seq_i] == 'B'))
771 std::string msg = "Letter ";
772 msg += a_motif[seq_i];
773 msg += " is not a valid IUPAC symbol";
774 throw motif_normalize_error(msg);
777 //std::cout << "valid_motif is: " << valid_motif << std::endl;
781 void Sequence::add_motif(const Sequence& a_motif)
783 std::vector<int> motif_starts = find_motif(a_motif);
785 for(std::vector<int>::iterator motif_start_i = motif_starts.begin();
786 motif_start_i != motif_starts.end();
789 motif_list.push_back(motif(*motif_start_i, a_motif));
793 void Sequence::clear_motifs()
798 const std::list<motif>& Sequence::motifs() const
804 Sequence::find_motif(std::string a_motif)
806 std::vector<int> motif_match_starts;
807 std::string a_motif_rc;
809 motif_match_starts.clear();
811 //std::cout << "motif is: " << a_motif << std::endl;
812 a_motif = motif_normalize(a_motif);
813 //std::cout << "motif is: " << a_motif << std::endl;
815 if (a_motif.size() > 0)
817 //std::cout << "Sequence: none blank motif\n";
818 motif_scan(a_motif, &motif_match_starts);
820 a_motif_rc = rc_motif(a_motif);
821 // make sure not to do search again if it is a palindrome
822 if (a_motif_rc != a_motif) {
823 motif_scan(a_motif_rc, &motif_match_starts);
826 return motif_match_starts;
830 Sequence::motif_scan(std::string a_motif, std::vector<int> * motif_match_starts)
833 std::string::size_type seq_i;
834 int motif_i, motif_len;
836 // faster to loop thru the sequence as a old c std::string (ie char array)
838 //std::cout << "Sequence: motif, seq len = " << sequence.length() << std::endl;
839 motif_len = a_motif.length();
841 //std::cout << "motif_length: " << motif_len << std::endl;
842 //std::cout << "RAAARRRRR\n";
846 //std::cout << "motif: " << a_motif << std::endl;
848 //std::cout << "Sequence: motif, length= " << length << std::endl;
850 while (seq_i < length())
852 //std::cout << seq_c[seq_i];
853 //std::cout << seq_c[seq_i] << "?" << a_motif[motif_i] << ":" << motif_i << " ";
854 // this is pretty much a straight translation of Nora's python code
855 // to match iupac letter codes
856 if (a_motif[motif_i] =='N')
858 else if (a_motif[motif_i] == seq_c[seq_i])
860 else if ((a_motif[motif_i] =='M') &&
861 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C')))
863 else if ((a_motif[motif_i] =='R') &&
864 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G')))
866 else if ((a_motif[motif_i] =='W') &&
867 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='T')))
869 else if ((a_motif[motif_i] =='S') &&
870 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G')))
872 else if ((a_motif[motif_i] =='Y') &&
873 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='T')))
875 else if ((a_motif[motif_i] =='K') &&
876 ((seq_c[seq_i]=='G') || (seq_c[seq_i]=='T')))
878 else if ((a_motif[motif_i] =='V') &&
879 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
880 (seq_c[seq_i]=='G')))
882 else if ((a_motif[seq_i] =='H') &&
883 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
884 (seq_c[seq_i]=='T')))
886 else if ((a_motif[motif_i] =='D') &&
887 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G') ||
888 (seq_c[seq_i]=='T')))
890 else if ((a_motif[motif_i] =='B') &&
891 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G') ||
892 (seq_c[seq_i]=='T')))
901 // end Nora stuff, now we see if a match is found this pass
902 if (motif_i == motif_len)
906 motif_match_starts->push_back(seq_i - motif_len + 1);
912 //std::cout << std::endl;
915 void Sequence::add_string_annotation(std::string a_seq,
918 std::vector<int> seq_starts = find_motif(a_seq);
920 //std::cout << "searching for " << a_seq << " found " << seq_starts.size() << std::endl;
922 for(std::vector<int>::iterator seq_start_i = seq_starts.begin();
923 seq_start_i != seq_starts.end();
926 annots.push_back(annot(*seq_start_i,
927 *seq_start_i+a_seq.size(),
933 void Sequence::find_sequences(std::list<Sequence>::iterator start,
934 std::list<Sequence>::iterator end)
936 while (start != end) {
937 add_string_annotation(*start, start->get_header());