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