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)
48 connect(&the_paths, SIGNAL(progress(const std::string&, int, int)),
49 this, SIGNAL(progress(const std::string&, int, int)));
52 // set all parameters to null state
57 ana_mode = TransitiveNway;
63 motif_sequences.clear();
64 if(color_mapper) color_mapper->clear();
68 // these 5 simple methods manually set the parameters for doing an analysis
69 // used so that the gui can take input from user and setup the analysis
70 // note - still need a set_append(bool, bool) method...
72 Mussa::set_name(string a_name)
74 analysis_name = a_name;
77 string Mussa::get_name()
85 if (the_seqs.size() > 0)
86 return the_seqs.size();
92 Mussa::set_window(int a_window)
97 int Mussa::get_window() const
103 Mussa::set_threshold(int a_threshold)
105 threshold = a_threshold;
106 if (a_threshold > soft_thres)
107 soft_thres = a_threshold;
110 int Mussa::get_threshold() const
116 Mussa::set_soft_threshold(int new_threshold)
118 if (new_threshold < threshold) {
119 soft_thres = threshold;
120 } else if (new_threshold > window) {
123 soft_thres = new_threshold;
127 int Mussa::get_soft_threshold() const
133 Mussa::set_analysis_mode(enum analysis_modes new_ana_mode)
135 ana_mode = new_ana_mode;
138 enum Mussa::analysis_modes Mussa::get_analysis_mode() const
143 string Mussa::get_analysis_mode_name() const
148 return string("Transitive");
151 return string("Radial");
154 return string("Entropy");
157 return string("[deprecated] Recursive");
160 throw runtime_error("invalid analysis mode type");
165 const NwayPaths& Mussa::paths() const
170 //template <class IteratorT>
171 //void Mussa::createLocalAlignment(IteratorT begin, IteratorT end)
172 void Mussa::createLocalAlignment(std::list<ConservedPath>::iterator begin,
173 std::list<ConservedPath>::iterator end,
174 std::list<ConservedPath::path_type>& result,
175 std::list<std::vector<bool> >& reversed)
177 const vector_sequence_type& raw_seq = the_seqs;
178 ConservedPath::path_type aligned_path;
181 int window_length, win_i;
184 vector<bool> rc_list;
186 vector<bool> matched;
190 for(std::list<ConservedPath>::iterator pathz_i=begin; pathz_i != end; ++pathz_i)
192 ConservedPath& a_path = *pathz_i;
193 window_length = a_path.window_size;
194 // determine which parts of the path are RC relative to first species
195 rc_list = a_path.reverseComplimented();
197 // loop over each bp in the conserved region for all sequences
198 for(win_i = 0; win_i < window_length; win_i++)
200 aligned_path.clear();
201 // determine which exact base pairs match between the sequences
203 for(i2 = 0; i2 < a_path.size()-1; i2++)
205 // assume not rc as most likely, adjust below
208 // no matter the case, any RC node needs adjustments
210 rc_1 = window_length-1;
211 if (a_path[i2+1] < 0)
212 rc_2 = window_length-1;
214 x_start = (abs(a_path[i2]-rc_1+win_i));
215 x_end = (abs(a_path[i2+1]-rc_2+win_i));
217 boost::shared_ptr<Sequence> cur(raw_seq[i2]) ;
218 boost::shared_ptr<Sequence> next(raw_seq[i2+1]);
220 // ugh, and xor...only want rc coloring if just one of the nodes is rc
221 // if both nodes are rc, then they are 'normal' relative to each other
222 if((rc_list[i2] || rc_list[i2+1] )&&!(rc_list[i2] && rc_list[i2+1]))
223 { //the hideous rc matching logic - not complex, but annoying
224 if(!(( ((*cur)[x_start]=='A')&&((*next)[x_end]=='T')) ||
225 (((*cur)[x_start]=='T')&&((*next)[x_end]=='A')) ||
226 (((*cur)[x_start]=='G')&&((*next)[x_end]=='C')) ||
227 (((*cur)[x_start]=='C')&&((*next)[x_end]=='G'))) )
231 aligned_path.push_back(x_start);
236 if (!( ((*cur)[x_start] == (*next)[x_end]) &&
237 ((*cur)[x_start] != 'N') && ((*next)[x_end] != 'N') ) ) {
240 aligned_path.push_back(x_start);
244 // grab the last part of our path, assuming we matched
246 aligned_path.push_back(x_end);
248 if (aligned_path.size() == a_path.size()) {
249 result.push_back(aligned_path);
250 reversed.push_back(rc_list);
258 void Mussa::append_sequence(const Sequence& a_seq)
260 boost::shared_ptr<Sequence> seq_copy(new Sequence(a_seq));
261 the_seqs.push_back(seq_copy);
264 void Mussa::append_sequence(boost::shared_ptr<Sequence> a_seq)
266 the_seqs.push_back(a_seq);
270 const vector<boost::shared_ptr<Sequence> >&
271 Mussa::sequences() const
276 void Mussa::load_sequence(fs::path seq_file, fs::path annot_file,
277 int fasta_index, int sub_seq_start, int sub_seq_end)
279 boost::shared_ptr<Sequence> aseq(new Sequence);
280 aseq->load_fasta(seq_file, fasta_index, sub_seq_start, sub_seq_end);
281 if ( not annot_file.empty() ) {
282 aseq->load_annot(annot_file, sub_seq_start, sub_seq_end);
284 the_seqs.push_back(aseq);
288 Mussa::load_mupa_file(fs::path para_file_path)
290 fs::ifstream para_file;
291 string file_data_line;
294 int split_index, fasta_index;
295 int sub_seq_start, sub_seq_end;
296 bool seq_params, did_seq;
299 string::size_type new_index, dir_index;
304 // if file was opened, read the parameter values
305 if (fs::exists(para_file_path))
307 para_file.open(para_file_path, ios::in);
309 // what directory is the mupa file in?
310 fs::path file_path_base = para_file_path.branch_path();
312 // setup loop by getting file's first line
313 getline(para_file,file_data_line);
314 split_index = file_data_line.find(" ");
315 param = file_data_line.substr(0,split_index);
316 value = file_data_line.substr(split_index+1);
318 while (!para_file.eof())
321 if (param == "ANA_NAME")
322 analysis_name = value;
323 else if (param == "APPEND_WIN")
325 else if (param == "APPEND_THRES")
327 else if (param == "SEQUENCE_NUM")
328 ; // ignore sequence_num now
329 else if (param == "WINDOW")
330 window = atoi(value.c_str());
331 else if (param == "THRESHOLD")
332 threshold = atoi(value.c_str());
333 else if (param == "SEQUENCE")
335 fs::path seq_file = file_path_base / value;
336 //cout << "seq_file_name " << seq_files.back() << endl;
343 while ((!para_file.eof()) && seq_params)
345 getline(para_file,file_data_line);
346 split_index = file_data_line.find(" ");
347 param = file_data_line.substr(0,split_index);
348 value = file_data_line.substr(split_index+1);
350 if (param == "FASTA_INDEX")
351 fasta_index = atoi(value.c_str());
352 else if (param == "ANNOTATION")
353 annot_file = file_path_base / value;
354 else if (param == "SEQ_START")
355 sub_seq_start = atoi(value.c_str());
356 else if (param == "SEQ_END")
358 sub_seq_end = atoi(value.c_str());
360 //ignore empty lines or that start with '#'
361 else if ((param == "") || (param == "#")) {}
362 else seq_params = false;
364 load_sequence(seq_file, annot_file, fasta_index, sub_seq_start,
368 //ignore empty lines or that start with '#'
369 else if ((param == "") || (param == "#")) {}
372 clog << "Illegal/misplaced mussa parameter in file\n";
373 clog << param << "\n";
378 getline(para_file,file_data_line);
379 split_index = file_data_line.find(" ");
380 param = file_data_line.substr(0,split_index);
381 value = file_data_line.substr(split_index+1);
388 soft_thres = threshold;
389 //cout << "nway mupa: analysis_name = " << analysis_name
390 // << " window = " << window
391 // << " threshold = " << threshold << endl;
393 // no file was loaded, signal error
396 throw mussa_load_error("Config File: " + para_file_path.string() + " not found");
404 time_t t1, t2, begin, end;
405 double seqloadtime, seqcomptime, nwaytime, savetime, totaltime;
411 if (the_seqs.size() < 2) {
412 throw mussa_analysis_error("you need to have at least 2 sequences to "
415 //cout << "nway ana: seq_num = " << the_seqs.size() << endl;
418 seqloadtime = difftime(t2, t1);
423 seqcomptime = difftime(t2, t1);
426 the_paths.setup(window, threshold);
429 nwaytime = difftime(t2, t1);
434 savetime = difftime(t2, t1);
437 totaltime = difftime(end, begin);
439 //cout << "seqload\tseqcomp\tnway\tsave\ttotal\n";
440 //cout << seqloadtime << "\t";
441 //cout << seqcomptime << "\t";
442 //cout << nwaytime << "\t";
443 //cout << savetime << "\t";
444 //cout << totaltime << "\n";
450 vector<int> seq_lens;
451 vector<FLPs> empty_FLP_vector;
453 string save_file_string;
455 empty_FLP_vector.clear();
456 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
458 all_comps.push_back(empty_FLP_vector);
459 for(vector<Sequence>::size_type i2 = 0; i2 < the_seqs.size(); i2++)
460 all_comps[i].push_back(dummy_comp);
462 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
463 seq_lens.push_back(the_seqs[i]->size());
465 int seqcomps_done = 0;
466 int seqcomps_todo = (the_seqs.size() * (the_seqs.size()-1)) / 2;
467 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
469 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
470 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
472 //cout << "seqcomping: " << i << " v. " << i2 << endl;
473 all_comps[i][i2].setup(window, threshold);
474 all_comps[i][i2].seqcomp(*the_seqs[i], *the_seqs[i2], false);
475 all_comps[i][i2].seqcomp(*the_seqs[i], the_seqs[i2]->rev_comp(),true);
477 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
485 the_paths.set_soft_threshold(soft_thres);
487 if (ana_mode == TransitiveNway) {
488 the_paths.trans_path_search(all_comps);
490 else if (ana_mode == RadialNway) {
491 the_paths.radiate_path_search(all_comps);
493 else if (ana_mode == EntropyNway)
495 vector<string> some_Seqs;
496 //unlike other methods, entropy needs to look at the sequence at this stage
498 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
500 some_Seqs.push_back(*the_seqs[i]);
503 the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
504 the_paths.entropy_path_search(all_comps);
507 // old recursive transitive analysis function
508 else if (ana_mode == RecursiveNway)
509 the_paths.find_paths_r(all_comps);
511 the_paths.simple_refine();
518 fs::path flp_filepath;
519 fs::fstream save_file;
520 ostringstream append_info;
521 int dir_create_status;
523 if (not analysis_name.empty()) {
524 // not sure why, but gotta close file each time since can't pass
526 save_name = analysis_name;
528 // gotta do bit with adding win & thres if to be appended
532 append_info << "_w" << window;
533 save_name += append_info.str();
539 append_info << "_t" << threshold;
540 save_name += append_info.str();
542 fs::path save_path( save_name);
544 if (not fs::exists(save_path)) {
545 fs::create_directory(save_path);
547 // save sequence and annots to a special mussa file
548 save_file.open(save_path / (save_name+".museq"), ios::out);
549 save_file << "<Mussa_Sequence>" << endl;
551 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
553 the_seqs[i]->save(save_file);
556 save_file << "</Mussa_Sequence>" << endl;
559 // save nway paths to its mussa save file
560 the_paths.save(save_path / (save_name + ".muway"));
562 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
563 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
566 append_info << "_sp_" << i << "v" << i2;
567 all_comps[i][i2].save(save_path/(save_name+append_info.str()+".flp"));
573 Mussa::save_muway(fs::path save_path)
575 the_paths.save(save_path);
579 Mussa::load(fs::path ana_file)
582 fs::path file_path_base;
583 fs::path a_file_path;
584 fs::path ana_path(ana_file);
587 ostringstream append_info;
588 vector<FLPs> empty_FLP_vector;
591 //cout << "ana_file name " << ana_file.string() << endl;
592 analysis_name = ana_path.leaf();
593 //cout << " ana_name " << analysis_name << endl;
594 file_path_base = ana_path.branch_path() / analysis_name;
595 a_file_path = file_path_base / (analysis_name + ".muway");
596 //cout << " loading museq: " << a_file_path.string() << endl;
597 the_paths.load(a_file_path);
598 // perhaps this could be more elegent, but at least this'll let
599 // us know what our threshold and window sizes were when we load a muway
600 window = the_paths.get_window();
601 threshold = the_paths.get_threshold();
602 soft_thres = threshold;
604 int seq_num = the_paths.sequence_count();
606 a_file_path = file_path_base / (analysis_name + ".museq");
608 // this is a bit of a hack due to C++ not acting like it should with files
609 for (i = 1; i <= seq_num; i++)
611 boost::shared_ptr<Sequence> tmp_seq(new Sequence);
612 //cout << "mussa_class: loading museq frag... " << a_file_path.string() << endl;
613 tmp_seq->load_museq(a_file_path, i);
614 the_seqs.push_back(tmp_seq);
617 empty_FLP_vector.clear();
618 for(i = 0; i < seq_num; i++)
620 all_comps.push_back(empty_FLP_vector);
621 for(i2 = 0; i2 < seq_num; i2++)
622 all_comps[i].push_back(dummy_comp);
625 for(i = 0; i < seq_num; i++)
627 for(i2 = i+1; i2 < seq_num; i2++)
630 append_info << analysis_name << "_sp_" << i << "v" << i2 << ".flp";
631 //cout << append_info.str() << endl;
632 a_file_path = file_path_base / append_info.str();
633 //cout << "path " << a_file_path.string() << endl;
634 all_comps[i][i2].load(a_file_path);
635 //cout << "real size = " << all_comps[i][i2].size() << endl;
644 fs::fstream save_file;
646 save_file.open(analysis_name, ios::out);
648 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
649 save_file << *(the_seqs[i]) << endl;
651 save_file << window << endl;
653 //note more complex eventually since analysis_name may need to have
654 //window size, threshold and other stuff to modify it...
655 the_paths.save_old(analysis_name);
660 Mussa::load_old(char * load_file_path, int s_num)
663 string file_data_line;
664 int i, space_split_i, comma_split_i;
665 vector<int> loaded_path;
666 string node_pair, node;
670 the_paths.setup(0, 0);
671 save_file.open(load_file_path, ios::in);
673 // currently loads old mussa format
676 for(i = 0; i < seq_num; i++)
678 getline(save_file, file_data_line);
679 boost::shared_ptr<Sequence> a_seq(new Sequence(file_data_line));
680 the_seqs.push_back(a_seq);
684 getline(save_file, file_data_line);
685 window = atoi(file_data_line.c_str());
688 while (!save_file.eof())
691 getline(save_file, file_data_line);
692 if (file_data_line != "")
693 for(i = 0; i < seq_num; i++)
695 space_split_i = file_data_line.find(" ");
696 node_pair = file_data_line.substr(0,space_split_i);
697 //cout << "np= " << node_pair;
698 comma_split_i = node_pair.find(",");
699 node = node_pair.substr(comma_split_i+1);
700 //cout << "n= " << node << " ";
701 loaded_path.push_back(atoi (node.c_str()));
702 file_data_line = file_data_line.substr(space_split_i+1);
705 // FIXME: do we have any information about what the threshold should be?
706 the_paths.add_path(0, loaded_path);
710 //the_paths.save("tmp.save");
713 void Mussa::add_motif(const string& motif, const Color& color)
715 motif_sequences.insert(motif);
716 color_mapper->appendInstanceColor("motif", motif, color);
719 void Mussa::add_motifs(const vector<string>& motifs,
720 const vector<Color>& colors)
722 if (motifs.size() != colors.size()) {
723 throw mussa_error("motif and color vectors must be the same size");
726 for(size_t i = 0; i != motifs.size(); ++i)
728 add_motif(motifs[i], colors[i]);
730 update_sequences_motifs();
733 // I mostly split the ifstream out so I can use a stringstream to test it.
734 void Mussa::load_motifs(std::istream &in)
743 in >> seq >> red >> green >> blue;
744 // if we couldn't read this line 'cause we're like at the end of the file
745 // try to exit the loop
749 seq = Sequence::motif_normalize(seq);
750 } catch(motif_normalize_error e) {
751 clog << "unable to parse " << seq << " skipping" << endl;
752 clog << e.what() << endl;
755 if (red < 0.0 or red > 1.0) {
756 clog << "invalid red value " << red << ". must be in range [0..1]"
760 if (green < 0.0 or green > 1.0) {
761 clog << "invalid green value " << green << ". must be in range [0..1]"
765 if (blue < 0.0 or blue > 1.0) {
766 clog << "invalid blue value " << blue << ". must be in range [0..1]"
770 if (motif_sequences.find(seq) == motif_sequences.end()) {
771 // sequence wasn't found
772 motif_sequences.insert(seq);
773 Color c(red, green, blue);
774 color_mapper->appendInstanceColor("motif", seq, c);
776 clog << "sequence " << seq << " was already defined skipping"
781 update_sequences_motifs();
784 void Mussa::load_motifs(fs::path filename)
787 f.open(filename, ifstream::in);
791 void Mussa::update_sequences_motifs()
793 // once we've loaded all the motifs from the file,
794 // lets attach them to the sequences
795 for(vector<boost::shared_ptr<Sequence> >::iterator seq_i = the_seqs.begin();
796 seq_i != the_seqs.end();
799 // clear out old motifs
800 (*seq_i)->clear_motifs();
801 // for all the motifs in our set, attach them to the current sequence
802 for(set<string>::iterator motif_i = motif_sequences.begin();
803 motif_i != motif_sequences.end();
806 (*seq_i)->add_motif(*motif_i);
811 const set<string>& Mussa::motifs() const
813 return motif_sequences;
816 boost::shared_ptr<AnnotationColors> Mussa::colorMapper()