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"
28 #include "motif_parser.hpp"
34 : color_mapper(new AnnotationColors)
37 connect(&the_paths, SIGNAL(progress(const QString&, int, int)),
38 this, SIGNAL(progress(const QString&, int, int)));
41 Mussa::Mussa(const Mussa& m)
42 : analysis_name(m.analysis_name),
44 threshold(m.threshold),
45 soft_thres(m.soft_thres),
47 win_append(m.win_append),
48 thres_append(m.thres_append),
49 motif_sequences(m.motif_sequences),
50 color_mapper(m.color_mapper),
51 analysis_path(m.analysis_path),
54 connect(&the_paths, SIGNAL(progress(const QString&, int, int)),
55 this, SIGNAL(progress(const QString&, int, int)));
58 MussaRef Mussa::init()
60 boost::shared_ptr<Mussa> m(new Mussa());
64 boost::filesystem::path Mussa::get_analysis_path() const
69 void Mussa::set_analysis_path(boost::filesystem::path pathname)
71 analysis_path = pathname;
74 // set all parameters to null state
79 ana_mode = TransitiveNway;
85 motif_sequences.clear();
86 if(color_mapper) color_mapper->clear();
89 analysis_path = fs::path();
93 void Mussa::set_append_window(bool v)
98 bool Mussa::get_append_window()
103 void Mussa::set_append_threshold(bool v)
108 bool Mussa::get_append_threshold()
113 void Mussa::set_dirty(bool new_state)
115 if (dirty != new_state) {
117 emit isModified(dirty);
121 bool Mussa::is_dirty() const
126 bool Mussa::empty() const
128 return the_seqs.empty();
132 // these 5 simple methods manually set the parameters for doing an analysis
133 // used so that the gui can take input from user and setup the analysis
134 // note - still need a set_append(bool, bool) method...
136 Mussa::set_name(string a_name)
138 analysis_name = a_name;
142 string Mussa::get_name() const
144 return analysis_name;
147 string Mussa::get_title() const
149 fs::path analysis_path = get_analysis_path();
150 if (not analysis_path.empty()) {
151 return analysis_path.native_file_string();
152 } else if (get_name().size() > 0) {
155 return std::string("Unnamed");
162 if (the_seqs.size() > 0)
163 return the_seqs.size();
169 Mussa::set_window(int a_window)
175 int Mussa::get_window() const
181 Mussa::set_threshold(int a_threshold)
183 threshold = a_threshold;
185 if (a_threshold > soft_thres) {
186 soft_thres = a_threshold;
190 int Mussa::get_threshold() const
196 Mussa::set_soft_threshold(int new_threshold)
198 if (new_threshold < threshold) {
199 soft_thres = threshold;
200 } else if (new_threshold > window) {
203 soft_thres = new_threshold;
207 int Mussa::get_soft_threshold() const
213 Mussa::set_analysis_mode(enum analysis_modes new_ana_mode)
215 ana_mode = new_ana_mode;
219 enum Mussa::analysis_modes Mussa::get_analysis_mode() const
224 string Mussa::get_analysis_mode_name() const
229 return string("Transitive");
232 return string("Radial");
235 return string("Entropy");
238 return string("[deprecated] Recursive");
241 throw runtime_error("invalid analysis mode type");
246 const NwayPaths& Mussa::paths() const
251 //template <class IteratorT>
252 //void Mussa::createLocalAlignment(IteratorT begin, IteratorT end)
253 void Mussa::createLocalAlignment(std::list<ConservedPath>::iterator begin,
254 std::list<ConservedPath>::iterator end,
255 std::list<ConservedPath::path_type>& result,
256 std::list<std::vector<bool> >& reversed)
258 const vector_sequence_type& raw_seq = the_seqs;
259 ConservedPath::path_type aligned_path;
262 int window_length, win_i;
265 vector<bool> rc_list;
267 vector<bool> matched;
271 for(std::list<ConservedPath>::iterator pathz_i=begin; pathz_i != end; ++pathz_i)
273 ConservedPath& a_path = *pathz_i;
274 window_length = a_path.window_size;
275 // determine which parts of the path are RC relative to first species
276 rc_list = a_path.reverseComplimented();
278 // loop over each bp in the conserved region for all sequences
279 for(win_i = 0; win_i < window_length; win_i++)
281 aligned_path.clear();
282 // determine which exact base pairs match between the sequences
284 for(i2 = 0; i2 < a_path.size()-1; i2++)
286 // assume not rc as most likely, adjust below
289 // no matter the case, any RC node needs adjustments
291 rc_1 = window_length-1;
292 if (a_path[i2+1] < 0)
293 rc_2 = window_length-1;
295 x_start = (abs(a_path[i2]-rc_1+win_i));
296 x_end = (abs(a_path[i2+1]-rc_2+win_i));
298 boost::shared_ptr<Sequence> cur(raw_seq[i2]) ;
299 boost::shared_ptr<Sequence> next(raw_seq[i2+1]);
301 // ugh, and xor...only want rc coloring if just one of the nodes is rc
302 // if both nodes are rc, then they are 'normal' relative to each other
303 if((rc_list[i2] || rc_list[i2+1] )&&!(rc_list[i2] && rc_list[i2+1]))
304 { //the hideous rc matching logic - not complex, but annoying
305 if(!(( ((*cur)[x_start]=='A')&&((*next)[x_end]=='T')) ||
306 (((*cur)[x_start]=='T')&&((*next)[x_end]=='A')) ||
307 (((*cur)[x_start]=='G')&&((*next)[x_end]=='C')) ||
308 (((*cur)[x_start]=='C')&&((*next)[x_end]=='G'))) )
312 aligned_path.push_back(x_start);
317 if (!( ((*cur)[x_start] == (*next)[x_end]) &&
318 ((*cur)[x_start] != 'N') && ((*next)[x_end] != 'N') ) ) {
321 aligned_path.push_back(x_start);
325 // grab the last part of our path, assuming we matched
327 aligned_path.push_back(x_end);
329 if (aligned_path.size() == a_path.size()) {
330 result.push_back(aligned_path);
331 reversed.push_back(rc_list);
339 void Mussa::append_sequence(const Sequence& a_seq)
341 boost::shared_ptr<Sequence> seq_copy(new Sequence(a_seq));
342 the_seqs.push_back(seq_copy);
346 void Mussa::append_sequence(boost::shared_ptr<Sequence> a_seq)
348 the_seqs.push_back(a_seq);
353 const vector<SequenceRef>&
354 Mussa::sequences() const
359 void Mussa::load_sequence(fs::path seq_file, fs::path annot_file,
360 int fasta_index, int sub_seq_start, int sub_seq_end,
363 boost::shared_ptr<Sequence> aseq(new Sequence);
364 aseq->load_fasta(seq_file, fasta_index, sub_seq_start, sub_seq_end);
365 if ( not annot_file.empty() ) {
366 aseq->load_annot(annot_file, sub_seq_start, sub_seq_end);
368 if (name != 0 and name->size() > 0 ) {
369 aseq->set_species(*name);
371 the_seqs.push_back(aseq);
375 void Mussa::load_mupa_file(std::string para_file_path) {
376 load_mupa_file(boost::filesystem::path(para_file_path));
380 Mussa::load_mupa_file(fs::path para_file_path)
382 if (not fs::exists(para_file_path))
384 throw mussa_load_error("Config File: " + para_file_path.string() + " not found");
385 } else if (fs::is_directory(para_file_path)) {
386 throw mussa_load_error("Config File: " + para_file_path.string() + " is a directory.");
387 } else if (fs::is_empty(para_file_path)) {
388 throw mussa_load_error("Config File: " + para_file_path.string() + " is empty");
390 // what directory is the mupa file in?
391 fs::path file_path_base( para_file_path.branch_path()) ;
393 fs::ifstream para_file;
394 para_file.open(para_file_path, ios::in);
396 load_mupa_stream(para_file, file_path_base);
402 Mussa::load_mupa_stream(std::istream& para_file, fs::path& file_path_base)
404 bool error_occured = false;
405 string file_data_line;
408 int split_index, fasta_index;
409 int sub_seq_start, sub_seq_end;
410 bool seq_params, did_seq;
413 string::size_type new_index, dir_index;
418 // setup loop by getting file's first line
419 getline(para_file, file_data_line);
420 split_index = file_data_line.find(" ");
421 param = file_data_line.substr(0,split_index);
422 value = file_data_line.substr(split_index+1);
427 if (param == "ANA_NAME")
428 analysis_name = value;
429 else if (param == "APPEND_WIN")
431 else if (param == "APPEND_THRES")
433 else if (param == "SEQUENCE_NUM")
434 ; // ignore sequence_num now
435 else if (param == "WINDOW")
436 window = atoi(value.c_str());
437 else if (param == "THRESHOLD")
438 threshold = atoi(value.c_str());
439 else if (param == "SEQUENCE")
441 fs::path seq_file = file_path_base / value;
442 //cout << "seq_file_name " << seq_files.back() << endl;
449 while (para_file && seq_params)
451 multiplatform_getline(para_file,file_data_line);
452 split_index = file_data_line.find(" ");
453 param = file_data_line.substr(0,split_index);
454 value = file_data_line.substr(split_index+1);
456 if (param == "FASTA_INDEX")
457 fasta_index = atoi(value.c_str());
458 else if (param == "ANNOTATION")
459 annot_file = file_path_base / value;
460 else if (param == "SEQ_START")
461 sub_seq_start = atoi(value.c_str());
462 else if (param == "SEQ_END")
464 sub_seq_end = atoi(value.c_str());
466 //ignore empty lines or that start with '#'
467 else if ((param == "") || (param == "#")) {
473 load_sequence(seq_file, annot_file, fasta_index, sub_seq_start,
477 //ignore empty lines or that start with '#'
478 else if ( (param.size() == 0) || (param[0] == '#'))
482 clog << "Illegal/misplaced mussa parameter in file\n";
483 clog << param << "\n";
484 error_occured = true;
489 multiplatform_getline(para_file,file_data_line);
490 split_index = file_data_line.find(" ");
491 param = file_data_line.substr(0,split_index);
492 value = file_data_line.substr(split_index+1);
498 throw mussa_load_error("Error parsing MUPA file");
500 soft_thres = threshold;
501 // no file was loaded, signal error
509 if (the_seqs.size() < 2) {
510 throw mussa_analysis_error("you need to have at least 2 sequences to "
515 the_paths.setup(window, threshold);
522 vector<int> seq_lens;
523 vector<FLPs> empty_FLP_vector;
525 string save_file_string;
527 empty_FLP_vector.clear();
528 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
530 all_comps.push_back(empty_FLP_vector);
531 for(vector<Sequence>::size_type i2 = 0; i2 < the_seqs.size(); i2++)
532 all_comps[i].push_back(dummy_comp);
534 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
535 seq_lens.push_back(the_seqs[i]->size());
537 int seqcomps_done = 0;
538 int seqcomps_todo = (the_seqs.size() * (the_seqs.size()-1)) / 2;
539 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
541 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
542 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
544 //cout << "seqcomping: " << i << " v. " << i2 << endl;
545 all_comps[i][i2].setup(window, threshold);
546 all_comps[i][i2].seqcomp(*the_seqs[i], *the_seqs[i2], false);
547 all_comps[i][i2].seqcomp(*the_seqs[i], the_seqs[i2]->rev_comp(),true);
549 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
557 the_paths.set_soft_threshold(soft_thres);
559 if (ana_mode == TransitiveNway) {
560 the_paths.trans_path_search(all_comps);
562 else if (ana_mode == RadialNway) {
563 the_paths.radiate_path_search(all_comps);
565 else if (ana_mode == EntropyNway)
567 vector<Sequence> some_Seqs;
568 //unlike other methods, entropy needs to look at the sequence at this stage
570 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
572 some_Seqs.push_back(*the_seqs[i]);
575 the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
576 the_paths.entropy_path_search(all_comps);
579 // old recursive transitive analysis function
580 else if (ana_mode == RecursiveNway)
581 the_paths.find_paths_r(all_comps);
583 the_paths.simple_refine();
587 Mussa::save(fs::path save_path)
589 fs::fstream save_file;
590 ostringstream append_info;
591 int dir_create_status;
593 if (save_path.empty()) {
594 if (not analysis_path.empty()) {
595 save_path = analysis_path;
596 } else if (not analysis_name.empty()) {
597 std::string save_name = analysis_name;
598 // gotta do bit with adding win & thres if to be appended
601 append_info << "_w" << window;
602 save_name += append_info.str();
607 append_info << "_t" << threshold;
608 save_name += append_info.str();
610 save_path = save_name;
612 throw mussa_save_error("Need filename or analysis name to save");
616 if (not fs::exists(save_path)) {
617 fs::create_directory(save_path);
620 std::string basename = save_path.leaf();
621 fs::path museq(basename + ".museq", fs::native);
623 // save sequence and annots to a special mussa file
624 save_file.open(save_path / museq, ios::out);
625 save_file << "<Mussa_Sequence>" << endl;
627 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
629 the_seqs[i]->save(save_file);
632 save_file << "</Mussa_Sequence>" << endl;
635 // if we have any motifs, save them.
636 if (motif_sequences.size()) {
637 fs::path mtl(basename + ".mtl", fs::native);
638 save_motifs(save_path / mtl);
641 // save nway paths to its mussa save file
642 fs::path muway(basename + ".muway", fs::native);
643 the_paths.save(save_path / muway);
645 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
646 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
649 append_info << "_sp_" << i << "v" << i2;
650 fs::path flp(basename+append_info.str()+".flp", fs::native);
651 all_comps[i][i2].save(save_path / flp);
656 analysis_path = save_path;
660 Mussa::save_muway(fs::path save_path)
662 the_paths.save(save_path);
666 Mussa::load(fs::path ana_file)
669 fs::path file_path_base;
670 fs::path a_file_path;
671 fs::path ana_path(ana_file);
674 ostringstream append_info;
675 vector<FLPs> empty_FLP_vector;
679 //--------------------------------------------------------
681 //--------------------------------------------------------
682 analysis_path = ana_file;
683 analysis_name = ana_path.leaf();
684 fs::path muway(analysis_name+".muway", fs::native);
685 a_file_path = analysis_path / muway;
686 the_paths.load(a_file_path);
687 // perhaps this could be more elegent, but at least this'll let
688 // us know what our threshold and window sizes were when we load a muway
689 window = the_paths.get_window();
690 threshold = the_paths.get_threshold();
691 soft_thres = the_paths.get_soft_threshold();
694 //--------------------------------------------------------
696 //--------------------------------------------------------
697 //int seq_num = the_paths.sequence_count();
699 fs::path museq(analysis_name + ".museq", fs::native);
700 a_file_path = analysis_path / museq;
702 // this is a bit of a hack due to C++ not acting like it should with files
703 /*for (i = 1; i <= seq_num; i++)
705 boost::shared_ptr<Sequence> tmp_seq(new Sequence);
706 tmp_seq->load_museq(a_file_path, i);
707 the_seqs.push_back(tmp_seq);
712 boost::filesystem::fstream load_museq_fs;
713 load_museq_fs.open(a_file_path, std::ios::in);
714 boost::shared_ptr<Sequence> tmp_seq;
717 tmp_seq = Sequence::load_museq(load_museq_fs);
721 the_seqs.push_back(tmp_seq);
729 //safe guard in case of an infinate loop.
730 //FIXME: If mussa can handle a comparison of 10000 sequences
731 // in the future, then this code should be fixed.
734 throw mussa_load_error(" Run away sequence load!");
738 load_museq_fs.close();
740 //--------------------------------------------------------
742 //--------------------------------------------------------
743 fs::path mtl(analysis_name + ".mtl", fs::native);
744 fs::path motif_file = analysis_path / mtl;
745 if (fs::exists(motif_file)) {
746 load_motifs(motif_file);
749 vector<Sequence>::size_type seq_num = the_seqs.size();
750 empty_FLP_vector.clear();
751 for(i = 0; i < seq_num; i++)
753 all_comps.push_back(empty_FLP_vector);
754 for(i2 = 0; i2 < seq_num; i2++)
755 all_comps[i].push_back(dummy_comp);
759 for(i = 0; i < seq_num; i++)
761 for(i2 = i+1; i2 < seq_num; i2++)
764 append_info << analysis_name << "_sp_" << i << "v" << i2 << ".flp";
765 //clog << append_info.str() << endl;
766 fs::path flp(append_info.str(), fs::native);
767 a_file_path = analysis_path / flp;
768 all_comps[i][i2].load(a_file_path);
776 fs::fstream save_file;
778 save_file.open(analysis_name, ios::out);
780 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
781 save_file << *(the_seqs[i]) << endl;
783 save_file << window << endl;
785 //note more complex eventually since analysis_name may need to have
786 //window size, threshold and other stuff to modify it...
787 the_paths.save_old(analysis_name);
792 Mussa::load_old(char * load_file_path, int s_num)
795 string file_data_line;
796 int i, space_split_i, comma_split_i;
797 vector<int> loaded_path;
798 string node_pair, node;
802 the_paths.setup(0, 0);
803 save_file.open(load_file_path, ios::in);
805 // currently loads old mussa format
808 for(i = 0; i < seq_num; i++)
810 getline(save_file, file_data_line);
811 boost::shared_ptr<Sequence> a_seq(new Sequence(file_data_line));
812 the_seqs.push_back(a_seq);
816 getline(save_file, file_data_line);
817 window = atoi(file_data_line.c_str());
820 while (!save_file.eof())
823 getline(save_file, file_data_line);
824 if (file_data_line != "")
825 for(i = 0; i < seq_num; i++)
827 space_split_i = file_data_line.find(" ");
828 node_pair = file_data_line.substr(0,space_split_i);
829 //cout << "np= " << node_pair;
830 comma_split_i = node_pair.find(",");
831 node = node_pair.substr(comma_split_i+1);
832 //cout << "n= " << node << " ";
833 loaded_path.push_back(atoi (node.c_str()));
834 file_data_line = file_data_line.substr(space_split_i+1);
837 // FIXME: do we have any information about what the threshold should be?
838 the_paths.add_path(0, loaded_path);
842 //the_paths.save("tmp.save");
845 void Mussa::add_motif(const Sequence& motif, const Color& color)
847 motif_sequences.insert(motif);
848 color_mapper->appendInstanceColor("motif", motif.get_sequence(), color);
852 void Mussa::set_motifs(const vector<Sequence>& motifs,
853 const vector<Color>& colors)
855 if (motifs.size() != colors.size()) {
856 throw mussa_error("motif and color vectors must be the same size");
859 motif_sequences.clear();
860 for(size_t i = 0; i != motifs.size(); ++i)
862 add_motif(motifs[i], colors[i]);
864 update_sequences_motifs();
867 void Mussa::load_motifs(fs::path filename)
870 f.open(filename, ifstream::in);
874 void Mussa::load_motifs(std::istream &in)
877 const char *alphabet = Alphabet::dna_cstr;
878 motif_parser::ParsedMotifs parsed_motifs(motif_sequences, color_mapper);
880 // slurp our data into a string
881 std::streamsize bytes_read = 1;
882 while (in.good() and bytes_read) {
883 const std::streamsize bufsiz=512;
885 bytes_read = in.readsome(buf, bufsiz);
886 data.append(buf, buf+bytes_read);
888 parsed_motifs.parse(data);
889 update_sequences_motifs();
892 void Mussa::save_motifs(fs::path filename)
894 fs::ofstream out_stream;
895 out_stream.open(filename, ofstream::out);
896 save_motifs(out_stream);
899 void Mussa::save_motifs(std::ostream& out)
901 for(motif_set::iterator motif_i = motif_sequences.begin();
902 motif_i != motif_sequences.end();
905 out << motif_i->get_sequence() << " ";
906 if (motif_i->get_name().size() > 0) {
907 out << "\"" << motif_i->get_name() << "\" ";
909 out << color_mapper->lookup("motif", motif_i->get_sequence());
914 void Mussa::update_sequences_motifs()
916 // once we've loaded all the motifs from the file,
917 // lets attach them to the sequences
918 for(vector<SequenceRef >::iterator seq_i = the_seqs.begin();
919 seq_i != the_seqs.end();
922 // clear out old motifs
923 (*seq_i)->clear_motifs();
924 // for all the motifs in our set, attach them to the current sequence
925 for(set<Sequence>::iterator motif_i = motif_sequences.begin();
926 motif_i != motif_sequences.end();
929 (*seq_i)->add_motif(*motif_i);
934 const set<Sequence>& Mussa::motifs() const
936 return motif_sequences;
939 boost::shared_ptr<AnnotationColors> Mussa::colorMapper()