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;
22 #include "mussa_exceptions.hpp"
23 #include "alg/mussa.hpp"
24 #include "alg/flp.hpp"
30 : color_mapper(new AnnotationColors)
33 connect(&the_paths, SIGNAL(progress(const std::string&, int, int)),
34 this, SIGNAL(progress(const std::string&, int, int)));
37 Mussa::Mussa(const Mussa& m)
38 : analysis_name(m.analysis_name),
40 threshold(m.threshold),
41 soft_thres(m.soft_thres),
43 win_append(m.win_append),
44 thres_append(m.thres_append),
45 motif_sequences(m.motif_sequences),
46 color_mapper(m.color_mapper),
47 analysis_path(m.analysis_path),
50 connect(&the_paths, SIGNAL(progress(const std::string&, int, int)),
51 this, SIGNAL(progress(const std::string&, int, int)));
54 boost::filesystem::path Mussa::get_analysis_path() const
59 // set all parameters to null state
64 ana_mode = TransitiveNway;
70 motif_sequences.clear();
71 if(color_mapper) color_mapper->clear();
74 analysis_path = fs::path();
78 bool Mussa::is_dirty() const
83 bool Mussa::empty() const
85 return the_seqs.empty();
89 // these 5 simple methods manually set the parameters for doing an analysis
90 // used so that the gui can take input from user and setup the analysis
91 // note - still need a set_append(bool, bool) method...
93 Mussa::set_name(string a_name)
95 analysis_name = a_name;
99 string Mussa::get_name()
101 return analysis_name;
107 if (the_seqs.size() > 0)
108 return the_seqs.size();
114 Mussa::set_window(int a_window)
120 int Mussa::get_window() const
126 Mussa::set_threshold(int a_threshold)
128 threshold = a_threshold;
130 if (a_threshold > soft_thres) {
131 soft_thres = a_threshold;
135 int Mussa::get_threshold() const
141 Mussa::set_soft_threshold(int new_threshold)
143 if (new_threshold < threshold) {
144 soft_thres = threshold;
145 } else if (new_threshold > window) {
148 soft_thres = new_threshold;
152 int Mussa::get_soft_threshold() const
158 Mussa::set_analysis_mode(enum analysis_modes new_ana_mode)
160 ana_mode = new_ana_mode;
164 enum Mussa::analysis_modes Mussa::get_analysis_mode() const
169 string Mussa::get_analysis_mode_name() const
174 return string("Transitive");
177 return string("Radial");
180 return string("Entropy");
183 return string("[deprecated] Recursive");
186 throw runtime_error("invalid analysis mode type");
191 const NwayPaths& Mussa::paths() const
196 //template <class IteratorT>
197 //void Mussa::createLocalAlignment(IteratorT begin, IteratorT end)
198 void Mussa::createLocalAlignment(std::list<ConservedPath>::iterator begin,
199 std::list<ConservedPath>::iterator end,
200 std::list<ConservedPath::path_type>& result,
201 std::list<std::vector<bool> >& reversed)
203 const vector_sequence_type& raw_seq = the_seqs;
204 ConservedPath::path_type aligned_path;
207 int window_length, win_i;
210 vector<bool> rc_list;
212 vector<bool> matched;
216 for(std::list<ConservedPath>::iterator pathz_i=begin; pathz_i != end; ++pathz_i)
218 ConservedPath& a_path = *pathz_i;
219 window_length = a_path.window_size;
220 // determine which parts of the path are RC relative to first species
221 rc_list = a_path.reverseComplimented();
223 // loop over each bp in the conserved region for all sequences
224 for(win_i = 0; win_i < window_length; win_i++)
226 aligned_path.clear();
227 // determine which exact base pairs match between the sequences
229 for(i2 = 0; i2 < a_path.size()-1; i2++)
231 // assume not rc as most likely, adjust below
234 // no matter the case, any RC node needs adjustments
236 rc_1 = window_length-1;
237 if (a_path[i2+1] < 0)
238 rc_2 = window_length-1;
240 x_start = (abs(a_path[i2]-rc_1+win_i));
241 x_end = (abs(a_path[i2+1]-rc_2+win_i));
243 boost::shared_ptr<Sequence> cur(raw_seq[i2]) ;
244 boost::shared_ptr<Sequence> next(raw_seq[i2+1]);
246 // ugh, and xor...only want rc coloring if just one of the nodes is rc
247 // if both nodes are rc, then they are 'normal' relative to each other
248 if((rc_list[i2] || rc_list[i2+1] )&&!(rc_list[i2] && rc_list[i2+1]))
249 { //the hideous rc matching logic - not complex, but annoying
250 if(!(( ((*cur)[x_start]=='A')&&((*next)[x_end]=='T')) ||
251 (((*cur)[x_start]=='T')&&((*next)[x_end]=='A')) ||
252 (((*cur)[x_start]=='G')&&((*next)[x_end]=='C')) ||
253 (((*cur)[x_start]=='C')&&((*next)[x_end]=='G'))) )
257 aligned_path.push_back(x_start);
262 if (!( ((*cur)[x_start] == (*next)[x_end]) &&
263 ((*cur)[x_start] != 'N') && ((*next)[x_end] != 'N') ) ) {
266 aligned_path.push_back(x_start);
270 // grab the last part of our path, assuming we matched
272 aligned_path.push_back(x_end);
274 if (aligned_path.size() == a_path.size()) {
275 result.push_back(aligned_path);
276 reversed.push_back(rc_list);
284 void Mussa::append_sequence(const Sequence& a_seq)
286 boost::shared_ptr<Sequence> seq_copy(new Sequence(a_seq));
287 the_seqs.push_back(seq_copy);
291 void Mussa::append_sequence(boost::shared_ptr<Sequence> a_seq)
293 the_seqs.push_back(a_seq);
298 const vector<boost::shared_ptr<Sequence> >&
299 Mussa::sequences() const
304 void Mussa::load_sequence(fs::path seq_file, fs::path annot_file,
305 int fasta_index, int sub_seq_start, int sub_seq_end,
308 boost::shared_ptr<Sequence> aseq(new Sequence);
309 aseq->load_fasta(seq_file, fasta_index, sub_seq_start, sub_seq_end);
310 if ( not annot_file.empty() ) {
311 aseq->load_annot(annot_file, sub_seq_start, sub_seq_end);
313 if (name != 0 and name->size() > 0 ) {
314 aseq->set_species(*name);
316 the_seqs.push_back(aseq);
321 Mussa::load_mupa_file(fs::path para_file_path)
323 fs::ifstream para_file;
324 string file_data_line;
327 int split_index, fasta_index;
328 int sub_seq_start, sub_seq_end;
329 bool seq_params, did_seq;
332 string::size_type new_index, dir_index;
337 // if file was opened, read the parameter values
338 if (not fs::exists(para_file_path))
340 throw mussa_load_error("Config File: " + para_file_path.string() + " not found");
341 } else if (fs::is_directory(para_file_path)) {
342 throw mussa_load_error("Config File: " + para_file_path.string() + " is a directory.");
343 } else if (fs::is_empty(para_file_path)) {
344 throw mussa_load_error("Config File: " + para_file_path.string() + " is empty");
346 para_file.open(para_file_path, ios::in);
348 // what directory is the mupa file in?
349 fs::path file_path_base = para_file_path.branch_path();
351 // setup loop by getting file's first line
352 getline(para_file,file_data_line);
353 split_index = file_data_line.find(" ");
354 param = file_data_line.substr(0,split_index);
355 value = file_data_line.substr(split_index+1);
360 if (param == "ANA_NAME")
361 analysis_name = value;
362 else if (param == "APPEND_WIN")
364 else if (param == "APPEND_THRES")
366 else if (param == "SEQUENCE_NUM")
367 ; // ignore sequence_num now
368 else if (param == "WINDOW")
369 window = atoi(value.c_str());
370 else if (param == "THRESHOLD")
371 threshold = atoi(value.c_str());
372 else if (param == "SEQUENCE")
374 fs::path seq_file = file_path_base / value;
375 //cout << "seq_file_name " << seq_files.back() << endl;
382 while (para_file && seq_params)
384 getline(para_file,file_data_line);
385 split_index = file_data_line.find(" ");
386 param = file_data_line.substr(0,split_index);
387 value = file_data_line.substr(split_index+1);
389 if (param == "FASTA_INDEX")
390 fasta_index = atoi(value.c_str());
391 else if (param == "ANNOTATION")
392 annot_file = file_path_base / value;
393 else if (param == "SEQ_START")
394 sub_seq_start = atoi(value.c_str());
395 else if (param == "SEQ_END")
397 sub_seq_end = atoi(value.c_str());
399 //ignore empty lines or that start with '#'
400 else if ((param == "") || (param == "#")) {}
401 else seq_params = false;
403 load_sequence(seq_file, annot_file, fasta_index, sub_seq_start,
407 //ignore empty lines or that start with '#'
408 else if ((param == "") || (param == "#")) {}
411 clog << "Illegal/misplaced mussa parameter in file\n";
412 clog << param << "\n";
417 getline(para_file,file_data_line);
418 split_index = file_data_line.find(" ");
419 param = file_data_line.substr(0,split_index);
420 value = file_data_line.substr(split_index+1);
427 soft_thres = threshold;
428 //cout << "nway mupa: analysis_name = " << analysis_name
429 // << " window = " << window
430 // << " threshold = " << threshold << endl;
432 // no file was loaded, signal error
440 if (the_seqs.size() < 2) {
441 throw mussa_analysis_error("you need to have at least 2 sequences to "
444 //cout << "nway ana: seq_num = " << the_seqs.size() << endl;
447 the_paths.setup(window, threshold);
454 vector<int> seq_lens;
455 vector<FLPs> empty_FLP_vector;
457 string save_file_string;
459 empty_FLP_vector.clear();
460 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
462 all_comps.push_back(empty_FLP_vector);
463 for(vector<Sequence>::size_type i2 = 0; i2 < the_seqs.size(); i2++)
464 all_comps[i].push_back(dummy_comp);
466 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
467 seq_lens.push_back(the_seqs[i]->size());
469 int seqcomps_done = 0;
470 int seqcomps_todo = (the_seqs.size() * (the_seqs.size()-1)) / 2;
471 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
473 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
474 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
476 //cout << "seqcomping: " << i << " v. " << i2 << endl;
477 all_comps[i][i2].setup(window, threshold);
478 all_comps[i][i2].seqcomp(*the_seqs[i], *the_seqs[i2], false);
479 all_comps[i][i2].seqcomp(*the_seqs[i], the_seqs[i2]->rev_comp(),true);
481 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
489 the_paths.set_soft_threshold(soft_thres);
491 if (ana_mode == TransitiveNway) {
492 the_paths.trans_path_search(all_comps);
494 else if (ana_mode == RadialNway) {
495 the_paths.radiate_path_search(all_comps);
497 else if (ana_mode == EntropyNway)
499 vector<Sequence> some_Seqs;
500 //unlike other methods, entropy needs to look at the sequence at this stage
502 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
504 some_Seqs.push_back(*the_seqs[i]);
507 the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
508 the_paths.entropy_path_search(all_comps);
511 // old recursive transitive analysis function
512 else if (ana_mode == RecursiveNway)
513 the_paths.find_paths_r(all_comps);
515 the_paths.simple_refine();
519 Mussa::save(fs::path save_path)
521 fs::path flp_filepath;
522 fs::fstream save_file;
523 ostringstream append_info;
524 int dir_create_status;
526 if (save_path.empty()) {
527 if (not analysis_name.empty()) {
528 std::string save_name = analysis_name;
529 // gotta do bit with adding win & thres if to be appended
532 append_info << "_w" << window;
533 save_name += append_info.str();
538 append_info << "_t" << threshold;
539 save_name += append_info.str();
541 save_path = save_name;
543 throw mussa_save_error("Need filename or analysis name to save");
547 if (not fs::exists(save_path)) {
548 fs::create_directory(save_path);
550 // save sequence and annots to a special mussa file
551 save_file.open(save_path / (save_path.leaf()+".museq"), ios::out);
552 save_file << "<Mussa_Sequence>" << endl;
554 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
556 the_seqs[i]->save(save_file);
559 save_file << "</Mussa_Sequence>" << endl;
562 // save nway paths to its mussa save file
563 the_paths.save(save_path / (save_path.leaf()+ ".muway"));
565 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
566 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
569 append_info << "_sp_" << i << "v" << i2;
570 all_comps[i][i2].save(save_path/(save_path.leaf()+append_info.str()+".flp"));
574 analysis_path = save_path;
578 Mussa::save_muway(fs::path save_path)
580 the_paths.save(save_path);
584 Mussa::load(fs::path ana_file)
587 fs::path file_path_base;
588 fs::path a_file_path;
589 fs::path ana_path(ana_file);
592 ostringstream append_info;
593 vector<FLPs> empty_FLP_vector;
596 analysis_path = ana_file;
597 //clog << "ana_file name " << ana_file.string() << endl;
598 analysis_name = ana_path.leaf();
599 //clog << " ana_name " << analysis_name << endl;
600 file_path_base = ana_path.branch_path() / analysis_name;
601 a_file_path = file_path_base / (analysis_name + ".muway");
602 //clog << " loading museq: " << a_file_path.string() << endl;
603 the_paths.load(a_file_path);
604 // perhaps this could be more elegent, but at least this'll let
605 // us know what our threshold and window sizes were when we load a muway
606 window = the_paths.get_window();
607 threshold = the_paths.get_threshold();
608 soft_thres = threshold;
610 int seq_num = the_paths.sequence_count();
612 a_file_path = file_path_base / (analysis_name + ".museq");
614 // this is a bit of a hack due to C++ not acting like it should with files
615 for (i = 1; i <= seq_num; i++)
617 boost::shared_ptr<Sequence> tmp_seq(new Sequence);
618 //clog << "mussa_class: loading museq frag... " << a_file_path.string() << endl;
619 tmp_seq->load_museq(a_file_path, i);
620 the_seqs.push_back(tmp_seq);
623 empty_FLP_vector.clear();
624 for(i = 0; i < seq_num; i++)
626 all_comps.push_back(empty_FLP_vector);
627 for(i2 = 0; i2 < seq_num; i2++)
628 all_comps[i].push_back(dummy_comp);
631 for(i = 0; i < seq_num; i++)
633 for(i2 = i+1; i2 < seq_num; i2++)
636 append_info << analysis_name << "_sp_" << i << "v" << i2 << ".flp";
637 //clog << append_info.str() << endl;
638 a_file_path = file_path_base / append_info.str();
639 //clog << "path " << a_file_path.string() << endl;
640 all_comps[i][i2].load(a_file_path);
641 //clog << "real size = " << all_comps[i][i2].size() << endl;
650 fs::fstream save_file;
652 save_file.open(analysis_name, ios::out);
654 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
655 save_file << *(the_seqs[i]) << endl;
657 save_file << window << endl;
659 //note more complex eventually since analysis_name may need to have
660 //window size, threshold and other stuff to modify it...
661 the_paths.save_old(analysis_name);
666 Mussa::load_old(char * load_file_path, int s_num)
669 string file_data_line;
670 int i, space_split_i, comma_split_i;
671 vector<int> loaded_path;
672 string node_pair, node;
676 the_paths.setup(0, 0);
677 save_file.open(load_file_path, ios::in);
679 // currently loads old mussa format
682 for(i = 0; i < seq_num; i++)
684 getline(save_file, file_data_line);
685 boost::shared_ptr<Sequence> a_seq(new Sequence(file_data_line));
686 the_seqs.push_back(a_seq);
690 getline(save_file, file_data_line);
691 window = atoi(file_data_line.c_str());
694 while (!save_file.eof())
697 getline(save_file, file_data_line);
698 if (file_data_line != "")
699 for(i = 0; i < seq_num; i++)
701 space_split_i = file_data_line.find(" ");
702 node_pair = file_data_line.substr(0,space_split_i);
703 //cout << "np= " << node_pair;
704 comma_split_i = node_pair.find(",");
705 node = node_pair.substr(comma_split_i+1);
706 //cout << "n= " << node << " ";
707 loaded_path.push_back(atoi (node.c_str()));
708 file_data_line = file_data_line.substr(space_split_i+1);
711 // FIXME: do we have any information about what the threshold should be?
712 the_paths.add_path(0, loaded_path);
716 //the_paths.save("tmp.save");
719 void Mussa::add_motif(const Sequence& motif, const Color& color)
721 motif_sequences.insert(motif);
722 color_mapper->appendInstanceColor("motif", motif.get_sequence(), color);
725 void Mussa::set_motifs(const vector<Sequence>& motifs,
726 const vector<Color>& colors)
728 if (motifs.size() != colors.size()) {
729 throw mussa_error("motif and color vectors must be the same size");
732 motif_sequences.clear();
733 for(size_t i = 0; i != motifs.size(); ++i)
735 add_motif(motifs[i], colors[i]);
737 update_sequences_motifs();
740 // I mostly split the ifstream out so I can use a stringstream to test it.
741 void Mussa::load_motifs(std::istream &in)
750 in >> seq >> red >> green >> blue;
751 // if we couldn't read this line 'cause we're like at the end of the file
752 // try to exit the loop
756 seq = Sequence::motif_normalize(seq);
757 } catch(motif_normalize_error e) {
758 clog << "unable to parse " << seq << " skipping" << endl;
759 clog << e.what() << endl;
762 if (red < 0.0 or red > 1.0) {
763 clog << "invalid red value " << red << ". must be in range [0..1]"
767 if (green < 0.0 or green > 1.0) {
768 clog << "invalid green value " << green << ". must be in range [0..1]"
772 if (blue < 0.0 or blue > 1.0) {
773 clog << "invalid blue value " << blue << ". must be in range [0..1]"
777 if (motif_sequences.find(seq) == motif_sequences.end()) {
778 // sequence wasn't found
779 motif_sequences.insert(seq);
780 Color c(red, green, blue);
781 color_mapper->appendInstanceColor("motif", seq, c);
783 clog << "sequence " << seq << " was already defined skipping"
788 update_sequences_motifs();
791 void Mussa::load_motifs(fs::path filename)
794 f.open(filename, ifstream::in);
798 void Mussa::update_sequences_motifs()
800 // once we've loaded all the motifs from the file,
801 // lets attach them to the sequences
802 for(vector<boost::shared_ptr<Sequence> >::iterator seq_i = the_seqs.begin();
803 seq_i != the_seqs.end();
806 // clear out old motifs
807 (*seq_i)->clear_motifs();
808 // for all the motifs in our set, attach them to the current sequence
809 for(set<Sequence>::iterator motif_i = motif_sequences.begin();
810 motif_i != motif_sequences.end();
813 (*seq_i)->add_motif(*motif_i);
818 const set<Sequence>& Mussa::motifs() const
820 return motif_sequences;
823 boost::shared_ptr<AnnotationColors> Mussa::colorMapper()