]> git.donarmstrong.com Git - mothur.git/blob - unifracunweightedcommand.cpp
you can now use a distance matrix as input for the heatmap.sim command.
[mothur.git] / unifracunweightedcommand.cpp
1 /*
2  *  unifracunweightedcommand.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 "unifracunweightedcommand.h"
11
12 /***********************************************************/
13 UnifracUnweightedCommand::UnifracUnweightedCommand(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.unweighted 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                         //if user selects distance = true and no groups it won't calc the pairwise
61                         if ((phylip) && (Groups.size() == 0)) {
62                                 groups = "all";
63                                 splitAtDash(groups, Groups);
64                                 globaldata->Groups = Groups;
65                         }
66                 
67                         if (abort == false) {
68                                 T = globaldata->gTree;
69                                 tmap = globaldata->gTreemap;
70                                 sumFile = globaldata->getTreeFile() + ".uwsummary";
71                                 openOutputFile(sumFile, outSum);
72                                 
73                                 util = new SharedUtil();
74                                 util->setGroups(globaldata->Groups, tmap->namesOfGroups, allGroups, numGroups, "unweighted");   //sets the groups the user wants to analyze
75                                 util->getCombos(groupComb, globaldata->Groups, numComp);
76                                 
77                                 if (numGroups == 1) { numComp++; groupComb.push_back(allGroups); }
78                                 
79                                 unweighted = new Unweighted(tmap);
80                                 
81                         }
82                         
83                 }
84                 
85         }
86         catch(exception& e) {
87                 errorOut(e, "UnifracUnweightedCommand", "UnifracUnweightedCommand");
88                 exit(1);
89         }
90 }
91
92 //**********************************************************************************************************************
93
94 void UnifracUnweightedCommand::help(){
95         try {
96                 mothurOut("The unifrac.unweighted command can only be executed after a successful read.tree command.\n");
97                 mothurOut("The unifrac.unweighted command parameters are groups, iters, distance and random.  No parameters are required.\n");
98                 mothurOut("The groups parameter allows you to specify which of the groups in your groupfile you would like analyzed.  You must enter at least 1 valid group.\n");
99                 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");
100                 mothurOut("The distance parameter allows you to create a distance file from the results. The default is false.\n");
101                 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");
102                 mothurOut("The unifrac.unweighted command should be in the following format: unifrac.unweighted(groups=yourGroups, iters=yourIters).\n");
103                 mothurOut("Example unifrac.unweighted(groups=A-B-C, iters=500).\n");
104                 mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
105                 mothurOut("The unifrac.unweighted command output two files: .unweighted and .uwsummary their descriptions are in the manual.\n");
106                 mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
107         }
108         catch(exception& e) {
109                 errorOut(e, "UnifracUnweightedCommand", "help");
110                 exit(1);
111         }
112 }
113
114
115 /***********************************************************/
116 int UnifracUnweightedCommand::execute() {
117         try {
118                 
119                 if (abort == true) { return 0; }
120                 
121                 userData.resize(numComp,0);  //data[0] = unweightedscore 
122                 randomData.resize(numComp,0); //data[0] = unweightedscore
123                 //create new tree with same num nodes and leaves as users
124                 
125                 outSum << "Tree#" << '\t' << "Groups" << '\t'  <<  "UWScore" <<'\t' << "UWSig" <<  endl;
126                 mothurOut("Tree#\tGroups\tUWScore\tUWSig"); mothurOutEndLine();
127                 
128                 //get pscores for users trees
129                 for (int i = 0; i < T.size(); i++) {
130                         counter = 0;
131                         
132                         if (random)  {  output = new ColumnFile(globaldata->getTreeFile()  + toString(i+1) + ".unweighted", itersString);  }
133                         
134                         //get unweighted for users tree
135                         rscoreFreq.resize(numComp);  
136                         rCumul.resize(numComp);  
137                         utreeScores.resize(numComp);  
138                         UWScoreSig.resize(numComp); 
139
140                         userData = unweighted->getValues(T[i]);  //userData[0] = unweightedscore
141                         
142                         //output scores for each combination
143                         for(int k = 0; k < numComp; k++) {
144                                 //saves users score
145                                 utreeScores[k].push_back(userData[k]);
146                                 
147                                 //add users score to validscores
148                                 validScores[userData[k]] = userData[k];
149                         }
150                         
151                         //get unweighted scores for random trees
152                         for (int j = 0; j < iters; j++) {
153                                 //we need a different getValues because when we swap the labels we only want to swap those in each pairwise comparison
154                                 randomData = unweighted->getValues(T[i], "", "");
155                         
156                                 for(int k = 0; k < numComp; k++) {      
157                                         //add trees unweighted score to map of scores
158                                         map<float,float>::iterator it = rscoreFreq[k].find(randomData[k]);
159                                         if (it != rscoreFreq[k].end()) {//already have that score
160                                                 rscoreFreq[k][randomData[k]]++;
161                                         }else{//first time we have seen this score
162                                                 rscoreFreq[k][randomData[k]] = 1;
163                                         }
164                                 
165                                         //add randoms score to validscores
166                                         validScores[randomData[k]] = randomData[k];
167                                 }
168                         }
169                 
170                         for(int a = 0; a < numComp; a++) {
171                                 float rcumul = 1.0000;
172                                 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
173                                 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
174                                         //make rscoreFreq map and rCumul
175                                         map<float,float>::iterator it2 = rscoreFreq[a].find(it->first);
176                                         rCumul[a][it->first] = rcumul;
177                                         //get percentage of random trees with that info
178                                         if (it2 != rscoreFreq[a].end()) {  rscoreFreq[a][it->first] /= iters; rcumul-= it2->second;  }
179                                         else { rscoreFreq[a][it->first] = 0.0000; } //no random trees with that score
180                                 }
181                                 
182                                 if (random) {   UWScoreSig[a].push_back(rCumul[a][userData[a]]);        }
183                                 else            {       UWScoreSig[a].push_back(0.0);                                           }
184                         }
185                 
186                         //print output files
187                         printUWSummaryFile(i);
188                         if (random)  {  printUnweightedFile();  delete output;  }
189                         if (phylip) {   createPhylipFile(i);            }
190                         
191                         rscoreFreq.clear(); 
192                         rCumul.clear();  
193                         validScores.clear(); 
194                         utreeScores.clear();  
195                         UWScoreSig.clear(); 
196                 }
197                 
198                 //reset groups parameter
199                 globaldata->Groups.clear(); 
200                 outSum.close();
201                 
202                 return 0;
203                 
204         }
205         catch(exception& e) {
206                 errorOut(e, "UnifracUnweightedCommand", "execute");
207                 exit(1);
208         }
209 }
210 /***********************************************************/
211 void UnifracUnweightedCommand::printUnweightedFile() {
212         try {
213                 vector<double> data;
214                 vector<string> tags;
215                 
216                 tags.push_back("Score");
217                 tags.push_back("RandFreq"); tags.push_back("RandCumul");
218                         
219                 for(int a = 0; a < numComp; a++) {
220                         output->initFile(groupComb[a], tags);
221                         //print each line
222                         for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
223                                 data.push_back(it->first);  data.push_back(rscoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);                                             
224                                 output->output(data);
225                                 data.clear();
226                         } 
227                         output->resetFile();
228                 }
229         }
230         catch(exception& e) {
231                 errorOut(e, "UnifracUnweightedCommand", "printUnweightedFile");
232                 exit(1);
233         }
234 }
235
236 /***********************************************************/
237 void UnifracUnweightedCommand::printUWSummaryFile(int i) {
238         try {
239                                 
240                 //format output
241                 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
242                         
243                 //print each line
244
245                 for(int a = 0; a < numComp; a++) {
246                         outSum << i+1 << '\t';
247                         mothurOut(toString(i+1) + "\t");
248                         
249                         if (random) {
250                                 if (UWScoreSig[a][0] > (1/(float)iters)) {
251                                         outSum << setprecision(6) << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << UWScoreSig[a][0] << endl;
252                                         cout << setprecision(6)  << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << UWScoreSig[a][0] << endl; 
253                                         mothurOutJustToLog(groupComb[a]  + "\t" + toString(utreeScores[a][0])  + "\t" + toString(UWScoreSig[a][0])); mothurOutEndLine(); 
254                                 }else {
255                                         outSum << setprecision(6) << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
256                                         cout << setprecision(6)  << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl; 
257                                         mothurOutJustToLog(groupComb[a]  + "\t" + toString(utreeScores[a][0])  + "\t<" + toString((1/float(iters)))); mothurOutEndLine();
258                                 }
259                         }else{
260                                 outSum << setprecision(6) << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << "0.00" << endl;
261                                 cout << setprecision(6)  << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << "0.00" << endl; 
262                                 mothurOutJustToLog(groupComb[a]  + "\t" + toString(utreeScores[a][0])  + "\t0.00"); mothurOutEndLine();
263                         }
264                 }
265                 
266         }
267         catch(exception& e) {
268                 errorOut(e, "UnifracUnweightedCommand", "printUWSummaryFile");
269                 exit(1);
270         }
271 }
272 /***********************************************************/
273 void UnifracUnweightedCommand::createPhylipFile(int i) {
274         try {
275                 string phylipFileName = globaldata->getTreeFile()  + toString(i+1) + ".unweighted.dist";
276                 ofstream out;
277                 openOutputFile(phylipFileName, out);
278                         
279                 //output numSeqs
280                 out << globaldata->Groups.size() << endl;
281                         
282                 //make matrix with scores in it
283                 vector< vector<float> > dists;  dists.resize(globaldata->Groups.size());
284                 for (int i = 0; i < globaldata->Groups.size(); i++) {
285                         dists[i].resize(globaldata->Groups.size(), 0.0);
286                 }
287                 
288                 //flip it so you can print it
289                 int count = 0;
290                 for (int r=0; r<globaldata->Groups.size(); r++) { 
291                         for (int l = r+1; l < globaldata->Groups.size(); l++) {
292                                 dists[r][l] = (1.0 - utreeScores[count][0]);
293                                 dists[l][r] = (1.0 - utreeScores[count][0]);
294                                 count++;
295                         }
296                 }
297                 
298                 //output to file
299                 for (int r=0; r<globaldata->Groups.size(); r++) { 
300                         //output name
301                         out << globaldata->Groups[r] << '\t';
302                         
303                         //output distances
304                         for (int l = 0; l < r; l++) {   out  << dists[r][l] << '\t';  }
305                         out << endl;
306                 }
307                 out.close();
308         }
309         catch(exception& e) {
310                 errorOut(e, "UnifracUnweightedCommand", "createPhylipFile");
311                 exit(1);
312         }
313 }
314 /***********************************************************/
315
316
317