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;
23 #include "mussa_exceptions.hpp"
24 #include "alg/flp.hpp"
25 #include "alg/mussa.hpp"
26 #include "alg/motif_parser.hpp"
32 : color_mapper(new AnnotationColors)
35 connect(&the_paths, SIGNAL(progress(const std::string&, int, int)),
36 this, SIGNAL(progress(const std::string&, int, int)));
39 Mussa::Mussa(const Mussa& m)
40 : analysis_name(m.analysis_name),
42 threshold(m.threshold),
43 soft_thres(m.soft_thres),
45 win_append(m.win_append),
46 thres_append(m.thres_append),
47 motif_sequences(m.motif_sequences),
48 color_mapper(m.color_mapper),
49 analysis_path(m.analysis_path),
52 connect(&the_paths, SIGNAL(progress(const std::string&, int, int)),
53 this, SIGNAL(progress(const std::string&, int, int)));
56 boost::filesystem::path Mussa::get_analysis_path() const
61 void Mussa::set_analysis_path(boost::filesystem::path pathname)
63 analysis_path = pathname;
66 // set all parameters to null state
71 ana_mode = TransitiveNway;
77 motif_sequences.clear();
78 if(color_mapper) color_mapper->clear();
81 analysis_path = fs::path();
85 void Mussa::set_dirty(bool new_state)
87 if (dirty != new_state) {
89 emit isModified(dirty);
93 bool Mussa::is_dirty() const
98 bool Mussa::empty() const
100 return the_seqs.empty();
104 // these 5 simple methods manually set the parameters for doing an analysis
105 // used so that the gui can take input from user and setup the analysis
106 // note - still need a set_append(bool, bool) method...
108 Mussa::set_name(string a_name)
110 analysis_name = a_name;
114 string Mussa::get_name() const
116 return analysis_name;
119 string Mussa::get_title() const
121 fs::path analysis_path = get_analysis_path();
122 if (not analysis_path.empty()) {
123 return analysis_path.native_file_string();
124 } else if (get_name().size() > 0) {
127 return std::string("Unnamed");
134 if (the_seqs.size() > 0)
135 return the_seqs.size();
141 Mussa::set_window(int a_window)
147 int Mussa::get_window() const
153 Mussa::set_threshold(int a_threshold)
155 threshold = a_threshold;
157 if (a_threshold > soft_thres) {
158 soft_thres = a_threshold;
162 int Mussa::get_threshold() const
168 Mussa::set_soft_threshold(int new_threshold)
170 if (new_threshold < threshold) {
171 soft_thres = threshold;
172 } else if (new_threshold > window) {
175 soft_thres = new_threshold;
179 int Mussa::get_soft_threshold() const
185 Mussa::set_analysis_mode(enum analysis_modes new_ana_mode)
187 ana_mode = new_ana_mode;
191 enum Mussa::analysis_modes Mussa::get_analysis_mode() const
196 string Mussa::get_analysis_mode_name() const
201 return string("Transitive");
204 return string("Radial");
207 return string("Entropy");
210 return string("[deprecated] Recursive");
213 throw runtime_error("invalid analysis mode type");
218 const NwayPaths& Mussa::paths() const
223 //template <class IteratorT>
224 //void Mussa::createLocalAlignment(IteratorT begin, IteratorT end)
225 void Mussa::createLocalAlignment(std::list<ConservedPath>::iterator begin,
226 std::list<ConservedPath>::iterator end,
227 std::list<ConservedPath::path_type>& result,
228 std::list<std::vector<bool> >& reversed)
230 const vector_sequence_type& raw_seq = the_seqs;
231 ConservedPath::path_type aligned_path;
234 int window_length, win_i;
237 vector<bool> rc_list;
239 vector<bool> matched;
243 for(std::list<ConservedPath>::iterator pathz_i=begin; pathz_i != end; ++pathz_i)
245 ConservedPath& a_path = *pathz_i;
246 window_length = a_path.window_size;
247 // determine which parts of the path are RC relative to first species
248 rc_list = a_path.reverseComplimented();
250 // loop over each bp in the conserved region for all sequences
251 for(win_i = 0; win_i < window_length; win_i++)
253 aligned_path.clear();
254 // determine which exact base pairs match between the sequences
256 for(i2 = 0; i2 < a_path.size()-1; i2++)
258 // assume not rc as most likely, adjust below
261 // no matter the case, any RC node needs adjustments
263 rc_1 = window_length-1;
264 if (a_path[i2+1] < 0)
265 rc_2 = window_length-1;
267 x_start = (abs(a_path[i2]-rc_1+win_i));
268 x_end = (abs(a_path[i2+1]-rc_2+win_i));
270 boost::shared_ptr<Sequence> cur(raw_seq[i2]) ;
271 boost::shared_ptr<Sequence> next(raw_seq[i2+1]);
273 // ugh, and xor...only want rc coloring if just one of the nodes is rc
274 // if both nodes are rc, then they are 'normal' relative to each other
275 if((rc_list[i2] || rc_list[i2+1] )&&!(rc_list[i2] && rc_list[i2+1]))
276 { //the hideous rc matching logic - not complex, but annoying
277 if(!(( ((*cur)[x_start]=='A')&&((*next)[x_end]=='T')) ||
278 (((*cur)[x_start]=='T')&&((*next)[x_end]=='A')) ||
279 (((*cur)[x_start]=='G')&&((*next)[x_end]=='C')) ||
280 (((*cur)[x_start]=='C')&&((*next)[x_end]=='G'))) )
284 aligned_path.push_back(x_start);
289 if (!( ((*cur)[x_start] == (*next)[x_end]) &&
290 ((*cur)[x_start] != 'N') && ((*next)[x_end] != 'N') ) ) {
293 aligned_path.push_back(x_start);
297 // grab the last part of our path, assuming we matched
299 aligned_path.push_back(x_end);
301 if (aligned_path.size() == a_path.size()) {
302 result.push_back(aligned_path);
303 reversed.push_back(rc_list);
311 void Mussa::append_sequence(const Sequence& a_seq)
313 boost::shared_ptr<Sequence> seq_copy(new Sequence(a_seq));
314 the_seqs.push_back(seq_copy);
318 void Mussa::append_sequence(boost::shared_ptr<Sequence> a_seq)
320 the_seqs.push_back(a_seq);
325 const vector<boost::shared_ptr<Sequence> >&
326 Mussa::sequences() const
331 void Mussa::load_sequence(fs::path seq_file, fs::path annot_file,
332 int fasta_index, int sub_seq_start, int sub_seq_end,
335 boost::shared_ptr<Sequence> aseq(new Sequence);
336 aseq->load_fasta(seq_file, fasta_index, sub_seq_start, sub_seq_end);
337 if ( not annot_file.empty() ) {
338 aseq->load_annot(annot_file, sub_seq_start, sub_seq_end);
340 if (name != 0 and name->size() > 0 ) {
341 aseq->set_species(*name);
343 the_seqs.push_back(aseq);
348 Mussa::load_mupa_file(fs::path para_file_path)
350 fs::ifstream para_file;
351 string file_data_line;
354 int split_index, fasta_index;
355 int sub_seq_start, sub_seq_end;
356 bool seq_params, did_seq;
359 string::size_type new_index, dir_index;
364 // if file was opened, read the parameter values
365 if (not fs::exists(para_file_path))
367 throw mussa_load_error("Config File: " + para_file_path.string() + " not found");
368 } else if (fs::is_directory(para_file_path)) {
369 throw mussa_load_error("Config File: " + para_file_path.string() + " is a directory.");
370 } else if (fs::is_empty(para_file_path)) {
371 throw mussa_load_error("Config File: " + para_file_path.string() + " is empty");
373 para_file.open(para_file_path, ios::in);
375 // what directory is the mupa file in?
376 fs::path file_path_base = para_file_path.branch_path();
378 // setup loop by getting file's first line
379 getline(para_file,file_data_line);
380 split_index = file_data_line.find(" ");
381 param = file_data_line.substr(0,split_index);
382 value = file_data_line.substr(split_index+1);
387 if (param == "ANA_NAME")
388 analysis_name = value;
389 else if (param == "APPEND_WIN")
391 else if (param == "APPEND_THRES")
393 else if (param == "SEQUENCE_NUM")
394 ; // ignore sequence_num now
395 else if (param == "WINDOW")
396 window = atoi(value.c_str());
397 else if (param == "THRESHOLD")
398 threshold = atoi(value.c_str());
399 else if (param == "SEQUENCE")
401 fs::path seq_file = file_path_base / value;
402 //cout << "seq_file_name " << seq_files.back() << endl;
409 while (para_file && seq_params)
411 getline(para_file,file_data_line);
412 split_index = file_data_line.find(" ");
413 param = file_data_line.substr(0,split_index);
414 value = file_data_line.substr(split_index+1);
416 if (param == "FASTA_INDEX")
417 fasta_index = atoi(value.c_str());
418 else if (param == "ANNOTATION")
419 annot_file = file_path_base / value;
420 else if (param == "SEQ_START")
421 sub_seq_start = atoi(value.c_str());
422 else if (param == "SEQ_END")
424 sub_seq_end = atoi(value.c_str());
426 //ignore empty lines or that start with '#'
427 else if ((param == "") || (param == "#")) {}
428 else seq_params = false;
430 load_sequence(seq_file, annot_file, fasta_index, sub_seq_start,
434 //ignore empty lines or that start with '#'
435 else if ((param == "") || (param == "#")) {}
438 clog << "Illegal/misplaced mussa parameter in file\n";
439 clog << param << "\n";
444 getline(para_file,file_data_line);
445 split_index = file_data_line.find(" ");
446 param = file_data_line.substr(0,split_index);
447 value = file_data_line.substr(split_index+1);
454 soft_thres = threshold;
455 //cout << "nway mupa: analysis_name = " << analysis_name
456 // << " window = " << window
457 // << " threshold = " << threshold << endl;
459 // no file was loaded, signal error
467 if (the_seqs.size() < 2) {
468 throw mussa_analysis_error("you need to have at least 2 sequences to "
473 the_paths.setup(window, threshold);
480 vector<int> seq_lens;
481 vector<FLPs> empty_FLP_vector;
483 string save_file_string;
485 empty_FLP_vector.clear();
486 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
488 all_comps.push_back(empty_FLP_vector);
489 for(vector<Sequence>::size_type i2 = 0; i2 < the_seqs.size(); i2++)
490 all_comps[i].push_back(dummy_comp);
492 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
493 seq_lens.push_back(the_seqs[i]->size());
495 int seqcomps_done = 0;
496 int seqcomps_todo = (the_seqs.size() * (the_seqs.size()-1)) / 2;
497 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
499 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
500 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
502 //cout << "seqcomping: " << i << " v. " << i2 << endl;
503 all_comps[i][i2].setup(window, threshold);
504 all_comps[i][i2].seqcomp(*the_seqs[i], *the_seqs[i2], false);
505 all_comps[i][i2].seqcomp(*the_seqs[i], the_seqs[i2]->rev_comp(),true);
507 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
515 the_paths.set_soft_threshold(soft_thres);
517 if (ana_mode == TransitiveNway) {
518 the_paths.trans_path_search(all_comps);
520 else if (ana_mode == RadialNway) {
521 the_paths.radiate_path_search(all_comps);
523 else if (ana_mode == EntropyNway)
525 vector<Sequence> some_Seqs;
526 //unlike other methods, entropy needs to look at the sequence at this stage
528 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
530 some_Seqs.push_back(*the_seqs[i]);
533 the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
534 the_paths.entropy_path_search(all_comps);
537 // old recursive transitive analysis function
538 else if (ana_mode == RecursiveNway)
539 the_paths.find_paths_r(all_comps);
541 the_paths.simple_refine();
545 Mussa::save(fs::path save_path)
547 fs::fstream save_file;
548 ostringstream append_info;
549 int dir_create_status;
551 if (save_path.empty()) {
552 if (not analysis_path.empty()) {
553 save_path = analysis_path;
554 } else if (not analysis_name.empty()) {
555 std::string save_name = analysis_name;
556 // gotta do bit with adding win & thres if to be appended
559 append_info << "_w" << window;
560 save_name += append_info.str();
565 append_info << "_t" << threshold;
566 save_name += append_info.str();
568 save_path = save_name;
570 throw mussa_save_error("Need filename or analysis name to save");
574 if (not fs::exists(save_path)) {
575 fs::create_directory(save_path);
578 std::string basename = save_path.leaf();
579 fs::path museq(basename + ".museq", fs::native);
581 // save sequence and annots to a special mussa file
582 save_file.open(save_path / museq, ios::out);
583 save_file << "<Mussa_Sequence>" << endl;
585 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
587 the_seqs[i]->save(save_file);
590 save_file << "</Mussa_Sequence>" << endl;
593 // if we have any motifs, save them.
594 if (motif_sequences.size()) {
595 fs::path mtl(basename + ".mtl", fs::native);
596 save_motifs(save_path / mtl);
599 // save nway paths to its mussa save file
600 fs::path muway(basename + ".muway", fs::native);
601 the_paths.save(save_path / muway);
603 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
604 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
607 append_info << "_sp_" << i << "v" << i2;
608 fs::path flp(basename+append_info.str()+".flp", fs::native);
609 all_comps[i][i2].save(save_path / flp);
614 analysis_path = save_path;
618 Mussa::save_muway(fs::path save_path)
620 the_paths.save(save_path);
624 Mussa::load(fs::path ana_file)
627 fs::path file_path_base;
628 fs::path a_file_path;
629 fs::path ana_path(ana_file);
632 ostringstream append_info;
633 vector<FLPs> empty_FLP_vector;
636 analysis_path = ana_file;
637 analysis_name = ana_path.leaf();
638 file_path_base = ana_path.branch_path() / analysis_name;
639 a_file_path = file_path_base / (analysis_name + ".muway");
640 the_paths.load(a_file_path);
641 // perhaps this could be more elegent, but at least this'll let
642 // us know what our threshold and window sizes were when we load a muway
643 window = the_paths.get_window();
644 threshold = the_paths.get_threshold();
645 soft_thres = threshold;
647 int seq_num = the_paths.sequence_count();
649 a_file_path = file_path_base / (analysis_name + ".museq");
651 // this is a bit of a hack due to C++ not acting like it should with files
652 for (i = 1; i <= seq_num; i++)
654 boost::shared_ptr<Sequence> tmp_seq(new Sequence);
655 tmp_seq->load_museq(a_file_path, i);
656 the_seqs.push_back(tmp_seq);
659 fs::path motif_file = file_path_base / (analysis_name + ".mtl");
660 if (fs::exists(motif_file)) {
661 load_motifs(motif_file);
663 empty_FLP_vector.clear();
664 for(i = 0; i < seq_num; i++)
666 all_comps.push_back(empty_FLP_vector);
667 for(i2 = 0; i2 < seq_num; i2++)
668 all_comps[i].push_back(dummy_comp);
671 for(i = 0; i < seq_num; i++)
673 for(i2 = i+1; i2 < seq_num; i2++)
676 append_info << analysis_name << "_sp_" << i << "v" << i2 << ".flp";
677 //clog << append_info.str() << endl;
678 a_file_path = file_path_base / append_info.str();
679 //clog << "path " << a_file_path.string() << endl;
680 all_comps[i][i2].load(a_file_path);
681 //clog << "real size = " << all_comps[i][i2].size() << endl;
690 fs::fstream save_file;
692 save_file.open(analysis_name, ios::out);
694 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
695 save_file << *(the_seqs[i]) << endl;
697 save_file << window << endl;
699 //note more complex eventually since analysis_name may need to have
700 //window size, threshold and other stuff to modify it...
701 the_paths.save_old(analysis_name);
706 Mussa::load_old(char * load_file_path, int s_num)
709 string file_data_line;
710 int i, space_split_i, comma_split_i;
711 vector<int> loaded_path;
712 string node_pair, node;
716 the_paths.setup(0, 0);
717 save_file.open(load_file_path, ios::in);
719 // currently loads old mussa format
722 for(i = 0; i < seq_num; i++)
724 getline(save_file, file_data_line);
725 boost::shared_ptr<Sequence> a_seq(new Sequence(file_data_line));
726 the_seqs.push_back(a_seq);
730 getline(save_file, file_data_line);
731 window = atoi(file_data_line.c_str());
734 while (!save_file.eof())
737 getline(save_file, file_data_line);
738 if (file_data_line != "")
739 for(i = 0; i < seq_num; i++)
741 space_split_i = file_data_line.find(" ");
742 node_pair = file_data_line.substr(0,space_split_i);
743 //cout << "np= " << node_pair;
744 comma_split_i = node_pair.find(",");
745 node = node_pair.substr(comma_split_i+1);
746 //cout << "n= " << node << " ";
747 loaded_path.push_back(atoi (node.c_str()));
748 file_data_line = file_data_line.substr(space_split_i+1);
751 // FIXME: do we have any information about what the threshold should be?
752 the_paths.add_path(0, loaded_path);
756 //the_paths.save("tmp.save");
759 void Mussa::add_motif(const Sequence& motif, const Color& color)
761 motif_sequences.insert(motif);
762 color_mapper->appendInstanceColor("motif", motif.get_sequence(), color);
766 void Mussa::set_motifs(const vector<Sequence>& motifs,
767 const vector<Color>& colors)
769 if (motifs.size() != colors.size()) {
770 throw mussa_error("motif and color vectors must be the same size");
773 motif_sequences.clear();
774 for(size_t i = 0; i != motifs.size(); ++i)
776 add_motif(motifs[i], colors[i]);
778 update_sequences_motifs();
781 void Mussa::load_motifs(fs::path filename)
784 f.open(filename, ifstream::in);
788 void Mussa::load_motifs(std::istream &in)
791 const char *alphabet = Alphabet::nucleic_cstr;
792 motif_parser::ParsedMotifs parsed_motifs(motif_sequences, color_mapper);
794 // slurp our data into a string
795 std::streamsize bytes_read = 1;
796 while (in.good() and bytes_read) {
797 const std::streamsize bufsiz=512;
799 bytes_read = in.readsome(buf, bufsiz);
800 data.append(buf, buf+bytes_read);
802 parsed_motifs.parse(data);
803 update_sequences_motifs();
806 void Mussa::save_motifs(fs::path filename)
808 fs::ofstream out_stream;
809 out_stream.open(filename, ofstream::out);
810 save_motifs(out_stream);
813 void Mussa::save_motifs(std::ostream& out)
815 for(motif_set::iterator motif_i = motif_sequences.begin();
816 motif_i != motif_sequences.end();
819 out << motif_i->get_sequence() << " ";
820 if (motif_i->get_name().size() > 0) {
821 out << "\"" << motif_i->get_name() << "\" ";
823 out << color_mapper->lookup("motif", motif_i->get_sequence());
828 void Mussa::update_sequences_motifs()
830 // once we've loaded all the motifs from the file,
831 // lets attach them to the sequences
832 for(vector<boost::shared_ptr<Sequence> >::iterator seq_i = the_seqs.begin();
833 seq_i != the_seqs.end();
836 // clear out old motifs
837 (*seq_i)->clear_motifs();
838 // for all the motifs in our set, attach them to the current sequence
839 for(set<Sequence>::iterator motif_i = motif_sequences.begin();
840 motif_i != motif_sequences.end();
843 (*seq_i)->add_motif(*motif_i);
848 const set<Sequence>& Mussa::motifs() const
850 return motif_sequences;
853 boost::shared_ptr<AnnotationColors> Mussa::colorMapper()