b538eccf0946bc8f992c62ea8cb81f8b6269c550
[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     soft_thres = threshold;
202   } else if (new_threshold > window) {
203     soft_thres = window; 
204   } else {
205     soft_thres = new_threshold;
206   }
207 }
208
209 int Mussa::get_soft_threshold() const
210 {
211   return soft_thres;
212 }
213
214
215 void
216 Mussa::set_analysis_mode(enum analysis_modes new_ana_mode)
217 {
218   ana_mode = new_ana_mode;
219   set_dirty(true);
220 }
221
222 enum Mussa::analysis_modes Mussa::get_analysis_mode() const
223 {
224   return ana_mode;
225 }
226
227 string Mussa::get_analysis_mode_name() const
228 {
229   switch (ana_mode)
230   {
231   case TransitiveNway:
232     return string("Transitive");
233     break;
234   case RadialNway:
235     return string("Radial");
236     break;
237   case EntropyNway:
238     return string("Entropy");
239     break;
240   case RecursiveNway:
241     return string("[deprecated] Recursive");
242     break;
243   default:
244     throw runtime_error("invalid analysis mode type");
245     break;
246   }
247 }
248
249 const NwayPaths& Mussa::paths() const
250 {
251   return the_paths;
252 }
253
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)
260 {
261   const vector_sequence_type& raw_seq = the_seqs;
262   ConservedPath::path_type aligned_path;
263   size_t i2, i3;
264   int x_start, x_end;
265   int window_length, win_i;
266   int rc_1 = 0; 
267   int rc_2 = 0;
268   vector<bool> rc_list;
269   bool full_match;
270   vector<bool> matched;
271   int align_counter;
272
273   align_counter = 0;
274   for(std::list<ConservedPath>::iterator pathz_i=begin; pathz_i != end; ++pathz_i)
275   {
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();
280     
281     // loop over each bp in the conserved region for all sequences
282     for(win_i = 0; win_i < window_length; win_i++)
283     {
284       aligned_path.clear();
285       // determine which exact base pairs match between the sequences
286       full_match = true;
287       for(i2 = 0; i2 < a_path.size()-1; i2++)
288       {
289         // assume not rc as most likely, adjust below
290         rc_1 = 0;
291         rc_2 = 0;
292         // no matter the case, any RC node needs adjustments
293         if (a_path[i2] < 0)
294           rc_1 = window_length-1;
295         if (a_path[i2+1] < 0)
296           rc_2 = window_length-1;        
297          
298         x_start = (abs(a_path[i2]-rc_1+win_i));
299         x_end =   (abs(a_path[i2+1]-rc_2+win_i));
300         
301         boost::shared_ptr<Sequence> cur(raw_seq[i2]) ;
302         boost::shared_ptr<Sequence> next(raw_seq[i2+1]);
303         // RC case handling
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'))) ) 
312           {
313             full_match = false;
314           } else {
315             aligned_path.push_back(x_start);
316           }
317         }
318         else
319         { // forward match
320           if (!( ((*cur)[x_start] == (*next)[x_end]) &&
321                 ((*cur)[x_start] != 'N') && ((*next)[x_end] != 'N') ) ) {
322             full_match = false;
323           } else {
324             aligned_path.push_back(x_start);
325           }
326         }
327       }
328       // grab the last part of our path, assuming we matched
329       if (full_match)
330         aligned_path.push_back(x_end);
331
332       if (aligned_path.size() == a_path.size()) {
333         result.push_back(aligned_path);
334         reversed.push_back(rc_list);
335       }
336     }
337     align_counter++;
338   }
339 }
340
341
342 void Mussa::append_sequence(const Sequence& a_seq)
343 {
344   boost::shared_ptr<Sequence> seq_copy(new Sequence(a_seq));
345   the_seqs.push_back(seq_copy);
346   set_dirty(true);
347 }
348
349 void Mussa::append_sequence(boost::shared_ptr<Sequence> a_seq)
350 {
351   the_seqs.push_back(a_seq);
352   set_dirty(true);
353 }
354
355
356 const vector<SequenceRef>& 
357 Mussa::sequences() const
358 {
359   return the_seqs;
360 }
361
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,
364                           std::string *name)
365 {
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);
370   }
371   if (name != 0 and name->size() > 0 ) {
372     aseq->set_species(*name);
373   }
374   the_seqs.push_back(aseq);
375   set_dirty(true);
376 }
377
378 void Mussa::load_mupa_file(std::string para_file_path) {
379   load_mupa_file(boost::filesystem::path(para_file_path));
380 }
381
382 void
383 Mussa::load_mupa_file(fs::path para_file_path)
384 {
385   if (not fs::exists(para_file_path))
386   {
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");
392   } else  {
393     // what directory is the mupa file in?
394     fs::path file_path_base( para_file_path.branch_path()) ;
395
396     fs::ifstream para_file;
397     para_file.open(para_file_path, ios::in);
398     
399     load_mupa_stream(para_file, file_path_base);
400     para_file.close();   
401   }
402 }
403
404 void
405 Mussa::load_mupa_stream(std::istream& para_file, fs::path& file_path_base)
406 {
407   std::string line;
408   std::vector< std::string > tokens;
409   int line_count = 0;
410
411   enum parsing_state_enum { START, INSEQUENCE };
412   parsing_state_enum parsing_state = START;
413   
414   // sequence file parameters
415   fs::path seq_file;
416   fs::path annot_file;
417   int split_index, fasta_index;
418   int sub_seq_start, sub_seq_end;
419   bool seq_params, did_seq;
420   std::string err_msg;
421
422   // initialize values
423   clear();
424
425   
426   while (para_file.good())
427   {
428     ++line_count;
429     // setup loop by getting file's first line
430     multiplatform_getline(para_file, line);
431     // strip leading/trailing whitespace
432     boost::trim(line);
433     // ignore commented out or blank lines
434     if ( line.size() == 0 or line[0] == '#' ) {
435       continue;
436     } 
437
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
445              << line;
446       throw mussa_load_error(errmsg.str());
447     }
448   
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
457
458       if (tokens[0] == "FASTA_INDEX") {
459         fasta_index = atoi(tokens[1].c_str());
460         continue;
461       } else if (tokens[0] == "ANNOTATION") {
462         annot_file = file_path_base / tokens[1];
463         continue;
464       } else if (tokens[0] == "SEQ_START") {
465         sub_seq_start = atoi(tokens[1].c_str());
466         continue;
467       } else if (tokens[0] == "SEQ_END") {
468         sub_seq_end = atoi(tokens[1].c_str());
469         continue;
470       } else {
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, 
476                       sub_seq_end);
477         parsing_state = START;
478       }
479     }
480     // if we didn't consume a token from the previous if block
481     // try 
482     // top level token parsing
483     if (tokens[0] == "ANA_NAME")  {
484       analysis_name = tokens[1];
485     } else if (tokens[0] == "APPEND_WIN") {
486       win_append = true;
487     } else if (tokens[0] == "APPEND_THRES") {
488       thres_append = true;
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, 
498                       sub_seq_end);
499         parsing_state = START;
500       }
501       // reset sequence parameters
502       seq_file = file_path_base / tokens[1];
503       fasta_index = 1;
504       annot_file = "";
505       sub_seq_start = 0;
506       sub_seq_end = 0;
507       seq_params = true;
508       parsing_state = INSEQUENCE;
509     } else {
510       clog << "Illegal/misplaced mussa parameter in file\n";
511       clog << tokens[0] << "\n";
512       std::stringstream errmsg;
513       errmsg << "Invalid mussa paaramater '" 
514              << tokens[0] 
515              << "' on line: "
516              << line_count << std::endl
517              << line;
518       throw mussa_load_error(errmsg.str());
519       throw mussa_load_error("Error parsing MUPA file");
520     }
521   }
522
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, 
527                   sub_seq_end);
528   }
529
530   soft_thres = threshold;
531   set_dirty(true);
532 }
533
534
535 void
536 Mussa::analyze()
537 {
538   if (the_seqs.size() < 2) {
539     throw mussa_analysis_error("you need to have at least 2 sequences to "
540                                "do an analysis.");
541   }
542   
543   seqcomp();
544   the_paths.setup(window, threshold);
545   nway();
546 }
547
548 void
549 Mussa::seqcomp()
550 {
551   vector<int> seq_lens;
552   vector<FLPs> empty_FLP_vector;
553   FLPs dummy_comp;
554   string save_file_string;
555
556   empty_FLP_vector.clear();
557   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
558   {
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);
562   }
563   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
564     seq_lens.push_back(the_seqs[i]->size());
565   }
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);
569
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++)
572     {
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);
577       ++seqcomps_done;
578       emit progress("seqcomp", seqcomps_done, seqcomps_todo);
579     }
580 }
581
582 void
583 Mussa::nway()
584 {
585
586   the_paths.set_soft_threshold(soft_thres);
587
588   if (ana_mode == TransitiveNway) {
589     the_paths.trans_path_search(all_comps);
590   }
591   else if (ana_mode == RadialNway) {
592     the_paths.radiate_path_search(all_comps);
593   }
594   else if (ana_mode == EntropyNway)
595   {
596     vector<Sequence> some_Seqs;
597     //unlike other methods, entropy needs to look at the sequence at this stage
598     some_Seqs.clear();
599     for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
600     {
601       some_Seqs.push_back(*the_seqs[i]);
602     }
603
604     the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
605     the_paths.entropy_path_search(all_comps);
606   }
607
608   // old recursive transitive analysis function
609   else if (ana_mode == RecursiveNway)
610     the_paths.find_paths_r(all_comps);
611
612   the_paths.simple_refine();
613 }
614
615 void
616 Mussa::save(fs::path save_path)
617 {
618   fs::fstream save_file;
619   ostringstream append_info;
620   int dir_create_status;
621
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
628        if (win_append) {
629         append_info.str("");
630         append_info <<  "_w" << window;
631         save_name += append_info.str();
632       }
633
634       if (thres_append) {
635         append_info.str("");
636         append_info <<  "_t" << threshold;
637         save_name += append_info.str();
638       }
639       save_path = save_name;
640     } else {
641       throw mussa_save_error("Need filename or analysis name to save");
642     }
643   }
644
645   if (not fs::exists(save_path)) {
646     fs::create_directory(save_path);
647   }
648   
649   std::string basename = save_path.leaf(); 
650   fs::path museq(basename + ".museq", fs::native);
651   
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;
655
656   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
657   {
658     the_seqs[i]->save(save_file);
659   }
660
661   save_file << "</Mussa_Sequence>" << endl;
662   save_file.close();
663
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);
668   }
669
670   // save nway paths to its mussa save file
671   fs::path muway(basename + ".muway", fs::native);
672   the_paths.save(save_path / muway);
673
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++)
676     {
677       append_info.str("");
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);
681     }
682   }
683
684   set_dirty(false);
685   analysis_path = save_path;
686 }
687
688 void
689 Mussa::save_muway(fs::path save_path)
690 {
691   the_paths.save(save_path);
692 }
693
694 void
695 Mussa::load(fs::path ana_file)
696 {
697   int i, i2;
698   fs::path file_path_base;
699   fs::path a_file_path; 
700   fs::path ana_path(ana_file);
701   bool parsing_path;
702   string err_msg;
703   ostringstream append_info;
704   vector<FLPs> empty_FLP_vector;
705   FLPs dummy_comp;
706
707
708   //--------------------------------------------------------
709   // Load Muway
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();
721
722
723   //--------------------------------------------------------
724   // Load Sequence
725   //--------------------------------------------------------
726   //int seq_num = the_paths.sequence_count();
727
728   fs::path museq(analysis_name + ".museq", fs::native);
729   a_file_path = analysis_path / museq;
730
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++)
733   {
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);
737   }*/
738   
739   i = 1;
740   //int seq_num = 0;
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;
744   while (1)
745   {
746     tmp_seq = Sequence::load_museq(load_museq_fs);
747     
748     if (tmp_seq)
749     {
750       the_seqs.push_back(tmp_seq);
751     }
752     else
753     {
754       break;
755     }
756     
757     
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.
761     if (i == 10000)
762     {
763       throw mussa_load_error(" Run away sequence load!");
764     }
765     i++;
766   }
767   load_museq_fs.close();
768   
769   //--------------------------------------------------------
770   // Load Motifs
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);
776   }
777   
778   vector<Sequence>::size_type seq_num = the_seqs.size();
779   empty_FLP_vector.clear();
780   for(i = 0; i < seq_num; i++)
781   {
782     all_comps.push_back(empty_FLP_vector); 
783     for(i2 = 0; i2 < seq_num; i2++)
784       all_comps[i].push_back(dummy_comp);
785   }
786   
787   
788   for(i = 0; i < seq_num; i++)
789   {
790     for(i2 = i+1; i2 < seq_num; i2++)
791     {
792       append_info.str("");
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);
798     }
799   }
800 }
801
802 void
803 Mussa::save_old()
804 {
805   fs::fstream save_file;
806
807   save_file.open(analysis_name, ios::out);
808
809   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
810     save_file << *(the_seqs[i]) << endl;
811
812   save_file << window << endl;
813   save_file.close();
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);
817 }
818
819
820 void
821 Mussa::load_old(char * load_file_path, int s_num)
822 {
823   fstream save_file;
824   string file_data_line; 
825   int i, space_split_i, comma_split_i;
826   vector<int> loaded_path;
827   string node_pair, node;
828   Sequence a_seq;
829
830   int seq_num = s_num;
831   the_paths.setup(0, 0);
832   save_file.open(load_file_path, ios::in);
833
834   // currently loads old mussa format
835
836   // get sequences
837   for(i = 0; i < seq_num; i++)
838   {
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);
842   }
843
844   // get window size
845   getline(save_file, file_data_line);
846   window = atoi(file_data_line.c_str());
847   // get paths
848
849   while (!save_file.eof())
850   {
851     loaded_path.clear();
852     getline(save_file, file_data_line);
853     if (file_data_line != "")
854     for(i = 0; i < seq_num; i++)
855     {
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);
864     }
865     //cout << endl;
866     // FIXME: do we have any information about what the threshold should be?
867     the_paths.add_path(0, loaded_path);
868   }
869   save_file.close();
870
871   //the_paths.save("tmp.save");
872 }
873
874 void Mussa::add_motif(const Sequence& motif, const Color& color)
875 {
876   motif_sequences.insert(motif);
877   color_mapper->appendInstanceColor("motif", motif.get_sequence(), color);
878   set_dirty(true);
879 }
880
881 void Mussa::set_motifs(const vector<Sequence>& motifs, 
882                        const vector<Color>& colors)
883 {
884   if (motifs.size() != colors.size()) {
885     throw mussa_error("motif and color vectors must be the same size");
886   }
887
888   motif_sequences.clear();
889   for(size_t i = 0; i != motifs.size(); ++i)
890   {
891     add_motif(motifs[i], colors[i]);
892   }
893   update_sequences_motifs();
894 }
895
896 void Mussa::load_motifs(fs::path filename)
897 {
898   fs::ifstream f;
899   f.open(filename, ifstream::in);
900   load_motifs(f);
901 }
902   
903 void Mussa::load_motifs(std::istream &in)
904 {
905   std::string data;
906   const char *alphabet = Alphabet::dna_cstr;
907   motif_parser::ParsedMotifs parsed_motifs(motif_sequences, color_mapper);
908
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;
913     char buf[bufsiz];
914     bytes_read = in.readsome(buf, bufsiz);
915     data.append(buf, buf+bytes_read);
916   }
917   parsed_motifs.parse(data);
918   update_sequences_motifs();
919 }
920
921 void Mussa::save_motifs(fs::path filename)
922 {
923   fs::ofstream out_stream;
924   out_stream.open(filename, ofstream::out);
925   save_motifs(out_stream);
926 }
927
928 void Mussa::save_motifs(std::ostream& out)
929 {
930   for(motif_set::iterator motif_i = motif_sequences.begin();
931       motif_i != motif_sequences.end();
932       ++motif_i)
933   {
934     out << motif_i->get_sequence() << " ";
935     if (motif_i->get_name().size() > 0) {
936       out << "\"" << motif_i->get_name() << "\" ";
937     }
938     out << color_mapper->lookup("motif", motif_i->get_sequence());
939     out << std::endl;
940   }
941 }
942
943 void Mussa::update_sequences_motifs()
944 {
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();
949       ++seq_i)
950   {
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();
956         ++motif_i)
957     {
958       (*seq_i)->add_motif(*motif_i);
959     }
960   }
961 }
962
963 const set<Sequence>& Mussa::motifs() const
964 {
965   return motif_sequences;
966 }
967
968 boost::shared_ptr<AnnotationColors> Mussa::colorMapper()
969 {
970   return color_mapper;
971 }