]> git.donarmstrong.com Git - mothur.git/blob - unifracweightedcommand.cpp
fixed unifrac bug with multiple processors if numComps was less than processors....
[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                 if (numComp < processors) { processors = numComp; }
192                                 
193                 //get weighted scores for users trees
194                 for (int i = 0; i < T.size(); i++) {
195                         
196                         if (m->control_pressed) { outSum.close(); for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());  } return 0; }
197
198                         counter = 0;
199                         rScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
200                         uScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
201                         
202                         if (random) {  
203                                 output = new ColumnFile(outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted", itersString);  
204                                 outputNames.push_back(outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted");
205                                 outputTypes["weighted"].push_back(outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted");
206                         } 
207
208                         userData = weighted->getValues(T[i], processors, outputDir);  //userData[0] = weightedscore
209                         
210                         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; }
211                         
212                         //save users score
213                         for (int s=0; s<numComp; s++) {
214                                 //add users score to vector of user scores
215                                 uScores[s].push_back(userData[s]);
216                                 
217                                 //save users tree score for summary file
218                                 utreeScores.push_back(userData[s]);
219                         }
220                         
221                         if (random) { 
222                         
223                                 //calculate number of comparisons i.e. with groups A,B,C = AB, AC, BC = 3;
224                                 vector< vector<string> > namesOfGroupCombos;
225                                 for (int a=0; a<numGroups; a++) { 
226                                         for (int l = 0; l < a; l++) {   
227                                                 vector<string> groups; groups.push_back(globaldata->Groups[a]); groups.push_back(globaldata->Groups[l]);
228                                                 namesOfGroupCombos.push_back(groups);
229                                         }
230                                 }
231                                 
232                                 lines.clear();
233                                 
234                                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
235                                         if(processors != 1){
236                                                 int numPairs = namesOfGroupCombos.size();
237                                                 int numPairsPerProcessor = numPairs / processors;
238                                         
239                                                 for (int i = 0; i < processors; i++) {
240                                                         int startPos = i * numPairsPerProcessor;
241                                                         if(i == processors - 1){
242                                                                 numPairsPerProcessor = numPairs - i * numPairsPerProcessor;
243                                                         }
244                                                         lines.push_back(linePair(startPos, numPairsPerProcessor));
245                                                 }
246                                         }
247                                 #endif
248
249                                 
250                                 //get scores for random trees
251                                 for (int j = 0; j < iters; j++) {
252                                 
253                                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
254                                                 if(processors == 1){
255                                                         driver(T[i],  namesOfGroupCombos, 0, namesOfGroupCombos.size(),  rScores);
256                                                 }else{
257                                                         createProcesses(T[i],  namesOfGroupCombos, rScores);
258                                                 }
259                                         #else
260                                                 driver(T[i], namesOfGroupCombos, 0, namesOfGroupCombos.size(), rScores);
261                                         #endif
262                                         
263                                         if (m->control_pressed) { delete output; outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str());  } return 0; }
264                                         
265                                         //report progress
266 //                                      m->mothurOut("Iter: " + toString(j+1)); m->mothurOutEndLine();          
267                                 }
268                                 lines.clear();
269                         
270                                 //find the signifigance of the score for summary file
271                                 for (int f = 0; f < numComp; f++) {
272                                         //sort random scores
273                                         sort(rScores[f].begin(), rScores[f].end());
274                                         
275                                         //the index of the score higher than yours is returned 
276                                         //so if you have 1000 random trees the index returned is 100 
277                                         //then there are 900 trees with a score greater then you. 
278                                         //giving you a signifigance of 0.900
279                                         int index = findIndex(userData[f], f);    if (index == -1) { m->mothurOut("error in UnifracWeightedCommand"); m->mothurOutEndLine(); exit(1); } //error code
280                                         
281                                         //the signifigance is the number of trees with the users score or higher 
282                                         WScoreSig.push_back((iters-index)/(float)iters);
283                                 }
284                                 
285                                 //out << "Tree# " << i << endl;
286                                 calculateFreqsCumuls();
287                                 printWeightedFile();
288                                 
289                                 delete output;
290                         
291                         }
292                         
293                         //clear data
294                         rScores.clear();
295                         uScores.clear();
296                         validScores.clear();
297                 }
298                 
299                 
300                 if (m->control_pressed) { outSum.close(); for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());  } return 0;  }
301                 
302                 printWSummaryFile();
303                 
304                 if (phylip) {   createPhylipFile();             }
305
306                 //clear out users groups
307                 globaldata->Groups.clear();
308                 
309                 
310                 if (m->control_pressed) { 
311                         for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  }
312                         return 0; 
313                 }
314                 
315                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run unifrac.weighted."); m->mothurOutEndLine();
316                 
317                 m->mothurOutEndLine();
318                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
319                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
320                 m->mothurOutEndLine();
321                 
322                 return 0;
323                 
324         }
325         catch(exception& e) {
326                 m->errorOut(e, "UnifracWeightedCommand", "execute");
327                 exit(1);
328         }
329 }
330 /**************************************************************************************************/
331
332 int UnifracWeightedCommand::createProcesses(Tree* t, vector< vector<string> > namesOfGroupCombos, vector< vector<double> >& scores) {
333         try {
334 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
335                 int process = 1;
336                 vector<int> processIDS;
337                 
338                 EstOutput results;
339                 
340                 //loop through and create all the processes you want
341                 while (process != processors) {
342                         int pid = fork();
343                         
344                         if (pid > 0) {
345                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
346                                 process++;
347                         }else if (pid == 0){
348                                 driver(t, namesOfGroupCombos, lines[process].start, lines[process].num, scores);
349                         
350                                 //pass numSeqs to parent
351                                 ofstream out;
352                                 string tempFile = outputDir + toString(getpid()) + ".weightedcommand.results.temp";
353                                 m->openOutputFile(tempFile, out);
354                                 for (int i = lines[process].start; i < (lines[process].start + lines[process].num); i++) { out << scores[i][(scores[i].size()-1)] << '\t';  } out << endl;
355                                 out.close();
356                                 
357                                 exit(0);
358                         }else { 
359                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
360                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
361                                 exit(0);
362                         }
363                 }
364                 
365                 driver(t, namesOfGroupCombos, lines[0].start, lines[0].num, scores);
366                 
367                 //force parent to wait until all the processes are done
368                 for (int i=0;i<(processors-1);i++) { 
369                         int temp = processIDS[i];
370                         wait(&temp);
371                 }
372                 
373                 //get data created by processes
374                 for (int i=0;i<(processors-1);i++) { 
375         
376                         ifstream in;
377                         string s = outputDir + toString(processIDS[i]) + ".weightedcommand.results.temp";
378                         m->openInputFile(s, in);
379                         
380                         double tempScore;
381                         for (int j = lines[(i+1)].start; j < (lines[(i+1)].start + lines[(i+1)].num); j++) { in >> tempScore; scores[j].push_back(tempScore); }
382                         in.close();
383                         remove(s.c_str());
384                 }
385                 
386                 return 0;
387 #endif          
388         }
389         catch(exception& e) {
390                 m->errorOut(e, "UnifracWeightedCommand", "createProcesses");
391                 exit(1);
392         }
393 }
394
395 /**************************************************************************************************/
396 int UnifracWeightedCommand::driver(Tree* t, vector< vector<string> > namesOfGroupCombos, int start, int num, vector< vector<double> >& scores) { 
397  try {
398                 Tree* randT = new Tree();
399
400                 for (int h = start; h < (start+num); h++) {
401         
402                         if (m->control_pressed) { return 0; }
403                 
404                         //initialize weighted score
405                         string groupA = namesOfGroupCombos[h][0]; 
406                         string groupB = namesOfGroupCombos[h][1];
407                         
408                         //copy T[i]'s info.
409                         randT->getCopy(t);
410                          
411                         //create a random tree with same topology as T[i], but different labels
412                         randT->assembleRandomUnifracTree(groupA, groupB);
413                         
414                         if (m->control_pressed) { delete randT;  return 0;  }
415
416                         //get wscore of random tree
417                         EstOutput randomData = weighted->getValues(randT, groupA, groupB);
418                 
419                         if (m->control_pressed) { delete randT;  return 0;  }
420                                                                                 
421                         //save scores
422                         scores[h].push_back(randomData[0]);
423                 }
424         
425                 delete randT;
426         
427                 return 0;
428
429         }
430         catch(exception& e) {
431                 m->errorOut(e, "UnifracWeightedCommand", "driver");
432                 exit(1);
433         }
434 }
435 /***********************************************************/
436 void UnifracWeightedCommand::printWeightedFile() {
437         try {
438                 vector<double> data;
439                 vector<string> tags;
440                 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
441                 
442                 for(int a = 0; a < numComp; a++) {
443                         output->initFile(groupComb[a], tags);
444                         //print each line
445                         for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
446                                 data.push_back(it->first);  data.push_back(rScoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]); 
447                                 output->output(data);
448                                 data.clear();
449                         } 
450                         output->resetFile();
451                 }
452         }
453         catch(exception& e) {
454                 m->errorOut(e, "UnifracWeightedCommand", "printWeightedFile");
455                 exit(1);
456         }
457 }
458
459
460 /***********************************************************/
461 void UnifracWeightedCommand::printWSummaryFile() {
462         try {
463                 //column headers
464                 outSum << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" <<  endl;
465                 m->mothurOut("Tree#\tGroups\tWScore\tWSig"); m->mothurOutEndLine(); 
466                 
467                 //format output
468                 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
469                 
470                 //print each line
471                 int count = 0;
472                 for (int i = 0; i < T.size(); i++) { 
473                         for (int j = 0; j < numComp; j++) {
474                                 if (random) {
475                                         if (WScoreSig[count] > (1/(float)iters)) {
476                                                 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl; 
477                                                 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl; 
478                                                 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t" +  toString(WScoreSig[count]) + "\n");   
479                                         }else{
480                                                 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl; 
481                                                 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl; 
482                                                 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t<" +  toString((1/float(iters))) + "\n");  
483                                         }
484                                 }else{
485                                         outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl; 
486                                         cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl; 
487                                         m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t0.00\n"); 
488                                 }
489                                 count++;
490                         }
491                 }
492                 outSum.close();
493         }
494         catch(exception& e) {
495                 m->errorOut(e, "UnifracWeightedCommand", "printWSummaryFile");
496                 exit(1);
497         }
498 }
499 /***********************************************************/
500 void UnifracWeightedCommand::createPhylipFile() {
501         try {
502                 int count = 0;
503                 //for each tree
504                 for (int i = 0; i < T.size(); i++) { 
505                 
506                         string phylipFileName;
507                         if ((outputForm == "lt") || (outputForm == "square")) {
508                                 phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted.phylip.dist";
509                                 outputNames.push_back(phylipFileName); outputTypes["phylip"].push_back(phylipFileName); 
510                         }else { //column
511                                 phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted.column.dist";
512                                 outputNames.push_back(phylipFileName); outputTypes["column"].push_back(phylipFileName); 
513                         }
514                         
515                         ofstream out;
516                         m->openOutputFile(phylipFileName, out);
517                         
518                         if ((outputForm == "lt") || (outputForm == "square")) {
519                                 //output numSeqs
520                                 out << globaldata->Groups.size() << endl;
521                         }
522
523                         //make matrix with scores in it
524                         vector< vector<float> > dists;  dists.resize(globaldata->Groups.size());
525                         for (int i = 0; i < globaldata->Groups.size(); i++) {
526                                 dists[i].resize(globaldata->Groups.size(), 0.0);
527                         }
528                         
529                         //flip it so you can print it
530                         for (int r=0; r<globaldata->Groups.size(); r++) { 
531                                 for (int l = 0; l < r; l++) {
532                                         dists[r][l] = utreeScores[count];
533                                         dists[l][r] = utreeScores[count];
534                                         count++;
535                                 }
536                         }
537
538                         //output to file
539                         for (int r=0; r<globaldata->Groups.size(); r++) { 
540                                 //output name
541                                 string name = globaldata->Groups[r];
542                                 if (name.length() < 10) { //pad with spaces to make compatible
543                                         while (name.length() < 10) {  name += " ";  }
544                                 }
545                                 
546                                 if (outputForm == "lt") {
547                                         out << name << '\t';
548                                         
549                                         //output distances
550                                         for (int l = 0; l < r; l++) {   out  << dists[r][l] << '\t';  }
551                                         out << endl;
552                                 }else if (outputForm == "square") {
553                                         out << name << '\t';
554                                         
555                                         //output distances
556                                         for (int l = 0; l < globaldata->Groups.size(); l++) {   out  << dists[r][l] << '\t';  }
557                                         out << endl;
558                                 }else{
559                                         //output distances
560                                         for (int l = 0; l < r; l++) {   
561                                                 string otherName = globaldata->Groups[l];
562                                                 if (otherName.length() < 10) { //pad with spaces to make compatible
563                                                         while (otherName.length() < 10) {  otherName += " ";  }
564                                                 }
565                                                 
566                                                 out  << name << '\t' << otherName << dists[r][l] << endl;  
567                                         }
568                                 }
569                         }
570                         out.close();
571                 }
572         }
573         catch(exception& e) {
574                 m->errorOut(e, "UnifracWeightedCommand", "createPhylipFile");
575                 exit(1);
576         }
577 }
578 /***********************************************************/
579 int UnifracWeightedCommand::findIndex(float score, int index) {
580         try{
581                 for (int i = 0; i < rScores[index].size(); i++) {
582                         if (rScores[index][i] >= score) {       return i;       }
583                 }
584                 return rScores[index].size();
585         }
586         catch(exception& e) {
587                 m->errorOut(e, "UnifracWeightedCommand", "findIndex");
588                 exit(1);
589         }
590 }
591
592 /***********************************************************/
593
594 void UnifracWeightedCommand::calculateFreqsCumuls() {
595         try {
596                 //clear out old tree values
597                 rScoreFreq.clear();
598                 rScoreFreq.resize(numComp);
599                 rCumul.clear();
600                 rCumul.resize(numComp);
601                 validScores.clear();
602         
603                 //calculate frequency
604                 for (int f = 0; f < numComp; f++) {
605                         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...
606                                 validScores[rScores[f][i]] = rScores[f][i];
607                                 map<float,float>::iterator it = rScoreFreq[f].find(rScores[f][i]);
608                                 if (it != rScoreFreq[f].end()) {
609                                         rScoreFreq[f][rScores[f][i]]++;
610                                 }else{
611                                         rScoreFreq[f][rScores[f][i]] = 1;
612                                 }
613                         }
614                 }
615                 
616                 //calculate rcumul
617                 for(int a = 0; a < numComp; a++) {
618                         float rcumul = 1.0000;
619                         //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
620                         for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
621                                 //make rscoreFreq map and rCumul
622                                 map<float,float>::iterator it2 = rScoreFreq[a].find(it->first);
623                                 rCumul[a][it->first] = rcumul;
624                                 //get percentage of random trees with that info
625                                 if (it2 != rScoreFreq[a].end()) {  rScoreFreq[a][it->first] /= iters; rcumul-= it2->second;  }
626                                 else { rScoreFreq[a][it->first] = 0.0000; } //no random trees with that score
627                         }
628                 }
629
630         }
631         catch(exception& e) {
632                 m->errorOut(e, "UnifracWeightedCommand", "calculateFreqsCums");
633                 exit(1);
634         }
635 }
636
637 /***********************************************************/
638
639
640
641
642