]> git.donarmstrong.com Git - mothur.git/blob - unifracweightedcommand.cpp
mods to amova command
[mothur.git] / unifracweightedcommand.cpp
1 /*
2  *  unifracweightedcommand.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 2/9/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
10 #include "unifracweightedcommand.h"
11
12 //**********************************************************************************************************************
13 vector<string> UnifracWeightedCommand::getValidParameters(){    
14         try {
15                 string Array[] =  {"groups","iters","distance","random","processors","outputdir","inputdir"};
16                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
17                 return myArray;
18         }
19         catch(exception& e) {
20                 m->errorOut(e, "UnifracWeightedCommand", "getValidParameters");
21                 exit(1);
22         }
23 }
24 //**********************************************************************************************************************
25 UnifracWeightedCommand::UnifracWeightedCommand(){       
26         try {
27                 abort = true; calledHelp = true; 
28                 vector<string> tempOutNames;
29                 outputTypes["weighted"] = tempOutNames;
30                 outputTypes["wsummary"] = tempOutNames;
31                 outputTypes["phylip"] = tempOutNames;
32                 outputTypes["column"] = tempOutNames;
33         }
34         catch(exception& e) {
35                 m->errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
36                 exit(1);
37         }
38 }
39 //**********************************************************************************************************************
40 vector<string> UnifracWeightedCommand::getRequiredParameters(){ 
41         try {
42                 vector<string> myArray;
43                 return myArray;
44         }
45         catch(exception& e) {
46                 m->errorOut(e, "UnifracWeightedCommand", "getRequiredParameters");
47                 exit(1);
48         }
49 }
50 //**********************************************************************************************************************
51 vector<string> UnifracWeightedCommand::getRequiredFiles(){      
52         try {
53                 string Array[] =  {"tree","group"};
54                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
55
56                 return myArray;
57         }
58         catch(exception& e) {
59                 m->errorOut(e, "UnifracWeightedCommand", "getRequiredFiles");
60                 exit(1);
61         }
62 }
63 /***********************************************************/
64 UnifracWeightedCommand::UnifracWeightedCommand(string option) {
65         try {
66                 globaldata = GlobalData::getInstance();
67                 abort = false; calledHelp = false;   
68                 Groups.clear();
69                         
70                 //allow user to run help
71                 if(option == "help") { help(); abort = true; calledHelp = true; }
72                 
73                 else {
74                         //valid paramters for this command
75                         string Array[] =  {"groups","iters","distance","random","processors","outputdir","inputdir"};
76                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
77                         
78                         OptionParser parser(option);
79                         map<string,string> parameters=parser.getParameters();
80                         
81                         ValidParameters validParameter;
82                 
83                         //check to make sure all parameters are valid for command
84                         for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) { 
85                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
86                         }
87                         
88                         //initialize outputTypes
89                         vector<string> tempOutNames;
90                         outputTypes["weighted"] = tempOutNames;
91                         outputTypes["wsummary"] = tempOutNames;
92                         outputTypes["phylip"] = tempOutNames;
93                         outputTypes["column"] = tempOutNames;
94                         
95                         if (globaldata->gTree.size() == 0) {//no trees were read
96                                 m->mothurOut("You must execute the read.tree command, before you may execute the unifrac.weighted command."); m->mothurOutEndLine(); abort = true;  }
97                         
98                         //if the user changes the output directory command factory will send this info to us in the output parameter 
99                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
100                                 outputDir = ""; 
101                                 outputDir += m->hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it       
102                         }
103                                                                                                                                         
104                         //check for optional parameter and set defaults
105                         // ...at some point should added some additional type checking...
106                         groups = validParameter.validFile(parameters, "groups", false);                 
107                         if (groups == "not found") { groups = ""; }
108                         else { 
109                                 m->splitAtDash(groups, Groups);
110                                 globaldata->Groups = Groups;
111                         }
112                                 
113                         itersString = validParameter.validFile(parameters, "iters", false);                     if (itersString == "not found") { itersString = "1000"; }
114                         convert(itersString, iters); 
115                         
116                         string temp = validParameter.validFile(parameters, "distance", false);                  
117                         if (temp == "not found") { phylip = false; outputForm = ""; }
118                         else{
119                                 if ((temp == "lt") || (temp == "column") || (temp == "square")) {  phylip = true;  outputForm = temp; }
120                                 else { m->mothurOut("Options for distance are: lt, square, or column. Using lt."); m->mothurOutEndLine(); phylip = true; outputForm = "lt"; }
121                         }
122                         
123                         temp = validParameter.validFile(parameters, "random", false);                                   if (temp == "not found") { temp = "F"; }
124                         random = m->isTrue(temp);
125                         
126                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = "1";                             }
127                         convert(temp, processors); 
128                         
129                         if (!random) {  iters = 0;  } //turn off random calcs
130
131                         
132                         if (abort == false) {
133                                 T = globaldata->gTree;
134                                 tmap = globaldata->gTreemap;
135                                 sumFile = outputDir + m->getSimpleName(globaldata->getTreeFile()) + ".wsummary";
136                                 m->openOutputFile(sumFile, outSum);
137                                 outputNames.push_back(sumFile);  outputTypes["wsummary"].push_back(sumFile);
138                                 
139                                 util = new SharedUtil();
140                                 string s; //to make work with setgroups
141                                 util->setGroups(globaldata->Groups, tmap->namesOfGroups, s, numGroups, "weighted");     //sets the groups the user wants to analyze
142                                 util->getCombos(groupComb, globaldata->Groups, numComp);
143                                 
144                                 weighted = new Weighted(tmap);
145                                 
146                         }
147                 }
148                 
149                 
150         }
151         catch(exception& e) {
152                 m->errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
153                 exit(1);
154         }
155 }
156 //**********************************************************************************************************************
157
158 void UnifracWeightedCommand::help(){
159         try {
160                 m->mothurOut("The unifrac.weighted command can only be executed after a successful read.tree command.\n");
161                 m->mothurOut("The unifrac.weighted command parameters are groups, iters, distance, processors and random.  No parameters are required.\n");
162                 m->mothurOut("The groups parameter allows you to specify which of the groups in your groupfile you would like analyzed.  You must enter at least 2 valid groups.\n");
163                 m->mothurOut("The group names are separated by dashes.  The iters parameter allows you to specify how many random trees you would like compared to your tree.\n");
164                 m->mothurOut("The distance parameter allows you to create a distance file from the results. The default is false.\n");
165                 m->mothurOut("The random parameter allows you to shut off the comparison to random trees. The default is false, meaning don't compare your trees with randomly generated trees.\n");
166                 m->mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
167                 m->mothurOut("The unifrac.weighted command should be in the following format: unifrac.weighted(groups=yourGroups, iters=yourIters).\n");
168                 m->mothurOut("Example unifrac.weighted(groups=A-B-C, iters=500).\n");
169                 m->mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
170                 m->mothurOut("The unifrac.weighted command output two files: .weighted and .wsummary their descriptions are in the manual.\n");
171                 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
172         }
173         catch(exception& e) {
174                 m->errorOut(e, "UnifracWeightedCommand", "help");
175                 exit(1);
176         }
177 }
178
179 /***********************************************************/
180 int UnifracWeightedCommand::execute() {
181         try {
182         
183                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
184                 
185                 int start = time(NULL);
186                 
187                 //get weighted for users tree
188                 userData.resize(numComp,0);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
189                 randomData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
190                                 
191                 //get weighted scores for users trees
192                 for (int i = 0; i < T.size(); i++) {
193                         
194                         if (m->control_pressed) { outSum.close(); for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());  } return 0; }
195
196                         counter = 0;
197                         rScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
198                         uScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
199                         
200                         if (random) {  
201                                 output = new ColumnFile(outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted", itersString);  
202                                 outputNames.push_back(outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted");
203                                 outputTypes["weighted"].push_back(outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted");
204                         } 
205
206                         userData = weighted->getValues(T[i], processors, outputDir);  //userData[0] = weightedscore
207                         
208                         if (m->control_pressed) { if (random) { delete output; } outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str());  } return 0; }
209                         
210                         //save users score
211                         for (int s=0; s<numComp; s++) {
212                                 //add users score to vector of user scores
213                                 uScores[s].push_back(userData[s]);
214                                 
215                                 //save users tree score for summary file
216                                 utreeScores.push_back(userData[s]);
217                         }
218                         
219                         if (random) { 
220                         
221                                 //calculate number of comparisons i.e. with groups A,B,C = AB, AC, BC = 3;
222                                 vector< vector<string> > namesOfGroupCombos;
223                                 for (int a=0; a<numGroups; a++) { 
224                                         for (int l = 0; l < a; l++) {   
225                                                 vector<string> groups; groups.push_back(globaldata->Groups[a]); groups.push_back(globaldata->Groups[l]);
226                                                 namesOfGroupCombos.push_back(groups);
227                                         }
228                                 }
229                                 
230                                 lines.clear();
231                                 
232                                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
233                                         if(processors != 1){
234                                                 int numPairs = namesOfGroupCombos.size();
235                                                 int numPairsPerProcessor = numPairs / processors;
236                                         
237                                                 for (int i = 0; i < processors; i++) {
238                                                         int startPos = i * numPairsPerProcessor;
239                                                         if(i == processors - 1){
240                                                                 numPairsPerProcessor = numPairs - i * numPairsPerProcessor;
241                                                         }
242                                                         lines.push_back(linePair(startPos, numPairsPerProcessor));
243                                                 }
244                                         }
245                                 #endif
246
247                                 
248                                 //get scores for random trees
249                                 for (int j = 0; j < iters; j++) {
250                                 
251                                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
252                                                 if(processors == 1){
253                                                         driver(T[i],  namesOfGroupCombos, 0, namesOfGroupCombos.size(),  rScores);
254                                                 }else{
255                                                         createProcesses(T[i],  namesOfGroupCombos, rScores);
256                                                 }
257                                         #else
258                                                 driver(T[i], namesOfGroupCombos, 0, namesOfGroupCombos.size(), rScores);
259                                         #endif
260                                         
261                                         if (m->control_pressed) { delete output; outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str());  } return 0; }
262                                         
263                                         //report progress
264 //                                      m->mothurOut("Iter: " + toString(j+1)); m->mothurOutEndLine();          
265                                 }
266                                 lines.clear();
267                         
268                                 //find the signifigance of the score for summary file
269                                 for (int f = 0; f < numComp; f++) {
270                                         //sort random scores
271                                         sort(rScores[f].begin(), rScores[f].end());
272                                         
273                                         //the index of the score higher than yours is returned 
274                                         //so if you have 1000 random trees the index returned is 100 
275                                         //then there are 900 trees with a score greater then you. 
276                                         //giving you a signifigance of 0.900
277                                         int index = findIndex(userData[f], f);    if (index == -1) { m->mothurOut("error in UnifracWeightedCommand"); m->mothurOutEndLine(); exit(1); } //error code
278                                         
279                                         //the signifigance is the number of trees with the users score or higher 
280                                         WScoreSig.push_back((iters-index)/(float)iters);
281                                 }
282                                 
283                                 //out << "Tree# " << i << endl;
284                                 calculateFreqsCumuls();
285                                 printWeightedFile();
286                                 
287                                 delete output;
288                         
289                         }
290                         
291                         //clear data
292                         rScores.clear();
293                         uScores.clear();
294                         validScores.clear();
295                 }
296                 
297                 
298                 if (m->control_pressed) { outSum.close(); for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());  } return 0;  }
299                 
300                 printWSummaryFile();
301                 
302                 if (phylip) {   createPhylipFile();             }
303
304                 //clear out users groups
305                 globaldata->Groups.clear();
306                 
307                 
308                 if (m->control_pressed) { 
309                         for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  }
310                         return 0; 
311                 }
312                 
313                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run unifrac.weighted."); m->mothurOutEndLine();
314                 
315                 m->mothurOutEndLine();
316                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
317                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
318                 m->mothurOutEndLine();
319                 
320                 return 0;
321                 
322         }
323         catch(exception& e) {
324                 m->errorOut(e, "UnifracWeightedCommand", "execute");
325                 exit(1);
326         }
327 }
328 /**************************************************************************************************/
329
330 int UnifracWeightedCommand::createProcesses(Tree* t, vector< vector<string> > namesOfGroupCombos, vector< vector<double> >& scores) {
331         try {
332 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
333                 int process = 1;
334                 vector<int> processIDS;
335                 
336                 EstOutput results;
337                 
338                 //loop through and create all the processes you want
339                 while (process != processors) {
340                         int pid = fork();
341                         
342                         if (pid > 0) {
343                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
344                                 process++;
345                         }else if (pid == 0){
346                                 driver(t, namesOfGroupCombos, lines[process].start, lines[process].num, scores);
347                         
348                                 //pass numSeqs to parent
349                                 ofstream out;
350                                 string tempFile = outputDir + toString(getpid()) + ".weightedcommand.results.temp";
351                                 m->openOutputFile(tempFile, out);
352                                 for (int i = lines[process].start; i < (lines[process].start + lines[process].num); i++) { out << scores[i][(scores[i].size()-1)] << '\t';  } out << endl;
353                                 out.close();
354                                 
355                                 exit(0);
356                         }else { 
357                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
358                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
359                                 exit(0);
360                         }
361                 }
362                 
363                 driver(t, namesOfGroupCombos, lines[0].start, lines[0].num, scores);
364                 
365                 //force parent to wait until all the processes are done
366                 for (int i=0;i<(processors-1);i++) { 
367                         int temp = processIDS[i];
368                         wait(&temp);
369                 }
370                 
371                 //get data created by processes
372                 for (int i=0;i<(processors-1);i++) { 
373         
374                         ifstream in;
375                         string s = outputDir + toString(processIDS[i]) + ".weightedcommand.results.temp";
376                         m->openInputFile(s, in);
377                         
378                         double tempScore;
379                         for (int j = lines[(i+1)].start; j < (lines[(i+1)].start + lines[(i+1)].num); j++) { in >> tempScore; scores[j].push_back(tempScore); }
380                         in.close();
381                         remove(s.c_str());
382                 }
383                 
384                 return 0;
385 #endif          
386         }
387         catch(exception& e) {
388                 m->errorOut(e, "UnifracWeightedCommand", "createProcesses");
389                 exit(1);
390         }
391 }
392
393 /**************************************************************************************************/
394 int UnifracWeightedCommand::driver(Tree* t, vector< vector<string> > namesOfGroupCombos, int start, int num, vector< vector<double> >& scores) { 
395  try {
396                 Tree* randT = new Tree();
397
398                 for (int h = start; h < (start+num); h++) {
399         
400                         if (m->control_pressed) { return 0; }
401                 
402                         //initialize weighted score
403                         string groupA = namesOfGroupCombos[h][0]; 
404                         string groupB = namesOfGroupCombos[h][1];
405                         
406                         //copy T[i]'s info.
407                         randT->getCopy(t);
408                          
409                         //create a random tree with same topology as T[i], but different labels
410                         randT->assembleRandomUnifracTree(groupA, groupB);
411                         
412                         if (m->control_pressed) { delete randT;  return 0;  }
413
414                         //get wscore of random tree
415                         EstOutput randomData = weighted->getValues(randT, groupA, groupB);
416                 
417                         if (m->control_pressed) { delete randT;  return 0;  }
418                                                                                 
419                         //save scores
420                         scores[h].push_back(randomData[0]);
421                 }
422         
423                 delete randT;
424         
425                 return 0;
426
427         }
428         catch(exception& e) {
429                 m->errorOut(e, "UnifracWeightedCommand", "driver");
430                 exit(1);
431         }
432 }
433 /***********************************************************/
434 void UnifracWeightedCommand::printWeightedFile() {
435         try {
436                 vector<double> data;
437                 vector<string> tags;
438                 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
439                 
440                 for(int a = 0; a < numComp; a++) {
441                         output->initFile(groupComb[a], tags);
442                         //print each line
443                         for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
444                                 data.push_back(it->first);  data.push_back(rScoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]); 
445                                 output->output(data);
446                                 data.clear();
447                         } 
448                         output->resetFile();
449                 }
450         }
451         catch(exception& e) {
452                 m->errorOut(e, "UnifracWeightedCommand", "printWeightedFile");
453                 exit(1);
454         }
455 }
456
457
458 /***********************************************************/
459 void UnifracWeightedCommand::printWSummaryFile() {
460         try {
461                 //column headers
462                 outSum << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" <<  endl;
463                 m->mothurOut("Tree#\tGroups\tWScore\tWSig"); m->mothurOutEndLine(); 
464                 
465                 //format output
466                 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
467                 
468                 //print each line
469                 int count = 0;
470                 for (int i = 0; i < T.size(); i++) { 
471                         for (int j = 0; j < numComp; j++) {
472                                 if (random) {
473                                         if (WScoreSig[count] > (1/(float)iters)) {
474                                                 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl; 
475                                                 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl; 
476                                                 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t" +  toString(WScoreSig[count]) + "\n");   
477                                         }else{
478                                                 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl; 
479                                                 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl; 
480                                                 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t<" +  toString((1/float(iters))) + "\n");  
481                                         }
482                                 }else{
483                                         outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl; 
484                                         cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl; 
485                                         m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t0.00\n"); 
486                                 }
487                                 count++;
488                         }
489                 }
490                 outSum.close();
491         }
492         catch(exception& e) {
493                 m->errorOut(e, "UnifracWeightedCommand", "printWSummaryFile");
494                 exit(1);
495         }
496 }
497 /***********************************************************/
498 void UnifracWeightedCommand::createPhylipFile() {
499         try {
500                 int count = 0;
501                 //for each tree
502                 for (int i = 0; i < T.size(); i++) { 
503                 
504                         string phylipFileName;
505                         if ((outputForm == "lt") || (outputForm == "square")) {
506                                 phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted.phylip.dist";
507                                 outputNames.push_back(phylipFileName); outputTypes["phylip"].push_back(phylipFileName); 
508                         }else { //column
509                                 phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted.column.dist";
510                                 outputNames.push_back(phylipFileName); outputTypes["column"].push_back(phylipFileName); 
511                         }
512                         
513                         ofstream out;
514                         m->openOutputFile(phylipFileName, out);
515                         
516                         if ((outputForm == "lt") || (outputForm == "square")) {
517                                 //output numSeqs
518                                 out << globaldata->Groups.size() << endl;
519                         }
520
521                         //make matrix with scores in it
522                         vector< vector<float> > dists;  dists.resize(globaldata->Groups.size());
523                         for (int i = 0; i < globaldata->Groups.size(); i++) {
524                                 dists[i].resize(globaldata->Groups.size(), 0.0);
525                         }
526                         
527                         //flip it so you can print it
528                         for (int r=0; r<globaldata->Groups.size(); r++) { 
529                                 for (int l = 0; l < r; l++) {
530                                         dists[r][l] = utreeScores[count];
531                                         dists[l][r] = utreeScores[count];
532                                         count++;
533                                 }
534                         }
535
536                         //output to file
537                         for (int r=0; r<globaldata->Groups.size(); r++) { 
538                                 //output name
539                                 string name = globaldata->Groups[r];
540                                 if (name.length() < 10) { //pad with spaces to make compatible
541                                         while (name.length() < 10) {  name += " ";  }
542                                 }
543                                 
544                                 if (outputForm == "lt") {
545                                         out << name << '\t';
546                                         
547                                         //output distances
548                                         for (int l = 0; l < r; l++) {   out  << dists[r][l] << '\t';  }
549                                         out << endl;
550                                 }else if (outputForm == "square") {
551                                         out << name << '\t';
552                                         
553                                         //output distances
554                                         for (int l = 0; l < globaldata->Groups.size(); l++) {   out  << dists[r][l] << '\t';  }
555                                         out << endl;
556                                 }else{
557                                         //output distances
558                                         for (int l = 0; l < r; l++) {   
559                                                 string otherName = globaldata->Groups[l];
560                                                 if (otherName.length() < 10) { //pad with spaces to make compatible
561                                                         while (otherName.length() < 10) {  otherName += " ";  }
562                                                 }
563                                                 
564                                                 out  << name << '\t' << otherName << dists[r][l] << endl;  
565                                         }
566                                 }
567                         }
568                         out.close();
569                 }
570         }
571         catch(exception& e) {
572                 m->errorOut(e, "UnifracWeightedCommand", "createPhylipFile");
573                 exit(1);
574         }
575 }
576 /***********************************************************/
577 int UnifracWeightedCommand::findIndex(float score, int index) {
578         try{
579                 for (int i = 0; i < rScores[index].size(); i++) {
580                         if (rScores[index][i] >= score) {       return i;       }
581                 }
582                 return rScores[index].size();
583         }
584         catch(exception& e) {
585                 m->errorOut(e, "UnifracWeightedCommand", "findIndex");
586                 exit(1);
587         }
588 }
589
590 /***********************************************************/
591
592 void UnifracWeightedCommand::calculateFreqsCumuls() {
593         try {
594                 //clear out old tree values
595                 rScoreFreq.clear();
596                 rScoreFreq.resize(numComp);
597                 rCumul.clear();
598                 rCumul.resize(numComp);
599                 validScores.clear();
600         
601                 //calculate frequency
602                 for (int f = 0; f < numComp; f++) {
603                         for (int i = 0; i < rScores[f].size(); i++) { //looks like 0,0,1,1,1,2,4,7...  you want to make a map that say rScoreFreq[0] = 2, rScoreFreq[1] = 3...
604                                 validScores[rScores[f][i]] = rScores[f][i];
605                                 map<float,float>::iterator it = rScoreFreq[f].find(rScores[f][i]);
606                                 if (it != rScoreFreq[f].end()) {
607                                         rScoreFreq[f][rScores[f][i]]++;
608                                 }else{
609                                         rScoreFreq[f][rScores[f][i]] = 1;
610                                 }
611                         }
612                 }
613                 
614                 //calculate rcumul
615                 for(int a = 0; a < numComp; a++) {
616                         float rcumul = 1.0000;
617                         //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
618                         for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
619                                 //make rscoreFreq map and rCumul
620                                 map<float,float>::iterator it2 = rScoreFreq[a].find(it->first);
621                                 rCumul[a][it->first] = rcumul;
622                                 //get percentage of random trees with that info
623                                 if (it2 != rScoreFreq[a].end()) {  rScoreFreq[a][it->first] /= iters; rcumul-= it2->second;  }
624                                 else { rScoreFreq[a][it->first] = 0.0000; } //no random trees with that score
625                         }
626                 }
627
628         }
629         catch(exception& e) {
630                 m->errorOut(e, "UnifracWeightedCommand", "calculateFreqsCums");
631                 exit(1);
632         }
633 }
634
635 /***********************************************************/
636
637
638
639
640