2 * unifracweightedcommand.cpp
5 * Created by Sarah Westcott on 2/9/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
10 #include "unifracweightedcommand.h"
12 /***********************************************************/
13 UnifracWeightedCommand::UnifracWeightedCommand(string option) {
15 globaldata = GlobalData::getInstance();
19 //allow user to run help
20 if(option == "help") { help(); abort = true; }
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)));
27 OptionParser parser(option);
28 map<string,string> parameters=parser.getParameters();
30 ValidParameters validParameter;
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; }
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; }
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"){
43 outputDir += m->hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it
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 = ""; }
51 m->splitAtDash(groups, Groups);
52 globaldata->Groups = Groups;
55 itersString = validParameter.validFile(parameters, "iters", false); if (itersString == "not found") { itersString = "1000"; }
56 convert(itersString, iters);
58 string temp = validParameter.validFile(parameters, "distance", false); if (temp == "not found") { temp = "false"; }
59 phylip = m->isTrue(temp);
61 temp = validParameter.validFile(parameters, "random", false); if (temp == "not found") { temp = "F"; }
62 random = m->isTrue(temp);
64 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = "1"; }
65 convert(temp, processors);
67 if (!random) { iters = 0; } //turn off random calcs
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);
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);
82 weighted = new Weighted(tmap);
90 m->errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
94 //**********************************************************************************************************************
96 void UnifracWeightedCommand::help(){
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");
110 catch(exception& e) {
111 m->errorOut(e, "UnifracWeightedCommand", "help");
116 /***********************************************************/
117 int UnifracWeightedCommand::execute() {
120 if (abort == true) { return 0; }
122 int start = time(NULL);
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...
128 //create new tree with same num nodes and leaves as users
131 //get weighted scores for users trees
132 for (int i = 0; i < T.size(); i++) {
134 if (m->control_pressed) { delete randT; outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
137 rScores.resize(numComp); //data[0] = weightedscore AB, data[1] = weightedscore AC...
138 uScores.resize(numComp); //data[0] = weightedscore AB, data[1] = weightedscore AC...
141 output = new ColumnFile(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted", itersString);
142 outputNames.push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted");
145 userData = weighted->getValues(T[i], processors, outputDir); //userData[0] = weightedscore
147 if (m->control_pressed) {
149 if (random) { delete output; }
151 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
157 for (int s=0; s<numComp; s++) {
158 //add users score to vector of user scores
159 uScores[s].push_back(userData[s]);
161 //save users tree score for summary file
162 utreeScores.push_back(userData[s]);
166 vector<double> sums = weighted->getBranchLengthSums(T[i]);
168 //calculate number of comparisons i.e. with groups A,B,C = AB, AC, BC = 3;
169 vector< vector<string> > namesOfGroupCombos;
170 for (int a=0; a<numGroups; a++) {
171 for (int l = a+1; l < numGroups; l++) {
172 vector<string> groups; groups.push_back(globaldata->Groups[a]); groups.push_back(globaldata->Groups[l]);
173 namesOfGroupCombos.push_back(groups);
177 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
179 int numPairs = namesOfGroupCombos.size();
180 int numPairsPerProcessor = numPairs / processors;
182 for (int i = 0; i < processors; i++) {
183 int startPos = i * numPairsPerProcessor;
184 if(i == processors - 1){
185 numPairsPerProcessor = numPairs - i * numPairsPerProcessor;
187 lines.push_back(new linePair(startPos, numPairsPerProcessor));
193 //get scores for random trees
194 for (int j = 0; j < iters; j++) {
196 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
198 driver(T[i], randT, namesOfGroupCombos, 0, namesOfGroupCombos.size(), sums, rScores);
200 createProcesses(T[i], randT, namesOfGroupCombos, sums, rScores);
203 driver(T[i], randT, namesOfGroupCombos, 0, namesOfGroupCombos.size(), sums, rScores);
206 if (m->control_pressed) { delete output; outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
209 m->mothurOut("Iter: " + toString(j+1)); m->mothurOutEndLine();
212 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
214 //find the signifigance of the score for summary file
215 for (int f = 0; f < numComp; f++) {
217 sort(rScores[f].begin(), rScores[f].end());
219 //the index of the score higher than yours is returned
220 //so if you have 1000 random trees the index returned is 100
221 //then there are 900 trees with a score greater then you.
222 //giving you a signifigance of 0.900
223 int index = findIndex(userData[f], f); if (index == -1) { m->mothurOut("error in UnifracWeightedCommand"); m->mothurOutEndLine(); exit(1); } //error code
225 //the signifigance is the number of trees with the users score or higher
226 WScoreSig.push_back((iters-index)/(float)iters);
229 //out << "Tree# " << i << endl;
230 calculateFreqsCumuls();
244 if (m->control_pressed) { delete randT; outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
248 if (phylip) { createPhylipFile(); }
250 //clear out users groups
251 globaldata->Groups.clear();
255 if (m->control_pressed) {
256 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
260 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run unifrac.weighted."); m->mothurOutEndLine();
262 m->mothurOutEndLine();
263 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
264 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
265 m->mothurOutEndLine();
270 catch(exception& e) {
271 m->errorOut(e, "UnifracWeightedCommand", "execute");
275 /**************************************************************************************************/
277 int UnifracWeightedCommand::createProcesses(Tree* t, Tree* randT, vector< vector<string> > namesOfGroupCombos, vector<double>& sums, vector< vector<double> >& scores) {
279 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
282 vector<int> processIDS;
286 //loop through and create all the processes you want
287 while (process != processors) {
291 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
294 driver(t, randT, namesOfGroupCombos, lines[process]->start, lines[process]->num, sums, scores);
296 //pass numSeqs to parent
298 string tempFile = outputDir + toString(getpid()) + ".weightedcommand.results.temp";
299 m->openOutputFile(tempFile, out);
300 for (int i = lines[process]->start; i < (lines[process]->start + lines[process]->num); i++) { out << scores[i][(scores[i].size()-1)] << '\t'; } out << endl;
304 }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
307 driver(t, randT, namesOfGroupCombos, lines[0]->start, lines[0]->num, sums, scores);
309 //force parent to wait until all the processes are done
310 for (int i=0;i<(processors-1);i++) {
311 int temp = processIDS[i];
315 //get data created by processes
316 for (int i=0;i<(processors-1);i++) {
318 string s = outputDir + toString(processIDS[i]) + ".weightedcommand.results.temp";
319 m->openInputFile(s, in);
322 for (int i = lines[process]->start; i < (lines[process]->start + lines[process]->num); i++) { in >> tempScore; scores[i].push_back(tempScore); }
330 catch(exception& e) {
331 m->errorOut(e, "UnifracWeightedCommand", "createProcesses");
336 /**************************************************************************************************/
337 int UnifracWeightedCommand::driver(Tree* t, Tree* randT, vector< vector<string> > namesOfGroupCombos, int start, int num, vector<double>& sums, vector< vector<double> >& scores) {
340 for (int h = start; h < (start+num); h++) {
341 cout << "doing " << h << endl;
342 if (m->control_pressed) { return 0; }
344 //initialize weighted score
345 string groupA = namesOfGroupCombos[h][0];
346 string groupB = namesOfGroupCombos[h][1];
351 //create a random tree with same topology as T[i], but different labels
352 randT->assembleRandomUnifracTree(groupA, groupB);
354 if (m->control_pressed) { delete randT; return 0; }
357 //get wscore of random tree
358 EstOutput randomData = weighted->getValues(randT, groupA, groupB, sums);
360 if (m->control_pressed) { delete randT; return 0; }
363 scores[h].push_back(randomData[0]);
369 catch(exception& e) {
370 m->errorOut(e, "UnifracWeightedCommand", "driver");
374 /***********************************************************/
375 void UnifracWeightedCommand::printWeightedFile() {
379 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
381 for(int a = 0; a < numComp; a++) {
382 output->initFile(groupComb[a], tags);
384 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
385 data.push_back(it->first); data.push_back(rScoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);
386 output->output(data);
392 catch(exception& e) {
393 m->errorOut(e, "UnifracWeightedCommand", "printWeightedFile");
399 /***********************************************************/
400 void UnifracWeightedCommand::printWSummaryFile() {
403 outSum << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" << endl;
404 m->mothurOut("Tree#\tGroups\tWScore\tWSig"); m->mothurOutEndLine();
407 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
411 for (int i = 0; i < T.size(); i++) {
412 for (int j = 0; j < numComp; j++) {
414 if (WScoreSig[count] > (1/(float)iters)) {
415 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl;
416 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl;
417 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t" + toString(WScoreSig[count])); m->mothurOutEndLine();
419 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
420 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
421 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t<" + toString((1/float(iters)))); m->mothurOutEndLine();
424 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl;
425 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl;
426 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t0.00"); m->mothurOutEndLine();
433 catch(exception& e) {
434 m->errorOut(e, "UnifracWeightedCommand", "printWSummaryFile");
438 /***********************************************************/
439 void UnifracWeightedCommand::createPhylipFile() {
443 for (int i = 0; i < T.size(); i++) {
445 string phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted.dist";
446 outputNames.push_back(phylipFileName);
448 m->openOutputFile(phylipFileName, out);
451 out << globaldata->Groups.size() << endl;
453 //make matrix with scores in it
454 vector< vector<float> > dists; dists.resize(globaldata->Groups.size());
455 for (int i = 0; i < globaldata->Groups.size(); i++) {
456 dists[i].resize(globaldata->Groups.size(), 0.0);
459 //flip it so you can print it
460 for (int r=0; r<globaldata->Groups.size(); r++) {
461 for (int l = r+1; l < globaldata->Groups.size(); l++) {
462 dists[r][l] = utreeScores[count];
463 dists[l][r] = utreeScores[count];
469 for (int r=0; r<globaldata->Groups.size(); r++) {
471 string name = globaldata->Groups[r];
472 if (name.length() < 10) { //pad with spaces to make compatible
473 while (name.length() < 10) { name += " "; }
478 for (int l = 0; l < r; l++) { out << dists[r][l] << '\t'; }
484 catch(exception& e) {
485 m->errorOut(e, "UnifracWeightedCommand", "createPhylipFile");
489 /***********************************************************/
490 int UnifracWeightedCommand::findIndex(float score, int index) {
492 for (int i = 0; i < rScores[index].size(); i++) {
493 if (rScores[index][i] >= score) { return i; }
495 return rScores[index].size();
497 catch(exception& e) {
498 m->errorOut(e, "UnifracWeightedCommand", "findIndex");
503 /***********************************************************/
505 void UnifracWeightedCommand::calculateFreqsCumuls() {
507 //clear out old tree values
509 rScoreFreq.resize(numComp);
511 rCumul.resize(numComp);
514 //calculate frequency
515 for (int f = 0; f < numComp; f++) {
516 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...
517 validScores[rScores[f][i]] = rScores[f][i];
518 map<float,float>::iterator it = rScoreFreq[f].find(rScores[f][i]);
519 if (it != rScoreFreq[f].end()) {
520 rScoreFreq[f][rScores[f][i]]++;
522 rScoreFreq[f][rScores[f][i]] = 1;
528 for(int a = 0; a < numComp; a++) {
529 float rcumul = 1.0000;
530 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
531 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
532 //make rscoreFreq map and rCumul
533 map<float,float>::iterator it2 = rScoreFreq[a].find(it->first);
534 rCumul[a][it->first] = rcumul;
535 //get percentage of random trees with that info
536 if (it2 != rScoreFreq[a].end()) { rScoreFreq[a][it->first] /= iters; rcumul-= it2->second; }
537 else { rScoreFreq[a][it->first] = 0.0000; } //no random trees with that score
542 catch(exception& e) {
543 m->errorOut(e, "UnifracWeightedCommand", "calculateFreqsCums");
548 /***********************************************************/