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