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