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 (fs::exists(para_file_path))
321 para_file.open(para_file_path, ios::in);
323 // what directory is the mupa file in?
324 fs::path file_path_base = para_file_path.branch_path();
326 // setup loop by getting file's first line
327 getline(para_file,file_data_line);
328 split_index = file_data_line.find(" ");
329 param = file_data_line.substr(0,split_index);
330 value = file_data_line.substr(split_index+1);
332 while (!para_file.eof())
335 if (param == "ANA_NAME")
336 analysis_name = value;
337 else if (param == "APPEND_WIN")
339 else if (param == "APPEND_THRES")
341 else if (param == "SEQUENCE_NUM")
342 ; // ignore sequence_num now
343 else if (param == "WINDOW")
344 window = atoi(value.c_str());
345 else if (param == "THRESHOLD")
346 threshold = atoi(value.c_str());
347 else if (param == "SEQUENCE")
349 fs::path seq_file = file_path_base / value;
350 //cout << "seq_file_name " << seq_files.back() << endl;
357 while ((!para_file.eof()) && seq_params)
359 getline(para_file,file_data_line);
360 split_index = file_data_line.find(" ");
361 param = file_data_line.substr(0,split_index);
362 value = file_data_line.substr(split_index+1);
364 if (param == "FASTA_INDEX")
365 fasta_index = atoi(value.c_str());
366 else if (param == "ANNOTATION")
367 annot_file = file_path_base / value;
368 else if (param == "SEQ_START")
369 sub_seq_start = atoi(value.c_str());
370 else if (param == "SEQ_END")
372 sub_seq_end = atoi(value.c_str());
374 //ignore empty lines or that start with '#'
375 else if ((param == "") || (param == "#")) {}
376 else seq_params = false;
378 load_sequence(seq_file, annot_file, fasta_index, sub_seq_start,
382 //ignore empty lines or that start with '#'
383 else if ((param == "") || (param == "#")) {}
386 clog << "Illegal/misplaced mussa parameter in file\n";
387 clog << param << "\n";
392 getline(para_file,file_data_line);
393 split_index = file_data_line.find(" ");
394 param = file_data_line.substr(0,split_index);
395 value = file_data_line.substr(split_index+1);
402 soft_thres = threshold;
403 //cout << "nway mupa: analysis_name = " << analysis_name
404 // << " window = " << window
405 // << " threshold = " << threshold << endl;
407 // no file was loaded, signal error
410 throw mussa_load_error("Config File: " + para_file_path.string() + " not found");
419 time_t t1, t2, begin, end;
420 double seqloadtime, seqcomptime, nwaytime, savetime, totaltime;
426 if (the_seqs.size() < 2) {
427 throw mussa_analysis_error("you need to have at least 2 sequences to "
430 //cout << "nway ana: seq_num = " << the_seqs.size() << endl;
433 seqloadtime = difftime(t2, t1);
438 seqcomptime = difftime(t2, t1);
441 the_paths.setup(window, threshold);
444 nwaytime = difftime(t2, t1);
449 savetime = difftime(t2, t1);
452 totaltime = difftime(end, begin);
454 //cout << "seqload\tseqcomp\tnway\tsave\ttotal\n";
455 //cout << seqloadtime << "\t";
456 //cout << seqcomptime << "\t";
457 //cout << nwaytime << "\t";
458 //cout << savetime << "\t";
459 //cout << totaltime << "\n";
465 vector<int> seq_lens;
466 vector<FLPs> empty_FLP_vector;
468 string save_file_string;
470 empty_FLP_vector.clear();
471 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
473 all_comps.push_back(empty_FLP_vector);
474 for(vector<Sequence>::size_type i2 = 0; i2 < the_seqs.size(); i2++)
475 all_comps[i].push_back(dummy_comp);
477 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
478 seq_lens.push_back(the_seqs[i]->size());
480 int seqcomps_done = 0;
481 int seqcomps_todo = (the_seqs.size() * (the_seqs.size()-1)) / 2;
482 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
484 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
485 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
487 //cout << "seqcomping: " << i << " v. " << i2 << endl;
488 all_comps[i][i2].setup(window, threshold);
489 all_comps[i][i2].seqcomp(*the_seqs[i], *the_seqs[i2], false);
490 all_comps[i][i2].seqcomp(*the_seqs[i], the_seqs[i2]->rev_comp(),true);
492 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
500 the_paths.set_soft_threshold(soft_thres);
502 if (ana_mode == TransitiveNway) {
503 the_paths.trans_path_search(all_comps);
505 else if (ana_mode == RadialNway) {
506 the_paths.radiate_path_search(all_comps);
508 else if (ana_mode == EntropyNway)
510 vector<string> some_Seqs;
511 //unlike other methods, entropy needs to look at the sequence at this stage
513 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
515 some_Seqs.push_back(*the_seqs[i]);
518 the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
519 the_paths.entropy_path_search(all_comps);
522 // old recursive transitive analysis function
523 else if (ana_mode == RecursiveNway)
524 the_paths.find_paths_r(all_comps);
526 the_paths.simple_refine();
533 fs::path flp_filepath;
534 fs::fstream save_file;
535 ostringstream append_info;
536 int dir_create_status;
538 if (not analysis_name.empty()) {
539 // not sure why, but gotta close file each time since can't pass
541 save_name = analysis_name;
543 // gotta do bit with adding win & thres if to be appended
547 append_info << "_w" << window;
548 save_name += append_info.str();
554 append_info << "_t" << threshold;
555 save_name += append_info.str();
557 fs::path save_path( save_name);
559 if (not fs::exists(save_path)) {
560 fs::create_directory(save_path);
562 // save sequence and annots to a special mussa file
563 save_file.open(save_path / (save_name+".museq"), ios::out);
564 save_file << "<Mussa_Sequence>" << endl;
566 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
568 the_seqs[i]->save(save_file);
571 save_file << "</Mussa_Sequence>" << endl;
574 // save nway paths to its mussa save file
575 the_paths.save(save_path / (save_name + ".muway"));
577 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
578 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
581 append_info << "_sp_" << i << "v" << i2;
582 all_comps[i][i2].save(save_path/(save_name+append_info.str()+".flp"));
585 throw mussa_error("Can't save analysis without an analysis name");
591 Mussa::save_muway(fs::path save_path)
593 the_paths.save(save_path);
597 Mussa::load(fs::path ana_file)
600 fs::path file_path_base;
601 fs::path a_file_path;
602 fs::path ana_path(ana_file);
605 ostringstream append_info;
606 vector<FLPs> empty_FLP_vector;
609 //clog << "ana_file name " << ana_file.string() << endl;
610 analysis_name = ana_path.leaf();
611 //clog << " ana_name " << analysis_name << endl;
612 file_path_base = ana_path.branch_path() / analysis_name;
613 a_file_path = file_path_base / (analysis_name + ".muway");
614 //clog << " loading museq: " << a_file_path.string() << endl;
615 the_paths.load(a_file_path);
616 // perhaps this could be more elegent, but at least this'll let
617 // us know what our threshold and window sizes were when we load a muway
618 window = the_paths.get_window();
619 threshold = the_paths.get_threshold();
620 soft_thres = threshold;
622 int seq_num = the_paths.sequence_count();
624 a_file_path = file_path_base / (analysis_name + ".museq");
626 // this is a bit of a hack due to C++ not acting like it should with files
627 for (i = 1; i <= seq_num; i++)
629 boost::shared_ptr<Sequence> tmp_seq(new Sequence);
630 //clog << "mussa_class: loading museq frag... " << a_file_path.string() << endl;
631 tmp_seq->load_museq(a_file_path, i);
632 the_seqs.push_back(tmp_seq);
635 empty_FLP_vector.clear();
636 for(i = 0; i < seq_num; i++)
638 all_comps.push_back(empty_FLP_vector);
639 for(i2 = 0; i2 < seq_num; i2++)
640 all_comps[i].push_back(dummy_comp);
643 for(i = 0; i < seq_num; i++)
645 for(i2 = i+1; i2 < seq_num; i2++)
648 append_info << analysis_name << "_sp_" << i << "v" << i2 << ".flp";
649 //clog << append_info.str() << endl;
650 a_file_path = file_path_base / append_info.str();
651 //clog << "path " << a_file_path.string() << endl;
652 all_comps[i][i2].load(a_file_path);
653 //clog << "real size = " << all_comps[i][i2].size() << endl;
662 fs::fstream save_file;
664 save_file.open(analysis_name, ios::out);
666 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
667 save_file << *(the_seqs[i]) << endl;
669 save_file << window << endl;
671 //note more complex eventually since analysis_name may need to have
672 //window size, threshold and other stuff to modify it...
673 the_paths.save_old(analysis_name);
678 Mussa::load_old(char * load_file_path, int s_num)
681 string file_data_line;
682 int i, space_split_i, comma_split_i;
683 vector<int> loaded_path;
684 string node_pair, node;
688 the_paths.setup(0, 0);
689 save_file.open(load_file_path, ios::in);
691 // currently loads old mussa format
694 for(i = 0; i < seq_num; i++)
696 getline(save_file, file_data_line);
697 boost::shared_ptr<Sequence> a_seq(new Sequence(file_data_line));
698 the_seqs.push_back(a_seq);
702 getline(save_file, file_data_line);
703 window = atoi(file_data_line.c_str());
706 while (!save_file.eof())
709 getline(save_file, file_data_line);
710 if (file_data_line != "")
711 for(i = 0; i < seq_num; i++)
713 space_split_i = file_data_line.find(" ");
714 node_pair = file_data_line.substr(0,space_split_i);
715 //cout << "np= " << node_pair;
716 comma_split_i = node_pair.find(",");
717 node = node_pair.substr(comma_split_i+1);
718 //cout << "n= " << node << " ";
719 loaded_path.push_back(atoi (node.c_str()));
720 file_data_line = file_data_line.substr(space_split_i+1);
723 // FIXME: do we have any information about what the threshold should be?
724 the_paths.add_path(0, loaded_path);
728 //the_paths.save("tmp.save");
731 void Mussa::add_motif(const Sequence& motif, const Color& color)
733 motif_sequences.insert(motif);
734 color_mapper->appendInstanceColor("motif", motif, color);
737 void Mussa::set_motifs(const vector<Sequence>& motifs,
738 const vector<Color>& colors)
740 if (motifs.size() != colors.size()) {
741 throw mussa_error("motif and color vectors must be the same size");
744 motif_sequences.clear();
745 for(size_t i = 0; i != motifs.size(); ++i)
747 add_motif(motifs[i], colors[i]);
749 update_sequences_motifs();
752 // I mostly split the ifstream out so I can use a stringstream to test it.
753 void Mussa::load_motifs(std::istream &in)
762 in >> seq >> red >> green >> blue;
763 // if we couldn't read this line 'cause we're like at the end of the file
764 // try to exit the loop
768 seq = Sequence::motif_normalize(seq);
769 } catch(motif_normalize_error e) {
770 clog << "unable to parse " << seq << " skipping" << endl;
771 clog << e.what() << endl;
774 if (red < 0.0 or red > 1.0) {
775 clog << "invalid red value " << red << ". must be in range [0..1]"
779 if (green < 0.0 or green > 1.0) {
780 clog << "invalid green value " << green << ". must be in range [0..1]"
784 if (blue < 0.0 or blue > 1.0) {
785 clog << "invalid blue value " << blue << ". must be in range [0..1]"
789 if (motif_sequences.find(seq) == motif_sequences.end()) {
790 // sequence wasn't found
791 motif_sequences.insert(seq);
792 Color c(red, green, blue);
793 color_mapper->appendInstanceColor("motif", seq, c);
795 clog << "sequence " << seq << " was already defined skipping"
800 update_sequences_motifs();
803 void Mussa::load_motifs(fs::path filename)
806 f.open(filename, ifstream::in);
810 void Mussa::update_sequences_motifs()
812 // once we've loaded all the motifs from the file,
813 // lets attach them to the sequences
814 for(vector<boost::shared_ptr<Sequence> >::iterator seq_i = the_seqs.begin();
815 seq_i != the_seqs.end();
818 // clear out old motifs
819 (*seq_i)->clear_motifs();
820 // for all the motifs in our set, attach them to the current sequence
821 for(set<Sequence>::iterator motif_i = motif_sequences.begin();
822 motif_i != motif_sequences.end();
825 (*seq_i)->add_motif(*motif_i);
830 const set<Sequence>& Mussa::motifs() const
832 return motif_sequences;
835 boost::shared_ptr<AnnotationColors> Mussa::colorMapper()