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/path.hpp>
16 #include <boost/filesystem/operations.hpp>
17 #include <boost/filesystem/fstream.hpp>
18 namespace fs = boost::filesystem;
23 #include "mussa_exceptions.hpp"
24 #include "alg/flp.hpp"
25 #include "alg/mussa.hpp"
26 #include "alg/motif_parser.hpp"
32 : color_mapper(new AnnotationColors)
35 connect(&the_paths, SIGNAL(progress(const QString&, int, int)),
36 this, SIGNAL(progress(const QString&, int, int)));
39 Mussa::Mussa(const Mussa& m)
40 : analysis_name(m.analysis_name),
42 threshold(m.threshold),
43 soft_thres(m.soft_thres),
45 win_append(m.win_append),
46 thres_append(m.thres_append),
47 motif_sequences(m.motif_sequences),
48 color_mapper(m.color_mapper),
49 analysis_path(m.analysis_path),
52 connect(&the_paths, SIGNAL(progress(const QString&, int, int)),
53 this, SIGNAL(progress(const QString&, int, int)));
56 MussaRef Mussa::init()
58 boost::shared_ptr<Mussa> m(new Mussa());
62 boost::filesystem::path Mussa::get_analysis_path() const
67 void Mussa::set_analysis_path(boost::filesystem::path pathname)
69 analysis_path = pathname;
72 // set all parameters to null state
77 ana_mode = TransitiveNway;
83 motif_sequences.clear();
84 if(color_mapper) color_mapper->clear();
87 analysis_path = fs::path();
91 void Mussa::set_dirty(bool new_state)
93 if (dirty != new_state) {
95 emit isModified(dirty);
99 bool Mussa::is_dirty() const
104 bool Mussa::empty() const
106 return the_seqs.empty();
110 // these 5 simple methods manually set the parameters for doing an analysis
111 // used so that the gui can take input from user and setup the analysis
112 // note - still need a set_append(bool, bool) method...
114 Mussa::set_name(string a_name)
116 analysis_name = a_name;
120 string Mussa::get_name() const
122 return analysis_name;
125 string Mussa::get_title() const
127 fs::path analysis_path = get_analysis_path();
128 if (not analysis_path.empty()) {
129 return analysis_path.native_file_string();
130 } else if (get_name().size() > 0) {
133 return std::string("Unnamed");
140 if (the_seqs.size() > 0)
141 return the_seqs.size();
147 Mussa::set_window(int a_window)
153 int Mussa::get_window() const
159 Mussa::set_threshold(int a_threshold)
161 threshold = a_threshold;
163 if (a_threshold > soft_thres) {
164 soft_thres = a_threshold;
168 int Mussa::get_threshold() const
174 Mussa::set_soft_threshold(int new_threshold)
176 if (new_threshold < threshold) {
177 soft_thres = threshold;
178 } else if (new_threshold > window) {
181 soft_thres = new_threshold;
185 int Mussa::get_soft_threshold() const
191 Mussa::set_analysis_mode(enum analysis_modes new_ana_mode)
193 ana_mode = new_ana_mode;
197 enum Mussa::analysis_modes Mussa::get_analysis_mode() const
202 string Mussa::get_analysis_mode_name() const
207 return string("Transitive");
210 return string("Radial");
213 return string("Entropy");
216 return string("[deprecated] Recursive");
219 throw runtime_error("invalid analysis mode type");
224 const NwayPaths& Mussa::paths() const
229 //template <class IteratorT>
230 //void Mussa::createLocalAlignment(IteratorT begin, IteratorT end)
231 void Mussa::createLocalAlignment(std::list<ConservedPath>::iterator begin,
232 std::list<ConservedPath>::iterator end,
233 std::list<ConservedPath::path_type>& result,
234 std::list<std::vector<bool> >& reversed)
236 const vector_sequence_type& raw_seq = the_seqs;
237 ConservedPath::path_type aligned_path;
240 int window_length, win_i;
243 vector<bool> rc_list;
245 vector<bool> matched;
249 for(std::list<ConservedPath>::iterator pathz_i=begin; pathz_i != end; ++pathz_i)
251 ConservedPath& a_path = *pathz_i;
252 window_length = a_path.window_size;
253 // determine which parts of the path are RC relative to first species
254 rc_list = a_path.reverseComplimented();
256 // loop over each bp in the conserved region for all sequences
257 for(win_i = 0; win_i < window_length; win_i++)
259 aligned_path.clear();
260 // determine which exact base pairs match between the sequences
262 for(i2 = 0; i2 < a_path.size()-1; i2++)
264 // assume not rc as most likely, adjust below
267 // no matter the case, any RC node needs adjustments
269 rc_1 = window_length-1;
270 if (a_path[i2+1] < 0)
271 rc_2 = window_length-1;
273 x_start = (abs(a_path[i2]-rc_1+win_i));
274 x_end = (abs(a_path[i2+1]-rc_2+win_i));
276 boost::shared_ptr<Sequence> cur(raw_seq[i2]) ;
277 boost::shared_ptr<Sequence> next(raw_seq[i2+1]);
279 // ugh, and xor...only want rc coloring if just one of the nodes is rc
280 // if both nodes are rc, then they are 'normal' relative to each other
281 if((rc_list[i2] || rc_list[i2+1] )&&!(rc_list[i2] && rc_list[i2+1]))
282 { //the hideous rc matching logic - not complex, but annoying
283 if(!(( ((*cur)[x_start]=='A')&&((*next)[x_end]=='T')) ||
284 (((*cur)[x_start]=='T')&&((*next)[x_end]=='A')) ||
285 (((*cur)[x_start]=='G')&&((*next)[x_end]=='C')) ||
286 (((*cur)[x_start]=='C')&&((*next)[x_end]=='G'))) )
290 aligned_path.push_back(x_start);
295 if (!( ((*cur)[x_start] == (*next)[x_end]) &&
296 ((*cur)[x_start] != 'N') && ((*next)[x_end] != 'N') ) ) {
299 aligned_path.push_back(x_start);
303 // grab the last part of our path, assuming we matched
305 aligned_path.push_back(x_end);
307 if (aligned_path.size() == a_path.size()) {
308 result.push_back(aligned_path);
309 reversed.push_back(rc_list);
317 void Mussa::append_sequence(const Sequence& a_seq)
319 boost::shared_ptr<Sequence> seq_copy(new Sequence(a_seq));
320 the_seqs.push_back(seq_copy);
324 void Mussa::append_sequence(boost::shared_ptr<Sequence> a_seq)
326 the_seqs.push_back(a_seq);
331 const vector<SequenceRef>&
332 Mussa::sequences() const
337 void Mussa::load_sequence(fs::path seq_file, fs::path annot_file,
338 int fasta_index, int sub_seq_start, int sub_seq_end,
341 boost::shared_ptr<Sequence> aseq(new Sequence);
342 aseq->load_fasta(seq_file, fasta_index, sub_seq_start, sub_seq_end);
343 if ( not annot_file.empty() ) {
344 aseq->load_annot(annot_file, sub_seq_start, sub_seq_end);
346 if (name != 0 and name->size() > 0 ) {
347 aseq->set_species(*name);
349 the_seqs.push_back(aseq);
354 Mussa::load_mupa_file(fs::path para_file_path)
356 fs::ifstream para_file;
357 string file_data_line;
360 int split_index, fasta_index;
361 int sub_seq_start, sub_seq_end;
362 bool seq_params, did_seq;
365 string::size_type new_index, dir_index;
370 // if file was opened, read the parameter values
371 if (not fs::exists(para_file_path))
373 throw mussa_load_error("Config File: " + para_file_path.string() + " not found");
374 } else if (fs::is_directory(para_file_path)) {
375 throw mussa_load_error("Config File: " + para_file_path.string() + " is a directory.");
376 } else if (fs::is_empty(para_file_path)) {
377 throw mussa_load_error("Config File: " + para_file_path.string() + " is empty");
379 para_file.open(para_file_path, ios::in);
381 // what directory is the mupa file in?
382 fs::path file_path_base = para_file_path.branch_path();
384 // setup loop by getting file's first line
385 getline(para_file,file_data_line);
386 split_index = file_data_line.find(" ");
387 param = file_data_line.substr(0,split_index);
388 value = file_data_line.substr(split_index+1);
393 if (param == "ANA_NAME")
394 analysis_name = value;
395 else if (param == "APPEND_WIN")
397 else if (param == "APPEND_THRES")
399 else if (param == "SEQUENCE_NUM")
400 ; // ignore sequence_num now
401 else if (param == "WINDOW")
402 window = atoi(value.c_str());
403 else if (param == "THRESHOLD")
404 threshold = atoi(value.c_str());
405 else if (param == "SEQUENCE")
407 fs::path seq_file = file_path_base / value;
408 //cout << "seq_file_name " << seq_files.back() << endl;
415 while (para_file && seq_params)
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);
422 if (param == "FASTA_INDEX")
423 fasta_index = atoi(value.c_str());
424 else if (param == "ANNOTATION")
425 annot_file = file_path_base / value;
426 else if (param == "SEQ_START")
427 sub_seq_start = atoi(value.c_str());
428 else if (param == "SEQ_END")
430 sub_seq_end = atoi(value.c_str());
432 //ignore empty lines or that start with '#'
433 else if ((param == "") || (param == "#")) {}
434 else seq_params = false;
436 load_sequence(seq_file, annot_file, fasta_index, sub_seq_start,
440 //ignore empty lines or that start with '#'
441 else if ((param == "") || (param == "#")) {}
444 clog << "Illegal/misplaced mussa parameter in file\n";
445 clog << param << "\n";
450 getline(para_file,file_data_line);
451 split_index = file_data_line.find(" ");
452 param = file_data_line.substr(0,split_index);
453 value = file_data_line.substr(split_index+1);
460 soft_thres = threshold;
461 //cout << "nway mupa: analysis_name = " << analysis_name
462 // << " window = " << window
463 // << " threshold = " << threshold << endl;
465 // no file was loaded, signal error
473 if (the_seqs.size() < 2) {
474 throw mussa_analysis_error("you need to have at least 2 sequences to "
479 the_paths.setup(window, threshold);
486 vector<int> seq_lens;
487 vector<FLPs> empty_FLP_vector;
489 string save_file_string;
491 empty_FLP_vector.clear();
492 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
494 all_comps.push_back(empty_FLP_vector);
495 for(vector<Sequence>::size_type i2 = 0; i2 < the_seqs.size(); i2++)
496 all_comps[i].push_back(dummy_comp);
498 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
499 seq_lens.push_back(the_seqs[i]->size());
501 int seqcomps_done = 0;
502 int seqcomps_todo = (the_seqs.size() * (the_seqs.size()-1)) / 2;
503 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
505 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
506 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
508 //cout << "seqcomping: " << i << " v. " << i2 << endl;
509 all_comps[i][i2].setup(window, threshold);
510 all_comps[i][i2].seqcomp(*the_seqs[i], *the_seqs[i2], false);
511 all_comps[i][i2].seqcomp(*the_seqs[i], the_seqs[i2]->rev_comp(),true);
513 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
521 the_paths.set_soft_threshold(soft_thres);
523 if (ana_mode == TransitiveNway) {
524 the_paths.trans_path_search(all_comps);
526 else if (ana_mode == RadialNway) {
527 the_paths.radiate_path_search(all_comps);
529 else if (ana_mode == EntropyNway)
531 vector<Sequence> some_Seqs;
532 //unlike other methods, entropy needs to look at the sequence at this stage
534 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
536 some_Seqs.push_back(*the_seqs[i]);
539 the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
540 the_paths.entropy_path_search(all_comps);
543 // old recursive transitive analysis function
544 else if (ana_mode == RecursiveNway)
545 the_paths.find_paths_r(all_comps);
547 the_paths.simple_refine();
551 Mussa::save(fs::path save_path)
553 fs::fstream save_file;
554 ostringstream append_info;
555 int dir_create_status;
557 if (save_path.empty()) {
558 if (not analysis_path.empty()) {
559 save_path = analysis_path;
560 } else if (not analysis_name.empty()) {
561 std::string save_name = analysis_name;
562 // gotta do bit with adding win & thres if to be appended
565 append_info << "_w" << window;
566 save_name += append_info.str();
571 append_info << "_t" << threshold;
572 save_name += append_info.str();
574 save_path = save_name;
576 throw mussa_save_error("Need filename or analysis name to save");
580 if (not fs::exists(save_path)) {
581 fs::create_directory(save_path);
584 std::string basename = save_path.leaf();
585 fs::path museq(basename + ".museq", fs::native);
587 // save sequence and annots to a special mussa file
588 save_file.open(save_path / museq, ios::out);
589 save_file << "<Mussa_Sequence>" << endl;
591 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
593 the_seqs[i]->save(save_file);
596 save_file << "</Mussa_Sequence>" << endl;
599 // if we have any motifs, save them.
600 if (motif_sequences.size()) {
601 fs::path mtl(basename + ".mtl", fs::native);
602 save_motifs(save_path / mtl);
605 // save nway paths to its mussa save file
606 fs::path muway(basename + ".muway", fs::native);
607 the_paths.save(save_path / muway);
609 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
610 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
613 append_info << "_sp_" << i << "v" << i2;
614 fs::path flp(basename+append_info.str()+".flp", fs::native);
615 all_comps[i][i2].save(save_path / flp);
620 analysis_path = save_path;
624 Mussa::save_muway(fs::path save_path)
626 the_paths.save(save_path);
630 Mussa::load(fs::path ana_file)
633 fs::path file_path_base;
634 fs::path a_file_path;
635 fs::path ana_path(ana_file);
638 ostringstream append_info;
639 vector<FLPs> empty_FLP_vector;
643 //--------------------------------------------------------
645 //--------------------------------------------------------
646 analysis_path = ana_file;
647 analysis_name = ana_path.leaf();
648 fs::path muway(analysis_name+".muway", fs::native);
649 a_file_path = analysis_path / muway;
650 the_paths.load(a_file_path);
651 // perhaps this could be more elegent, but at least this'll let
652 // us know what our threshold and window sizes were when we load a muway
653 window = the_paths.get_window();
654 threshold = the_paths.get_threshold();
655 soft_thres = threshold;
658 //--------------------------------------------------------
660 //--------------------------------------------------------
661 //int seq_num = the_paths.sequence_count();
663 fs::path museq(analysis_name + ".museq", fs::native);
664 a_file_path = analysis_path / museq;
666 // this is a bit of a hack due to C++ not acting like it should with files
667 /*for (i = 1; i <= seq_num; i++)
669 boost::shared_ptr<Sequence> tmp_seq(new Sequence);
670 tmp_seq->load_museq(a_file_path, i);
671 the_seqs.push_back(tmp_seq);
676 boost::filesystem::fstream load_museq_fs;
677 load_museq_fs.open(a_file_path, std::ios::in);
678 boost::shared_ptr<Sequence> tmp_seq;
681 tmp_seq = Sequence::load_museq(load_museq_fs);
685 the_seqs.push_back(tmp_seq);
693 //safe guard in case of an infinate loop.
694 //FIXME: If mussa can handle a comparison of 10000 sequences
695 // in the future, then this code should be fixed.
698 throw mussa_load_error(" Run away sequence load!");
702 load_museq_fs.close();
704 //--------------------------------------------------------
706 //--------------------------------------------------------
707 fs::path mtl(analysis_name + ".mtl", fs::native);
708 fs::path motif_file = analysis_path / mtl;
709 if (fs::exists(motif_file)) {
710 load_motifs(motif_file);
713 vector<Sequence>::size_type seq_num = the_seqs.size();
714 empty_FLP_vector.clear();
715 for(i = 0; i < seq_num; i++)
717 all_comps.push_back(empty_FLP_vector);
718 for(i2 = 0; i2 < seq_num; i2++)
719 all_comps[i].push_back(dummy_comp);
723 for(i = 0; i < seq_num; i++)
725 for(i2 = i+1; i2 < seq_num; i2++)
728 append_info << analysis_name << "_sp_" << i << "v" << i2 << ".flp";
729 //clog << append_info.str() << endl;
730 fs::path flp(append_info.str(), fs::native);
731 a_file_path = analysis_path / flp;
732 all_comps[i][i2].load(a_file_path);
740 fs::fstream save_file;
742 save_file.open(analysis_name, ios::out);
744 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
745 save_file << *(the_seqs[i]) << endl;
747 save_file << window << endl;
749 //note more complex eventually since analysis_name may need to have
750 //window size, threshold and other stuff to modify it...
751 the_paths.save_old(analysis_name);
756 Mussa::load_old(char * load_file_path, int s_num)
759 string file_data_line;
760 int i, space_split_i, comma_split_i;
761 vector<int> loaded_path;
762 string node_pair, node;
766 the_paths.setup(0, 0);
767 save_file.open(load_file_path, ios::in);
769 // currently loads old mussa format
772 for(i = 0; i < seq_num; i++)
774 getline(save_file, file_data_line);
775 boost::shared_ptr<Sequence> a_seq(new Sequence(file_data_line));
776 the_seqs.push_back(a_seq);
780 getline(save_file, file_data_line);
781 window = atoi(file_data_line.c_str());
784 while (!save_file.eof())
787 getline(save_file, file_data_line);
788 if (file_data_line != "")
789 for(i = 0; i < seq_num; i++)
791 space_split_i = file_data_line.find(" ");
792 node_pair = file_data_line.substr(0,space_split_i);
793 //cout << "np= " << node_pair;
794 comma_split_i = node_pair.find(",");
795 node = node_pair.substr(comma_split_i+1);
796 //cout << "n= " << node << " ";
797 loaded_path.push_back(atoi (node.c_str()));
798 file_data_line = file_data_line.substr(space_split_i+1);
801 // FIXME: do we have any information about what the threshold should be?
802 the_paths.add_path(0, loaded_path);
806 //the_paths.save("tmp.save");
809 void Mussa::add_motif(const Sequence& motif, const Color& color)
811 motif_sequences.insert(motif);
812 color_mapper->appendInstanceColor("motif", motif.get_sequence(), color);
816 void Mussa::set_motifs(const vector<Sequence>& motifs,
817 const vector<Color>& colors)
819 if (motifs.size() != colors.size()) {
820 throw mussa_error("motif and color vectors must be the same size");
823 motif_sequences.clear();
824 for(size_t i = 0; i != motifs.size(); ++i)
826 add_motif(motifs[i], colors[i]);
828 update_sequences_motifs();
831 void Mussa::load_motifs(fs::path filename)
834 f.open(filename, ifstream::in);
838 void Mussa::load_motifs(std::istream &in)
841 const char *alphabet = Alphabet::dna_cstr;
842 motif_parser::ParsedMotifs parsed_motifs(motif_sequences, color_mapper);
844 // slurp our data into a string
845 std::streamsize bytes_read = 1;
846 while (in.good() and bytes_read) {
847 const std::streamsize bufsiz=512;
849 bytes_read = in.readsome(buf, bufsiz);
850 data.append(buf, buf+bytes_read);
852 parsed_motifs.parse(data);
853 update_sequences_motifs();
856 void Mussa::save_motifs(fs::path filename)
858 fs::ofstream out_stream;
859 out_stream.open(filename, ofstream::out);
860 save_motifs(out_stream);
863 void Mussa::save_motifs(std::ostream& out)
865 for(motif_set::iterator motif_i = motif_sequences.begin();
866 motif_i != motif_sequences.end();
869 out << motif_i->get_sequence() << " ";
870 if (motif_i->get_name().size() > 0) {
871 out << "\"" << motif_i->get_name() << "\" ";
873 out << color_mapper->lookup("motif", motif_i->get_sequence());
878 void Mussa::update_sequences_motifs()
880 // once we've loaded all the motifs from the file,
881 // lets attach them to the sequences
882 for(vector<SequenceRef >::iterator seq_i = the_seqs.begin();
883 seq_i != the_seqs.end();
886 // clear out old motifs
887 (*seq_i)->clear_motifs();
888 // for all the motifs in our set, attach them to the current sequence
889 for(set<Sequence>::iterator motif_i = motif_sequences.begin();
890 motif_i != motif_sequences.end();
893 (*seq_i)->add_motif(*motif_i);
898 const set<Sequence>& Mussa::motifs() const
900 return motif_sequences;
903 boost::shared_ptr<AnnotationColors> Mussa::colorMapper()