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/operations.hpp>
16 #include <boost/filesystem/fstream.hpp>
17 namespace fs = boost::filesystem;
19 #include <boost/spirit/core.hpp>
20 #include <boost/spirit/actor/push_back_actor.hpp>
21 #include <boost/spirit/iterator/file_iterator.hpp>
22 #include <boost/spirit/utility/chset.hpp>
23 namespace spirit = boost::spirit;
28 #include "mussa_exceptions.hpp"
29 #include "alg/mussa.hpp"
30 #include "alg/flp.hpp"
36 : color_mapper(new AnnotationColors)
39 connect(&the_paths, SIGNAL(progress(const std::string&, int, int)),
40 this, SIGNAL(progress(const std::string&, int, int)));
43 Mussa::Mussa(const Mussa& m)
44 : analysis_name(m.analysis_name),
46 threshold(m.threshold),
47 soft_thres(m.soft_thres),
49 win_append(m.win_append),
50 thres_append(m.thres_append),
51 motif_sequences(m.motif_sequences),
52 color_mapper(m.color_mapper),
53 analysis_path(m.analysis_path),
56 connect(&the_paths, SIGNAL(progress(const std::string&, int, int)),
57 this, SIGNAL(progress(const std::string&, int, int)));
60 boost::filesystem::path Mussa::get_analysis_path() const
65 // set all parameters to null state
70 ana_mode = TransitiveNway;
76 motif_sequences.clear();
77 if(color_mapper) color_mapper->clear();
80 analysis_path = fs::path();
84 bool Mussa::is_dirty() const
89 bool Mussa::empty() const
91 return the_seqs.empty();
95 // these 5 simple methods manually set the parameters for doing an analysis
96 // used so that the gui can take input from user and setup the analysis
97 // note - still need a set_append(bool, bool) method...
99 Mussa::set_name(string a_name)
101 analysis_name = a_name;
105 string Mussa::get_name()
107 return analysis_name;
113 if (the_seqs.size() > 0)
114 return the_seqs.size();
120 Mussa::set_window(int a_window)
126 int Mussa::get_window() const
132 Mussa::set_threshold(int a_threshold)
134 threshold = a_threshold;
136 if (a_threshold > soft_thres) {
137 soft_thres = a_threshold;
141 int Mussa::get_threshold() const
147 Mussa::set_soft_threshold(int new_threshold)
149 if (new_threshold < threshold) {
150 soft_thres = threshold;
151 } else if (new_threshold > window) {
154 soft_thres = new_threshold;
158 int Mussa::get_soft_threshold() const
164 Mussa::set_analysis_mode(enum analysis_modes new_ana_mode)
166 ana_mode = new_ana_mode;
170 enum Mussa::analysis_modes Mussa::get_analysis_mode() const
175 string Mussa::get_analysis_mode_name() const
180 return string("Transitive");
183 return string("Radial");
186 return string("Entropy");
189 return string("[deprecated] Recursive");
192 throw runtime_error("invalid analysis mode type");
197 const NwayPaths& Mussa::paths() const
202 //template <class IteratorT>
203 //void Mussa::createLocalAlignment(IteratorT begin, IteratorT end)
204 void Mussa::createLocalAlignment(std::list<ConservedPath>::iterator begin,
205 std::list<ConservedPath>::iterator end,
206 std::list<ConservedPath::path_type>& result,
207 std::list<std::vector<bool> >& reversed)
209 const vector_sequence_type& raw_seq = the_seqs;
210 ConservedPath::path_type aligned_path;
213 int window_length, win_i;
216 vector<bool> rc_list;
218 vector<bool> matched;
222 for(std::list<ConservedPath>::iterator pathz_i=begin; pathz_i != end; ++pathz_i)
224 ConservedPath& a_path = *pathz_i;
225 window_length = a_path.window_size;
226 // determine which parts of the path are RC relative to first species
227 rc_list = a_path.reverseComplimented();
229 // loop over each bp in the conserved region for all sequences
230 for(win_i = 0; win_i < window_length; win_i++)
232 aligned_path.clear();
233 // determine which exact base pairs match between the sequences
235 for(i2 = 0; i2 < a_path.size()-1; i2++)
237 // assume not rc as most likely, adjust below
240 // no matter the case, any RC node needs adjustments
242 rc_1 = window_length-1;
243 if (a_path[i2+1] < 0)
244 rc_2 = window_length-1;
246 x_start = (abs(a_path[i2]-rc_1+win_i));
247 x_end = (abs(a_path[i2+1]-rc_2+win_i));
249 boost::shared_ptr<Sequence> cur(raw_seq[i2]) ;
250 boost::shared_ptr<Sequence> next(raw_seq[i2+1]);
252 // ugh, and xor...only want rc coloring if just one of the nodes is rc
253 // if both nodes are rc, then they are 'normal' relative to each other
254 if((rc_list[i2] || rc_list[i2+1] )&&!(rc_list[i2] && rc_list[i2+1]))
255 { //the hideous rc matching logic - not complex, but annoying
256 if(!(( ((*cur)[x_start]=='A')&&((*next)[x_end]=='T')) ||
257 (((*cur)[x_start]=='T')&&((*next)[x_end]=='A')) ||
258 (((*cur)[x_start]=='G')&&((*next)[x_end]=='C')) ||
259 (((*cur)[x_start]=='C')&&((*next)[x_end]=='G'))) )
263 aligned_path.push_back(x_start);
268 if (!( ((*cur)[x_start] == (*next)[x_end]) &&
269 ((*cur)[x_start] != 'N') && ((*next)[x_end] != 'N') ) ) {
272 aligned_path.push_back(x_start);
276 // grab the last part of our path, assuming we matched
278 aligned_path.push_back(x_end);
280 if (aligned_path.size() == a_path.size()) {
281 result.push_back(aligned_path);
282 reversed.push_back(rc_list);
290 void Mussa::append_sequence(const Sequence& a_seq)
292 boost::shared_ptr<Sequence> seq_copy(new Sequence(a_seq));
293 the_seqs.push_back(seq_copy);
297 void Mussa::append_sequence(boost::shared_ptr<Sequence> a_seq)
299 the_seqs.push_back(a_seq);
304 const vector<boost::shared_ptr<Sequence> >&
305 Mussa::sequences() const
310 void Mussa::load_sequence(fs::path seq_file, fs::path annot_file,
311 int fasta_index, int sub_seq_start, int sub_seq_end,
314 boost::shared_ptr<Sequence> aseq(new Sequence);
315 aseq->load_fasta(seq_file, fasta_index, sub_seq_start, sub_seq_end);
316 if ( not annot_file.empty() ) {
317 aseq->load_annot(annot_file, sub_seq_start, sub_seq_end);
319 if (name != 0 and name->size() > 0 ) {
320 aseq->set_species(*name);
322 the_seqs.push_back(aseq);
327 Mussa::load_mupa_file(fs::path para_file_path)
329 fs::ifstream para_file;
330 string file_data_line;
333 int split_index, fasta_index;
334 int sub_seq_start, sub_seq_end;
335 bool seq_params, did_seq;
338 string::size_type new_index, dir_index;
343 // if file was opened, read the parameter values
344 if (not fs::exists(para_file_path))
346 throw mussa_load_error("Config File: " + para_file_path.string() + " not found");
347 } else if (fs::is_directory(para_file_path)) {
348 throw mussa_load_error("Config File: " + para_file_path.string() + " is a directory.");
349 } else if (fs::is_empty(para_file_path)) {
350 throw mussa_load_error("Config File: " + para_file_path.string() + " is empty");
352 para_file.open(para_file_path, ios::in);
354 // what directory is the mupa file in?
355 fs::path file_path_base = para_file_path.branch_path();
357 // setup loop by getting file's first line
358 getline(para_file,file_data_line);
359 split_index = file_data_line.find(" ");
360 param = file_data_line.substr(0,split_index);
361 value = file_data_line.substr(split_index+1);
366 if (param == "ANA_NAME")
367 analysis_name = value;
368 else if (param == "APPEND_WIN")
370 else if (param == "APPEND_THRES")
372 else if (param == "SEQUENCE_NUM")
373 ; // ignore sequence_num now
374 else if (param == "WINDOW")
375 window = atoi(value.c_str());
376 else if (param == "THRESHOLD")
377 threshold = atoi(value.c_str());
378 else if (param == "SEQUENCE")
380 fs::path seq_file = file_path_base / value;
381 //cout << "seq_file_name " << seq_files.back() << endl;
388 while (para_file && seq_params)
390 getline(para_file,file_data_line);
391 split_index = file_data_line.find(" ");
392 param = file_data_line.substr(0,split_index);
393 value = file_data_line.substr(split_index+1);
395 if (param == "FASTA_INDEX")
396 fasta_index = atoi(value.c_str());
397 else if (param == "ANNOTATION")
398 annot_file = file_path_base / value;
399 else if (param == "SEQ_START")
400 sub_seq_start = atoi(value.c_str());
401 else if (param == "SEQ_END")
403 sub_seq_end = atoi(value.c_str());
405 //ignore empty lines or that start with '#'
406 else if ((param == "") || (param == "#")) {}
407 else seq_params = false;
409 load_sequence(seq_file, annot_file, fasta_index, sub_seq_start,
413 //ignore empty lines or that start with '#'
414 else if ((param == "") || (param == "#")) {}
417 clog << "Illegal/misplaced mussa parameter in file\n";
418 clog << param << "\n";
423 getline(para_file,file_data_line);
424 split_index = file_data_line.find(" ");
425 param = file_data_line.substr(0,split_index);
426 value = file_data_line.substr(split_index+1);
433 soft_thres = threshold;
434 //cout << "nway mupa: analysis_name = " << analysis_name
435 // << " window = " << window
436 // << " threshold = " << threshold << endl;
438 // no file was loaded, signal error
446 if (the_seqs.size() < 2) {
447 throw mussa_analysis_error("you need to have at least 2 sequences to "
450 //cout << "nway ana: seq_num = " << the_seqs.size() << endl;
453 the_paths.setup(window, threshold);
460 vector<int> seq_lens;
461 vector<FLPs> empty_FLP_vector;
463 string save_file_string;
465 empty_FLP_vector.clear();
466 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
468 all_comps.push_back(empty_FLP_vector);
469 for(vector<Sequence>::size_type i2 = 0; i2 < the_seqs.size(); i2++)
470 all_comps[i].push_back(dummy_comp);
472 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
473 seq_lens.push_back(the_seqs[i]->size());
475 int seqcomps_done = 0;
476 int seqcomps_todo = (the_seqs.size() * (the_seqs.size()-1)) / 2;
477 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
479 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
480 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
482 //cout << "seqcomping: " << i << " v. " << i2 << endl;
483 all_comps[i][i2].setup(window, threshold);
484 all_comps[i][i2].seqcomp(*the_seqs[i], *the_seqs[i2], false);
485 all_comps[i][i2].seqcomp(*the_seqs[i], the_seqs[i2]->rev_comp(),true);
487 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
495 the_paths.set_soft_threshold(soft_thres);
497 if (ana_mode == TransitiveNway) {
498 the_paths.trans_path_search(all_comps);
500 else if (ana_mode == RadialNway) {
501 the_paths.radiate_path_search(all_comps);
503 else if (ana_mode == EntropyNway)
505 vector<Sequence> some_Seqs;
506 //unlike other methods, entropy needs to look at the sequence at this stage
508 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
510 some_Seqs.push_back(*the_seqs[i]);
513 the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
514 the_paths.entropy_path_search(all_comps);
517 // old recursive transitive analysis function
518 else if (ana_mode == RecursiveNway)
519 the_paths.find_paths_r(all_comps);
521 the_paths.simple_refine();
525 Mussa::save(fs::path save_path)
527 fs::path flp_filepath;
528 fs::fstream save_file;
529 ostringstream append_info;
530 int dir_create_status;
532 if (save_path.empty()) {
533 if (not analysis_path.empty()) {
534 save_path = analysis_path;
535 } else if (not analysis_name.empty()) {
536 std::string save_name = analysis_name;
537 // gotta do bit with adding win & thres if to be appended
540 append_info << "_w" << window;
541 save_name += append_info.str();
546 append_info << "_t" << threshold;
547 save_name += append_info.str();
549 save_path = save_name;
551 throw mussa_save_error("Need filename or analysis name to save");
555 if (not fs::exists(save_path)) {
556 fs::create_directory(save_path);
558 // save sequence and annots to a special mussa file
559 save_file.open(save_path / (save_path.leaf()+".museq"), ios::out);
560 save_file << "<Mussa_Sequence>" << endl;
562 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
564 the_seqs[i]->save(save_file);
567 save_file << "</Mussa_Sequence>" << endl;
570 // save nway paths to its mussa save file
571 the_paths.save(save_path / (save_path.leaf()+ ".muway"));
573 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
574 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
577 append_info << "_sp_" << i << "v" << i2;
578 all_comps[i][i2].save(save_path/(save_path.leaf()+append_info.str()+".flp"));
582 analysis_path = save_path;
586 Mussa::save_muway(fs::path save_path)
588 the_paths.save(save_path);
592 Mussa::load(fs::path ana_file)
595 fs::path file_path_base;
596 fs::path a_file_path;
597 fs::path ana_path(ana_file);
600 ostringstream append_info;
601 vector<FLPs> empty_FLP_vector;
604 analysis_path = ana_file;
605 //clog << "ana_file name " << ana_file.string() << endl;
606 analysis_name = ana_path.leaf();
607 //clog << " ana_name " << analysis_name << endl;
608 file_path_base = ana_path.branch_path() / analysis_name;
609 a_file_path = file_path_base / (analysis_name + ".muway");
610 //clog << " loading museq: " << a_file_path.string() << endl;
611 the_paths.load(a_file_path);
612 // perhaps this could be more elegent, but at least this'll let
613 // us know what our threshold and window sizes were when we load a muway
614 window = the_paths.get_window();
615 threshold = the_paths.get_threshold();
616 soft_thres = threshold;
618 int seq_num = the_paths.sequence_count();
620 a_file_path = file_path_base / (analysis_name + ".museq");
622 // this is a bit of a hack due to C++ not acting like it should with files
623 for (i = 1; i <= seq_num; i++)
625 boost::shared_ptr<Sequence> tmp_seq(new Sequence);
626 //clog << "mussa_class: loading museq frag... " << a_file_path.string() << endl;
627 tmp_seq->load_museq(a_file_path, i);
628 the_seqs.push_back(tmp_seq);
631 empty_FLP_vector.clear();
632 for(i = 0; i < seq_num; i++)
634 all_comps.push_back(empty_FLP_vector);
635 for(i2 = 0; i2 < seq_num; i2++)
636 all_comps[i].push_back(dummy_comp);
639 for(i = 0; i < seq_num; i++)
641 for(i2 = i+1; i2 < seq_num; i2++)
644 append_info << analysis_name << "_sp_" << i << "v" << i2 << ".flp";
645 //clog << append_info.str() << endl;
646 a_file_path = file_path_base / append_info.str();
647 //clog << "path " << a_file_path.string() << endl;
648 all_comps[i][i2].load(a_file_path);
649 //clog << "real size = " << all_comps[i][i2].size() << endl;
658 fs::fstream save_file;
660 save_file.open(analysis_name, ios::out);
662 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
663 save_file << *(the_seqs[i]) << endl;
665 save_file << window << endl;
667 //note more complex eventually since analysis_name may need to have
668 //window size, threshold and other stuff to modify it...
669 the_paths.save_old(analysis_name);
674 Mussa::load_old(char * load_file_path, int s_num)
677 string file_data_line;
678 int i, space_split_i, comma_split_i;
679 vector<int> loaded_path;
680 string node_pair, node;
684 the_paths.setup(0, 0);
685 save_file.open(load_file_path, ios::in);
687 // currently loads old mussa format
690 for(i = 0; i < seq_num; i++)
692 getline(save_file, file_data_line);
693 boost::shared_ptr<Sequence> a_seq(new Sequence(file_data_line));
694 the_seqs.push_back(a_seq);
698 getline(save_file, file_data_line);
699 window = atoi(file_data_line.c_str());
702 while (!save_file.eof())
705 getline(save_file, file_data_line);
706 if (file_data_line != "")
707 for(i = 0; i < seq_num; i++)
709 space_split_i = file_data_line.find(" ");
710 node_pair = file_data_line.substr(0,space_split_i);
711 //cout << "np= " << node_pair;
712 comma_split_i = node_pair.find(",");
713 node = node_pair.substr(comma_split_i+1);
714 //cout << "n= " << node << " ";
715 loaded_path.push_back(atoi (node.c_str()));
716 file_data_line = file_data_line.substr(space_split_i+1);
719 // FIXME: do we have any information about what the threshold should be?
720 the_paths.add_path(0, loaded_path);
724 //the_paths.save("tmp.save");
727 void Mussa::add_motif(const Sequence& motif, const Color& color)
729 motif_sequences.insert(motif);
730 color_mapper->appendInstanceColor("motif", motif.get_sequence(), color);
733 void Mussa::set_motifs(const vector<Sequence>& motifs,
734 const vector<Color>& colors)
736 if (motifs.size() != colors.size()) {
737 throw mussa_error("motif and color vectors must be the same size");
740 motif_sequences.clear();
741 for(size_t i = 0; i != motifs.size(); ++i)
743 add_motif(motifs[i], colors[i]);
745 update_sequences_motifs();
749 // Helper functor to append created motifs to our Mussa analysis
750 struct push_back_motif {
751 std::set<Sequence>& motif_set;
752 boost::shared_ptr<AnnotationColors> color_mapper;
753 std::string& seq_string;
759 push_back_motif(std::set<Sequence>& motif_set_,
760 boost::shared_ptr<AnnotationColors> color_mapper_,
763 float red_, float green_, float blue_)
764 : motif_set(motif_set_),
765 color_mapper(color_mapper_),
774 void operator()(std::string::const_iterator,
775 std::string::const_iterator) const
777 //std::cout << "motif: " << seq_string << "/" << name << endl;
779 Sequence seq(seq_string);
780 // shouldn't we have a better field than "fasta header" and speices?
781 seq.set_fasta_header(name);
782 // we need to clear the name in case the next motif doesn't have one.
784 // be nice if glsequence was a subclass of sequence so we could
785 // just attach colors directly to the motif.
786 Color c(red, green, blue);
787 color_mapper->appendInstanceColor("motif", seq.c_str(), c);
788 motif_set.insert(seq);
792 // I mostly split the ifstream out so I can use a stringstream to test it.
793 void Mussa::load_motifs(std::istream &in)
796 const char *alphabet = Sequence::nucleic_iupac_alphabet.c_str();
803 // slurp our data into a string
804 std::streamsize bytes_read = 1;
805 while (in.good() and bytes_read) {
806 const std::streamsize bufsiz=512;
808 bytes_read = in.readsome(buf, bufsiz);
809 data.append(buf, buf+bytes_read);
812 bool status = spirit::parse(data.begin(), data.end(),
816 (+spirit::chset<>(alphabet))[spirit::assign_a(seq)] >>
820 (spirit::alpha_p >> *spirit::alnum_p)[spirit::assign_a(name)]
823 spirit::real_p[spirit::assign_a(red)] >> +spirit::space_p >>
824 spirit::real_p[spirit::assign_a(green)] >> +spirit::space_p >>
825 spirit::real_p[spirit::assign_a(blue)] >> +spirit::space_p
826 )[push_back_motif(motif_sequences, color_mapper, seq, name, red, green, blue)]
828 update_sequences_motifs();
831 void Mussa::load_motifs(fs::path filename)
834 f.open(filename, ifstream::in);
838 void Mussa::update_sequences_motifs()
840 // once we've loaded all the motifs from the file,
841 // lets attach them to the sequences
842 for(vector<boost::shared_ptr<Sequence> >::iterator seq_i = the_seqs.begin();
843 seq_i != the_seqs.end();
846 // clear out old motifs
847 (*seq_i)->clear_motifs();
848 // for all the motifs in our set, attach them to the current sequence
849 for(set<Sequence>::iterator motif_i = motif_sequences.begin();
850 motif_i != motif_sequences.end();
853 (*seq_i)->add_motif(*motif_i);
858 const set<Sequence>& Mussa::motifs() const
860 return motif_sequences;
863 boost::shared_ptr<AnnotationColors> Mussa::colorMapper()