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