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 // ----------------------------------------
12 // ---------- mussa_class.cc -----------
13 // ----------------------------------------
15 #include <boost/filesystem/path.hpp>
16 #include <boost/filesystem/operations.hpp>
17 #include <boost/filesystem/fstream.hpp>
18 namespace fs = boost::filesystem;
20 #include <boost/spirit/core.hpp>
21 #include <boost/spirit/actor/push_back_actor.hpp>
22 #include <boost/spirit/iterator/file_iterator.hpp>
23 #include <boost/spirit/utility/chset.hpp>
24 namespace spirit = boost::spirit;
29 #include "mussa_exceptions.hpp"
30 #include "alg/mussa.hpp"
31 #include "alg/flp.hpp"
37 : color_mapper(new AnnotationColors)
40 connect(&the_paths, SIGNAL(progress(const std::string&, int, int)),
41 this, SIGNAL(progress(const std::string&, int, int)));
44 Mussa::Mussa(const Mussa& m)
45 : analysis_name(m.analysis_name),
47 threshold(m.threshold),
48 soft_thres(m.soft_thres),
50 win_append(m.win_append),
51 thres_append(m.thres_append),
52 motif_sequences(m.motif_sequences),
53 color_mapper(m.color_mapper),
54 analysis_path(m.analysis_path),
57 connect(&the_paths, SIGNAL(progress(const std::string&, int, int)),
58 this, SIGNAL(progress(const std::string&, int, int)));
61 boost::filesystem::path Mussa::get_analysis_path() const
66 void Mussa::set_analysis_path(boost::filesystem::path pathname)
68 analysis_path = pathname;
71 // set all parameters to null state
76 ana_mode = TransitiveNway;
82 motif_sequences.clear();
83 if(color_mapper) color_mapper->clear();
86 analysis_path = fs::path();
90 bool Mussa::is_dirty() const
95 bool Mussa::empty() const
97 return the_seqs.empty();
101 // these 5 simple methods manually set the parameters for doing an analysis
102 // used so that the gui can take input from user and setup the analysis
103 // note - still need a set_append(bool, bool) method...
105 Mussa::set_name(string a_name)
107 analysis_name = a_name;
111 string Mussa::get_name() const
113 return analysis_name;
116 string Mussa::get_title() const
118 fs::path analysis_path = get_analysis_path();
119 if (not analysis_path.empty()) {
120 return analysis_path.native_file_string();
121 } else if (get_name().size() > 0) {
124 return std::string("Unnamed");
131 if (the_seqs.size() > 0)
132 return the_seqs.size();
138 Mussa::set_window(int a_window)
144 int Mussa::get_window() const
150 Mussa::set_threshold(int a_threshold)
152 threshold = a_threshold;
154 if (a_threshold > soft_thres) {
155 soft_thres = a_threshold;
159 int Mussa::get_threshold() const
165 Mussa::set_soft_threshold(int new_threshold)
167 if (new_threshold < threshold) {
168 soft_thres = threshold;
169 } else if (new_threshold > window) {
172 soft_thres = new_threshold;
176 int Mussa::get_soft_threshold() const
182 Mussa::set_analysis_mode(enum analysis_modes new_ana_mode)
184 ana_mode = new_ana_mode;
188 enum Mussa::analysis_modes Mussa::get_analysis_mode() const
193 string Mussa::get_analysis_mode_name() const
198 return string("Transitive");
201 return string("Radial");
204 return string("Entropy");
207 return string("[deprecated] Recursive");
210 throw runtime_error("invalid analysis mode type");
215 const NwayPaths& Mussa::paths() const
220 //template <class IteratorT>
221 //void Mussa::createLocalAlignment(IteratorT begin, IteratorT end)
222 void Mussa::createLocalAlignment(std::list<ConservedPath>::iterator begin,
223 std::list<ConservedPath>::iterator end,
224 std::list<ConservedPath::path_type>& result,
225 std::list<std::vector<bool> >& reversed)
227 const vector_sequence_type& raw_seq = the_seqs;
228 ConservedPath::path_type aligned_path;
231 int window_length, win_i;
234 vector<bool> rc_list;
236 vector<bool> matched;
240 for(std::list<ConservedPath>::iterator pathz_i=begin; pathz_i != end; ++pathz_i)
242 ConservedPath& a_path = *pathz_i;
243 window_length = a_path.window_size;
244 // determine which parts of the path are RC relative to first species
245 rc_list = a_path.reverseComplimented();
247 // loop over each bp in the conserved region for all sequences
248 for(win_i = 0; win_i < window_length; win_i++)
250 aligned_path.clear();
251 // determine which exact base pairs match between the sequences
253 for(i2 = 0; i2 < a_path.size()-1; i2++)
255 // assume not rc as most likely, adjust below
258 // no matter the case, any RC node needs adjustments
260 rc_1 = window_length-1;
261 if (a_path[i2+1] < 0)
262 rc_2 = window_length-1;
264 x_start = (abs(a_path[i2]-rc_1+win_i));
265 x_end = (abs(a_path[i2+1]-rc_2+win_i));
267 boost::shared_ptr<Sequence> cur(raw_seq[i2]) ;
268 boost::shared_ptr<Sequence> next(raw_seq[i2+1]);
270 // ugh, and xor...only want rc coloring if just one of the nodes is rc
271 // if both nodes are rc, then they are 'normal' relative to each other
272 if((rc_list[i2] || rc_list[i2+1] )&&!(rc_list[i2] && rc_list[i2+1]))
273 { //the hideous rc matching logic - not complex, but annoying
274 if(!(( ((*cur)[x_start]=='A')&&((*next)[x_end]=='T')) ||
275 (((*cur)[x_start]=='T')&&((*next)[x_end]=='A')) ||
276 (((*cur)[x_start]=='G')&&((*next)[x_end]=='C')) ||
277 (((*cur)[x_start]=='C')&&((*next)[x_end]=='G'))) )
281 aligned_path.push_back(x_start);
286 if (!( ((*cur)[x_start] == (*next)[x_end]) &&
287 ((*cur)[x_start] != 'N') && ((*next)[x_end] != 'N') ) ) {
290 aligned_path.push_back(x_start);
294 // grab the last part of our path, assuming we matched
296 aligned_path.push_back(x_end);
298 if (aligned_path.size() == a_path.size()) {
299 result.push_back(aligned_path);
300 reversed.push_back(rc_list);
308 void Mussa::append_sequence(const Sequence& a_seq)
310 boost::shared_ptr<Sequence> seq_copy(new Sequence(a_seq));
311 the_seqs.push_back(seq_copy);
315 void Mussa::append_sequence(boost::shared_ptr<Sequence> a_seq)
317 the_seqs.push_back(a_seq);
322 const vector<boost::shared_ptr<Sequence> >&
323 Mussa::sequences() const
328 void Mussa::load_sequence(fs::path seq_file, fs::path annot_file,
329 int fasta_index, int sub_seq_start, int sub_seq_end,
332 boost::shared_ptr<Sequence> aseq(new Sequence);
333 aseq->load_fasta(seq_file, fasta_index, sub_seq_start, sub_seq_end);
334 if ( not annot_file.empty() ) {
335 aseq->load_annot(annot_file, sub_seq_start, sub_seq_end);
337 if (name != 0 and name->size() > 0 ) {
338 aseq->set_species(*name);
340 the_seqs.push_back(aseq);
345 Mussa::load_mupa_file(fs::path para_file_path)
347 fs::ifstream para_file;
348 string file_data_line;
351 int split_index, fasta_index;
352 int sub_seq_start, sub_seq_end;
353 bool seq_params, did_seq;
356 string::size_type new_index, dir_index;
361 // if file was opened, read the parameter values
362 if (not fs::exists(para_file_path))
364 throw mussa_load_error("Config File: " + para_file_path.string() + " not found");
365 } else if (fs::is_directory(para_file_path)) {
366 throw mussa_load_error("Config File: " + para_file_path.string() + " is a directory.");
367 } else if (fs::is_empty(para_file_path)) {
368 throw mussa_load_error("Config File: " + para_file_path.string() + " is empty");
370 para_file.open(para_file_path, ios::in);
372 // what directory is the mupa file in?
373 fs::path file_path_base = para_file_path.branch_path();
375 // setup loop by getting file's first line
376 getline(para_file,file_data_line);
377 split_index = file_data_line.find(" ");
378 param = file_data_line.substr(0,split_index);
379 value = file_data_line.substr(split_index+1);
384 if (param == "ANA_NAME")
385 analysis_name = value;
386 else if (param == "APPEND_WIN")
388 else if (param == "APPEND_THRES")
390 else if (param == "SEQUENCE_NUM")
391 ; // ignore sequence_num now
392 else if (param == "WINDOW")
393 window = atoi(value.c_str());
394 else if (param == "THRESHOLD")
395 threshold = atoi(value.c_str());
396 else if (param == "SEQUENCE")
398 fs::path seq_file = file_path_base / value;
399 //cout << "seq_file_name " << seq_files.back() << endl;
406 while (para_file && seq_params)
408 getline(para_file,file_data_line);
409 split_index = file_data_line.find(" ");
410 param = file_data_line.substr(0,split_index);
411 value = file_data_line.substr(split_index+1);
413 if (param == "FASTA_INDEX")
414 fasta_index = atoi(value.c_str());
415 else if (param == "ANNOTATION")
416 annot_file = file_path_base / value;
417 else if (param == "SEQ_START")
418 sub_seq_start = atoi(value.c_str());
419 else if (param == "SEQ_END")
421 sub_seq_end = atoi(value.c_str());
423 //ignore empty lines or that start with '#'
424 else if ((param == "") || (param == "#")) {}
425 else seq_params = false;
427 load_sequence(seq_file, annot_file, fasta_index, sub_seq_start,
431 //ignore empty lines or that start with '#'
432 else if ((param == "") || (param == "#")) {}
435 clog << "Illegal/misplaced mussa parameter in file\n";
436 clog << param << "\n";
441 getline(para_file,file_data_line);
442 split_index = file_data_line.find(" ");
443 param = file_data_line.substr(0,split_index);
444 value = file_data_line.substr(split_index+1);
451 soft_thres = threshold;
452 //cout << "nway mupa: analysis_name = " << analysis_name
453 // << " window = " << window
454 // << " threshold = " << threshold << endl;
456 // no file was loaded, signal error
464 if (the_seqs.size() < 2) {
465 throw mussa_analysis_error("you need to have at least 2 sequences to "
470 the_paths.setup(window, threshold);
477 vector<int> seq_lens;
478 vector<FLPs> empty_FLP_vector;
480 string save_file_string;
482 empty_FLP_vector.clear();
483 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
485 all_comps.push_back(empty_FLP_vector);
486 for(vector<Sequence>::size_type i2 = 0; i2 < the_seqs.size(); i2++)
487 all_comps[i].push_back(dummy_comp);
489 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
490 seq_lens.push_back(the_seqs[i]->size());
492 int seqcomps_done = 0;
493 int seqcomps_todo = (the_seqs.size() * (the_seqs.size()-1)) / 2;
494 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
496 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
497 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
499 //cout << "seqcomping: " << i << " v. " << i2 << endl;
500 all_comps[i][i2].setup(window, threshold);
501 all_comps[i][i2].seqcomp(*the_seqs[i], *the_seqs[i2], false);
502 all_comps[i][i2].seqcomp(*the_seqs[i], the_seqs[i2]->rev_comp(),true);
504 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
512 the_paths.set_soft_threshold(soft_thres);
514 if (ana_mode == TransitiveNway) {
515 the_paths.trans_path_search(all_comps);
517 else if (ana_mode == RadialNway) {
518 the_paths.radiate_path_search(all_comps);
520 else if (ana_mode == EntropyNway)
522 vector<Sequence> some_Seqs;
523 //unlike other methods, entropy needs to look at the sequence at this stage
525 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
527 some_Seqs.push_back(*the_seqs[i]);
530 the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
531 the_paths.entropy_path_search(all_comps);
534 // old recursive transitive analysis function
535 else if (ana_mode == RecursiveNway)
536 the_paths.find_paths_r(all_comps);
538 the_paths.simple_refine();
542 Mussa::save(fs::path save_path)
544 fs::fstream save_file;
545 ostringstream append_info;
546 int dir_create_status;
548 if (save_path.empty()) {
549 if (not analysis_path.empty()) {
550 save_path = analysis_path;
551 } else if (not analysis_name.empty()) {
552 std::string save_name = analysis_name;
553 // gotta do bit with adding win & thres if to be appended
556 append_info << "_w" << window;
557 save_name += append_info.str();
562 append_info << "_t" << threshold;
563 save_name += append_info.str();
565 save_path = save_name;
567 throw mussa_save_error("Need filename or analysis name to save");
571 if (not fs::exists(save_path)) {
572 fs::create_directory(save_path);
575 std::string basename = save_path.leaf();
576 fs::path museq(basename + ".museq", fs::native);
578 // save sequence and annots to a special mussa file
579 save_file.open(save_path / museq, ios::out);
580 save_file << "<Mussa_Sequence>" << endl;
582 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
584 the_seqs[i]->save(save_file);
587 save_file << "</Mussa_Sequence>" << endl;
590 // if we have any motifs, save them.
591 if (motif_sequences.size()) {
592 fs::path mtl(basename + ".mtl", fs::native);
593 save_motifs(save_path / mtl);
596 // save nway paths to its mussa save file
597 fs::path muway(basename + ".muway", fs::native);
598 the_paths.save(save_path / muway);
600 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
601 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
604 append_info << "_sp_" << i << "v" << i2;
605 fs::path flp(basename+append_info.str()+".flp", fs::native);
606 all_comps[i][i2].save(save_path / flp);
611 analysis_path = save_path;
615 Mussa::save_muway(fs::path save_path)
617 the_paths.save(save_path);
621 Mussa::load(fs::path ana_file)
624 fs::path file_path_base;
625 fs::path a_file_path;
626 fs::path ana_path(ana_file);
629 ostringstream append_info;
630 vector<FLPs> empty_FLP_vector;
633 analysis_path = ana_file;
634 analysis_name = ana_path.leaf();
635 file_path_base = ana_path.branch_path() / analysis_name;
636 a_file_path = file_path_base / (analysis_name + ".muway");
637 the_paths.load(a_file_path);
638 // perhaps this could be more elegent, but at least this'll let
639 // us know what our threshold and window sizes were when we load a muway
640 window = the_paths.get_window();
641 threshold = the_paths.get_threshold();
642 soft_thres = threshold;
644 int seq_num = the_paths.sequence_count();
646 a_file_path = file_path_base / (analysis_name + ".museq");
648 // this is a bit of a hack due to C++ not acting like it should with files
649 for (i = 1; i <= seq_num; i++)
651 boost::shared_ptr<Sequence> tmp_seq(new Sequence);
652 tmp_seq->load_museq(a_file_path, i);
653 the_seqs.push_back(tmp_seq);
656 fs::path motif_file = file_path_base / (analysis_name + ".mtl");
657 if (fs::exists(motif_file)) {
658 load_motifs(motif_file);
660 empty_FLP_vector.clear();
661 for(i = 0; i < seq_num; i++)
663 all_comps.push_back(empty_FLP_vector);
664 for(i2 = 0; i2 < seq_num; i2++)
665 all_comps[i].push_back(dummy_comp);
668 for(i = 0; i < seq_num; i++)
670 for(i2 = i+1; i2 < seq_num; i2++)
673 append_info << analysis_name << "_sp_" << i << "v" << i2 << ".flp";
674 //clog << append_info.str() << endl;
675 a_file_path = file_path_base / append_info.str();
676 //clog << "path " << a_file_path.string() << endl;
677 all_comps[i][i2].load(a_file_path);
678 //clog << "real size = " << all_comps[i][i2].size() << endl;
687 fs::fstream save_file;
689 save_file.open(analysis_name, ios::out);
691 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
692 save_file << *(the_seqs[i]) << endl;
694 save_file << window << endl;
696 //note more complex eventually since analysis_name may need to have
697 //window size, threshold and other stuff to modify it...
698 the_paths.save_old(analysis_name);
703 Mussa::load_old(char * load_file_path, int s_num)
706 string file_data_line;
707 int i, space_split_i, comma_split_i;
708 vector<int> loaded_path;
709 string node_pair, node;
713 the_paths.setup(0, 0);
714 save_file.open(load_file_path, ios::in);
716 // currently loads old mussa format
719 for(i = 0; i < seq_num; i++)
721 getline(save_file, file_data_line);
722 boost::shared_ptr<Sequence> a_seq(new Sequence(file_data_line));
723 the_seqs.push_back(a_seq);
727 getline(save_file, file_data_line);
728 window = atoi(file_data_line.c_str());
731 while (!save_file.eof())
734 getline(save_file, file_data_line);
735 if (file_data_line != "")
736 for(i = 0; i < seq_num; i++)
738 space_split_i = file_data_line.find(" ");
739 node_pair = file_data_line.substr(0,space_split_i);
740 //cout << "np= " << node_pair;
741 comma_split_i = node_pair.find(",");
742 node = node_pair.substr(comma_split_i+1);
743 //cout << "n= " << node << " ";
744 loaded_path.push_back(atoi (node.c_str()));
745 file_data_line = file_data_line.substr(space_split_i+1);
748 // FIXME: do we have any information about what the threshold should be?
749 the_paths.add_path(0, loaded_path);
753 //the_paths.save("tmp.save");
756 void Mussa::add_motif(const Sequence& motif, const Color& color)
758 motif_sequences.insert(motif);
759 color_mapper->appendInstanceColor("motif", motif.get_sequence(), color);
763 void Mussa::set_motifs(const vector<Sequence>& motifs,
764 const vector<Color>& colors)
766 if (motifs.size() != colors.size()) {
767 throw mussa_error("motif and color vectors must be the same size");
770 motif_sequences.clear();
771 for(size_t i = 0; i != motifs.size(); ++i)
773 add_motif(motifs[i], colors[i]);
775 update_sequences_motifs();
778 // Helper functor to append created motifs to our Mussa analysis
779 struct push_back_motif {
780 Mussa::motif_set& motifs;
781 boost::shared_ptr<AnnotationColors> color_mapper;
782 std::string& seq_string;
790 push_back_motif(Mussa::motif_set& motifs_,
791 boost::shared_ptr<AnnotationColors> color_mapper_,
794 float &red_, float &green_, float &blue_, float &alpha_,
797 color_mapper(color_mapper_),
808 void operator()(std::string::const_iterator,
809 std::string::const_iterator) const
811 Sequence seq(seq_string, Sequence::nucleic_alphabet);
812 // shouldn't we have a better field than "fasta header" and speices?
813 seq.set_fasta_header(name);
814 // we need to clear the name in case the next motif doesn't have one.
816 // be nice if glsequence was a subclass of sequence so we could
817 // just attach colors directly to the motif.
818 Color c(red, green, blue, alpha);
819 color_mapper->appendInstanceColor("motif", seq.c_str(), c);
826 void Mussa::load_motifs(fs::path filename)
829 f.open(filename, ifstream::in);
833 // I mostly split the ifstream out so I can use a stringstream to test it.
834 void Mussa::load_motifs(std::istream &in)
837 const char *alphabet = Alphabet::nucleic_alphabet.c_str();
846 // slurp our data into a string
847 std::streamsize bytes_read = 1;
848 while (in.good() and bytes_read) {
849 const std::streamsize bufsiz=512;
851 bytes_read = in.readsome(buf, bufsiz);
852 data.append(buf, buf+bytes_read);
855 bool ok = spirit::parse(data.begin(), data.end(),
859 (+spirit::chset<>(alphabet))[spirit::assign_a(seq)] >>
864 // names can either be letter followed by non-space characters
865 (spirit::alpha_p >> *spirit::graph_p)[spirit::assign_a(name)]
867 // or a quoted string
870 (+(~spirit::ch_p('"')))[spirit::assign_a(name)] >>
873 ) >> +spirit::space_p
875 spirit::real_p[spirit::assign_a(red)] >> +spirit::space_p >>
876 spirit::real_p[spirit::assign_a(green)] >> +spirit::space_p >>
877 spirit::real_p[spirit::assign_a(blue)] >> +spirit::space_p >>
878 !(spirit::real_p[spirit::assign_a(alpha)] >> +spirit::space_p)
879 )[push_back_motif(motif_sequences, color_mapper, seq, name, red, green, blue, alpha, parsed)]
883 msg << "Error parsing motif #" << parsed;
884 // erase our potentially broken motif list
885 motif_sequences.clear();
886 throw motif_load_error(msg.str());
888 update_sequences_motifs();
891 void Mussa::save_motifs(fs::path filename)
893 fs::ofstream out_stream;
894 out_stream.open(filename, ofstream::out);
895 save_motifs(out_stream);
898 void Mussa::save_motifs(std::ostream& out)
900 for(motif_set::iterator motif_i = motif_sequences.begin();
901 motif_i != motif_sequences.end();
904 out << motif_i->get_sequence() << " ";
905 if (motif_i->get_name().size() > 0) {
906 out << "\"" << motif_i->get_name() << "\" ";
908 out << color_mapper->lookup("motif", motif_i->get_sequence());
913 void Mussa::update_sequences_motifs()
915 // once we've loaded all the motifs from the file,
916 // lets attach them to the sequences
917 for(vector<boost::shared_ptr<Sequence> >::iterator seq_i = the_seqs.begin();
918 seq_i != the_seqs.end();
921 // clear out old motifs
922 (*seq_i)->clear_motifs();
923 // for all the motifs in our set, attach them to the current sequence
924 for(set<Sequence>::iterator motif_i = motif_sequences.begin();
925 motif_i != motif_sequences.end();
928 (*seq_i)->add_motif(*motif_i);
933 const set<Sequence>& Mussa::motifs() const
935 return motif_sequences;
938 boost::shared_ptr<AnnotationColors> Mussa::colorMapper()