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;
33 outputTypes["column"] = tempOutNames;
36 m->errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
40 //**********************************************************************************************************************
41 vector<string> UnifracWeightedCommand::getRequiredParameters(){
43 vector<string> myArray;
47 m->errorOut(e, "UnifracWeightedCommand", "getRequiredParameters");
51 //**********************************************************************************************************************
52 vector<string> UnifracWeightedCommand::getRequiredFiles(){
54 string Array[] = {"tree","group"};
55 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
60 m->errorOut(e, "UnifracWeightedCommand", "getRequiredFiles");
64 /***********************************************************/
65 UnifracWeightedCommand::UnifracWeightedCommand(string option) {
67 globaldata = GlobalData::getInstance();
71 //allow user to run help
72 if(option == "help") { help(); abort = true; }
75 //valid paramters for this command
76 string Array[] = {"groups","iters","distance","random","processors","outputdir","inputdir"};
77 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
79 OptionParser parser(option);
80 map<string,string> parameters=parser.getParameters();
82 ValidParameters validParameter;
84 //check to make sure all parameters are valid for command
85 for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) {
86 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
89 //initialize outputTypes
90 vector<string> tempOutNames;
91 outputTypes["weighted"] = tempOutNames;
92 outputTypes["wsummary"] = tempOutNames;
93 outputTypes["phylip"] = tempOutNames;
94 outputTypes["column"] = tempOutNames;
96 if (globaldata->gTree.size() == 0) {//no trees were read
97 m->mothurOut("You must execute the read.tree command, before you may execute the unifrac.weighted command."); m->mothurOutEndLine(); abort = true; }
99 //if the user changes the output directory command factory will send this info to us in the output parameter
100 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
102 outputDir += m->hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it
105 //check for optional parameter and set defaults
106 // ...at some point should added some additional type checking...
107 groups = validParameter.validFile(parameters, "groups", false);
108 if (groups == "not found") { groups = ""; }
110 m->splitAtDash(groups, Groups);
111 globaldata->Groups = Groups;
114 itersString = validParameter.validFile(parameters, "iters", false); if (itersString == "not found") { itersString = "1000"; }
115 convert(itersString, iters);
117 string temp = validParameter.validFile(parameters, "distance", false);
118 if (temp == "not found") { phylip = false; outputForm = ""; }
120 if ((temp == "lt") || (temp == "column") || (temp == "square")) { phylip = true; outputForm = temp; }
121 else { m->mothurOut("Options for distance are: lt, square, or column. Using lt."); m->mothurOutEndLine(); phylip = true; outputForm = "lt"; }
124 temp = validParameter.validFile(parameters, "random", false); if (temp == "not found") { temp = "F"; }
125 random = m->isTrue(temp);
127 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = "1"; }
128 convert(temp, processors);
130 if (!random) { iters = 0; } //turn off random calcs
133 if (abort == false) {
134 T = globaldata->gTree;
135 tmap = globaldata->gTreemap;
136 sumFile = outputDir + m->getSimpleName(globaldata->getTreeFile()) + ".wsummary";
137 m->openOutputFile(sumFile, outSum);
138 outputNames.push_back(sumFile); outputTypes["wsummary"].push_back(sumFile);
140 util = new SharedUtil();
141 string s; //to make work with setgroups
142 util->setGroups(globaldata->Groups, tmap->namesOfGroups, s, numGroups, "weighted"); //sets the groups the user wants to analyze
143 util->getCombos(groupComb, globaldata->Groups, numComp);
145 weighted = new Weighted(tmap);
152 catch(exception& e) {
153 m->errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
157 //**********************************************************************************************************************
159 void UnifracWeightedCommand::help(){
161 m->mothurOut("The unifrac.weighted command can only be executed after a successful read.tree command.\n");
162 m->mothurOut("The unifrac.weighted command parameters are groups, iters, distance, processors and random. No parameters are required.\n");
163 m->mothurOut("The groups parameter allows you to specify which of the groups in your groupfile you would like analyzed. You must enter at least 2 valid groups.\n");
164 m->mothurOut("The group names are separated by dashes. The iters parameter allows you to specify how many random trees you would like compared to your tree.\n");
165 m->mothurOut("The distance parameter allows you to create a distance file from the results. The default is false.\n");
166 m->mothurOut("The random parameter allows you to shut off the comparison to random trees. The default is false, meaning don't compare your trees with randomly generated trees.\n");
167 m->mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
168 m->mothurOut("The unifrac.weighted command should be in the following format: unifrac.weighted(groups=yourGroups, iters=yourIters).\n");
169 m->mothurOut("Example unifrac.weighted(groups=A-B-C, iters=500).\n");
170 m->mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
171 m->mothurOut("The unifrac.weighted command output two files: .weighted and .wsummary their descriptions are in the manual.\n");
172 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
174 catch(exception& e) {
175 m->errorOut(e, "UnifracWeightedCommand", "help");
180 /***********************************************************/
181 int UnifracWeightedCommand::execute() {
184 if (abort == true) { return 0; }
186 int start = time(NULL);
188 //get weighted for users tree
189 userData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
190 randomData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
192 //get weighted scores for users trees
193 for (int i = 0; i < T.size(); i++) {
195 if (m->control_pressed) { outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
198 rScores.resize(numComp); //data[0] = weightedscore AB, data[1] = weightedscore AC...
199 uScores.resize(numComp); //data[0] = weightedscore AB, data[1] = weightedscore AC...
202 output = new ColumnFile(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted", itersString);
203 outputNames.push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted");
204 outputTypes["weighted"].push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted");
207 userData = weighted->getValues(T[i], processors, outputDir); //userData[0] = weightedscore
209 if (m->control_pressed) { if (random) { delete output; } outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
212 for (int s=0; s<numComp; s++) {
213 //add users score to vector of user scores
214 uScores[s].push_back(userData[s]);
216 //save users tree score for summary file
217 utreeScores.push_back(userData[s]);
222 //calculate number of comparisons i.e. with groups A,B,C = AB, AC, BC = 3;
223 vector< vector<string> > namesOfGroupCombos;
224 for (int a=0; a<numGroups; a++) {
225 for (int l = 0; l < a; l++) {
226 vector<string> groups; groups.push_back(globaldata->Groups[a]); groups.push_back(globaldata->Groups[l]);
227 namesOfGroupCombos.push_back(groups);
233 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
235 int numPairs = namesOfGroupCombos.size();
236 int numPairsPerProcessor = numPairs / processors;
238 for (int i = 0; i < processors; i++) {
239 int startPos = i * numPairsPerProcessor;
240 if(i == processors - 1){
241 numPairsPerProcessor = numPairs - i * numPairsPerProcessor;
243 lines.push_back(linePair(startPos, numPairsPerProcessor));
249 //get scores for random trees
250 for (int j = 0; j < iters; j++) {
252 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
254 driver(T[i], namesOfGroupCombos, 0, namesOfGroupCombos.size(), rScores);
256 createProcesses(T[i], namesOfGroupCombos, rScores);
259 driver(T[i], namesOfGroupCombos, 0, namesOfGroupCombos.size(), rScores);
262 if (m->control_pressed) { delete output; outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
265 m->mothurOut("Iter: " + toString(j+1)); m->mothurOutEndLine();
269 //find the signifigance of the score for summary file
270 for (int f = 0; f < numComp; f++) {
272 sort(rScores[f].begin(), rScores[f].end());
274 //the index of the score higher than yours is returned
275 //so if you have 1000 random trees the index returned is 100
276 //then there are 900 trees with a score greater then you.
277 //giving you a signifigance of 0.900
278 int index = findIndex(userData[f], f); if (index == -1) { m->mothurOut("error in UnifracWeightedCommand"); m->mothurOutEndLine(); exit(1); } //error code
280 //the signifigance is the number of trees with the users score or higher
281 WScoreSig.push_back((iters-index)/(float)iters);
284 //out << "Tree# " << i << endl;
285 calculateFreqsCumuls();
299 if (m->control_pressed) { outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
303 if (phylip) { createPhylipFile(); }
305 //clear out users groups
306 globaldata->Groups.clear();
309 if (m->control_pressed) {
310 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
314 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run unifrac.weighted."); m->mothurOutEndLine();
316 m->mothurOutEndLine();
317 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
318 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
319 m->mothurOutEndLine();
324 catch(exception& e) {
325 m->errorOut(e, "UnifracWeightedCommand", "execute");
329 /**************************************************************************************************/
331 int UnifracWeightedCommand::createProcesses(Tree* t, vector< vector<string> > namesOfGroupCombos, vector< vector<double> >& scores) {
333 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
336 vector<int> processIDS;
340 //loop through and create all the processes you want
341 while (process != processors) {
345 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
348 driver(t, namesOfGroupCombos, lines[process].start, lines[process].num, scores);
350 //pass numSeqs to parent
352 string tempFile = outputDir + toString(getpid()) + ".weightedcommand.results.temp";
353 m->openOutputFile(tempFile, out);
354 for (int i = lines[process].start; i < (lines[process].start + lines[process].num); i++) { out << scores[i][(scores[i].size()-1)] << '\t'; } out << endl;
359 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
360 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
365 driver(t, namesOfGroupCombos, lines[0].start, lines[0].num, scores);
367 //force parent to wait until all the processes are done
368 for (int i=0;i<(processors-1);i++) {
369 int temp = processIDS[i];
373 //get data created by processes
374 for (int i=0;i<(processors-1);i++) {
377 string s = outputDir + toString(processIDS[i]) + ".weightedcommand.results.temp";
378 m->openInputFile(s, in);
381 for (int j = lines[(i+1)].start; j < (lines[(i+1)].start + lines[(i+1)].num); j++) { in >> tempScore; scores[j].push_back(tempScore); }
389 catch(exception& e) {
390 m->errorOut(e, "UnifracWeightedCommand", "createProcesses");
395 /**************************************************************************************************/
396 int UnifracWeightedCommand::driver(Tree* t, vector< vector<string> > namesOfGroupCombos, int start, int num, vector< vector<double> >& scores) {
398 Tree* randT = new Tree();
400 for (int h = start; h < (start+num); h++) {
402 if (m->control_pressed) { return 0; }
404 //initialize weighted score
405 string groupA = namesOfGroupCombos[h][0];
406 string groupB = namesOfGroupCombos[h][1];
411 //create a random tree with same topology as T[i], but different labels
412 randT->assembleRandomUnifracTree(groupA, groupB);
414 if (m->control_pressed) { delete randT; return 0; }
416 //get wscore of random tree
417 EstOutput randomData = weighted->getValues(randT, groupA, groupB);
419 if (m->control_pressed) { delete randT; return 0; }
422 scores[h].push_back(randomData[0]);
430 catch(exception& e) {
431 m->errorOut(e, "UnifracWeightedCommand", "driver");
435 /***********************************************************/
436 void UnifracWeightedCommand::printWeightedFile() {
440 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
442 for(int a = 0; a < numComp; a++) {
443 output->initFile(groupComb[a], tags);
445 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
446 data.push_back(it->first); data.push_back(rScoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);
447 output->output(data);
453 catch(exception& e) {
454 m->errorOut(e, "UnifracWeightedCommand", "printWeightedFile");
460 /***********************************************************/
461 void UnifracWeightedCommand::printWSummaryFile() {
464 outSum << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" << endl;
465 m->mothurOut("Tree#\tGroups\tWScore\tWSig"); m->mothurOutEndLine();
468 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
472 for (int i = 0; i < T.size(); i++) {
473 for (int j = 0; j < numComp; j++) {
475 if (WScoreSig[count] > (1/(float)iters)) {
476 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl;
477 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl;
478 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t" + toString(WScoreSig[count]) + "\n");
480 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
481 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
482 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t<" + toString((1/float(iters))) + "\n");
485 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl;
486 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl;
487 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t0.00\n");
494 catch(exception& e) {
495 m->errorOut(e, "UnifracWeightedCommand", "printWSummaryFile");
499 /***********************************************************/
500 void UnifracWeightedCommand::createPhylipFile() {
504 for (int i = 0; i < T.size(); i++) {
506 string phylipFileName;
507 if ((outputForm == "lt") || (outputForm == "square")) {
508 phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted.phylip.dist";
509 outputNames.push_back(phylipFileName); outputTypes["phylip"].push_back(phylipFileName);
511 phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted.column.dist";
512 outputNames.push_back(phylipFileName); outputTypes["column"].push_back(phylipFileName);
516 m->openOutputFile(phylipFileName, out);
518 if ((outputForm == "lt") || (outputForm == "square")) {
520 out << globaldata->Groups.size() << endl;
523 //make matrix with scores in it
524 vector< vector<float> > dists; dists.resize(globaldata->Groups.size());
525 for (int i = 0; i < globaldata->Groups.size(); i++) {
526 dists[i].resize(globaldata->Groups.size(), 0.0);
529 //flip it so you can print it
530 for (int r=0; r<globaldata->Groups.size(); r++) {
531 for (int l = r+1; l < globaldata->Groups.size(); l++) {
532 dists[r][l] = utreeScores[count];
533 dists[l][r] = utreeScores[count];
539 for (int r=0; r<globaldata->Groups.size(); r++) {
541 string name = globaldata->Groups[r];
542 if (name.length() < 10) { //pad with spaces to make compatible
543 while (name.length() < 10) { name += " "; }
546 if (outputForm == "lt") {
550 for (int l = 0; l < r; l++) { out << dists[r][l] << '\t'; }
552 }else if (outputForm == "square") {
556 for (int l = 0; l < globaldata->Groups.size(); l++) { out << dists[r][l] << '\t'; }
560 for (int l = 0; l < r; l++) {
561 string otherName = globaldata->Groups[l];
562 if (otherName.length() < 10) { //pad with spaces to make compatible
563 while (otherName.length() < 10) { otherName += " "; }
566 out << name << '\t' << otherName << dists[r][l] << endl;
573 catch(exception& e) {
574 m->errorOut(e, "UnifracWeightedCommand", "createPhylipFile");
578 /***********************************************************/
579 int UnifracWeightedCommand::findIndex(float score, int index) {
581 for (int i = 0; i < rScores[index].size(); i++) {
582 if (rScores[index][i] >= score) { return i; }
584 return rScores[index].size();
586 catch(exception& e) {
587 m->errorOut(e, "UnifracWeightedCommand", "findIndex");
592 /***********************************************************/
594 void UnifracWeightedCommand::calculateFreqsCumuls() {
596 //clear out old tree values
598 rScoreFreq.resize(numComp);
600 rCumul.resize(numComp);
603 //calculate frequency
604 for (int f = 0; f < numComp; f++) {
605 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...
606 validScores[rScores[f][i]] = rScores[f][i];
607 map<float,float>::iterator it = rScoreFreq[f].find(rScores[f][i]);
608 if (it != rScoreFreq[f].end()) {
609 rScoreFreq[f][rScores[f][i]]++;
611 rScoreFreq[f][rScores[f][i]] = 1;
617 for(int a = 0; a < numComp; a++) {
618 float rcumul = 1.0000;
619 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
620 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
621 //make rscoreFreq map and rCumul
622 map<float,float>::iterator it2 = rScoreFreq[a].find(it->first);
623 rCumul[a][it->first] = rcumul;
624 //get percentage of random trees with that info
625 if (it2 != rScoreFreq[a].end()) { rScoreFreq[a][it->first] /= iters; rcumul-= it2->second; }
626 else { rScoreFreq[a][it->first] = 0.0000; } //no random trees with that score
631 catch(exception& e) {
632 m->errorOut(e, "UnifracWeightedCommand", "calculateFreqsCums");
637 /***********************************************************/