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 // ----------------------------------------
14 #include <boost/filesystem/operations.hpp>
15 #include <boost/filesystem/fstream.hpp>
16 namespace fs = boost::filesystem;
21 #include "mussa_exceptions.hpp"
22 #include "alg/mussa.hpp"
23 #include "alg/flp.hpp"
32 Mussa::Mussa(const Mussa& m)
33 : analysis_name(m.analysis_name),
35 threshold(m.threshold),
36 soft_thres(m.soft_thres),
38 win_append(m.win_append),
39 thres_append(m.thres_append),
40 motif_sequences(m.motif_sequences),
41 color_mapper(m.color_mapper)
45 // set all parameters to null state
50 ana_mode = TransitiveNway;
56 motif_sequences.clear();
60 // these 5 simple methods manually set the parameters for doing an analysis
61 // used so that the gui can take input from user and setup the analysis
62 // note - still need a set_append(bool, bool) method...
64 Mussa::set_name(string a_name)
66 analysis_name = a_name;
69 string Mussa::get_name()
77 if (the_seqs.size() > 0)
78 return the_seqs.size();
84 Mussa::set_window(int a_window)
89 int Mussa::get_window() const
95 Mussa::set_threshold(int a_threshold)
97 threshold = a_threshold;
98 if (a_threshold > soft_thres)
99 soft_thres = a_threshold;
102 int Mussa::get_threshold() const
108 Mussa::set_soft_threshold(int new_threshold)
110 if (new_threshold < threshold) {
111 soft_thres = threshold;
112 } else if (new_threshold > window) {
115 soft_thres = new_threshold;
119 int Mussa::get_soft_threshold() const
125 Mussa::set_analysis_mode(enum analysis_modes new_ana_mode)
127 ana_mode = new_ana_mode;
130 enum Mussa::analysis_modes Mussa::get_analysis_mode() const
135 string Mussa::get_analysis_mode_name() const
140 return string("Transitive");
143 return string("Radial");
146 return string("Entropy");
149 return string("[deprecated] Recursive");
152 throw runtime_error("invalid analysis mode type");
157 const NwayPaths& Mussa::paths() const
162 //template <class IteratorT>
163 //void Mussa::createLocalAlignment(IteratorT begin, IteratorT end)
164 void Mussa::createLocalAlignment(std::list<ConservedPath>::iterator begin,
165 std::list<ConservedPath>::iterator end,
166 std::list<ConservedPath::path_type>& result,
167 std::list<std::vector<bool> >& reversed)
169 const vector<Sequence>& raw_seq = the_seqs;
170 ConservedPath::path_type aligned_path;
173 int window_length, win_i;
176 vector<bool> rc_list;
178 vector<bool> matched;
182 for(std::list<ConservedPath>::iterator pathz_i=begin; pathz_i != end; ++pathz_i)
184 ConservedPath& a_path = *pathz_i;
185 window_length = a_path.window_size;
186 // determine which parts of the path are RC relative to first species
187 rc_list = a_path.reverseComplimented();
189 // loop over each bp in the conserved region for all sequences
190 for(win_i = 0; win_i < window_length; win_i++)
192 aligned_path.clear();
193 // determine which exact base pairs match between the sequences
195 for(i2 = 0; i2 < a_path.size()-1; i2++)
197 // assume not rc as most likely, adjust below
200 // no matter the case, any RC node needs adjustments
202 rc_1 = window_length-1;
203 if (a_path[i2+1] < 0)
204 rc_2 = window_length-1;
206 x_start = (abs(a_path[i2]-rc_1+win_i));
207 x_end = (abs(a_path[i2+1]-rc_2+win_i));
210 // ugh, and xor...only want rc coloring if just one of the nodes is rc
211 // if both nodes are rc, then they are 'normal' relative to each other
212 if((rc_list[i2] || rc_list[i2+1] )&&!(rc_list[i2] && rc_list[i2+1]))
213 { //the hideous rc matching logic - not complex, but annoying
214 if(!(( (raw_seq[i2][x_start]=='A')&&(raw_seq[i2+1][x_end]=='T')) ||
215 ((raw_seq[i2][x_start]=='T')&&(raw_seq[i2+1][x_end]=='A')) ||
216 ((raw_seq[i2][x_start]=='G')&&(raw_seq[i2+1][x_end]=='C')) ||
217 ((raw_seq[i2][x_start]=='C')&&(raw_seq[i2+1][x_end]=='G'))) )
221 aligned_path.push_back(x_start);
226 if (!( (raw_seq[i2][x_start] == raw_seq[i2+1][x_end]) &&
227 (raw_seq[i2][x_start] != 'N') &&
228 (raw_seq[i2+1][x_end] != 'N') ) ) {
231 aligned_path.push_back(x_start);
235 // grab the last part of our path, assuming we matched
237 aligned_path.push_back(x_end);
239 if (aligned_path.size() == a_path.size()) {
240 result.push_back(aligned_path);
241 reversed.push_back(rc_list);
249 // takes a string and sets it as the next seq
251 Mussa::add_a_seq(string a_seq)
256 the_seqs.push_back(aSeq);
259 const vector<Sequence>&
260 Mussa::sequences() const
265 void Mussa::load_sequence(fs::path seq_file, fs::path annot_file,
266 int fasta_index, int sub_seq_start, int sub_seq_end)
269 aseq.load_fasta(seq_file, fasta_index, sub_seq_start, sub_seq_end);
270 if ( not annot_file.empty() ) {
271 aseq.load_annot(annot_file, sub_seq_start, sub_seq_end);
273 the_seqs.push_back(aseq);
277 Mussa::load_mupa_file(fs::path para_file_path)
279 fs::ifstream para_file;
280 string file_data_line;
283 int split_index, fasta_index;
284 int sub_seq_start, sub_seq_end;
285 bool seq_params, did_seq;
288 string::size_type new_index, dir_index;
293 // if file was opened, read the parameter values
294 if (fs::exists(para_file_path))
296 para_file.open(para_file_path, ios::in);
298 // what directory is the mupa file in?
299 fs::path file_path_base = para_file_path.branch_path();
301 // setup loop by getting file's first line
302 getline(para_file,file_data_line);
303 split_index = file_data_line.find(" ");
304 param = file_data_line.substr(0,split_index);
305 value = file_data_line.substr(split_index+1);
307 while (!para_file.eof())
310 if (param == "ANA_NAME")
311 analysis_name = value;
312 else if (param == "APPEND_WIN")
314 else if (param == "APPEND_THRES")
316 else if (param == "SEQUENCE_NUM")
317 ; // ignore sequence_num now
318 else if (param == "WINDOW")
319 window = atoi(value.c_str());
320 else if (param == "THRESHOLD")
321 threshold = atoi(value.c_str());
322 else if (param == "SEQUENCE")
324 fs::path seq_file = file_path_base / value;
325 //cout << "seq_file_name " << seq_files.back() << endl;
332 while ((!para_file.eof()) && seq_params)
334 getline(para_file,file_data_line);
335 split_index = file_data_line.find(" ");
336 param = file_data_line.substr(0,split_index);
337 value = file_data_line.substr(split_index+1);
339 if (param == "FASTA_INDEX")
340 fasta_index = atoi(value.c_str());
341 else if (param == "ANNOTATION")
342 annot_file = file_path_base / value;
343 else if (param == "SEQ_START")
344 sub_seq_start = atoi(value.c_str());
345 else if (param == "SEQ_END")
347 sub_seq_end = atoi(value.c_str());
349 //ignore empty lines or that start with '#'
350 else if ((param == "") || (param == "#")) {}
351 else seq_params = false;
353 load_sequence(seq_file, annot_file, fasta_index, sub_seq_start,
357 //ignore empty lines or that start with '#'
358 else if ((param == "") || (param == "#")) {}
361 clog << "Illegal/misplaced mussa parameter in file\n";
362 clog << param << "\n";
367 getline(para_file,file_data_line);
368 split_index = file_data_line.find(" ");
369 param = file_data_line.substr(0,split_index);
370 value = file_data_line.substr(split_index+1);
377 soft_thres = threshold;
378 //cout << "nway mupa: analysis_name = " << analysis_name
379 // << " window = " << window
380 // << " threshold = " << threshold << endl;
382 // no file was loaded, signal error
385 throw mussa_load_error("Config File: " + para_file_path.string() + " not found");
391 Mussa::analyze(int w, int t, enum Mussa::analysis_modes the_ana_mode, double new_ent_thres)
393 time_t t1, t2, begin, end;
394 double seqloadtime, seqcomptime, nwaytime, savetime, totaltime;
398 ana_mode = the_ana_mode;
399 ent_thres = new_ent_thres;
410 if (the_seqs.size() < 2) {
411 throw mussa_analysis_error("you need to have at least 2 sequences to "
414 //cout << "nway ana: seq_num = " << the_seqs.size() << endl;
417 seqloadtime = difftime(t2, t1);
422 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);
440 //cout << "seqload\tseqcomp\tnway\tsave\ttotal\n";
441 //cout << seqloadtime << "\t";
442 //cout << seqcomptime << "\t";
443 //cout << nwaytime << "\t";
444 //cout << savetime << "\t";
445 //cout << totaltime << "\n";
451 vector<int> seq_lens;
452 vector<FLPs> empty_FLP_vector;
454 string save_file_string;
456 empty_FLP_vector.clear();
457 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
459 all_comps.push_back(empty_FLP_vector);
460 for(vector<Sequence>::size_type i2 = 0; i2 < the_seqs.size(); i2++)
461 all_comps[i].push_back(dummy_comp);
463 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
464 seq_lens.push_back(the_seqs[i].size());
466 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
467 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
469 //cout << "seqcomping: " << i << " v. " << i2 << endl;
470 all_comps[i][i2].setup(window, threshold);
471 all_comps[i][i2].seqcomp(the_seqs[i].get_seq(), the_seqs[i2].get_seq(), false);
472 all_comps[i][i2].seqcomp(the_seqs[i].get_seq(),the_seqs[i2].rev_comp(),true);
479 vector<string> some_Seqs;
481 the_paths.set_soft_threshold(soft_thres);
483 if (ana_mode == TransitiveNway) {
484 the_paths.trans_path_search(all_comps);
486 else if (ana_mode == RadialNway) {
487 the_paths.radiate_path_search(all_comps);
489 else if (ana_mode == EntropyNway)
491 //unlike other methods, entropy needs to look at the sequence at this stage
493 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
495 some_Seqs.push_back(the_seqs[i].get_seq());
498 the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
499 the_paths.entropy_path_search(all_comps);
502 // old recursive transitive analysis function
503 else if (ana_mode == RecursiveNway)
504 the_paths.find_paths_r(all_comps);
506 the_paths.simple_refine();
513 fs::path flp_filepath;
514 fs::fstream save_file;
515 ostringstream append_info;
516 int dir_create_status;
518 if (not analysis_name.empty()) {
519 // not sure why, but gotta close file each time since can't pass
521 save_name = analysis_name;
523 // gotta do bit with adding win & thres if to be appended
527 append_info << "_w" << window;
528 save_name += append_info.str();
534 append_info << "_t" << threshold;
535 save_name += append_info.str();
537 fs::path save_path( save_name);
539 if (not fs::exists(save_path)) {
540 fs::create_directory(save_path);
542 // save sequence and annots to a special mussa file
543 save_file.open(save_path / (save_name+".museq"), ios::out);
544 save_file << "<Mussa_Sequence>" << endl;
546 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
548 the_seqs[i].save(save_file);
551 save_file << "</Mussa_Sequence>" << endl;
554 // save nway paths to its mussa save file
555 the_paths.save(save_path / (save_name + ".muway"));
557 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
558 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
561 append_info << "_sp_" << i << "v" << i2;
562 all_comps[i][i2].save(save_path/(save_name+append_info.str()+".flp"));
568 Mussa::save_muway(fs::path save_path)
570 the_paths.save(save_path);
574 Mussa::load(fs::path ana_file)
577 fs::path file_path_base;
578 fs::path a_file_path;
579 fs::path ana_path(ana_file);
583 ostringstream append_info;
584 vector<FLPs> empty_FLP_vector;
587 //cout << "ana_file name " << ana_file.string() << endl;
588 analysis_name = ana_path.leaf();
589 //cout << " ana_name " << analysis_name << endl;
590 file_path_base = ana_path.branch_path() / analysis_name;
591 a_file_path = file_path_base / (analysis_name + ".muway");
592 //cout << " loading museq: " << a_file_path.string() << endl;
593 the_paths.load(a_file_path);
594 // perhaps this could be more elegent, but at least this'll let
595 // us know what our threshold and window sizes were when we load a muway
596 window = the_paths.get_window();
597 threshold = the_paths.get_threshold();
598 soft_thres = threshold;
600 int seq_num = the_paths.sequence_count();
602 a_file_path = file_path_base / (analysis_name + ".museq");
604 // this is a bit of a hack due to C++ not acting like it should with files
605 for (i = 1; i <= seq_num; i++)
608 //cout << "mussa_class: loading museq frag... " << a_file_path.string() << endl;
609 tmp_seq.load_museq(a_file_path, i);
610 the_seqs.push_back(tmp_seq);
613 empty_FLP_vector.clear();
614 for(i = 0; i < seq_num; i++)
616 all_comps.push_back(empty_FLP_vector);
617 for(i2 = 0; i2 < seq_num; i2++)
618 all_comps[i].push_back(dummy_comp);
621 for(i = 0; i < seq_num; i++)
623 for(i2 = i+1; i2 < seq_num; i2++)
626 append_info << analysis_name << "_sp_" << i << "v" << i2 << ".flp";
627 //cout << append_info.str() << endl;
628 a_file_path = file_path_base / append_info.str();
629 //cout << "path " << a_file_path.string() << endl;
630 all_comps[i][i2].load(a_file_path);
631 //cout << "real size = " << all_comps[i][i2].size() << endl;
640 fs::fstream save_file;
642 save_file.open(analysis_name, ios::out);
644 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
645 save_file << the_seqs[i].get_seq() << endl;
647 save_file << window << endl;
649 //note more complex eventually since analysis_name may need to have
650 //window size, threshold and other stuff to modify it...
651 the_paths.save_old(analysis_name);
656 Mussa::load_old(char * load_file_path, int s_num)
659 string file_data_line;
660 int i, space_split_i, comma_split_i;
661 vector<int> loaded_path;
662 string node_pair, node;
666 the_paths.setup(0, 0);
667 save_file.open(load_file_path, ios::in);
669 // currently loads old mussa format
672 for(i = 0; i < seq_num; i++)
674 getline(save_file, file_data_line);
675 a_seq.set_seq(file_data_line);
676 the_seqs.push_back(a_seq);
680 getline(save_file, file_data_line);
681 window = atoi(file_data_line.c_str());
684 while (!save_file.eof())
687 getline(save_file, file_data_line);
688 if (file_data_line != "")
689 for(i = 0; i < seq_num; i++)
691 space_split_i = file_data_line.find(" ");
692 node_pair = file_data_line.substr(0,space_split_i);
693 //cout << "np= " << node_pair;
694 comma_split_i = node_pair.find(",");
695 node = node_pair.substr(comma_split_i+1);
696 //cout << "n= " << node << " ";
697 loaded_path.push_back(atoi (node.c_str()));
698 file_data_line = file_data_line.substr(space_split_i+1);
701 // FIXME: do we have any information about what the threshold should be?
702 the_paths.add_path(0, loaded_path);
706 //the_paths.save("tmp.save");
709 void Mussa::add_motifs(const vector<string>& motifs,
710 const vector<Color>& colors)
712 if (motifs.size() != colors.size()) {
713 throw mussa_error("motif and color vectors must be the same size");
716 for(size_t i = 0; i != motifs.size(); ++i)
718 motif_sequences.insert(motifs[i]);
719 color_mapper.appendInstanceColor("motif", motifs[i], colors[i]);
721 update_sequences_motifs();
724 // I mostly split the ifstream out so I can use a stringstream to test it.
725 void Mussa::load_motifs(std::istream &in)
734 in >> seq >> red >> green >> blue;
735 // if we couldn't read this line 'cause we're like at the end of the file
736 // try to exit the loop
740 seq = Sequence::motif_normalize(seq);
741 } catch(motif_normalize_error e) {
742 clog << "unable to parse " << seq << " skipping" << endl;
743 clog << e.what() << endl;
746 if (red < 0.0 or red > 1.0) {
747 clog << "invalid red value " << red << ". must be in range [0..1]"
751 if (green < 0.0 or green > 1.0) {
752 clog << "invalid green value " << green << ". must be in range [0..1]"
756 if (blue < 0.0 or blue > 1.0) {
757 clog << "invalid blue value " << blue << ". must be in range [0..1]"
761 if (motif_sequences.find(seq) == motif_sequences.end()) {
762 // sequence wasn't found
763 motif_sequences.insert(seq);
764 Color c(red, green, blue);
765 color_mapper.appendInstanceColor("motif", seq, c);
767 clog << "sequence " << seq << " was already defined skipping"
772 update_sequences_motifs();
775 void Mussa::load_motifs(fs::path filename)
778 f.open(filename, ifstream::in);
782 void Mussa::update_sequences_motifs()
784 // once we've loaded all the motifs from the file,
785 // lets attach them to the sequences
786 for(vector<Sequence>::iterator seq_i = the_seqs.begin();
787 seq_i != the_seqs.end();
790 // clear out old motifs
791 seq_i->clear_motifs();
792 // for all the motifs in our set, attach them to the current sequence
793 for(set<string>::iterator motif_i = motif_sequences.begin();
794 motif_i != motif_sequences.end();
797 seq_i->add_motif(*motif_i);
802 const set<string>& Mussa::motifs() const
804 return motif_sequences;
807 AnnotationColors& Mussa::colorMapper()