Extend the python mussa interface.
[mussa.git] / alg / mussa.cpp
1 //  This file is part of the Mussa source distribution.
2 //  http://mussa.caltech.edu/
3 //  Contact author: Tristan  De Buysscher, tristan@caltech.edu
4
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.
9
10
11 //                        ----------------------------------------
12 //                          ---------- mussa_class.cc -----------
13 //                        ----------------------------------------
14
15 #include <boost/filesystem/path.hpp>
16 #include <boost/filesystem/operations.hpp>
17 #include <boost/filesystem/fstream.hpp>
18 namespace fs = boost::filesystem;
19
20 #include <boost/algorithm/string.hpp>
21
22 #include <iostream>
23 #include <sstream>
24
25 #include "mussa_exceptions.hpp"
26
27 #include "flp.hpp"
28 #include "io.hpp"
29 #include "mussa.hpp"
30 #include "motif_parser.hpp"
31
32 using namespace std;
33
34
35 Mussa::Mussa()
36   : color_mapper(new AnnotationColors)
37 {
38   clear();
39   connect(&the_paths, SIGNAL(progress(const QString&, int, int)), 
40           this, SIGNAL(progress(const QString&, int, int)));
41 }
42
43 Mussa::Mussa(const Mussa& m)
44   : analysis_name(m.analysis_name),
45     window(m.window),
46     threshold(m.threshold),
47     soft_thres(m.soft_thres),
48     ana_mode(m.ana_mode),
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),
54     dirty(m.dirty)
55 {
56   connect(&the_paths, SIGNAL(progress(const QString&, int, int)), 
57           this, SIGNAL(progress(const QString&, int, int)));
58 }
59
60 MussaRef Mussa::init() 
61 {
62   boost::shared_ptr<Mussa> m(new Mussa());
63   return m;
64 }
65
66 boost::filesystem::path Mussa::get_analysis_path() const
67 {
68   return analysis_path;
69 }
70
71 void Mussa::set_analysis_path(boost::filesystem::path pathname)
72 {
73   analysis_path = pathname;
74 }
75
76 // set all parameters to null state
77 void
78 Mussa::clear()
79 {
80   analysis_name = "";
81   ana_mode = TransitiveNway;
82   window = 0;
83   threshold = 0;
84   soft_thres = 0;
85   win_append = false;
86   thres_append = false;
87   motif_sequences.clear();
88   if(color_mapper) color_mapper->clear();
89   the_seqs.clear();
90   the_paths.clear();
91   analysis_path = fs::path();
92   set_dirty(false);
93 }
94
95 void Mussa::set_append_window(bool v) 
96 {
97   win_append = v;
98 }
99
100 bool Mussa::get_append_window()
101 {
102   return win_append;
103 }
104
105 void Mussa::set_append_threshold(bool v)
106 {
107   thres_append = v;
108 }
109
110 bool Mussa::get_append_threshold()
111 {
112   return thres_append;
113 }
114
115 void Mussa::set_dirty(bool new_state)
116 {
117   if (dirty != new_state) {
118     dirty = new_state;
119     emit isModified(dirty);
120   }
121 }
122
123 bool Mussa::is_dirty() const
124 {
125   return dirty;
126 }
127
128 bool Mussa::empty() const
129 {
130   return the_seqs.empty();
131 }
132
133
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...
137 void
138 Mussa::set_name(string a_name)
139 {
140   analysis_name = a_name;
141   set_dirty(true);
142 }
143
144 string Mussa::get_name() const
145 {
146   return analysis_name;
147 }
148
149 string Mussa::get_title() const
150 {
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) {
155     return get_name();
156   } else {
157     return std::string("Unnamed");
158   }
159 }
160
161 int 
162 Mussa::size() const
163 {
164   if (the_seqs.size() > 0)
165     return the_seqs.size();
166   else
167     return 0;
168 }
169
170 void
171 Mussa::set_window(int a_window)
172 {
173   window = a_window;
174   set_dirty(true);
175 }
176
177 int Mussa::get_window() const
178 {
179   return window;
180 }
181
182 void
183 Mussa::set_threshold(int a_threshold)
184 {
185   threshold = a_threshold;
186   set_dirty(true);
187   if (a_threshold > soft_thres) {
188     soft_thres = a_threshold;
189   }
190 }
191
192 int Mussa::get_threshold() const
193 {
194   return threshold;
195 }
196
197 void
198 Mussa::set_soft_threshold(int new_threshold)
199 {
200   if (new_threshold < threshold) {
201     new_threshold = threshold;
202   } else if (new_threshold > window) {
203     new_threshold = window; 
204   }
205   if (soft_thres != new_threshold) {
206     soft_thres = new_threshold;
207     nway();
208   }
209 }
210
211 int Mussa::get_soft_threshold() const
212 {
213   return soft_thres;
214 }
215
216
217 void
218 Mussa::set_analysis_mode(enum analysis_modes new_ana_mode)
219 {
220   ana_mode = new_ana_mode;
221   set_dirty(true);
222 }
223
224 enum Mussa::analysis_modes Mussa::get_analysis_mode() const
225 {
226   return ana_mode;
227 }
228
229 string Mussa::get_analysis_mode_name() const
230 {
231   switch (ana_mode)
232   {
233   case TransitiveNway:
234     return string("Transitive");
235     break;
236   case RadialNway:
237     return string("Radial");
238     break;
239   case EntropyNway:
240     return string("Entropy");
241     break;
242   case RecursiveNway:
243     return string("[deprecated] Recursive");
244     break;
245   default:
246     throw runtime_error("invalid analysis mode type");
247     break;
248   }
249 }
250
251 const NwayPaths& Mussa::paths() const
252 {
253   return the_paths;
254 }
255
256 //template <class IteratorT>
257 //void Mussa::createLocalAlignment(IteratorT begin, IteratorT end)
258 void Mussa::createLocalAlignment(std::list<ConservedPath>::iterator begin, 
259                                  std::list<ConservedPath>::iterator end, 
260                                  std::list<ConservedPath::path_type>& result,
261                                  std::list<std::vector<bool> >& reversed)
262 {
263   const vector_sequence_type& raw_seq = the_seqs;
264   ConservedPath::path_type aligned_path;
265   size_t i2, i3;
266   int x_start, x_end;
267   int window_length, win_i;
268   int rc_1 = 0; 
269   int rc_2 = 0;
270   vector<bool> rc_list;
271   bool full_match;
272   vector<bool> matched;
273   int align_counter;
274
275   align_counter = 0;
276   for(std::list<ConservedPath>::iterator pathz_i=begin; pathz_i != end; ++pathz_i)
277   {
278     ConservedPath& a_path = *pathz_i;
279     window_length = a_path.window_size;
280     // determine which parts of the path are RC relative to first species
281     rc_list = a_path.reverseComplimented();
282     
283     // loop over each bp in the conserved region for all sequences
284     for(win_i = 0; win_i < window_length; win_i++)
285     {
286       aligned_path.clear();
287       // determine which exact base pairs match between the sequences
288       full_match = true;
289       for(i2 = 0; i2 < a_path.size()-1; i2++)
290       {
291         // assume not rc as most likely, adjust below
292         rc_1 = 0;
293         rc_2 = 0;
294         // no matter the case, any RC node needs adjustments
295         if (a_path[i2] < 0)
296           rc_1 = window_length-1;
297         if (a_path[i2+1] < 0)
298           rc_2 = window_length-1;        
299          
300         x_start = (abs(a_path[i2]-rc_1+win_i));
301         x_end =   (abs(a_path[i2+1]-rc_2+win_i));
302         
303         boost::shared_ptr<Sequence> cur(raw_seq[i2]) ;
304         boost::shared_ptr<Sequence> next(raw_seq[i2+1]);
305         // RC case handling
306         // ugh, and xor...only want rc coloring if just one of the nodes is rc
307         // if both nodes are rc, then they are 'normal' relative to each other
308         if((rc_list[i2] || rc_list[i2+1] )&&!(rc_list[i2] && rc_list[i2+1]))
309         { //the hideous rc matching logic - not complex, but annoying
310           if(!(( ((*cur)[x_start]=='A')&&((*next)[x_end]=='T')) ||
311                 (((*cur)[x_start]=='T')&&((*next)[x_end]=='A')) ||
312                 (((*cur)[x_start]=='G')&&((*next)[x_end]=='C')) ||
313                 (((*cur)[x_start]=='C')&&((*next)[x_end]=='G'))) ) 
314           {
315             full_match = false;
316           } else {
317             aligned_path.push_back(x_start);
318           }
319         }
320         else
321         { // forward match
322           if (!( ((*cur)[x_start] == (*next)[x_end]) &&
323                 ((*cur)[x_start] != 'N') && ((*next)[x_end] != 'N') ) ) {
324             full_match = false;
325           } else {
326             aligned_path.push_back(x_start);
327           }
328         }
329       }
330       // grab the last part of our path, assuming we matched
331       if (full_match)
332         aligned_path.push_back(x_end);
333
334       if (aligned_path.size() == a_path.size()) {
335         result.push_back(aligned_path);
336         reversed.push_back(rc_list);
337       }
338     }
339     align_counter++;
340   }
341 }
342
343
344 void Mussa::append_sequence(const Sequence& a_seq)
345 {
346   boost::shared_ptr<Sequence> seq_copy(new Sequence(a_seq));
347   the_seqs.push_back(seq_copy);
348   set_dirty(true);
349 }
350
351 void Mussa::append_sequence(boost::shared_ptr<Sequence> a_seq)
352 {
353   the_seqs.push_back(a_seq);
354   set_dirty(true);
355 }
356
357
358 const vector<SequenceRef>& 
359 Mussa::sequences() const
360 {
361   return the_seqs;
362 }
363
364 void Mussa::load_sequence(fs::path seq_file, fs::path annot_file, 
365                           int fasta_index, int sub_seq_start, int sub_seq_end,
366                           std::string *name)
367 {
368   boost::shared_ptr<Sequence> aseq(new Sequence);
369   aseq->load_fasta(seq_file, fasta_index, sub_seq_start, sub_seq_end);
370   if ( not annot_file.empty() ) {
371     aseq->load_annot(annot_file, sub_seq_start, sub_seq_end);
372   }
373   if (name != 0 and name->size() > 0 ) {
374     aseq->set_species(*name);
375   }
376   the_seqs.push_back(aseq);
377   set_dirty(true);
378 }
379
380 void
381 Mussa::load_mupa_file(fs::path para_file_path)
382 {
383   if (not fs::exists(para_file_path))
384   {
385     throw mussa_load_error("Config File: " + para_file_path.string() + " not found");
386   } else if (fs::is_directory(para_file_path)) {
387     throw mussa_load_error("Config File: " + para_file_path.string() + " is a directory.");
388   } else if (fs::is_empty(para_file_path)) {
389     throw mussa_load_error("Config File: " + para_file_path.string() + " is empty");
390   } else  {
391     // what directory is the mupa file in?
392     fs::path file_path_base( para_file_path.branch_path()) ;
393
394     fs::ifstream para_file;
395     para_file.open(para_file_path, ios::in);
396     
397     load_mupa_stream(para_file, file_path_base);
398     para_file.close();   
399   }
400 }
401
402 void
403 Mussa::load_mupa_stream(std::istream& para_file, fs::path& file_path_base)
404 {
405   std::string line;
406   std::vector< std::string > tokens;
407   int line_count = 0;
408
409   enum parsing_state_enum { START, INSEQUENCE };
410   parsing_state_enum parsing_state = START;
411   
412   // sequence file parameters
413   fs::path seq_file;
414   fs::path annot_file;
415   int split_index, fasta_index;
416   int sub_seq_start, sub_seq_end;
417   bool seq_params, did_seq;
418   std::string err_msg;
419
420   // initialize values
421   clear();
422
423   
424   while (para_file.good())
425   {
426     ++line_count;
427     // setup loop by getting file's first line
428     multiplatform_getline(para_file, line);
429     // strip leading/trailing whitespace
430     boost::trim(line);
431     // ignore commented out or blank lines
432     if ( line.size() == 0 or line[0] == '#' ) {
433       continue;
434     } 
435
436     // split the line on white spance
437     boost::split(tokens, line, boost::is_space());
438     // do we have a name/value pair?
439     if (tokens.size() != 2) { 
440       std::stringstream errmsg;
441       errmsg << "Error parsing MUPA file line: "
442              << line_count << std::endl
443              << line;
444       throw mussa_load_error(errmsg.str());
445     }
446   
447     boost::to_upper(tokens[0]);
448     // Parameters only useful after a sequence block
449     if (parsing_state == INSEQUENCE) {
450       // in the following if blocks, if we do 
451       // successfully match a token we should continue
452       // on to the next token
453       // but if we don't match a token we want to 
454       // fall through to the top level parsing
455
456       if (tokens[0] == "FASTA_INDEX") {
457         fasta_index = atoi(tokens[1].c_str());
458         continue;
459       } else if (tokens[0] == "ANNOTATION") {
460         annot_file = file_path_base / tokens[1];
461         continue;
462       } else if (tokens[0] == "SEQ_START") {
463         sub_seq_start = atoi(tokens[1].c_str());
464         continue;
465       } else if (tokens[0] == "SEQ_END") {
466         sub_seq_end = atoi(tokens[1].c_str());
467         continue;
468       } else {
469         // any other token means we're done with this
470         // sequence so we should load it 
471         // (and let the "unknown" token fall through into the 
472         // top level token parser)
473         load_sequence(seq_file, annot_file, fasta_index, sub_seq_start, 
474                       sub_seq_end);
475         parsing_state = START;
476       }
477     }
478     // if we didn't consume a token from the previous if block
479     // try 
480     // top level token parsing
481     if (tokens[0] == "ANA_NAME")  {
482       analysis_name = tokens[1];
483     } else if (tokens[0] == "APPEND_WIN") {
484       win_append = true;
485     } else if (tokens[0] == "APPEND_THRES") {
486       thres_append = true;
487     } else if (tokens[0] == "SEQUENCE_NUM") {
488       ; // ignore sequence_num now
489     } else if (tokens[0] == "WINDOW") {
490       window = atoi(tokens[1].c_str());
491     } else if (tokens[0] == "THRESHOLD") {
492       threshold = atoi(tokens[1].c_str());
493     } else if (tokens[0] == "SEQUENCE") {
494       if (parsing_state == INSEQUENCE) {
495         load_sequence(seq_file, annot_file, fasta_index, sub_seq_start, 
496                       sub_seq_end);
497         parsing_state = START;
498       }
499       // reset sequence parameters
500       seq_file = file_path_base / tokens[1];
501       fasta_index = 1;
502       annot_file = "";
503       sub_seq_start = 0;
504       sub_seq_end = 0;
505       seq_params = true;
506       parsing_state = INSEQUENCE;
507     } else {
508       clog << "Illegal/misplaced mussa parameter in file\n";
509       clog << tokens[0] << "\n";
510       std::stringstream errmsg;
511       errmsg << "Invalid mussa paaramater '" 
512              << tokens[0] 
513              << "' on line: "
514              << line_count << std::endl
515              << line;
516       throw mussa_load_error(errmsg.str());
517       throw mussa_load_error("Error parsing MUPA file");
518     }
519   }
520
521   // if we hit the end of the file and there's a sequence
522   // pending, go ahead and load it
523   if (parsing_state == INSEQUENCE) {
524     load_sequence(seq_file, annot_file, fasta_index, sub_seq_start, 
525                   sub_seq_end);
526   }
527
528   soft_thres = threshold;
529   set_dirty(true);
530 }
531
532
533 void
534 Mussa::analyze()
535 {
536   if (the_seqs.size() < 2) {
537     throw mussa_analysis_error("you need to have at least 2 sequences to "
538                                "do an analysis.");
539   }
540   
541   seqcomp();
542   the_paths.setup(window, threshold);
543   nway();
544 }
545
546 void
547 Mussa::seqcomp()
548 {
549   vector<int> seq_lens;
550   vector<FLPs> empty_FLP_vector;
551   FLPs dummy_comp;
552   string save_file_string;
553
554   empty_FLP_vector.clear();
555   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
556   {
557     all_comps.push_back(empty_FLP_vector); 
558     for(vector<Sequence>::size_type i2 = 0; i2 < the_seqs.size(); i2++)
559       all_comps[i].push_back(dummy_comp);
560   }
561   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
562     seq_lens.push_back(the_seqs[i]->size());
563   }
564   int seqcomps_done = 0;
565   int seqcomps_todo = (the_seqs.size() * (the_seqs.size()-1)) / 2;
566   emit progress("seqcomp", seqcomps_done, seqcomps_todo);
567
568   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
569     for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
570     {
571       //cout << "seqcomping: " << i << " v. " << i2 << endl;
572       all_comps[i][i2].setup(window, threshold);
573       all_comps[i][i2].seqcomp(*the_seqs[i], *the_seqs[i2], false);
574       all_comps[i][i2].seqcomp(*the_seqs[i], the_seqs[i2]->rev_comp(),true);
575       ++seqcomps_done;
576       emit progress("seqcomp", seqcomps_done, seqcomps_todo);
577     }
578 }
579
580 void
581 Mussa::nway()
582 {
583
584   the_paths.set_soft_threshold(soft_thres);
585
586   if (ana_mode == TransitiveNway) {
587     the_paths.trans_path_search(all_comps);
588   }
589   else if (ana_mode == RadialNway) {
590     the_paths.radiate_path_search(all_comps);
591   }
592   else if (ana_mode == EntropyNway)
593   {
594     vector<Sequence> some_Seqs;
595     //unlike other methods, entropy needs to look at the sequence at this stage
596     some_Seqs.clear();
597     for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
598     {
599       some_Seqs.push_back(*the_seqs[i]);
600     }
601
602     the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
603     the_paths.entropy_path_search(all_comps);
604   }
605
606   // old recursive transitive analysis function
607   else if (ana_mode == RecursiveNway)
608     the_paths.find_paths_r(all_comps);
609
610   the_paths.simple_refine();
611 }
612
613 void
614 Mussa::save(fs::path save_path)
615 {
616   fs::fstream save_file;
617   ostringstream append_info;
618   int dir_create_status;
619
620   if (save_path.empty()) {
621     if (not analysis_path.empty()) {
622       save_path = analysis_path;
623     } else if (not analysis_name.empty()) {
624       std::string save_name = analysis_name;
625        // gotta do bit with adding win & thres if to be appended
626        if (win_append) {
627         append_info.str("");
628         append_info <<  "_w" << window;
629         save_name += append_info.str();
630       }
631
632       if (thres_append) {
633         append_info.str("");
634         append_info <<  "_t" << threshold;
635         save_name += append_info.str();
636       }
637       save_path = save_name;
638     } else {
639       throw mussa_save_error("Need filename or analysis name to save");
640     }
641   }
642
643   if (not fs::exists(save_path)) {
644     fs::create_directory(save_path);
645   }
646   
647   std::string basename = save_path.leaf(); 
648   fs::path museq(basename + ".museq", fs::native);
649   
650   // save sequence and annots to a special mussa file
651   save_file.open(save_path / museq, ios::out);
652   save_file << "<Mussa_Sequence>" << endl;
653
654   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
655   {
656     the_seqs[i]->save(save_file);
657   }
658
659   save_file << "</Mussa_Sequence>" << endl;
660   save_file.close();
661
662   // if we have any motifs, save them.
663   if (motif_sequences.size()) {
664     fs::path mtl(basename + ".mtl", fs::native);
665     save_motifs(save_path / mtl);
666   }
667
668   // save nway paths to its mussa save file
669   fs::path muway(basename + ".muway", fs::native);
670   the_paths.save(save_path / muway);
671
672   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
673     for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
674     {
675       append_info.str("");
676       append_info <<  "_sp_" << i << "v" << i2;
677       fs::path flp(basename+append_info.str()+".flp", fs::native);
678       all_comps[i][i2].save(save_path / flp);
679     }
680   }
681
682   set_dirty(false);
683   analysis_path = save_path;
684 }
685
686 void
687 Mussa::save_muway(fs::path save_path)
688 {
689   the_paths.save(save_path);
690 }
691
692 void
693 Mussa::load(fs::path ana_file)
694 {
695   int i, i2;
696   fs::path file_path_base;
697   fs::path a_file_path; 
698   fs::path ana_path(ana_file);
699   bool parsing_path;
700   string err_msg;
701   ostringstream append_info;
702   vector<FLPs> empty_FLP_vector;
703   FLPs dummy_comp;
704
705
706   //--------------------------------------------------------
707   // Load Muway
708   //--------------------------------------------------------
709   analysis_path = ana_file;
710   analysis_name = ana_path.leaf();
711   fs::path muway(analysis_name+".muway", fs::native);
712   a_file_path = analysis_path / muway;
713   the_paths.load(a_file_path);
714   // perhaps this could be more elegent, but at least this'll let
715   // us know what our threshold and window sizes were when we load a muway
716   window = the_paths.get_window();
717   threshold = the_paths.get_threshold();
718   soft_thres = the_paths.get_soft_threshold();
719
720
721   //--------------------------------------------------------
722   // Load Sequence
723   //--------------------------------------------------------
724   //int seq_num = the_paths.sequence_count();
725
726   fs::path museq(analysis_name + ".museq", fs::native);
727   a_file_path = analysis_path / museq;
728
729   // this is a bit of a hack due to C++ not acting like it should with files
730   /*for (i = 1; i <= seq_num; i++)
731   {
732     boost::shared_ptr<Sequence> tmp_seq(new Sequence);
733     tmp_seq->load_museq(a_file_path, i);
734     the_seqs.push_back(tmp_seq);
735   }*/
736   
737   i = 1;
738   //int seq_num = 0;
739   boost::filesystem::fstream load_museq_fs;
740   load_museq_fs.open(a_file_path, std::ios::in);
741   boost::shared_ptr<Sequence> tmp_seq;
742   while (1)
743   {
744     tmp_seq = Sequence::load_museq(load_museq_fs);
745     
746     if (tmp_seq)
747     {
748       the_seqs.push_back(tmp_seq);
749     }
750     else
751     {
752       break;
753     }
754     
755     
756     //safe guard in case of an infinate loop.
757     //FIXME: If mussa can handle a comparison of 10000 sequences
758     // in the future, then this code should be fixed.
759     if (i == 10000)
760     {
761       throw mussa_load_error(" Run away sequence load!");
762     }
763     i++;
764   }
765   load_museq_fs.close();
766   
767   //--------------------------------------------------------
768   // Load Motifs
769   //--------------------------------------------------------
770   fs::path mtl(analysis_name + ".mtl", fs::native);
771   fs::path motif_file = analysis_path / mtl;
772   if (fs::exists(motif_file)) {
773     load_motifs(motif_file);
774   }
775   
776   vector<Sequence>::size_type seq_num = the_seqs.size();
777   empty_FLP_vector.clear();
778   for(i = 0; i < seq_num; i++)
779   {
780     all_comps.push_back(empty_FLP_vector); 
781     for(i2 = 0; i2 < seq_num; i2++)
782       all_comps[i].push_back(dummy_comp);
783   }
784   
785   
786   for(i = 0; i < seq_num; i++)
787   {
788     for(i2 = i+1; i2 < seq_num; i2++)
789     {
790       append_info.str("");
791       append_info << analysis_name <<  "_sp_" << i << "v" << i2 << ".flp";
792       //clog << append_info.str() << endl;
793       fs::path flp(append_info.str(), fs::native);
794       a_file_path = analysis_path / flp;
795       all_comps[i][i2].load(a_file_path);
796     }
797   }
798 }
799
800 void
801 Mussa::save_old()
802 {
803   fs::fstream save_file;
804
805   save_file.open(analysis_name, ios::out);
806
807   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
808     save_file << *(the_seqs[i]) << endl;
809
810   save_file << window << endl;
811   save_file.close();
812   //note more complex eventually since analysis_name may need to have
813   //window size, threshold and other stuff to modify it...
814   the_paths.save_old(analysis_name);
815 }
816
817
818 void
819 Mussa::load_old(char * load_file_path, int s_num)
820 {
821   fstream save_file;
822   string file_data_line; 
823   int i, space_split_i, comma_split_i;
824   vector<int> loaded_path;
825   string node_pair, node;
826   Sequence a_seq;
827
828   int seq_num = s_num;
829   the_paths.setup(0, 0);
830   save_file.open(load_file_path, ios::in);
831
832   // currently loads old mussa format
833
834   // get sequences
835   for(i = 0; i < seq_num; i++)
836   {
837     getline(save_file, file_data_line);
838     boost::shared_ptr<Sequence> a_seq(new Sequence(file_data_line));
839     the_seqs.push_back(a_seq);
840   }
841
842   // get window size
843   getline(save_file, file_data_line);
844   window = atoi(file_data_line.c_str());
845   // get paths
846
847   while (!save_file.eof())
848   {
849     loaded_path.clear();
850     getline(save_file, file_data_line);
851     if (file_data_line != "")
852     for(i = 0; i < seq_num; i++)
853     {
854       space_split_i = file_data_line.find(" ");
855       node_pair = file_data_line.substr(0,space_split_i);
856       //cout << "np= " << node_pair;
857       comma_split_i = node_pair.find(",");
858       node = node_pair.substr(comma_split_i+1);
859       //cout << "n= " << node << " ";
860       loaded_path.push_back(atoi (node.c_str()));
861       file_data_line = file_data_line.substr(space_split_i+1);
862     }
863     //cout << endl;
864     // FIXME: do we have any information about what the threshold should be?
865     the_paths.add_path(0, loaded_path);
866   }
867   save_file.close();
868
869   //the_paths.save("tmp.save");
870 }
871
872 void Mussa::add_motif(const Sequence& motif, const Color& color)
873 {
874   motif_sequences.insert(motif);
875   color_mapper->appendInstanceColor("motif", motif.get_sequence(), color);
876   set_dirty(true);
877 }
878
879 void Mussa::set_motifs(const vector<Sequence>& motifs, 
880                        const vector<Color>& colors)
881 {
882   if (motifs.size() != colors.size()) {
883     throw mussa_error("motif and color vectors must be the same size");
884   }
885
886   motif_sequences.clear();
887   for(size_t i = 0; i != motifs.size(); ++i)
888   {
889     add_motif(motifs[i], colors[i]);
890   }
891   update_sequences_motifs();
892 }
893
894 void Mussa::load_motifs(fs::path filename)
895 {
896   fs::ifstream f;
897   f.open(filename, ifstream::in);
898   load_motifs(f);
899 }
900   
901 void Mussa::load_motifs(std::istream &in)
902 {
903   std::string data;
904   const char *alphabet = Alphabet::dna_cstr;
905   motif_parser::ParsedMotifs parsed_motifs(motif_sequences, color_mapper);
906
907   // slurp our data into a string
908   std::streamsize bytes_read = 1;
909   while (in.good() and bytes_read) {
910     const std::streamsize bufsiz=512;
911     char buf[bufsiz];
912     bytes_read = in.readsome(buf, bufsiz);
913     data.append(buf, buf+bytes_read);
914   }
915   parsed_motifs.parse(data);
916   update_sequences_motifs();
917 }
918
919 void Mussa::save_motifs(fs::path filename)
920 {
921   fs::ofstream out_stream;
922   out_stream.open(filename, ofstream::out);
923   save_motifs(out_stream);
924 }
925
926 void Mussa::save_motifs(std::ostream& out)
927 {
928   for(motif_set::iterator motif_i = motif_sequences.begin();
929       motif_i != motif_sequences.end();
930       ++motif_i)
931   {
932     out << motif_i->get_sequence() << " ";
933     if (motif_i->get_name().size() > 0) {
934       out << "\"" << motif_i->get_name() << "\" ";
935     }
936     out << color_mapper->lookup("motif", motif_i->get_sequence());
937     out << std::endl;
938   }
939 }
940
941 void Mussa::update_sequences_motifs()
942 {
943   // once we've loaded all the motifs from the file, 
944   // lets attach them to the sequences
945   for(vector<SequenceRef >::iterator seq_i = the_seqs.begin();
946       seq_i != the_seqs.end();
947       ++seq_i)
948   {
949     // clear out old motifs
950     (*seq_i)->clear_motifs();
951     // for all the motifs in our set, attach them to the current sequence
952     for(set<Sequence>::iterator motif_i = motif_sequences.begin();
953         motif_i != motif_sequences.end();
954         ++motif_i)
955     {
956       (*seq_i)->add_motif(*motif_i);
957     }
958   }
959 }
960
961 const set<Sequence>& Mussa::motifs() const
962 {
963   return motif_sequences;
964 }
965
966 boost::shared_ptr<AnnotationColors> Mussa::colorMapper()
967 {
968   return color_mapper;
969 }