]> git.donarmstrong.com Git - mothur.git/blob - unifracweightedcommand.cpp
you can now use a distance matrix as input for the heatmap.sim command.
[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"};
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                                 mothurOut("You must execute the read.tree command, before you may execute the unifrac.weighted command."); mothurOutEndLine(); abort = true;  }
39                                                                                 
40                         //check for optional parameter and set defaults
41                         // ...at some point should added some additional type checking...
42                         groups = validParameter.validFile(parameters, "groups", false);                 
43                         if (groups == "not found") { groups = ""; }
44                         else { 
45                                 splitAtDash(groups, Groups);
46                                 globaldata->Groups = Groups;
47                         }
48                                 
49                         itersString = validParameter.validFile(parameters, "iters", false);                     if (itersString == "not found") { itersString = "1000"; }
50                         convert(itersString, iters); 
51                         
52                         string temp = validParameter.validFile(parameters, "distance", false);                  if (temp == "not found") { temp = "false"; }
53                         phylip = isTrue(temp);
54                 
55                         temp = validParameter.validFile(parameters, "random", false);                                   if (temp == "not found") { temp = "true"; }
56                         random = isTrue(temp);
57                         
58                         if (!random) {  iters = 0;  } //turn off random calcs
59
60                         
61                         if (abort == false) {
62                                 T = globaldata->gTree;
63                                 tmap = globaldata->gTreemap;
64                                 sumFile = globaldata->getTreeFile() + ".wsummary";
65                                 openOutputFile(sumFile, outSum);
66                                 
67                                 util = new SharedUtil();
68                                 string s; //to make work with setgroups
69                                 util->setGroups(globaldata->Groups, tmap->namesOfGroups, s, numGroups, "weighted");     //sets the groups the user wants to analyze
70                                 util->getCombos(groupComb, globaldata->Groups, numComp);
71                                 
72                                 weighted = new Weighted(tmap);
73                                 
74                         }
75                 }
76                 
77                 
78         }
79         catch(exception& e) {
80                 errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
81                 exit(1);
82         }
83 }
84 //**********************************************************************************************************************
85
86 void UnifracWeightedCommand::help(){
87         try {
88                 mothurOut("The unifrac.weighted command can only be executed after a successful read.tree command.\n");
89                 mothurOut("The unifrac.weighted command parameters are groups, iters, distance and random.  No parameters are required.\n");
90                 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");
91                 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");
92                 mothurOut("The distance parameter allows you to create a distance file from the results. The default is false.\n");
93                 mothurOut("The random parameter allows you to shut off the comparison to random trees. The default is true, meaning compare your trees with randomly generated trees.\n");
94                 mothurOut("The unifrac.weighted command should be in the following format: unifrac.weighted(groups=yourGroups, iters=yourIters).\n");
95                 mothurOut("Example unifrac.weighted(groups=A-B-C, iters=500).\n");
96                 mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
97                 mothurOut("The unifrac.weighted command output two files: .weighted and .wsummary their descriptions are in the manual.\n");
98                 mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
99         }
100         catch(exception& e) {
101                 errorOut(e, "UnifracWeightedCommand", "help");
102                 exit(1);
103         }
104 }
105
106 /***********************************************************/
107 int UnifracWeightedCommand::execute() {
108         try {
109         
110                 if (abort == true) { return 0; }
111                 
112                 Progress* reading;
113                 if (random) {   reading = new Progress("Comparing to random:", iters);  }
114                 
115                 //get weighted for users tree
116                 userData.resize(numComp,0);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
117                 randomData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
118                                 
119                 //create new tree with same num nodes and leaves as users
120                 randT = new Tree();
121                 
122                 //get weighted scores for users trees
123                 for (int i = 0; i < T.size(); i++) {
124                         counter = 0;
125                         rScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
126                         uScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
127                         
128                         if (random) {  output = new ColumnFile(globaldata->getTreeFile()  + toString(i+1) + ".weighted", itersString);  } 
129
130                         userData = weighted->getValues(T[i]);  //userData[0] = weightedscore
131                         
132                         //save users score
133                         for (int s=0; s<numComp; s++) {
134                                 //add users score to vector of user scores
135                                 uScores[s].push_back(userData[s]);
136                                 
137                                 //save users tree score for summary file
138                                 utreeScores.push_back(userData[s]);
139                         }
140                         
141                         //get scores for random trees
142                         for (int j = 0; j < iters; j++) {
143                                 int count = 0;
144                                 for (int r=0; r<numGroups; r++) { 
145                                         for (int l = r+1; l < numGroups; l++) {
146                                                 //copy T[i]'s info.
147                                                 randT->getCopy(T[i]);
148                                                  
149                                                 //create a random tree with same topology as T[i], but different labels
150                                                 randT->assembleRandomUnifracTree(globaldata->Groups[r], globaldata->Groups[l]);
151                                                 //get wscore of random tree
152                                                 randomData = weighted->getValues(randT, globaldata->Groups[r], globaldata->Groups[l]);
153                                                 
154                                                 //save scores
155                                                 rScores[count].push_back(randomData[0]);
156                                                 count++;
157                                         }
158                                 }
159                                 
160                                 //update progress bar
161                                 reading->update(j);
162
163                         }
164
165                         //removeValidScoresDuplicates(); 
166                         //find the signifigance of the score for summary file
167                         if (random) {
168                                 for (int f = 0; f < numComp; f++) {
169                                         //sort random scores
170                                         sort(rScores[f].begin(), rScores[f].end());
171                                         
172                                         //the index of the score higher than yours is returned 
173                                         //so if you have 1000 random trees the index returned is 100 
174                                         //then there are 900 trees with a score greater then you. 
175                                         //giving you a signifigance of 0.900
176                                         int index = findIndex(userData[f], f);    if (index == -1) { mothurOut("error in UnifracWeightedCommand"); mothurOutEndLine(); exit(1); } //error code
177                                         
178                                         //the signifigance is the number of trees with the users score or higher 
179                                         WScoreSig.push_back((iters-index)/(float)iters);
180                                 }
181                                 
182                                 //out << "Tree# " << i << endl;
183                                 calculateFreqsCumuls();
184                                 printWeightedFile();
185                                 
186                                 delete output;
187                         }
188                         
189                         //clear data
190                         rScores.clear();
191                         uScores.clear();
192                         validScores.clear();
193                 }
194                 
195                 //finish progress bar
196                 if (random) {   reading->finish();      delete reading;         }
197                 
198                 printWSummaryFile();
199                 
200                 if (phylip) {   createPhylipFile();             }
201
202                 //clear out users groups
203                 globaldata->Groups.clear();
204                 
205                 delete randT;
206                 
207                 return 0;
208                 
209         }
210         catch(exception& e) {
211                 errorOut(e, "UnifracWeightedCommand", "execute");
212                 exit(1);
213         }
214 }
215 /***********************************************************/
216 void UnifracWeightedCommand::printWeightedFile() {
217         try {
218                 vector<double> data;
219                 vector<string> tags;
220                 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
221                 
222                 for(int a = 0; a < numComp; a++) {
223                         output->initFile(groupComb[a], tags);
224                         //print each line
225                         for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
226                                 data.push_back(it->first);  data.push_back(rScoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]); 
227                                 output->output(data);
228                                 data.clear();
229                         } 
230                         output->resetFile();
231                 }
232         }
233         catch(exception& e) {
234                 errorOut(e, "UnifracWeightedCommand", "printWeightedFile");
235                 exit(1);
236         }
237 }
238
239
240 /***********************************************************/
241 void UnifracWeightedCommand::printWSummaryFile() {
242         try {
243                 //column headers
244                 outSum << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" <<  endl;
245                 mothurOut("Tree#\tGroups\tWScore\tWSig"); mothurOutEndLine(); 
246                 
247                 //format output
248                 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
249                 
250                 //print each line
251                 int count = 0;
252                 for (int i = 0; i < T.size(); i++) { 
253                         for (int j = 0; j < numComp; j++) {
254                                 if (random) {
255                                         if (WScoreSig[count] > (1/(float)iters)) {
256                                                 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl; 
257                                                 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl; 
258                                                 mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t" +  toString(WScoreSig[count])); mothurOutEndLine();  
259                                         }else{
260                                                 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl; 
261                                                 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl; 
262                                                 mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t<" +  toString((1/float(iters)))); mothurOutEndLine();  
263                                         }
264                                 }else{
265                                         outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl; 
266                                         cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl; 
267                                         mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t0.00"); mothurOutEndLine(); 
268                                 }
269                                 count++;
270                         }
271                 }
272                 outSum.close();
273         }
274         catch(exception& e) {
275                 errorOut(e, "UnifracWeightedCommand", "printWSummaryFile");
276                 exit(1);
277         }
278 }
279 /***********************************************************/
280 void UnifracWeightedCommand::createPhylipFile() {
281         try {
282                 int count = 0;
283                 //for each tree
284                 for (int i = 0; i < T.size(); i++) { 
285                 
286                         string phylipFileName = globaldata->getTreeFile()  + toString(i+1) + ".weighted.dist";
287                         ofstream out;
288                         openOutputFile(phylipFileName, out);
289                         
290                         //output numSeqs
291                         out << globaldata->Groups.size() << endl;
292                         
293                         //make matrix with scores in it
294                         vector< vector<float> > dists;  dists.resize(globaldata->Groups.size());
295                         for (int i = 0; i < globaldata->Groups.size(); i++) {
296                                 dists[i].resize(globaldata->Groups.size(), 0.0);
297                         }
298                         
299                         //flip it so you can print it
300                         for (int r=0; r<globaldata->Groups.size(); r++) { 
301                                 for (int l = r+1; l < globaldata->Groups.size(); l++) {
302                                         dists[r][l] = (1.0 - utreeScores[count]);
303                                         dists[l][r] = (1.0 - utreeScores[count]);
304                                         count++;
305                                 }
306                         }
307
308                         //output to file
309                         for (int r=0; r<globaldata->Groups.size(); r++) { 
310                                 //output name
311                                 out << globaldata->Groups[r] << '\t';
312                                 
313                                 //output distances
314                                 for (int l = 0; l < r; l++) {   out  << dists[r][l] << '\t';  }
315                                 out << endl;
316                         }
317                         out.close();
318                 }
319         }
320         catch(exception& e) {
321                 errorOut(e, "UnifracWeightedCommand", "createPhylipFile");
322                 exit(1);
323         }
324 }
325 /***********************************************************/
326 int UnifracWeightedCommand::findIndex(float score, int index) {
327         try{
328                 for (int i = 0; i < rScores[index].size(); i++) {
329                         if (rScores[index][i] >= score) {       return i;       }
330                 }
331                 return rScores[index].size();
332         }
333         catch(exception& e) {
334                 errorOut(e, "UnifracWeightedCommand", "findIndex");
335                 exit(1);
336         }
337 }
338
339 /***********************************************************/
340
341 void UnifracWeightedCommand::calculateFreqsCumuls() {
342         try {
343                 //clear out old tree values
344                 rScoreFreq.clear();
345                 rScoreFreq.resize(numComp);
346                 rCumul.clear();
347                 rCumul.resize(numComp);
348                 validScores.clear();
349         
350                 //calculate frequency
351                 for (int f = 0; f < numComp; f++) {
352                         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...
353                                 validScores[rScores[f][i]] = rScores[f][i];
354                                 map<float,float>::iterator it = rScoreFreq[f].find(rScores[f][i]);
355                                 if (it != rScoreFreq[f].end()) {
356                                         rScoreFreq[f][rScores[f][i]]++;
357                                 }else{
358                                         rScoreFreq[f][rScores[f][i]] = 1;
359                                 }
360                         }
361                 }
362                 
363                 //calculate rcumul
364                 for(int a = 0; a < numComp; a++) {
365                         float rcumul = 1.0000;
366                         //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
367                         for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
368                                 //make rscoreFreq map and rCumul
369                                 map<float,float>::iterator it2 = rScoreFreq[a].find(it->first);
370                                 rCumul[a][it->first] = rcumul;
371                                 //get percentage of random trees with that info
372                                 if (it2 != rScoreFreq[a].end()) {  rScoreFreq[a][it->first] /= iters; rcumul-= it2->second;  }
373                                 else { rScoreFreq[a][it->first] = 0.0000; } //no random trees with that score
374                         }
375                 }
376
377         }
378         catch(exception& e) {
379                 errorOut(e, "UnifracWeightedCommand", "calculateFreqsCums");
380                 exit(1);
381         }
382 }
383
384 /***********************************************************/
385
386
387
388
389