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),
100 Sequence::Sequence(const std::string& seq)
105 set_filtered_sequence(seq);
108 Sequence::Sequence(const Sequence& o)
113 motif_list(o.motif_list)
117 Sequence &Sequence::operator=(const Sequence& s)
120 //sequence = s.sequence;
129 Sequence &Sequence::operator=(const std::string& s)
131 set_filtered_sequence(s);
135 static void multiplatform_getline(std::istream& in, std::string& line)
140 while(in.good() and !(c == '\012' or c == '\015') ) {
144 // if we have cr-lf eat it
146 if (c=='\012' or c == '\015') {
151 //! load a fasta file into a sequence
153 * \param file_path the location of the fasta file in the filesystem
154 * \param seq_num which sequence in the file to load
155 * \param start_index starting position in the fasta sequence, 0 for beginning
156 * \param end_index ending position in the fasta sequence, 0 for end
157 * \return error message, empty string if no error. (gag!)
159 void Sequence::load_fasta(fs::path file_path, int seq_num,
160 int start_index, int end_index)
162 fs::fstream data_file;
163 data_file.open(file_path, std::ios::in);
165 if (!data_file.good())
167 throw mussa_load_error("Sequence File: "+file_path.string()+" not found");
170 load_fasta(data_file, seq_num, start_index, end_index);
171 } catch(sequence_empty_error e) {
172 // there doesn't appear to be any sequence
173 // catch and rethrow to include the filename
174 std::stringstream msg;
175 msg << "The selected sequence in "
176 << file_path.native_file_string()
177 << " appears to be empty";
178 throw sequence_empty_error(msg.str());
179 } catch(sequence_empty_file_error e) {
180 std::stringstream errormsg;
181 errormsg << file_path.native_file_string()
182 << " did not have any fasta sequences" << std::endl;
183 throw sequence_empty_file_error(errormsg.str());
189 Sequence::load_fasta(std::iostream& data_file, int seq_num,
190 int start_index, int end_index)
192 std::string file_data_line;
193 int header_counter = 0;
194 bool read_seq = true;
195 std::string rev_comp;
196 std::string sequence_raw;
197 std::string seq_tmp; // holds sequence during basic filtering
200 throw mussa_load_error("fasta sequence number is 1 based (can't be 0)");
203 // search for the header of the fasta sequence we want
204 while ( (!data_file.eof()) && (header_counter < seq_num) )
206 multiplatform_getline(data_file, file_data_line);
207 if (file_data_line.substr(0,1) == ">")
211 if (header_counter > 0) {
212 header = file_data_line.substr(1);
216 while ( !data_file.eof() && read_seq ) {
217 multiplatform_getline(data_file,file_data_line);
218 if (file_data_line.substr(0,1) == ">")
220 else sequence_raw += file_data_line;
223 // Lastly, if subselection of the sequence was specified we keep cut out
224 // and only keep that part
225 // end_index = 0 means no end was specified, so cut to the end
227 end_index = sequence_raw.size();
229 // sequence filtering for upcasing agctn and convert non AGCTN to N
230 if (end_index-start_index <= 0) {
231 std::string msg("The selected sequence appears to be empty");
232 throw sequence_empty_error(msg);
234 set_filtered_sequence(sequence_raw, start_index, end_index-start_index);
236 std::string errormsg("There were no fasta sequences");
237 throw sequence_empty_file_error(errormsg);
241 void Sequence::set_filtered_sequence(const std::string &old_seq,
242 std::string::size_type start,
243 std::string::size_type count)
245 char conversionTable[257];
248 count = old_seq.size() - start;
249 std::string::clear();
252 // Make a conversion table
254 // everything we don't specify below will become 'N'
255 for(int table_i=0; table_i < 256; table_i++)
257 conversionTable[table_i] = 'N';
259 // add end of string character for printing out table for testing purposes
260 conversionTable[256] = '\0';
262 // we want these to map to themselves - ie not to change
263 conversionTable[(int)'A'] = 'A';
264 conversionTable[(int)'T'] = 'T';
265 conversionTable[(int)'G'] = 'G';
266 conversionTable[(int)'C'] = 'C';
268 conversionTable[(int)'a'] = 'A';
269 conversionTable[(int)'t'] = 'T';
270 conversionTable[(int)'g'] = 'G';
271 conversionTable[(int)'c'] = 'C';
273 // finally, the actual conversion loop
274 for(std::string::size_type seq_index = 0; seq_index < count; seq_index++)
276 append(1, conversionTable[ (int)old_seq[seq_index+start]]);
280 // this doesn't work properly under gcc 3.x ... it can't recognize toupper
281 //transform(sequence.begin(), sequence.end(), sequence.begin(), toupper);
284 Sequence::load_annot(fs::path file_path, int start_index, int end_index)
286 fs::fstream data_stream(file_path, std::ios::in);
289 throw mussa_load_error("Sequence File: " + file_path.string() + " not found");
292 // so i should probably be passing the parse function some iterators
293 // but the annotations files are (currently) small, so i think i can
294 // get away with loading the whole file into memory
297 while(data_stream.good()) {
303 parse_annot(data, start_index, end_index);
306 /* If this works, yikes, this is some brain hurting code.
308 * what's going on is that when pb_annot is instantiated it stores references
309 * to begin, end, name, type, declared in the parse function, then
310 * when operator() is called it grabs values from those references
311 * and uses that to instantiate an annot object and append that to our
314 * This weirdness is because the spirit library requires that actions
315 * conform to a specific prototype operator()(IteratorT, IteratorT)
316 * which doesn't provide any useful opportunity for me to actually
317 * grab the results of our parsing.
319 * so I instantiate this structure in order to have a place to grab
323 struct push_back_annot {
324 std::list<annot>& annot_list;
330 push_back_annot(std::list<annot>& annot_list_,
335 : annot_list(annot_list_),
343 void operator()(std::string::const_iterator,
344 std::string::const_iterator) const
346 //std::cout << "adding annot: " << begin << " " << end << " " << name << " " << type << std::endl;
347 annot_list.push_back(annot(begin, end, name, type));
351 struct push_back_seq {
352 std::list<Sequence>& seq_list;
356 push_back_seq(std::list<Sequence>& seq_list_,
359 : seq_list(seq_list_),
365 void operator()(std::string::const_iterator,
366 std::string::const_iterator) const
368 // filter out newlines from our sequence
370 for(std::string::const_iterator seq_i = seq.begin();
374 if (*seq_i != '\015' && *seq_i != '\012') new_seq += *seq_i;
376 //std::cout << "adding seq: " << name << " " << new_seq << std::endl;
380 seq_list.push_back(s);
385 Sequence::parse_annot(std::string data, int start_index, int end_index)
392 std::list<Sequence> query_seqs;
394 bool status = spirit::parse(data.begin(), data.end(),
397 (+(spirit::alpha_p))[spirit::assign_a(species)] >>
398 +(spirit::space_p) >>
400 ( // parse an absolute location name
401 (spirit::uint_p[spirit::assign_a(start)] >>
403 spirit::uint_p[spirit::assign_a(end)] >>
405 (*(spirit::alpha_p|spirit::digit_p))[spirit::assign_a(name)] >>
409 (*(spirit::alpha_p))[spirit::assign_a(type)]
411 // to understand how this group gets set
412 // read the comment above struct push_back_annot
413 )[push_back_annot(annots, start, end, type, name)]
415 (spirit::ch_p('>') >>
416 (*(spirit::print_p))[spirit::assign_a(name)] >>
418 (+(spirit::chset<>(iupac_alphabet)))[spirit::assign_a(seq)]
419 )[push_back_seq(query_seqs, name, seq)]
425 spirit::space_p*/).full;
427 // go seearch for query sequences
428 find_sequences(query_seqs.begin(), query_seqs.end());
431 const std::string& Sequence::get_species() const
436 void Sequence::add_annotation(const annot& a)
441 const std::list<annot>& Sequence::annotations() const
447 Sequence::subseq(int start, int count) const
449 // there might be an off by one error with start+count > size()
450 if ( count == npos || start+count > size()) {
451 count = size()-start;
453 Sequence new_seq(std::string::substr(start, count));
454 new_seq.set_header(get_header());
455 //new_seq.set_species(get_species());
457 new_seq.motif_list = motif_list;
458 // attempt to copy & reannotate position based annotations
459 int end = start+count;
461 for(std::list<annot>::const_iterator annot_i = annots.begin();
462 annot_i != annots.end();
465 int annot_start = annot_i->start;
466 int annot_end = annot_i->end;
468 if (annot_start < end) {
469 if (annot_start >=start) {
470 annot_start -= start;
475 if (annot_end < end) {
481 annot new_annot(annot_start, annot_end, annot_i->type, annot_i->name);
482 new_seq.annots.push_back(new_annot);
490 Sequence::rev_comp() const
492 std::string rev_comp;
493 char conversionTable[257];
494 int seq_i, table_i, len;
497 rev_comp.reserve(len);
498 // make a conversion table
499 // init all parts of conversion table to '~' character
500 // '~' I doubt will ever appear in a sequence file (jeez, I hope)
501 // and may the fleas of 1000 camels infest the genitals of any biologist (and
502 // seven generations of their progeny) who decides to make it mean
503 // something special!!!
504 // PS - double the curse for any smartass non-biologist who tries it as well
505 for(table_i=0; table_i < 256; table_i++)
507 conversionTable[table_i] = '~';
509 // add end of string character for printing out table for testing purposes
510 conversionTable[256] = '\0';
512 // add in the characters for the bases we want to convert
513 conversionTable[(int)'A'] = 'T';
514 conversionTable[(int)'T'] = 'A';
515 conversionTable[(int)'G'] = 'C';
516 conversionTable[(int)'C'] = 'G';
517 conversionTable[(int)'N'] = 'N';
519 // finally, the actual conversion loop
520 for(seq_i = len - 1; seq_i >= 0; seq_i--)
522 table_i = (int) at(seq_i);
523 rev_comp += conversionTable[table_i];
529 void Sequence::set_header(std::string header_)
535 Sequence::get_header() const
540 //FIXME: i don't think this code is callable
542 Sequence::sp_name() const
559 std::string::clear();
566 Sequence::save(fs::fstream &save_file)
567 //std::string save_file_path)
570 std::list<annot>::iterator annots_i;
572 // not sure why, or if i'm doing something wrong, but can't seem to pass
573 // file pointers down to this method from the mussa control class
574 // so each call to save a sequence appends to the file started by mussa_class
575 //save_file.open(save_file_path.c_str(), std::ios::app);
577 save_file << "<Sequence>" << std::endl;
578 save_file << *this << std::endl;
579 save_file << "</Sequence>" << std::endl;
581 save_file << "<Annotations>" << std::endl;
582 save_file << species << std::endl;
583 for (annots_i = annots.begin(); annots_i != annots.end(); ++annots_i)
585 save_file << annots_i->start << " " << annots_i->end << " " ;
586 save_file << annots_i->name << " " << annots_i->type << std::endl;
588 save_file << "</Annotations>" << std::endl;
593 Sequence::load_museq(fs::path load_file_path, int seq_num)
595 fs::fstream load_file;
596 std::string file_data_line;
599 std::string::size_type space_split_i;
600 std::string annot_value;
603 load_file.open(load_file_path, std::ios::in);
606 // search for the seq_num-th sequence
607 while ( (!load_file.eof()) && (seq_counter < seq_num) )
609 getline(load_file,file_data_line);
610 if (file_data_line == "<Sequence>")
613 getline(load_file, file_data_line);
614 assign(file_data_line);
615 getline(load_file, file_data_line);
616 getline(load_file, file_data_line);
617 if (file_data_line == "<Annotations>")
619 getline(load_file, file_data_line);
620 species = file_data_line;
621 while ( (!load_file.eof()) && (file_data_line != "</Annotations>") )
623 getline(load_file,file_data_line);
624 if ((file_data_line != "") && (file_data_line != "</Annotations>"))
626 // need to get 4 values...almost same code 4 times...
627 // get annot start index
628 space_split_i = file_data_line.find(" ");
629 annot_value = file_data_line.substr(0,space_split_i);
630 an_annot.start = atoi (annot_value.c_str());
631 file_data_line = file_data_line.substr(space_split_i+1);
632 // get annot end index
633 space_split_i = file_data_line.find(" ");
634 annot_value = file_data_line.substr(0,space_split_i);
635 an_annot.end = atoi (annot_value.c_str());
637 if (space_split_i == std::string::npos) // no entry for type or name
639 std::cout << "seq, annots - no type or name\n";
643 else // else get annot type
645 file_data_line = file_data_line.substr(space_split_i+1);
646 space_split_i = file_data_line.find(" ");
647 annot_value = file_data_line.substr(0,space_split_i);
648 an_annot.type = annot_value;
649 if (space_split_i == std::string::npos) // no entry for name
651 std::cout << "seq, annots - no name\n";
654 else // get annot name
656 file_data_line = file_data_line.substr(space_split_i+1);
657 space_split_i = file_data_line.find(" ");
658 annot_value = file_data_line.substr(0,space_split_i);
659 an_annot.type = annot_value;
662 annots.push_back(an_annot); // don't forget to actually add the annot
664 //std::cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
665 // << "-->" << an_annot.type << "::" << an_annot.name << std::endl;
673 Sequence::rc_motif(std::string a_motif)
675 std::string rev_comp;
676 char conversionTable[257];
677 int seq_i, table_i, len;
679 len = a_motif.length();
680 rev_comp.reserve(len);
682 for(table_i=0; table_i < 256; table_i++)
684 conversionTable[table_i] = '~';
686 // add end of std::string character for printing out table for testing purposes
687 conversionTable[256] = '\0';
689 // add in the characters for the bases we want to convert (IUPAC)
690 conversionTable[(int)'A'] = 'T';
691 conversionTable[(int)'T'] = 'A';
692 conversionTable[(int)'G'] = 'C';
693 conversionTable[(int)'C'] = 'G';
694 conversionTable[(int)'N'] = 'N';
695 conversionTable[(int)'M'] = 'K';
696 conversionTable[(int)'R'] = 'Y';
697 conversionTable[(int)'W'] = 'W';
698 conversionTable[(int)'S'] = 'S';
699 conversionTable[(int)'Y'] = 'R';
700 conversionTable[(int)'K'] = 'M';
701 conversionTable[(int)'V'] = 'B';
702 conversionTable[(int)'H'] = 'D';
703 conversionTable[(int)'D'] = 'H';
704 conversionTable[(int)'B'] = 'V';
706 // finally, the actual conversion loop
707 for(seq_i = len - 1; seq_i >= 0; seq_i--)
709 //std::cout << "** i = " << seq_i << " bp = " <<
710 table_i = (int) a_motif[seq_i];
711 rev_comp += conversionTable[table_i];
714 //std::cout << "seq: " << a_motif << std::endl;
715 //std::cout << "rc: " << rev_comp << std::endl;
721 Sequence::motif_normalize(std::string a_motif)
723 std::string valid_motif;
726 len = a_motif.length();
727 valid_motif.reserve(len);
729 // this just upcases IUPAC symbols. Eventually should return an error if non IUPAC is present.
730 // current nonIUPAC symbols are omitted, which is not reported atm
731 for(seq_i = 0; seq_i < len; seq_i++)
733 if ((a_motif[seq_i] == 'a') || (a_motif[seq_i] == 'A'))
735 else if ((a_motif[seq_i] == 't') || (a_motif[seq_i] == 'T'))
737 else if ((a_motif[seq_i] == 'g') || (a_motif[seq_i] == 'G'))
739 else if ((a_motif[seq_i] == 'c') || (a_motif[seq_i] == 'C'))
741 else if ((a_motif[seq_i] == 'n') || (a_motif[seq_i] == 'N'))
743 else if ((a_motif[seq_i] == 'm') || (a_motif[seq_i] == 'M'))
745 else if ((a_motif[seq_i] == 'r') || (a_motif[seq_i] == 'R'))
747 else if ((a_motif[seq_i] == 'w') || (a_motif[seq_i] == 'W'))
749 else if ((a_motif[seq_i] == 's') || (a_motif[seq_i] == 'S'))
751 else if ((a_motif[seq_i] == 'y') || (a_motif[seq_i] == 'Y'))
753 else if ((a_motif[seq_i] == 'k') || (a_motif[seq_i] == 'K'))
755 else if ((a_motif[seq_i] == 'v') || (a_motif[seq_i] == 'V'))
757 else if ((a_motif[seq_i] == 'h') || (a_motif[seq_i] == 'H'))
759 else if ((a_motif[seq_i] == 'd') || (a_motif[seq_i] == 'D'))
761 else if ((a_motif[seq_i] == 'b') || (a_motif[seq_i] == 'B'))
764 std::string msg = "Letter ";
765 msg += a_motif[seq_i];
766 msg += " is not a valid IUPAC symbol";
767 throw motif_normalize_error(msg);
770 //std::cout << "valid_motif is: " << valid_motif << std::endl;
774 void Sequence::add_motif(std::string a_motif)
776 std::vector<int> motif_starts = find_motif(a_motif);
778 for(std::vector<int>::iterator motif_start_i = motif_starts.begin();
779 motif_start_i != motif_starts.end();
782 motif_list.push_back(motif(*motif_start_i, a_motif));
786 void Sequence::clear_motifs()
791 const std::list<motif>& Sequence::motifs() const
797 Sequence::find_motif(std::string a_motif)
799 std::vector<int> motif_match_starts;
800 std::string a_motif_rc;
802 motif_match_starts.clear();
804 //std::cout << "motif is: " << a_motif << std::endl;
805 a_motif = motif_normalize(a_motif);
806 //std::cout << "motif is: " << a_motif << std::endl;
810 //std::cout << "Sequence: none blank motif\n";
811 motif_scan(a_motif, &motif_match_starts);
813 a_motif_rc = rc_motif(a_motif);
814 // make sure not to do search again if it is a palindrome
815 if (a_motif_rc != a_motif)
816 motif_scan(a_motif_rc, &motif_match_starts);
818 return motif_match_starts;
822 Sequence::motif_scan(std::string a_motif, std::vector<int> * motif_match_starts)
825 std::string::size_type seq_i;
826 int motif_i, motif_len;
828 // faster to loop thru the sequence as a old c std::string (ie char array)
830 //std::cout << "Sequence: motif, seq len = " << sequence.length() << std::endl;
831 motif_len = a_motif.length();
833 //std::cout << "motif_length: " << motif_len << std::endl;
834 //std::cout << "RAAARRRRR\n";
838 //std::cout << "motif: " << a_motif << std::endl;
840 //std::cout << "Sequence: motif, length= " << length << std::endl;
842 while (seq_i < length())
844 //std::cout << seq_c[seq_i];
845 //std::cout << seq_c[seq_i] << "?" << a_motif[motif_i] << ":" << motif_i << " ";
846 // this is pretty much a straight translation of Nora's python code
847 // to match iupac letter codes
848 if (a_motif[motif_i] =='N')
850 else if (a_motif[motif_i] == seq_c[seq_i])
852 else if ((a_motif[motif_i] =='M') &&
853 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C')))
855 else if ((a_motif[motif_i] =='R') &&
856 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G')))
858 else if ((a_motif[motif_i] =='W') &&
859 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='T')))
861 else if ((a_motif[motif_i] =='S') &&
862 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G')))
864 else if ((a_motif[motif_i] =='Y') &&
865 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='T')))
867 else if ((a_motif[motif_i] =='K') &&
868 ((seq_c[seq_i]=='G') || (seq_c[seq_i]=='T')))
870 else if ((a_motif[motif_i] =='V') &&
871 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
872 (seq_c[seq_i]=='G')))
874 else if ((a_motif[seq_i] =='H') &&
875 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
876 (seq_c[seq_i]=='T')))
878 else if ((a_motif[motif_i] =='D') &&
879 ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G') ||
880 (seq_c[seq_i]=='T')))
882 else if ((a_motif[motif_i] =='B') &&
883 ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G') ||
884 (seq_c[seq_i]=='T')))
893 // end Nora stuff, now we see if a match is found this pass
894 if (motif_i == motif_len)
898 motif_match_starts->push_back(seq_i - motif_len + 1);
904 //std::cout << std::endl;
907 void Sequence::add_string_annotation(std::string a_seq,
910 std::vector<int> seq_starts = find_motif(a_seq);
912 //std::cout << "searching for " << a_seq << " found " << seq_starts.size() << std::endl;
914 for(std::vector<int>::iterator seq_start_i = seq_starts.begin();
915 seq_start_i != seq_starts.end();
918 annots.push_back(annot(*seq_start_i,
919 *seq_start_i+a_seq.size(),
925 void Sequence::find_sequences(std::list<Sequence>::iterator start,
926 std::list<Sequence>::iterator end)
928 while (start != end) {
929 add_string_annotation(*start, start->get_header());