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