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;
20 #include <boost/algorithm/string.hpp>
25 #include "mussa_exceptions.hpp"
30 #include "motif_parser.hpp"
36 : color_mapper(new AnnotationColors)
39 connect(&the_paths, SIGNAL(progress(const QString&, int, int)),
40 this, SIGNAL(progress(const QString&, int, int)));
43 Mussa::Mussa(const Mussa& m)
44 : analysis_name(m.analysis_name),
46 threshold(m.threshold),
47 soft_thres(m.soft_thres),
49 win_append(m.win_append),
50 thres_append(m.thres_append),
51 motif_sequences(m.motif_sequences),
52 color_mapper(m.color_mapper),
53 analysis_path(m.analysis_path),
56 connect(&the_paths, SIGNAL(progress(const QString&, int, int)),
57 this, SIGNAL(progress(const QString&, int, int)));
60 MussaRef Mussa::init()
62 boost::shared_ptr<Mussa> m(new Mussa());
66 boost::filesystem::path Mussa::get_analysis_path() const
71 void Mussa::set_analysis_path(boost::filesystem::path pathname)
73 analysis_path = pathname;
76 // set all parameters to null state
81 ana_mode = TransitiveNway;
87 motif_sequences.clear();
88 if(color_mapper) color_mapper->clear();
91 analysis_path = fs::path();
95 void Mussa::set_append_window(bool v)
100 bool Mussa::get_append_window()
105 void Mussa::set_append_threshold(bool v)
110 bool Mussa::get_append_threshold()
115 void Mussa::set_dirty(bool new_state)
117 if (dirty != new_state) {
119 emit isModified(dirty);
123 bool Mussa::is_dirty() const
128 bool Mussa::empty() const
130 return the_seqs.empty();
134 // these 5 simple methods manually set the parameters for doing an analysis
135 // used so that the gui can take input from user and setup the analysis
136 // note - still need a set_append(bool, bool) method...
138 Mussa::set_name(string a_name)
140 analysis_name = a_name;
144 string Mussa::get_name() const
146 return analysis_name;
149 string Mussa::get_title() const
151 fs::path analysis_path = get_analysis_path();
152 if (not analysis_path.empty()) {
153 return analysis_path.native_file_string();
154 } else if (get_name().size() > 0) {
157 return std::string("Unnamed");
164 if (the_seqs.size() > 0)
165 return the_seqs.size();
171 Mussa::set_window(int a_window)
177 int Mussa::get_window() const
183 Mussa::set_threshold(int a_threshold)
185 threshold = a_threshold;
187 if (a_threshold > soft_thres) {
188 soft_thres = a_threshold;
192 int Mussa::get_threshold() const
198 Mussa::set_soft_threshold(int new_threshold)
200 if (new_threshold < threshold) {
201 soft_thres = threshold;
202 } else if (new_threshold > window) {
205 soft_thres = new_threshold;
209 int Mussa::get_soft_threshold() const
216 Mussa::set_analysis_mode(enum analysis_modes new_ana_mode)
218 ana_mode = new_ana_mode;
222 enum Mussa::analysis_modes Mussa::get_analysis_mode() const
227 string Mussa::get_analysis_mode_name() const
232 return string("Transitive");
235 return string("Radial");
238 return string("Entropy");
241 return string("[deprecated] Recursive");
244 throw runtime_error("invalid analysis mode type");
249 const NwayPaths& Mussa::paths() const
254 //template <class IteratorT>
255 //void Mussa::createLocalAlignment(IteratorT begin, IteratorT end)
256 void Mussa::createLocalAlignment(std::list<ConservedPath>::iterator begin,
257 std::list<ConservedPath>::iterator end,
258 std::list<ConservedPath::path_type>& result,
259 std::list<std::vector<bool> >& reversed)
261 const vector_sequence_type& raw_seq = the_seqs;
262 ConservedPath::path_type aligned_path;
265 int window_length, win_i;
268 vector<bool> rc_list;
270 vector<bool> matched;
274 for(std::list<ConservedPath>::iterator pathz_i=begin; pathz_i != end; ++pathz_i)
276 ConservedPath& a_path = *pathz_i;
277 window_length = a_path.window_size;
278 // determine which parts of the path are RC relative to first species
279 rc_list = a_path.reverseComplimented();
281 // loop over each bp in the conserved region for all sequences
282 for(win_i = 0; win_i < window_length; win_i++)
284 aligned_path.clear();
285 // determine which exact base pairs match between the sequences
287 for(i2 = 0; i2 < a_path.size()-1; i2++)
289 // assume not rc as most likely, adjust below
292 // no matter the case, any RC node needs adjustments
294 rc_1 = window_length-1;
295 if (a_path[i2+1] < 0)
296 rc_2 = window_length-1;
298 x_start = (abs(a_path[i2]-rc_1+win_i));
299 x_end = (abs(a_path[i2+1]-rc_2+win_i));
301 boost::shared_ptr<Sequence> cur(raw_seq[i2]) ;
302 boost::shared_ptr<Sequence> next(raw_seq[i2+1]);
304 // ugh, and xor...only want rc coloring if just one of the nodes is rc
305 // if both nodes are rc, then they are 'normal' relative to each other
306 if((rc_list[i2] || rc_list[i2+1] )&&!(rc_list[i2] && rc_list[i2+1]))
307 { //the hideous rc matching logic - not complex, but annoying
308 if(!(( ((*cur)[x_start]=='A')&&((*next)[x_end]=='T')) ||
309 (((*cur)[x_start]=='T')&&((*next)[x_end]=='A')) ||
310 (((*cur)[x_start]=='G')&&((*next)[x_end]=='C')) ||
311 (((*cur)[x_start]=='C')&&((*next)[x_end]=='G'))) )
315 aligned_path.push_back(x_start);
320 if (!( ((*cur)[x_start] == (*next)[x_end]) &&
321 ((*cur)[x_start] != 'N') && ((*next)[x_end] != 'N') ) ) {
324 aligned_path.push_back(x_start);
328 // grab the last part of our path, assuming we matched
330 aligned_path.push_back(x_end);
332 if (aligned_path.size() == a_path.size()) {
333 result.push_back(aligned_path);
334 reversed.push_back(rc_list);
342 void Mussa::append_sequence(const Sequence& a_seq)
344 boost::shared_ptr<Sequence> seq_copy(new Sequence(a_seq));
345 the_seqs.push_back(seq_copy);
349 void Mussa::append_sequence(boost::shared_ptr<Sequence> a_seq)
351 the_seqs.push_back(a_seq);
356 const vector<SequenceRef>&
357 Mussa::sequences() const
362 void Mussa::load_sequence(fs::path seq_file, fs::path annot_file,
363 int fasta_index, int sub_seq_start, int sub_seq_end,
366 boost::shared_ptr<Sequence> aseq(new Sequence);
367 aseq->load_fasta(seq_file, fasta_index, sub_seq_start, sub_seq_end);
368 if ( not annot_file.empty() ) {
369 aseq->load_annot(annot_file, sub_seq_start, sub_seq_end);
371 if (name != 0 and name->size() > 0 ) {
372 aseq->set_species(*name);
374 the_seqs.push_back(aseq);
378 void Mussa::load_mupa_file(std::string para_file_path) {
379 load_mupa_file(boost::filesystem::path(para_file_path));
383 Mussa::load_mupa_file(fs::path para_file_path)
385 if (not fs::exists(para_file_path))
387 throw mussa_load_error("Config File: " + para_file_path.string() + " not found");
388 } else if (fs::is_directory(para_file_path)) {
389 throw mussa_load_error("Config File: " + para_file_path.string() + " is a directory.");
390 } else if (fs::is_empty(para_file_path)) {
391 throw mussa_load_error("Config File: " + para_file_path.string() + " is empty");
393 // what directory is the mupa file in?
394 fs::path file_path_base( para_file_path.branch_path()) ;
396 fs::ifstream para_file;
397 para_file.open(para_file_path, ios::in);
399 load_mupa_stream(para_file, file_path_base);
405 Mussa::load_mupa_stream(std::istream& para_file, fs::path& file_path_base)
408 std::vector< std::string > tokens;
411 enum parsing_state_enum { START, INSEQUENCE };
412 parsing_state_enum parsing_state = START;
414 // sequence file parameters
417 int split_index, fasta_index;
418 int sub_seq_start, sub_seq_end;
419 bool seq_params, did_seq;
426 while (para_file.good())
429 // setup loop by getting file's first line
430 multiplatform_getline(para_file, line);
431 // strip leading/trailing whitespace
433 // ignore commented out or blank lines
434 if ( line.size() == 0 or line[0] == '#' ) {
438 // split the line on white spance
439 boost::split(tokens, line, boost::is_space());
440 // do we have a name/value pair?
441 if (tokens.size() != 2) {
442 std::stringstream errmsg;
443 errmsg << "Error parsing MUPA file line: "
444 << line_count << std::endl
446 throw mussa_load_error(errmsg.str());
449 boost::to_upper(tokens[0]);
450 // Parameters only useful after a sequence block
451 if (parsing_state == INSEQUENCE) {
452 // in the following if blocks, if we do
453 // successfully match a token we should continue
454 // on to the next token
455 // but if we don't match a token we want to
456 // fall through to the top level parsing
458 if (tokens[0] == "FASTA_INDEX") {
459 fasta_index = atoi(tokens[1].c_str());
461 } else if (tokens[0] == "ANNOTATION") {
462 annot_file = file_path_base / tokens[1];
464 } else if (tokens[0] == "SEQ_START") {
465 sub_seq_start = atoi(tokens[1].c_str());
467 } else if (tokens[0] == "SEQ_END") {
468 sub_seq_end = atoi(tokens[1].c_str());
471 // any other token means we're done with this
472 // sequence so we should load it
473 // (and let the "unknown" token fall through into the
474 // top level token parser)
475 load_sequence(seq_file, annot_file, fasta_index, sub_seq_start,
477 parsing_state = START;
480 // if we didn't consume a token from the previous if block
482 // top level token parsing
483 if (tokens[0] == "ANA_NAME") {
484 analysis_name = tokens[1];
485 } else if (tokens[0] == "APPEND_WIN") {
487 } else if (tokens[0] == "APPEND_THRES") {
489 } else if (tokens[0] == "SEQUENCE_NUM") {
490 ; // ignore sequence_num now
491 } else if (tokens[0] == "WINDOW") {
492 window = atoi(tokens[1].c_str());
493 } else if (tokens[0] == "THRESHOLD") {
494 threshold = atoi(tokens[1].c_str());
495 } else if (tokens[0] == "SEQUENCE") {
496 if (parsing_state == INSEQUENCE) {
497 load_sequence(seq_file, annot_file, fasta_index, sub_seq_start,
499 parsing_state = START;
501 // reset sequence parameters
502 seq_file = file_path_base / tokens[1];
508 parsing_state = INSEQUENCE;
510 clog << "Illegal/misplaced mussa parameter in file\n";
511 clog << tokens[0] << "\n";
512 std::stringstream errmsg;
513 errmsg << "Invalid mussa paaramater '"
516 << line_count << std::endl
518 throw mussa_load_error(errmsg.str());
519 throw mussa_load_error("Error parsing MUPA file");
523 // if we hit the end of the file and there's a sequence
524 // pending, go ahead and load it
525 if (parsing_state == INSEQUENCE) {
526 load_sequence(seq_file, annot_file, fasta_index, sub_seq_start,
530 soft_thres = threshold;
538 if (the_seqs.size() < 2) {
539 throw mussa_analysis_error("you need to have at least 2 sequences to "
544 the_paths.setup(window, threshold);
551 vector<int> seq_lens;
552 vector<FLPs> empty_FLP_vector;
554 string save_file_string;
556 empty_FLP_vector.clear();
557 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
559 all_comps.push_back(empty_FLP_vector);
560 for(vector<Sequence>::size_type i2 = 0; i2 < the_seqs.size(); i2++)
561 all_comps[i].push_back(dummy_comp);
563 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
564 seq_lens.push_back(the_seqs[i]->size());
566 int seqcomps_done = 0;
567 int seqcomps_todo = (the_seqs.size() * (the_seqs.size()-1)) / 2;
568 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
570 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
571 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
573 //cout << "seqcomping: " << i << " v. " << i2 << endl;
574 all_comps[i][i2].setup(window, threshold);
575 all_comps[i][i2].seqcomp(*the_seqs[i], *the_seqs[i2], false);
576 all_comps[i][i2].seqcomp(*the_seqs[i], the_seqs[i2]->rev_comp(),true);
578 emit progress("seqcomp", seqcomps_done, seqcomps_todo);
586 the_paths.set_soft_threshold(soft_thres);
588 if (ana_mode == TransitiveNway) {
589 the_paths.trans_path_search(all_comps);
591 else if (ana_mode == RadialNway) {
592 the_paths.radiate_path_search(all_comps);
594 else if (ana_mode == EntropyNway)
596 vector<Sequence> some_Seqs;
597 //unlike other methods, entropy needs to look at the sequence at this stage
599 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
601 some_Seqs.push_back(*the_seqs[i]);
604 the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
605 the_paths.entropy_path_search(all_comps);
608 // old recursive transitive analysis function
609 else if (ana_mode == RecursiveNway)
610 the_paths.find_paths_r(all_comps);
612 the_paths.simple_refine();
616 Mussa::save(fs::path save_path)
618 fs::fstream save_file;
619 ostringstream append_info;
620 int dir_create_status;
622 if (save_path.empty()) {
623 if (not analysis_path.empty()) {
624 save_path = analysis_path;
625 } else if (not analysis_name.empty()) {
626 std::string save_name = analysis_name;
627 // gotta do bit with adding win & thres if to be appended
630 append_info << "_w" << window;
631 save_name += append_info.str();
636 append_info << "_t" << threshold;
637 save_name += append_info.str();
639 save_path = save_name;
641 throw mussa_save_error("Need filename or analysis name to save");
645 if (not fs::exists(save_path)) {
646 fs::create_directory(save_path);
649 std::string basename = save_path.leaf();
650 fs::path museq(basename + ".museq", fs::native);
652 // save sequence and annots to a special mussa file
653 save_file.open(save_path / museq, ios::out);
654 save_file << "<Mussa_Sequence>" << endl;
656 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
658 the_seqs[i]->save(save_file);
661 save_file << "</Mussa_Sequence>" << endl;
664 // if we have any motifs, save them.
665 if (motif_sequences.size()) {
666 fs::path mtl(basename + ".mtl", fs::native);
667 save_motifs(save_path / mtl);
670 // save nway paths to its mussa save file
671 fs::path muway(basename + ".muway", fs::native);
672 the_paths.save(save_path / muway);
674 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
675 for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
678 append_info << "_sp_" << i << "v" << i2;
679 fs::path flp(basename+append_info.str()+".flp", fs::native);
680 all_comps[i][i2].save(save_path / flp);
685 analysis_path = save_path;
689 Mussa::save_muway(fs::path save_path)
691 the_paths.save(save_path);
695 Mussa::load(fs::path ana_file)
698 fs::path file_path_base;
699 fs::path a_file_path;
700 fs::path ana_path(ana_file);
703 ostringstream append_info;
704 vector<FLPs> empty_FLP_vector;
708 //--------------------------------------------------------
710 //--------------------------------------------------------
711 analysis_path = ana_file;
712 analysis_name = ana_path.leaf();
713 fs::path muway(analysis_name+".muway", fs::native);
714 a_file_path = analysis_path / muway;
715 the_paths.load(a_file_path);
716 // perhaps this could be more elegent, but at least this'll let
717 // us know what our threshold and window sizes were when we load a muway
718 window = the_paths.get_window();
719 threshold = the_paths.get_threshold();
720 soft_thres = the_paths.get_soft_threshold();
723 //--------------------------------------------------------
725 //--------------------------------------------------------
726 //int seq_num = the_paths.sequence_count();
728 fs::path museq(analysis_name + ".museq", fs::native);
729 a_file_path = analysis_path / museq;
731 // this is a bit of a hack due to C++ not acting like it should with files
732 /*for (i = 1; i <= seq_num; i++)
734 boost::shared_ptr<Sequence> tmp_seq(new Sequence);
735 tmp_seq->load_museq(a_file_path, i);
736 the_seqs.push_back(tmp_seq);
741 boost::filesystem::fstream load_museq_fs;
742 load_museq_fs.open(a_file_path, std::ios::in);
743 boost::shared_ptr<Sequence> tmp_seq;
746 tmp_seq = Sequence::load_museq(load_museq_fs);
750 the_seqs.push_back(tmp_seq);
758 //safe guard in case of an infinate loop.
759 //FIXME: If mussa can handle a comparison of 10000 sequences
760 // in the future, then this code should be fixed.
763 throw mussa_load_error(" Run away sequence load!");
767 load_museq_fs.close();
769 //--------------------------------------------------------
771 //--------------------------------------------------------
772 fs::path mtl(analysis_name + ".mtl", fs::native);
773 fs::path motif_file = analysis_path / mtl;
774 if (fs::exists(motif_file)) {
775 load_motifs(motif_file);
778 vector<Sequence>::size_type seq_num = the_seqs.size();
779 empty_FLP_vector.clear();
780 for(i = 0; i < seq_num; i++)
782 all_comps.push_back(empty_FLP_vector);
783 for(i2 = 0; i2 < seq_num; i2++)
784 all_comps[i].push_back(dummy_comp);
788 for(i = 0; i < seq_num; i++)
790 for(i2 = i+1; i2 < seq_num; i2++)
793 append_info << analysis_name << "_sp_" << i << "v" << i2 << ".flp";
794 //clog << append_info.str() << endl;
795 fs::path flp(append_info.str(), fs::native);
796 a_file_path = analysis_path / flp;
797 all_comps[i][i2].load(a_file_path);
805 fs::fstream save_file;
807 save_file.open(analysis_name, ios::out);
809 for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
810 save_file << *(the_seqs[i]) << endl;
812 save_file << window << endl;
814 //note more complex eventually since analysis_name may need to have
815 //window size, threshold and other stuff to modify it...
816 the_paths.save_old(analysis_name);
821 Mussa::load_old(char * load_file_path, int s_num)
824 string file_data_line;
825 int i, space_split_i, comma_split_i;
826 vector<int> loaded_path;
827 string node_pair, node;
831 the_paths.setup(0, 0);
832 save_file.open(load_file_path, ios::in);
834 // currently loads old mussa format
837 for(i = 0; i < seq_num; i++)
839 getline(save_file, file_data_line);
840 boost::shared_ptr<Sequence> a_seq(new Sequence(file_data_line));
841 the_seqs.push_back(a_seq);
845 getline(save_file, file_data_line);
846 window = atoi(file_data_line.c_str());
849 while (!save_file.eof())
852 getline(save_file, file_data_line);
853 if (file_data_line != "")
854 for(i = 0; i < seq_num; i++)
856 space_split_i = file_data_line.find(" ");
857 node_pair = file_data_line.substr(0,space_split_i);
858 //cout << "np= " << node_pair;
859 comma_split_i = node_pair.find(",");
860 node = node_pair.substr(comma_split_i+1);
861 //cout << "n= " << node << " ";
862 loaded_path.push_back(atoi (node.c_str()));
863 file_data_line = file_data_line.substr(space_split_i+1);
866 // FIXME: do we have any information about what the threshold should be?
867 the_paths.add_path(0, loaded_path);
871 //the_paths.save("tmp.save");
874 void Mussa::add_motif(const Sequence& motif, const Color& color)
876 motif_sequences.insert(motif);
877 color_mapper->appendInstanceColor("motif", motif.get_sequence(), color);
881 void Mussa::set_motifs(const vector<Sequence>& motifs,
882 const vector<Color>& colors)
884 if (motifs.size() != colors.size()) {
885 throw mussa_error("motif and color vectors must be the same size");
888 motif_sequences.clear();
889 for(size_t i = 0; i != motifs.size(); ++i)
891 add_motif(motifs[i], colors[i]);
893 update_sequences_motifs();
896 void Mussa::load_motifs(fs::path filename)
899 f.open(filename, ifstream::in);
903 void Mussa::load_motifs(std::istream &in)
906 const char *alphabet = Alphabet::dna_cstr;
907 motif_parser::ParsedMotifs parsed_motifs(motif_sequences, color_mapper);
909 // slurp our data into a string
910 std::streamsize bytes_read = 1;
911 while (in.good() and bytes_read) {
912 const std::streamsize bufsiz=512;
914 bytes_read = in.readsome(buf, bufsiz);
915 data.append(buf, buf+bytes_read);
917 parsed_motifs.parse(data);
918 update_sequences_motifs();
921 void Mussa::save_motifs(fs::path filename)
923 fs::ofstream out_stream;
924 out_stream.open(filename, ofstream::out);
925 save_motifs(out_stream);
928 void Mussa::save_motifs(std::ostream& out)
930 for(motif_set::iterator motif_i = motif_sequences.begin();
931 motif_i != motif_sequences.end();
934 out << motif_i->get_sequence() << " ";
935 if (motif_i->get_name().size() > 0) {
936 out << "\"" << motif_i->get_name() << "\" ";
938 out << color_mapper->lookup("motif", motif_i->get_sequence());
943 void Mussa::update_sequences_motifs()
945 // once we've loaded all the motifs from the file,
946 // lets attach them to the sequences
947 for(vector<SequenceRef >::iterator seq_i = the_seqs.begin();
948 seq_i != the_seqs.end();
951 // clear out old motifs
952 (*seq_i)->clear_motifs();
953 // for all the motifs in our set, attach them to the current sequence
954 for(set<Sequence>::iterator motif_i = motif_sequences.begin();
955 motif_i != motif_sequences.end();
958 (*seq_i)->add_motif(*motif_i);
963 const set<Sequence>& Mussa::motifs() const
965 return motif_sequences;
968 boost::shared_ptr<AnnotationColors> Mussa::colorMapper()