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),
49 connect(&the_paths, SIGNAL(progress(const std::string&, int, int)),
50 this, SIGNAL(progress(const std::string&, int, int)));
53 // set all parameters to null state
58 ana_mode = TransitiveNway;
64 motif_sequences.clear();
65 if(color_mapper) color_mapper->clear();
70 // these 5 simple methods manually set the parameters for doing an analysis
71 // used so that the gui can take input from user and setup the analysis
72 // note - still need a set_append(bool, bool) method...
74 Mussa::set_name(string a_name)
76 analysis_name = a_name;
80 string Mussa::get_name()
88 if (the_seqs.size() > 0)
89 return the_seqs.size();
95 Mussa::set_window(int a_window)
101 int Mussa::get_window() const
107 Mussa::set_threshold(int a_threshold)
109 threshold = a_threshold;
111 if (a_threshold > soft_thres) {
112 soft_thres = a_threshold;
116 int Mussa::get_threshold() const
122 Mussa::set_soft_threshold(int new_threshold)
124 if (new_threshold < threshold) {
125 soft_thres = threshold;
126 } else if (new_threshold > window) {
129 soft_thres = new_threshold;
133 int Mussa::get_soft_threshold() const
139 Mussa::set_analysis_mode(enum analysis_modes new_ana_mode)
141 ana_mode = new_ana_mode;
145 enum Mussa::analysis_modes Mussa::get_analysis_mode() const
150 string Mussa::get_analysis_mode_name() const
155 return string("Transitive");
158 return string("Radial");
161 return string("Entropy");
164 return string("[deprecated] Recursive");
167 throw runtime_error("invalid analysis mode type");
172 const NwayPaths& Mussa::paths() const
177 //template <class IteratorT>
178 //void Mussa::createLocalAlignment(IteratorT begin, IteratorT end)
179 void Mussa::createLocalAlignment(std::list<ConservedPath>::iterator begin,
180 std::list<ConservedPath>::iterator end,
181 std::list<ConservedPath::path_type>& result,
182 std::list<std::vector<bool> >& reversed)
184 const vector_sequence_type& raw_seq = the_seqs;
185 ConservedPath::path_type aligned_path;
188 int window_length, win_i;
191 vector<bool> rc_list;
193 vector<bool> matched;
197 for(std::list<ConservedPath>::iterator pathz_i=begin; pathz_i != end; ++pathz_i)
199 ConservedPath& a_path = *pathz_i;
200 window_length = a_path.window_size;
201 // determine which parts of the path are RC relative to first species
202 rc_list = a_path.reverseComplimented();
204 // loop over each bp in the conserved region for all sequences
205 for(win_i = 0; win_i < window_length; win_i++)
207 aligned_path.clear();
208 // determine which exact base pairs match between the sequences
210 for(i2 = 0; i2 < a_path.size()-1; i2++)
212 // assume not rc as most likely, adjust below
215 // no matter the case, any RC node needs adjustments
217 rc_1 = window_length-1;
218 if (a_path[i2+1] < 0)
219 rc_2 = window_length-1;
221 x_start = (abs(a_path[i2]-rc_1+win_i));
222 x_end = (abs(a_path[i2+1]-rc_2+win_i));
224 boost::shared_ptr<Sequence> cur(raw_seq[i2]) ;
225 boost::shared_ptr<Sequence> next(raw_seq[i2+1]);
227 // ugh, and xor...only want rc coloring if just one of the nodes is rc
228 // if both nodes are rc, then they are 'normal' relative to each other
229 if((rc_list[i2] || rc_list[i2+1] )&&!(rc_list[i2] && rc_list[i2+1]))
230 { //the hideous rc matching logic - not complex, but annoying
231 if(!(( ((*cur)[x_start]=='A')&&((*next)[x_end]=='T')) ||
232 (((*cur)[x_start]=='T')&&((*next)[x_end]=='A')) ||
233 (((*cur)[x_start]=='G')&&((*next)[x_end]=='C')) ||
234 (((*cur)[x_start]=='C')&&((*next)[x_end]=='G'))) )
238 aligned_path.push_back(x_start);
243 if (!( ((*cur)[x_start] == (*next)[x_end]) &&
244 ((*cur)[x_start] != 'N') && ((*next)[x_end] != 'N') ) ) {
247 aligned_path.push_back(x_start);
251 // grab the last part of our path, assuming we matched
253 aligned_path.push_back(x_end);
255 if (aligned_path.size() == a_path.size()) {
256 result.push_back(aligned_path);
257 reversed.push_back(rc_list);
265 void Mussa::append_sequence(const Sequence& a_seq)
267 boost::shared_ptr<Sequence> seq_copy(new Sequence(a_seq));
268 the_seqs.push_back(seq_copy);
272 void Mussa::append_sequence(boost::shared_ptr<Sequence> a_seq)
274 the_seqs.push_back(a_seq);
279 const vector<boost::shared_ptr<Sequence> >&
280 Mussa::sequences() const
285 void Mussa::load_sequence(fs::path seq_file, fs::path annot_file,
286 int fasta_index, int sub_seq_start, int sub_seq_end,
289 boost::shared_ptr<Sequence> aseq(new Sequence);
290 aseq->load_fasta(seq_file, fasta_index, sub_seq_start, sub_seq_end);
291 if ( not annot_file.empty() ) {
292 aseq->load_annot(annot_file, sub_seq_start, sub_seq_end);
294 if (name != 0 and name->size() > 0 ) {
295 aseq->set_species(*name);
297 the_seqs.push_back(aseq);
302 Mussa::load_mupa_file(fs::path para_file_path)
304 fs::ifstream para_file;
305 string file_data_line;
308 int split_index, fasta_index;
309 int sub_seq_start, sub_seq_end;
310 bool seq_params, did_seq;
313 string::size_type new_index, dir_index;
318 // if file was opened, read the parameter values
319 if (not fs::exists(para_file_path))
321 throw mussa_load_error("Config File: " + para_file_path.string() + " not found");
322 } else if (fs::is_directory(para_file_path)) {
323 throw mussa_load_error("Config File: " + para_file_path.string() + " is a directory.");
324 } else if (fs::is_empty(para_file_path)) {
325 throw mussa_load_error("Config File: " + para_file_path.string() + " is empty");
327 para_file.open(para_file_path, ios::in);
329 // what directory is the mupa file in?
330 fs::path file_path_base = para_file_path.branch_path();
332 // setup loop by getting file's first line
333 getline(para_file,file_data_line);
334 split_index = file_data_line.find(" ");
335 param = file_data_line.substr(0,split_index);
336 value = file_data_line.substr(split_index+1);
341 if (param == "ANA_NAME")
342 analysis_name = value;
343 else if (param == "APPEND_WIN")
345 else if (param == "APPEND_THRES")
347 else if (param == "SEQUENCE_NUM")
348 ; // ignore sequence_num now
349 else if (param == "WINDOW")
350 window = atoi(value.c_str());
351 else if (param == "THRESHOLD")
352 threshold = atoi(value.c_str());
353 else if (param == "SEQUENCE")
355 fs::path seq_file = file_path_base / value;
356 //cout << "seq_file_name " << seq_files.back() << endl;
363 while (para_file && seq_params)
365 getline(para_file,file_data_line);
366 split_index = file_data_line.find(" ");
367 param = file_data_line.substr(0,split_index);
368 value = file_data_line.substr(split_index+1);
370 if (param == "FASTA_INDEX")
371 fasta_index = atoi(value.c_str());
372 else if (param == "ANNOTATION")
373 annot_file = file_path_base / value;
374 else if (param == "SEQ_START")
375 sub_seq_start = atoi(value.c_str());
376 else if (param == "SEQ_END")
378 sub_seq_end = atoi(value.c_str());
380 //ignore empty lines or that start with '#'
381 else if ((param == "") || (param == "#")) {}
382 else seq_params = false;
384 load_sequence(seq_file, annot_file, fasta_index, sub_seq_start,
388 //ignore empty lines or that start with '#'
389 else if ((param == "") || (param == "#")) {}
392 clog << "Illegal/misplaced mussa parameter in file\n";
393 clog << param << "\n";
398 getline(para_file,file_data_line);
399 split_index = file_data_line.find(" ");
400 param = file_data_line.substr(0,split_index);
401 value = file_data_line.substr(split_index+1);
408 soft_thres = threshold;
409 //cout << "nway mupa: analysis_name = " << analysis_name
410 // << " window = " << window
411 // << " threshold = " << threshold << endl;
413 // no file was loaded, signal error
421 if (the_seqs.size() < 2) {
422 throw mussa_analysis_error("you need to have at least 2 sequences to "
425 //cout << "nway ana: seq_num = " << the_seqs.size() << endl;
428 the_paths.setup(window, threshold);
430 // FIXME: once we implement a save feature we should remove this
431 if (not analysis_name.empty()) {
439 vector<int> seq_lens;
440 vector<FLPs> empty_FLP_vector;
442 string save_file_string;
444 empty_FLP_vector.clear();
445 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
447 all_comps.push_back(empty_FLP_vector);
448 for(vector<Sequence>::size_type i2 = 0; i2 < the_seqs.size(); i2++)
449 all_comps[i].push_back(dummy_comp);
451 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
452 seq_lens.push_back(the_seqs[i]->size());
454 int seqcomps_done = 0;
455 int seqcomps_todo = (the_seqs.size() * (the_seqs.size()-1)) / 2;
456 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
458 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
459 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
461 //cout << "seqcomping: " << i << " v. " << i2 << endl;
462 all_comps[i][i2].setup(window, threshold);
463 all_comps[i][i2].seqcomp(*the_seqs[i], *the_seqs[i2], false);
464 all_comps[i][i2].seqcomp(*the_seqs[i], the_seqs[i2]->rev_comp(),true);
466 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
474 the_paths.set_soft_threshold(soft_thres);
476 if (ana_mode == TransitiveNway) {
477 the_paths.trans_path_search(all_comps);
479 else if (ana_mode == RadialNway) {
480 the_paths.radiate_path_search(all_comps);
482 else if (ana_mode == EntropyNway)
484 vector<Sequence> some_Seqs;
485 //unlike other methods, entropy needs to look at the sequence at this stage
487 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
489 some_Seqs.push_back(*the_seqs[i]);
492 the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
493 the_paths.entropy_path_search(all_comps);
496 // old recursive transitive analysis function
497 else if (ana_mode == RecursiveNway)
498 the_paths.find_paths_r(all_comps);
500 the_paths.simple_refine();
504 Mussa::save(fs::path save_path)
506 fs::path flp_filepath;
507 fs::fstream save_file;
508 ostringstream append_info;
509 int dir_create_status;
511 if (save_path.empty()) {
512 if (not analysis_name.empty()) {
513 std::string save_name = analysis_name;
514 // gotta do bit with adding win & thres if to be appended
517 append_info << "_w" << window;
518 save_name += append_info.str();
523 append_info << "_t" << threshold;
524 save_name += append_info.str();
526 save_path = save_name;
528 throw mussa_save_error("Need filename or analysis name to save");
532 if (not fs::exists(save_path)) {
533 fs::create_directory(save_path);
535 // save sequence and annots to a special mussa file
536 save_file.open(save_path / (save_path.leaf()+".museq"), ios::out);
537 save_file << "<Mussa_Sequence>" << endl;
539 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
541 the_seqs[i]->save(save_file);
544 save_file << "</Mussa_Sequence>" << endl;
547 // save nway paths to its mussa save file
548 the_paths.save(save_path / (save_path.leaf()+ ".muway"));
550 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
551 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
554 append_info << "_sp_" << i << "v" << i2;
555 all_comps[i][i2].save(save_path/(save_path.leaf()+append_info.str()+".flp"));
562 Mussa::save_muway(fs::path save_path)
564 the_paths.save(save_path);
568 Mussa::load(fs::path ana_file)
571 fs::path file_path_base;
572 fs::path a_file_path;
573 fs::path ana_path(ana_file);
576 ostringstream append_info;
577 vector<FLPs> empty_FLP_vector;
580 //clog << "ana_file name " << ana_file.string() << endl;
581 analysis_name = ana_path.leaf();
582 //clog << " ana_name " << analysis_name << endl;
583 file_path_base = ana_path.branch_path() / analysis_name;
584 a_file_path = file_path_base / (analysis_name + ".muway");
585 //clog << " loading museq: " << a_file_path.string() << endl;
586 the_paths.load(a_file_path);
587 // perhaps this could be more elegent, but at least this'll let
588 // us know what our threshold and window sizes were when we load a muway
589 window = the_paths.get_window();
590 threshold = the_paths.get_threshold();
591 soft_thres = threshold;
593 int seq_num = the_paths.sequence_count();
595 a_file_path = file_path_base / (analysis_name + ".museq");
597 // this is a bit of a hack due to C++ not acting like it should with files
598 for (i = 1; i <= seq_num; i++)
600 boost::shared_ptr<Sequence> tmp_seq(new Sequence);
601 //clog << "mussa_class: loading museq frag... " << a_file_path.string() << endl;
602 tmp_seq->load_museq(a_file_path, i);
603 the_seqs.push_back(tmp_seq);
606 empty_FLP_vector.clear();
607 for(i = 0; i < seq_num; i++)
609 all_comps.push_back(empty_FLP_vector);
610 for(i2 = 0; i2 < seq_num; i2++)
611 all_comps[i].push_back(dummy_comp);
614 for(i = 0; i < seq_num; i++)
616 for(i2 = i+1; i2 < seq_num; i2++)
619 append_info << analysis_name << "_sp_" << i << "v" << i2 << ".flp";
620 //clog << append_info.str() << endl;
621 a_file_path = file_path_base / append_info.str();
622 //clog << "path " << a_file_path.string() << endl;
623 all_comps[i][i2].load(a_file_path);
624 //clog << "real size = " << all_comps[i][i2].size() << endl;
633 fs::fstream save_file;
635 save_file.open(analysis_name, ios::out);
637 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
638 save_file << *(the_seqs[i]) << endl;
640 save_file << window << endl;
642 //note more complex eventually since analysis_name may need to have
643 //window size, threshold and other stuff to modify it...
644 the_paths.save_old(analysis_name);
649 Mussa::load_old(char * load_file_path, int s_num)
652 string file_data_line;
653 int i, space_split_i, comma_split_i;
654 vector<int> loaded_path;
655 string node_pair, node;
659 the_paths.setup(0, 0);
660 save_file.open(load_file_path, ios::in);
662 // currently loads old mussa format
665 for(i = 0; i < seq_num; i++)
667 getline(save_file, file_data_line);
668 boost::shared_ptr<Sequence> a_seq(new Sequence(file_data_line));
669 the_seqs.push_back(a_seq);
673 getline(save_file, file_data_line);
674 window = atoi(file_data_line.c_str());
677 while (!save_file.eof())
680 getline(save_file, file_data_line);
681 if (file_data_line != "")
682 for(i = 0; i < seq_num; i++)
684 space_split_i = file_data_line.find(" ");
685 node_pair = file_data_line.substr(0,space_split_i);
686 //cout << "np= " << node_pair;
687 comma_split_i = node_pair.find(",");
688 node = node_pair.substr(comma_split_i+1);
689 //cout << "n= " << node << " ";
690 loaded_path.push_back(atoi (node.c_str()));
691 file_data_line = file_data_line.substr(space_split_i+1);
694 // FIXME: do we have any information about what the threshold should be?
695 the_paths.add_path(0, loaded_path);
699 //the_paths.save("tmp.save");
702 void Mussa::add_motif(const Sequence& motif, const Color& color)
704 motif_sequences.insert(motif);
705 color_mapper->appendInstanceColor("motif", motif.get_sequence(), color);
708 void Mussa::set_motifs(const vector<Sequence>& motifs,
709 const vector<Color>& colors)
711 if (motifs.size() != colors.size()) {
712 throw mussa_error("motif and color vectors must be the same size");
715 motif_sequences.clear();
716 for(size_t i = 0; i != motifs.size(); ++i)
718 add_motif(motifs[i], colors[i]);
720 update_sequences_motifs();
723 // I mostly split the ifstream out so I can use a stringstream to test it.
724 void Mussa::load_motifs(std::istream &in)
733 in >> seq >> red >> green >> blue;
734 // if we couldn't read this line 'cause we're like at the end of the file
735 // try to exit the loop
739 seq = Sequence::motif_normalize(seq);
740 } catch(motif_normalize_error e) {
741 clog << "unable to parse " << seq << " skipping" << endl;
742 clog << e.what() << endl;
745 if (red < 0.0 or red > 1.0) {
746 clog << "invalid red value " << red << ". must be in range [0..1]"
750 if (green < 0.0 or green > 1.0) {
751 clog << "invalid green value " << green << ". must be in range [0..1]"
755 if (blue < 0.0 or blue > 1.0) {
756 clog << "invalid blue value " << blue << ". must be in range [0..1]"
760 if (motif_sequences.find(seq) == motif_sequences.end()) {
761 // sequence wasn't found
762 motif_sequences.insert(seq);
763 Color c(red, green, blue);
764 color_mapper->appendInstanceColor("motif", seq, c);
766 clog << "sequence " << seq << " was already defined skipping"
771 update_sequences_motifs();
774 void Mussa::load_motifs(fs::path filename)
777 f.open(filename, ifstream::in);
781 void Mussa::update_sequences_motifs()
783 // once we've loaded all the motifs from the file,
784 // lets attach them to the sequences
785 for(vector<boost::shared_ptr<Sequence> >::iterator seq_i = the_seqs.begin();
786 seq_i != the_seqs.end();
789 // clear out old motifs
790 (*seq_i)->clear_motifs();
791 // for all the motifs in our set, attach them to the current sequence
792 for(set<Sequence>::iterator motif_i = motif_sequences.begin();
793 motif_i != motif_sequences.end();
796 (*seq_i)->add_motif(*motif_i);
801 const set<Sequence>& Mussa::motifs() const
803 return motif_sequences;
806 boost::shared_ptr<AnnotationColors> Mussa::colorMapper()