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