make the mupa parser more robust
[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         cout << "seq_file_name call2" << seq_file << endl;
498         load_sequence(seq_file, annot_file, fasta_index, sub_seq_start, 
499                       sub_seq_end);
500         parsing_state = START;
501       }
502       // reset sequence parameters
503       seq_file = file_path_base / tokens[1];
504       fasta_index = 1;
505       annot_file = "";
506       sub_seq_start = 0;
507       sub_seq_end = 0;
508       seq_params = true;
509       parsing_state = INSEQUENCE;
510     } else {
511       clog << "Illegal/misplaced mussa parameter in file\n";
512       clog << tokens[0] << "\n";
513       std::stringstream errmsg;
514       errmsg << "Invalid mussa paaramater '" 
515              << tokens[0] 
516              << "' on line: "
517              << line_count << std::endl
518              << line;
519       throw mussa_load_error(errmsg.str());
520       throw mussa_load_error("Error parsing MUPA file");
521     }
522   }
523
524   // if we hit the end of the file and there's a sequence
525   // pending, go ahead and load it
526   if (parsing_state == INSEQUENCE) {
527     load_sequence(seq_file, annot_file, fasta_index, sub_seq_start, 
528                   sub_seq_end);
529   }
530
531   soft_thres = threshold;
532   set_dirty(true);
533 }
534
535
536 void
537 Mussa::analyze()
538 {
539   if (the_seqs.size() < 2) {
540     throw mussa_analysis_error("you need to have at least 2 sequences to "
541                                "do an analysis.");
542   }
543   
544   seqcomp();
545   the_paths.setup(window, threshold);
546   nway();
547 }
548
549 void
550 Mussa::seqcomp()
551 {
552   vector<int> seq_lens;
553   vector<FLPs> empty_FLP_vector;
554   FLPs dummy_comp;
555   string save_file_string;
556
557   empty_FLP_vector.clear();
558   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
559   {
560     all_comps.push_back(empty_FLP_vector); 
561     for(vector<Sequence>::size_type i2 = 0; i2 < the_seqs.size(); i2++)
562       all_comps[i].push_back(dummy_comp);
563   }
564   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
565     seq_lens.push_back(the_seqs[i]->size());
566   }
567   int seqcomps_done = 0;
568   int seqcomps_todo = (the_seqs.size() * (the_seqs.size()-1)) / 2;
569   emit progress("seqcomp", seqcomps_done, seqcomps_todo);
570
571   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
572     for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
573     {
574       //cout << "seqcomping: " << i << " v. " << i2 << endl;
575       all_comps[i][i2].setup(window, threshold);
576       all_comps[i][i2].seqcomp(*the_seqs[i], *the_seqs[i2], false);
577       all_comps[i][i2].seqcomp(*the_seqs[i], the_seqs[i2]->rev_comp(),true);
578       ++seqcomps_done;
579       emit progress("seqcomp", seqcomps_done, seqcomps_todo);
580     }
581 }
582
583 void
584 Mussa::nway()
585 {
586
587   the_paths.set_soft_threshold(soft_thres);
588
589   if (ana_mode == TransitiveNway) {
590     the_paths.trans_path_search(all_comps);
591   }
592   else if (ana_mode == RadialNway) {
593     the_paths.radiate_path_search(all_comps);
594   }
595   else if (ana_mode == EntropyNway)
596   {
597     vector<Sequence> some_Seqs;
598     //unlike other methods, entropy needs to look at the sequence at this stage
599     some_Seqs.clear();
600     for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
601     {
602       some_Seqs.push_back(*the_seqs[i]);
603     }
604
605     the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
606     the_paths.entropy_path_search(all_comps);
607   }
608
609   // old recursive transitive analysis function
610   else if (ana_mode == RecursiveNway)
611     the_paths.find_paths_r(all_comps);
612
613   the_paths.simple_refine();
614 }
615
616 void
617 Mussa::save(fs::path save_path)
618 {
619   fs::fstream save_file;
620   ostringstream append_info;
621   int dir_create_status;
622
623   if (save_path.empty()) {
624     if (not analysis_path.empty()) {
625       save_path = analysis_path;
626     } else if (not analysis_name.empty()) {
627       std::string save_name = analysis_name;
628        // gotta do bit with adding win & thres if to be appended
629        if (win_append) {
630         append_info.str("");
631         append_info <<  "_w" << window;
632         save_name += append_info.str();
633       }
634
635       if (thres_append) {
636         append_info.str("");
637         append_info <<  "_t" << threshold;
638         save_name += append_info.str();
639       }
640       save_path = save_name;
641     } else {
642       throw mussa_save_error("Need filename or analysis name to save");
643     }
644   }
645
646   if (not fs::exists(save_path)) {
647     fs::create_directory(save_path);
648   }
649   
650   std::string basename = save_path.leaf(); 
651   fs::path museq(basename + ".museq", fs::native);
652   
653   // save sequence and annots to a special mussa file
654   save_file.open(save_path / museq, ios::out);
655   save_file << "<Mussa_Sequence>" << endl;
656
657   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
658   {
659     the_seqs[i]->save(save_file);
660   }
661
662   save_file << "</Mussa_Sequence>" << endl;
663   save_file.close();
664
665   // if we have any motifs, save them.
666   if (motif_sequences.size()) {
667     fs::path mtl(basename + ".mtl", fs::native);
668     save_motifs(save_path / mtl);
669   }
670
671   // save nway paths to its mussa save file
672   fs::path muway(basename + ".muway", fs::native);
673   the_paths.save(save_path / muway);
674
675   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
676     for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
677     {
678       append_info.str("");
679       append_info <<  "_sp_" << i << "v" << i2;
680       fs::path flp(basename+append_info.str()+".flp", fs::native);
681       all_comps[i][i2].save(save_path / flp);
682     }
683   }
684
685   set_dirty(false);
686   analysis_path = save_path;
687 }
688
689 void
690 Mussa::save_muway(fs::path save_path)
691 {
692   the_paths.save(save_path);
693 }
694
695 void
696 Mussa::load(fs::path ana_file)
697 {
698   int i, i2;
699   fs::path file_path_base;
700   fs::path a_file_path; 
701   fs::path ana_path(ana_file);
702   bool parsing_path;
703   string err_msg;
704   ostringstream append_info;
705   vector<FLPs> empty_FLP_vector;
706   FLPs dummy_comp;
707
708
709   //--------------------------------------------------------
710   // Load Muway
711   //--------------------------------------------------------
712   analysis_path = ana_file;
713   analysis_name = ana_path.leaf();
714   fs::path muway(analysis_name+".muway", fs::native);
715   a_file_path = analysis_path / muway;
716   the_paths.load(a_file_path);
717   // perhaps this could be more elegent, but at least this'll let
718   // us know what our threshold and window sizes were when we load a muway
719   window = the_paths.get_window();
720   threshold = the_paths.get_threshold();
721   soft_thres = the_paths.get_soft_threshold();
722
723
724   //--------------------------------------------------------
725   // Load Sequence
726   //--------------------------------------------------------
727   //int seq_num = the_paths.sequence_count();
728
729   fs::path museq(analysis_name + ".museq", fs::native);
730   a_file_path = analysis_path / museq;
731
732   // this is a bit of a hack due to C++ not acting like it should with files
733   /*for (i = 1; i <= seq_num; i++)
734   {
735     boost::shared_ptr<Sequence> tmp_seq(new Sequence);
736     tmp_seq->load_museq(a_file_path, i);
737     the_seqs.push_back(tmp_seq);
738   }*/
739   
740   i = 1;
741   //int seq_num = 0;
742   boost::filesystem::fstream load_museq_fs;
743   load_museq_fs.open(a_file_path, std::ios::in);
744   boost::shared_ptr<Sequence> tmp_seq;
745   while (1)
746   {
747     tmp_seq = Sequence::load_museq(load_museq_fs);
748     
749     if (tmp_seq)
750     {
751       the_seqs.push_back(tmp_seq);
752     }
753     else
754     {
755       break;
756     }
757     
758     
759     //safe guard in case of an infinate loop.
760     //FIXME: If mussa can handle a comparison of 10000 sequences
761     // in the future, then this code should be fixed.
762     if (i == 10000)
763     {
764       throw mussa_load_error(" Run away sequence load!");
765     }
766     i++;
767   }
768   load_museq_fs.close();
769   
770   //--------------------------------------------------------
771   // Load Motifs
772   //--------------------------------------------------------
773   fs::path mtl(analysis_name + ".mtl", fs::native);
774   fs::path motif_file = analysis_path / mtl;
775   if (fs::exists(motif_file)) {
776     load_motifs(motif_file);
777   }
778   
779   vector<Sequence>::size_type seq_num = the_seqs.size();
780   empty_FLP_vector.clear();
781   for(i = 0; i < seq_num; i++)
782   {
783     all_comps.push_back(empty_FLP_vector); 
784     for(i2 = 0; i2 < seq_num; i2++)
785       all_comps[i].push_back(dummy_comp);
786   }
787   
788   
789   for(i = 0; i < seq_num; i++)
790   {
791     for(i2 = i+1; i2 < seq_num; i2++)
792     {
793       append_info.str("");
794       append_info << analysis_name <<  "_sp_" << i << "v" << i2 << ".flp";
795       //clog << append_info.str() << endl;
796       fs::path flp(append_info.str(), fs::native);
797       a_file_path = analysis_path / flp;
798       all_comps[i][i2].load(a_file_path);
799     }
800   }
801 }
802
803 void
804 Mussa::save_old()
805 {
806   fs::fstream save_file;
807
808   save_file.open(analysis_name, ios::out);
809
810   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
811     save_file << *(the_seqs[i]) << endl;
812
813   save_file << window << endl;
814   save_file.close();
815   //note more complex eventually since analysis_name may need to have
816   //window size, threshold and other stuff to modify it...
817   the_paths.save_old(analysis_name);
818 }
819
820
821 void
822 Mussa::load_old(char * load_file_path, int s_num)
823 {
824   fstream save_file;
825   string file_data_line; 
826   int i, space_split_i, comma_split_i;
827   vector<int> loaded_path;
828   string node_pair, node;
829   Sequence a_seq;
830
831   int seq_num = s_num;
832   the_paths.setup(0, 0);
833   save_file.open(load_file_path, ios::in);
834
835   // currently loads old mussa format
836
837   // get sequences
838   for(i = 0; i < seq_num; i++)
839   {
840     getline(save_file, file_data_line);
841     boost::shared_ptr<Sequence> a_seq(new Sequence(file_data_line));
842     the_seqs.push_back(a_seq);
843   }
844
845   // get window size
846   getline(save_file, file_data_line);
847   window = atoi(file_data_line.c_str());
848   // get paths
849
850   while (!save_file.eof())
851   {
852     loaded_path.clear();
853     getline(save_file, file_data_line);
854     if (file_data_line != "")
855     for(i = 0; i < seq_num; i++)
856     {
857       space_split_i = file_data_line.find(" ");
858       node_pair = file_data_line.substr(0,space_split_i);
859       //cout << "np= " << node_pair;
860       comma_split_i = node_pair.find(",");
861       node = node_pair.substr(comma_split_i+1);
862       //cout << "n= " << node << " ";
863       loaded_path.push_back(atoi (node.c_str()));
864       file_data_line = file_data_line.substr(space_split_i+1);
865     }
866     //cout << endl;
867     // FIXME: do we have any information about what the threshold should be?
868     the_paths.add_path(0, loaded_path);
869   }
870   save_file.close();
871
872   //the_paths.save("tmp.save");
873 }
874
875 void Mussa::add_motif(const Sequence& motif, const Color& color)
876 {
877   motif_sequences.insert(motif);
878   color_mapper->appendInstanceColor("motif", motif.get_sequence(), color);
879   set_dirty(true);
880 }
881
882 void Mussa::set_motifs(const vector<Sequence>& motifs, 
883                        const vector<Color>& colors)
884 {
885   if (motifs.size() != colors.size()) {
886     throw mussa_error("motif and color vectors must be the same size");
887   }
888
889   motif_sequences.clear();
890   for(size_t i = 0; i != motifs.size(); ++i)
891   {
892     add_motif(motifs[i], colors[i]);
893   }
894   update_sequences_motifs();
895 }
896
897 void Mussa::load_motifs(fs::path filename)
898 {
899   fs::ifstream f;
900   f.open(filename, ifstream::in);
901   load_motifs(f);
902 }
903   
904 void Mussa::load_motifs(std::istream &in)
905 {
906   std::string data;
907   const char *alphabet = Alphabet::dna_cstr;
908   motif_parser::ParsedMotifs parsed_motifs(motif_sequences, color_mapper);
909
910   // slurp our data into a string
911   std::streamsize bytes_read = 1;
912   while (in.good() and bytes_read) {
913     const std::streamsize bufsiz=512;
914     char buf[bufsiz];
915     bytes_read = in.readsome(buf, bufsiz);
916     data.append(buf, buf+bytes_read);
917   }
918   parsed_motifs.parse(data);
919   update_sequences_motifs();
920 }
921
922 void Mussa::save_motifs(fs::path filename)
923 {
924   fs::ofstream out_stream;
925   out_stream.open(filename, ofstream::out);
926   save_motifs(out_stream);
927 }
928
929 void Mussa::save_motifs(std::ostream& out)
930 {
931   for(motif_set::iterator motif_i = motif_sequences.begin();
932       motif_i != motif_sequences.end();
933       ++motif_i)
934   {
935     out << motif_i->get_sequence() << " ";
936     if (motif_i->get_name().size() > 0) {
937       out << "\"" << motif_i->get_name() << "\" ";
938     }
939     out << color_mapper->lookup("motif", motif_i->get_sequence());
940     out << std::endl;
941   }
942 }
943
944 void Mussa::update_sequences_motifs()
945 {
946   // once we've loaded all the motifs from the file, 
947   // lets attach them to the sequences
948   for(vector<SequenceRef >::iterator seq_i = the_seqs.begin();
949       seq_i != the_seqs.end();
950       ++seq_i)
951   {
952     // clear out old motifs
953     (*seq_i)->clear_motifs();
954     // for all the motifs in our set, attach them to the current sequence
955     for(set<Sequence>::iterator motif_i = motif_sequences.begin();
956         motif_i != motif_sequences.end();
957         ++motif_i)
958     {
959       (*seq_i)->add_motif(*motif_i);
960     }
961   }
962 }
963
964 const set<Sequence>& Mussa::motifs() const
965 {
966   return motif_sequences;
967 }
968
969 boost::shared_ptr<AnnotationColors> Mussa::colorMapper()
970 {
971   return color_mapper;
972 }