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 vector<string> UnifracWeightedCommand::getValidParameters(){
15 string Array[] = {"groups","iters","distance","random","processors","outputdir","inputdir"};
16 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
20 m->errorOut(e, "UnifracWeightedCommand", "getValidParameters");
24 //**********************************************************************************************************************
25 UnifracWeightedCommand::UnifracWeightedCommand(){
28 //initialize outputTypes
29 vector<string> tempOutNames;
30 outputTypes["weighted"] = tempOutNames;
31 outputTypes["wsummary"] = tempOutNames;
32 outputTypes["phylip"] = tempOutNames;
35 m->errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
39 //**********************************************************************************************************************
40 vector<string> UnifracWeightedCommand::getRequiredParameters(){
42 vector<string> myArray;
46 m->errorOut(e, "UnifracWeightedCommand", "getRequiredParameters");
50 //**********************************************************************************************************************
51 vector<string> UnifracWeightedCommand::getRequiredFiles(){
53 string Array[] = {"tree","group"};
54 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
59 m->errorOut(e, "UnifracWeightedCommand", "getRequiredFiles");
63 /***********************************************************/
64 UnifracWeightedCommand::UnifracWeightedCommand(string option) {
66 globaldata = GlobalData::getInstance();
70 //allow user to run help
71 if(option == "help") { help(); abort = true; }
74 //valid paramters for this command
75 string Array[] = {"groups","iters","distance","random","processors","outputdir","inputdir"};
76 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
78 OptionParser parser(option);
79 map<string,string> parameters=parser.getParameters();
81 ValidParameters validParameter;
83 //check to make sure all parameters are valid for command
84 for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) {
85 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
88 //initialize outputTypes
89 vector<string> tempOutNames;
90 outputTypes["weighted"] = tempOutNames;
91 outputTypes["wsummary"] = tempOutNames;
92 outputTypes["phylip"] = tempOutNames;
94 if (globaldata->gTree.size() == 0) {//no trees were read
95 m->mothurOut("You must execute the read.tree command, before you may execute the unifrac.weighted command."); m->mothurOutEndLine(); abort = true; }
97 //if the user changes the output directory command factory will send this info to us in the output parameter
98 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
100 outputDir += m->hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it
103 //check for optional parameter and set defaults
104 // ...at some point should added some additional type checking...
105 groups = validParameter.validFile(parameters, "groups", false);
106 if (groups == "not found") { groups = ""; }
108 m->splitAtDash(groups, Groups);
109 globaldata->Groups = Groups;
112 itersString = validParameter.validFile(parameters, "iters", false); if (itersString == "not found") { itersString = "1000"; }
113 convert(itersString, iters);
115 string temp = validParameter.validFile(parameters, "distance", false); if (temp == "not found") { temp = "false"; }
116 phylip = m->isTrue(temp);
118 temp = validParameter.validFile(parameters, "random", false); if (temp == "not found") { temp = "F"; }
119 random = m->isTrue(temp);
121 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = "1"; }
122 convert(temp, processors);
124 if (!random) { iters = 0; } //turn off random calcs
127 if (abort == false) {
128 T = globaldata->gTree;
129 tmap = globaldata->gTreemap;
130 sumFile = outputDir + m->getSimpleName(globaldata->getTreeFile()) + ".wsummary";
131 m->openOutputFile(sumFile, outSum);
132 outputNames.push_back(sumFile); outputTypes["wsummary"].push_back(sumFile);
134 util = new SharedUtil();
135 string s; //to make work with setgroups
136 util->setGroups(globaldata->Groups, tmap->namesOfGroups, s, numGroups, "weighted"); //sets the groups the user wants to analyze
137 util->getCombos(groupComb, globaldata->Groups, numComp);
139 weighted = new Weighted(tmap);
146 catch(exception& e) {
147 m->errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
151 //**********************************************************************************************************************
153 void UnifracWeightedCommand::help(){
155 m->mothurOut("The unifrac.weighted command can only be executed after a successful read.tree command.\n");
156 m->mothurOut("The unifrac.weighted command parameters are groups, iters, distance, processors and random. No parameters are required.\n");
157 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");
158 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");
159 m->mothurOut("The distance parameter allows you to create a distance file from the results. The default is false.\n");
160 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");
161 m->mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
162 m->mothurOut("The unifrac.weighted command should be in the following format: unifrac.weighted(groups=yourGroups, iters=yourIters).\n");
163 m->mothurOut("Example unifrac.weighted(groups=A-B-C, iters=500).\n");
164 m->mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
165 m->mothurOut("The unifrac.weighted command output two files: .weighted and .wsummary their descriptions are in the manual.\n");
166 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
168 catch(exception& e) {
169 m->errorOut(e, "UnifracWeightedCommand", "help");
174 /***********************************************************/
175 int UnifracWeightedCommand::execute() {
178 if (abort == true) { return 0; }
180 int start = time(NULL);
182 //get weighted for users tree
183 userData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
184 randomData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
186 //get weighted scores for users trees
187 for (int i = 0; i < T.size(); i++) {
189 if (m->control_pressed) { outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
192 rScores.resize(numComp); //data[0] = weightedscore AB, data[1] = weightedscore AC...
193 uScores.resize(numComp); //data[0] = weightedscore AB, data[1] = weightedscore AC...
196 output = new ColumnFile(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted", itersString);
197 outputNames.push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted");
198 outputTypes["weighted"].push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted");
201 userData = weighted->getValues(T[i], processors, outputDir); //userData[0] = weightedscore
203 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; }
206 for (int s=0; s<numComp; s++) {
207 //add users score to vector of user scores
208 uScores[s].push_back(userData[s]);
210 //save users tree score for summary file
211 utreeScores.push_back(userData[s]);
216 //calculate number of comparisons i.e. with groups A,B,C = AB, AC, BC = 3;
217 vector< vector<string> > namesOfGroupCombos;
218 for (int a=0; a<numGroups; a++) {
219 for (int l = 0; l < a; l++) {
220 vector<string> groups; groups.push_back(globaldata->Groups[a]); groups.push_back(globaldata->Groups[l]);
221 namesOfGroupCombos.push_back(groups);
227 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
229 int numPairs = namesOfGroupCombos.size();
230 int numPairsPerProcessor = numPairs / processors;
232 for (int i = 0; i < processors; i++) {
233 int startPos = i * numPairsPerProcessor;
234 if(i == processors - 1){
235 numPairsPerProcessor = numPairs - i * numPairsPerProcessor;
237 lines.push_back(linePair(startPos, numPairsPerProcessor));
243 //get scores for random trees
244 for (int j = 0; j < iters; j++) {
246 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
248 driver(T[i], namesOfGroupCombos, 0, namesOfGroupCombos.size(), rScores);
250 createProcesses(T[i], namesOfGroupCombos, rScores);
253 driver(T[i], namesOfGroupCombos, 0, namesOfGroupCombos.size(), rScores);
256 if (m->control_pressed) { delete output; outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
259 m->mothurOut("Iter: " + toString(j+1)); m->mothurOutEndLine();
263 //find the signifigance of the score for summary file
264 for (int f = 0; f < numComp; f++) {
266 sort(rScores[f].begin(), rScores[f].end());
268 //the index of the score higher than yours is returned
269 //so if you have 1000 random trees the index returned is 100
270 //then there are 900 trees with a score greater then you.
271 //giving you a signifigance of 0.900
272 int index = findIndex(userData[f], f); if (index == -1) { m->mothurOut("error in UnifracWeightedCommand"); m->mothurOutEndLine(); exit(1); } //error code
274 //the signifigance is the number of trees with the users score or higher
275 WScoreSig.push_back((iters-index)/(float)iters);
278 //out << "Tree# " << i << endl;
279 calculateFreqsCumuls();
293 if (m->control_pressed) { outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
297 if (phylip) { createPhylipFile(); }
299 //clear out users groups
300 globaldata->Groups.clear();
303 if (m->control_pressed) {
304 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
308 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run unifrac.weighted."); m->mothurOutEndLine();
310 m->mothurOutEndLine();
311 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
312 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
313 m->mothurOutEndLine();
318 catch(exception& e) {
319 m->errorOut(e, "UnifracWeightedCommand", "execute");
323 /**************************************************************************************************/
325 int UnifracWeightedCommand::createProcesses(Tree* t, vector< vector<string> > namesOfGroupCombos, vector< vector<double> >& scores) {
327 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
330 vector<int> processIDS;
334 //loop through and create all the processes you want
335 while (process != processors) {
339 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
342 driver(t, namesOfGroupCombos, lines[process].start, lines[process].num, scores);
344 //pass numSeqs to parent
346 string tempFile = outputDir + toString(getpid()) + ".weightedcommand.results.temp";
347 m->openOutputFile(tempFile, out);
348 for (int i = lines[process].start; i < (lines[process].start + lines[process].num); i++) { out << scores[i][(scores[i].size()-1)] << '\t'; } out << endl;
353 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
354 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
359 driver(t, namesOfGroupCombos, lines[0].start, lines[0].num, scores);
361 //force parent to wait until all the processes are done
362 for (int i=0;i<(processors-1);i++) {
363 int temp = processIDS[i];
367 //get data created by processes
368 for (int i=0;i<(processors-1);i++) {
371 string s = outputDir + toString(processIDS[i]) + ".weightedcommand.results.temp";
372 m->openInputFile(s, in);
375 for (int j = lines[(i+1)].start; j < (lines[(i+1)].start + lines[(i+1)].num); j++) { in >> tempScore; scores[j].push_back(tempScore); }
383 catch(exception& e) {
384 m->errorOut(e, "UnifracWeightedCommand", "createProcesses");
389 /**************************************************************************************************/
390 int UnifracWeightedCommand::driver(Tree* t, vector< vector<string> > namesOfGroupCombos, int start, int num, vector< vector<double> >& scores) {
392 Tree* randT = new Tree();
394 for (int h = start; h < (start+num); h++) {
396 if (m->control_pressed) { return 0; }
398 //initialize weighted score
399 string groupA = namesOfGroupCombos[h][0];
400 string groupB = namesOfGroupCombos[h][1];
405 //create a random tree with same topology as T[i], but different labels
406 randT->assembleRandomUnifracTree(groupA, groupB);
408 if (m->control_pressed) { delete randT; return 0; }
410 //get wscore of random tree
411 EstOutput randomData = weighted->getValues(randT, groupA, groupB);
413 if (m->control_pressed) { delete randT; return 0; }
416 scores[h].push_back(randomData[0]);
424 catch(exception& e) {
425 m->errorOut(e, "UnifracWeightedCommand", "driver");
429 /***********************************************************/
430 void UnifracWeightedCommand::printWeightedFile() {
434 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
436 for(int a = 0; a < numComp; a++) {
437 output->initFile(groupComb[a], tags);
439 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
440 data.push_back(it->first); data.push_back(rScoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);
441 output->output(data);
447 catch(exception& e) {
448 m->errorOut(e, "UnifracWeightedCommand", "printWeightedFile");
454 /***********************************************************/
455 void UnifracWeightedCommand::printWSummaryFile() {
458 outSum << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" << endl;
459 m->mothurOut("Tree#\tGroups\tWScore\tWSig"); m->mothurOutEndLine();
462 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
466 for (int i = 0; i < T.size(); i++) {
467 for (int j = 0; j < numComp; j++) {
469 if (WScoreSig[count] > (1/(float)iters)) {
470 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl;
471 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl;
472 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t" + toString(WScoreSig[count]) + "\n");
474 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
475 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
476 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t<" + toString((1/float(iters))) + "\n");
479 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl;
480 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl;
481 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t0.00\n");
488 catch(exception& e) {
489 m->errorOut(e, "UnifracWeightedCommand", "printWSummaryFile");
493 /***********************************************************/
494 void UnifracWeightedCommand::createPhylipFile() {
498 for (int i = 0; i < T.size(); i++) {
500 string phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted.dist";
501 outputNames.push_back(phylipFileName);
502 outputTypes["phylip"].push_back(phylipFileName);
504 m->openOutputFile(phylipFileName, out);
507 out << globaldata->Groups.size() << endl;
509 //make matrix with scores in it
510 vector< vector<float> > dists; dists.resize(globaldata->Groups.size());
511 for (int i = 0; i < globaldata->Groups.size(); i++) {
512 dists[i].resize(globaldata->Groups.size(), 0.0);
515 //flip it so you can print it
516 for (int r=0; r<globaldata->Groups.size(); r++) {
517 for (int l = r+1; l < globaldata->Groups.size(); l++) {
518 dists[r][l] = utreeScores[count];
519 dists[l][r] = utreeScores[count];
525 for (int r=0; r<globaldata->Groups.size(); r++) {
527 string name = globaldata->Groups[r];
528 if (name.length() < 10) { //pad with spaces to make compatible
529 while (name.length() < 10) { name += " "; }
534 for (int l = 0; l < r; l++) { out << dists[r][l] << '\t'; }
540 catch(exception& e) {
541 m->errorOut(e, "UnifracWeightedCommand", "createPhylipFile");
545 /***********************************************************/
546 int UnifracWeightedCommand::findIndex(float score, int index) {
548 for (int i = 0; i < rScores[index].size(); i++) {
549 if (rScores[index][i] >= score) { return i; }
551 return rScores[index].size();
553 catch(exception& e) {
554 m->errorOut(e, "UnifracWeightedCommand", "findIndex");
559 /***********************************************************/
561 void UnifracWeightedCommand::calculateFreqsCumuls() {
563 //clear out old tree values
565 rScoreFreq.resize(numComp);
567 rCumul.resize(numComp);
570 //calculate frequency
571 for (int f = 0; f < numComp; f++) {
572 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...
573 validScores[rScores[f][i]] = rScores[f][i];
574 map<float,float>::iterator it = rScoreFreq[f].find(rScores[f][i]);
575 if (it != rScoreFreq[f].end()) {
576 rScoreFreq[f][rScores[f][i]]++;
578 rScoreFreq[f][rScores[f][i]] = 1;
584 for(int a = 0; a < numComp; a++) {
585 float rcumul = 1.0000;
586 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
587 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
588 //make rscoreFreq map and rCumul
589 map<float,float>::iterator it2 = rScoreFreq[a].find(it->first);
590 rCumul[a][it->first] = rcumul;
591 //get percentage of random trees with that info
592 if (it2 != rScoreFreq[a].end()) { rScoreFreq[a][it->first] /= iters; rcumul-= it2->second; }
593 else { rScoreFreq[a][it->first] = 0.0000; } //no random trees with that score
598 catch(exception& e) {
599 m->errorOut(e, "UnifracWeightedCommand", "calculateFreqsCums");
604 /***********************************************************/