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