]> git.donarmstrong.com Git - mothur.git/blob - amovacommand.cpp
working on windows paralellization, added trimOligos class to be used by trim.flows...
[mothur.git] / amovacommand.cpp
1 /*
2  *  amovacommand.cpp
3  *  mothur
4  *
5  *  Created by westcott on 2/7/11.
6  *  Copyright 2011 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "amovacommand.h"
11 #include "readphylipvector.h"
12 #include "groupmap.h"
13
14
15 //**********************************************************************************************************************
16 vector<string> AmovaCommand::setParameters(){   
17         try {
18                 CommandParameter pdesign("design", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pdesign);
19                 CommandParameter pphylip("phylip", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pphylip);
20                 CommandParameter piters("iters", "Number", "", "1000", "", "", "",false,false); parameters.push_back(piters);
21                 CommandParameter palpha("alpha", "Number", "", "0.05", "", "", "",false,false); parameters.push_back(palpha);
22                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
23                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
24         
25                 vector<string> myArray;
26                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
27                 return myArray;
28         }
29         catch(exception& e) {
30                 m->errorOut(e, "AmovaCommand", "setParameters");
31                 exit(1);
32         }
33 }
34 //**********************************************************************************************************************
35 string AmovaCommand::getHelpString(){   
36         try {
37                 string helpString = "";
38                 helpString += "Referenced: Anderson MJ (2001). A new method for non-parametric multivariate analysis of variance. Austral Ecol 26: 32-46.";
39                 helpString += "The amova command outputs a .amova file.";
40                 helpString += "The amova command parameters are phylip, iters, and alpha.  The phylip and design parameters are required, unless you have valid current files.";
41                 helpString += "The design parameter allows you to assign your samples to groups when you are running amova. It is required.";
42                 helpString += "The design file looks like the group file.  It is a 2 column tab delimited file, where the first column is the sample name and the second column is the group the sample belongs to.";
43                 helpString += "The iters parameter allows you to set number of randomization for the P value.  The default is 1000.";
44                 helpString += "The amova command should be in the following format: amova(phylip=file.dist, design=file.design).";
45                 helpString += "Note: No spaces between parameter labels (i.e. iters), '=' and parameters (i.e. 1000).";
46                 return helpString;
47         }
48         catch(exception& e) {
49                 m->errorOut(e, "AmovaCommand", "getHelpString");
50                 exit(1);
51         }
52 }
53 //**********************************************************************************************************************
54 AmovaCommand::AmovaCommand(){   
55         try {
56                 abort = true; calledHelp = true; 
57                 setParameters();
58                 vector<string> tempOutNames;
59                 outputTypes["amova"] = tempOutNames;
60         }
61         catch(exception& e) {
62                 m->errorOut(e, "AmovaCommand", "AmovaCommand");
63                 exit(1);
64         }
65 }
66 //**********************************************************************************************************************
67 AmovaCommand::AmovaCommand(string option) {
68         try {
69                 abort = false; calledHelp = false;   
70                 
71                 //allow user to run help
72                 if(option == "help") { help(); abort = true; calledHelp = true; }
73                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
74                 
75                 else {
76                         vector<string> myArray = setParameters();
77                         
78                         OptionParser parser(option);
79                         map<string,string> parameters = parser.getParameters();
80                         
81                         ValidParameters validParameter;
82                         
83                         //check to make sure all parameters are valid for command
84                         map<string,string>::iterator it;
85                         for (it = parameters.begin(); it != parameters.end(); it++) { 
86                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
87                         }
88                         
89                         //initialize outputTypes
90                         vector<string> tempOutNames;
91                         outputTypes["amova"] = tempOutNames;
92                         
93                         //if the user changes the output directory command factory will send this info to us in the output parameter 
94                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
95                         
96                         //if the user changes the input directory command factory will send this info to us in the output parameter 
97                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
98                         if (inputDir == "not found"){   inputDir = "";          }
99                         else {
100                                 string path;
101                                 it = parameters.find("design");
102                                 //user has given a template file
103                                 if(it != parameters.end()){ 
104                                         path = m->hasPath(it->second);
105                                         //if the user has not given a path then, add inputdir. else leave path alone.
106                                         if (path == "") {       parameters["design"] = inputDir + it->second;           }
107                                 }
108                                 
109                                 it = parameters.find("phylip");
110                                 //user has given a template file
111                                 if(it != parameters.end()){ 
112                                         path = m->hasPath(it->second);
113                                         //if the user has not given a path then, add inputdir. else leave path alone.
114                                         if (path == "") {       parameters["phylip"] = inputDir + it->second;           }
115                                 }
116                         }
117                         
118                         phylipFileName = validParameter.validFile(parameters, "phylip", true);
119                         if (phylipFileName == "not open") { phylipFileName = ""; abort = true; }
120                         else if (phylipFileName == "not found") { 
121                                 //if there is a current phylip file, use it
122                                 phylipFileName = m->getPhylipFile(); 
123                                 if (phylipFileName != "") { m->mothurOut("Using " + phylipFileName + " as input file for the phylip parameter."); m->mothurOutEndLine(); }
124                                 else {  m->mothurOut("You have no current phylip file and the phylip parameter is required."); m->mothurOutEndLine(); abort = true; }
125                         }else { m->setPhylipFile(phylipFileName); }
126                         
127                         //check for required parameters
128                         designFileName = validParameter.validFile(parameters, "design", true);
129                         if (designFileName == "not open") { designFileName = ""; abort = true; }
130                         else if (designFileName == "not found") {
131                                 //if there is a current design file, use it
132                                 designFileName = m->getDesignFile(); 
133                                 if (designFileName != "") { m->mothurOut("Using " + designFileName + " as input file for the design parameter."); m->mothurOutEndLine(); }
134                                 else {  m->mothurOut("You have no current design file and the design parameter is required."); m->mothurOutEndLine(); abort = true; }                           
135                         }else { m->setDesignFile(designFileName); }     
136
137                         string temp = validParameter.validFile(parameters, "iters", false);
138                         if (temp == "not found") { temp = "1000"; }
139                         convert(temp, iters); 
140                         
141                         temp = validParameter.validFile(parameters, "alpha", false);
142                         if (temp == "not found") { temp = "0.05"; }
143                         convert(temp, experimentwiseAlpha); 
144                 }
145         }
146         catch(exception& e) {
147                 m->errorOut(e, "AmovaCommand", "AmovaCommand");
148                 exit(1);
149         }
150 }
151 //**********************************************************************************************************************
152
153 int AmovaCommand::execute(){
154         try {
155                 
156                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
157                 
158                 //read design file
159                 designMap = new GroupMap(designFileName);
160                 designMap->readDesignMap();
161
162                 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
163                                                 
164                 //read in distance matrix and square it
165                 ReadPhylipVector readMatrix(phylipFileName);
166                 vector<string> sampleNames = readMatrix.read(distanceMatrix);
167                 
168                 for(int i=0;i<distanceMatrix.size();i++){
169                         for(int j=0;j<i;j++){
170                                 distanceMatrix[i][j] *= distanceMatrix[i][j];   
171                         }
172                 }
173                 
174                 //link designMap to rows/columns in distance matrix
175                 map<string, vector<int> > origGroupSampleMap;
176                 for(int i=0;i<sampleNames.size();i++){
177                         string group = designMap->getGroup(sampleNames[i]);
178                         
179                         if (group == "not found") {
180                                 m->mothurOut("[ERROR]: " + sampleNames[i] + " is not in your design file, please correct."); m->mothurOutEndLine(); m->control_pressed = true;
181                         }else { origGroupSampleMap[group].push_back(i); }
182                         
183                 }
184                 int numGroups = origGroupSampleMap.size();
185                 
186                 if (m->control_pressed) { delete designMap; return 0; }
187                 
188                 //create a new filename
189                 ofstream AMOVAFile;
190                 string AMOVAFileName = outputDir + m->getRootName(m->getSimpleName(phylipFileName))  + "amova";                         
191                 m->openOutputFile(AMOVAFileName, AMOVAFile);
192                 outputNames.push_back(AMOVAFileName); outputTypes["amova"].push_back(AMOVAFileName);
193                 
194                 double fullANOVAPValue = runAMOVA(AMOVAFile, origGroupSampleMap, experimentwiseAlpha);
195                 if(fullANOVAPValue <= experimentwiseAlpha && numGroups > 2){
196                         
197                         int numCombos = numGroups * (numGroups-1) / 2;
198                         double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
199                         
200                         map<string, vector<int> >::iterator itA;
201                         map<string, vector<int> >::iterator itB;
202                         
203                         for(itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
204                                 itB = itA;itB++;
205                                 for(itB;itB!=origGroupSampleMap.end();itB++){
206                                         
207                                         map<string, vector<int> > pairwiseGroupSampleMap;
208                                         pairwiseGroupSampleMap[itA->first] = itA->second;
209                                         pairwiseGroupSampleMap[itB->first] = itB->second;
210                                         
211                                         runAMOVA(AMOVAFile, pairwiseGroupSampleMap, pairwiseAlpha);
212                                 }                       
213                         }
214                         m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
215                         m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
216                 }
217                 else{
218                         m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
219                 }
220                 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
221                 AMOVAFile.close();
222                 
223                 delete designMap;
224          
225                 m->mothurOutEndLine();
226                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
227                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
228                 m->mothurOutEndLine();
229                 
230                 return 0;
231         }
232         catch(exception& e) {
233                 m->errorOut(e, "AmovaCommand", "execute");
234                 exit(1);
235         }
236 }
237
238 //**********************************************************************************************************************
239
240 double AmovaCommand::runAMOVA(ofstream& AMOVAFile, map<string, vector<int> > groupSampleMap, double alpha) {
241         try {
242                 map<string, vector<int> >::iterator it;
243
244                 int numGroups = groupSampleMap.size();
245                 int totalNumSamples = 0;
246
247                 for(it = groupSampleMap.begin();it!=groupSampleMap.end();it++){
248                         totalNumSamples += it->second.size();                   
249                 }
250
251                 double ssTotalOrig = calcSSTotal(groupSampleMap);
252                 double ssWithinOrig = calcSSWithin(groupSampleMap);
253                 double ssAmongOrig = ssTotalOrig - ssWithinOrig;
254                 
255                 double counter = 0;
256                 for(int i=0;i<iters;i++){
257                         map<string, vector<int> > randomizedGroup = getRandomizedGroups(groupSampleMap);
258                         double ssWithinRand = calcSSWithin(randomizedGroup);
259                         if(ssWithinRand < ssWithinOrig){        counter++;      }
260                 }
261                 
262                 double pValue = (double)counter / (double) iters;
263                 string pString = "";
264                 if(pValue < 1/(double)iters){   pString = '<' + toString(1/(double)iters);      }
265                 else                                            {       pString = toString(pValue);                                     }
266                 
267                 
268                 //print anova table
269                 it = groupSampleMap.begin();
270                 AMOVAFile << it->first;
271                 m->mothurOut(it->first);
272                 it++;
273                 for(it;it!=groupSampleMap.end();it++){
274                         AMOVAFile << '-' << it->first;
275                         m->mothurOut('-' + it->first);
276                 }
277                 
278                 AMOVAFile << "\tAmong\tWithin\tTotal" << endl;
279                 m->mothurOut("\tAmong\tWithin\tTotal\n");
280                 
281                 AMOVAFile << "SS\t" << ssAmongOrig << '\t' << ssWithinOrig << '\t' << ssTotalOrig << endl;
282                 m->mothurOut("SS\t" + toString(ssAmongOrig) + '\t' + toString(ssWithinOrig) + '\t' + toString(ssTotalOrig) + '\n');
283                 
284                 int dfAmong = numGroups - 1;                            double MSAmong = ssAmongOrig / (double) dfAmong;
285                 int dfWithin = totalNumSamples - numGroups;     double MSWithin = ssWithinOrig / (double) dfWithin;
286                 int dfTotal = totalNumSamples - 1;                      double Fs = MSAmong / MSWithin;
287                 
288                 AMOVAFile << "df\t" << dfAmong << '\t' << dfWithin << '\t' << dfTotal << endl;
289                 m->mothurOut("df\t" + toString(dfAmong) + '\t' + toString(dfWithin) + '\t' + toString(dfTotal) + '\n');
290
291                 AMOVAFile << "MS\t" << MSAmong << '\t' << MSWithin << endl << endl;
292                 m->mothurOut("MS\t" + toString(MSAmong) + '\t' + toString(MSWithin) + "\n\n");
293
294                 AMOVAFile << "Fs:\t" << Fs << endl;
295                 m->mothurOut("Fs:\t" + toString(Fs) + '\n');
296                 
297                 AMOVAFile << "p-value: " << pString;
298                 m->mothurOut("p-value: " + pString);
299
300                 if(pValue < alpha){
301                         AMOVAFile << "*";
302                         m->mothurOut("*");
303                 }
304                 AMOVAFile << endl << endl;
305                 m->mothurOutEndLine();m->mothurOutEndLine();
306
307                 return pValue;
308         }
309         catch(exception& e) {
310                 m->errorOut(e, "AmovaCommand", "runAMOVA");
311                 exit(1);
312         }
313 }
314
315 //**********************************************************************************************************************
316
317 map<string, vector<int> > AmovaCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
318         try{
319                 vector<int> sampleIndices;
320                 vector<int> samplesPerGroup;
321                 
322                 map<string, vector<int> >::iterator it;
323                 for(it=origMapping.begin();it!=origMapping.end();it++){
324                         vector<int> indices = it->second;
325                         samplesPerGroup.push_back(indices.size());
326                         sampleIndices.insert(sampleIndices.end(), indices.begin(), indices.end());
327                 }
328                 
329                 random_shuffle(sampleIndices.begin(), sampleIndices.end());
330                 
331                 int index = 0;
332                 map<string, vector<int> > randomizedGroups = origMapping;
333                 for(it=randomizedGroups.begin();it!=randomizedGroups.end();it++){
334                         for(int i=0;i<it->second.size();i++){
335                                 it->second[i] = sampleIndices[index++];                         
336                         }
337                 }
338
339                 return randomizedGroups;                
340         }
341         catch (exception& e) {
342                 m->errorOut(e, "AmovaCommand", "getRandomizedGroups");
343                 exit(1);
344         }
345 }
346
347 //**********************************************************************************************************************
348
349 double AmovaCommand::calcSSTotal(map<string, vector<int> >& groupSampleMap) {
350         try {
351                 
352                 vector<int> indices;
353                 map<string, vector<int> >::iterator it;
354                 for(it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
355                         indices.insert(indices.end(), it->second.begin(), it->second.end());                    
356                 }
357                 sort(indices.begin(), indices.end());
358                         
359                 int numIndices =indices.size();
360                 double ssTotal = 0.0;
361                 
362                 for(int i=1;i<numIndices;i++){
363                         int row = indices[i];
364                         
365                         for(int j=0;j<i;j++){
366                                 ssTotal += distanceMatrix[row][indices[j]];
367                         }
368                 }
369                 ssTotal /= numIndices;
370                         
371                 return ssTotal;
372         }
373         catch(exception& e) {
374                 m->errorOut(e, "AmovaCommand", "calcSSTotal");
375                 exit(1);
376         }
377 }
378
379 //**********************************************************************************************************************
380
381 double AmovaCommand::calcSSWithin(map<string, vector<int> >& groupSampleMap) {
382         try {
383
384                 double ssWithin = 0.0;
385                 
386                 map<string, vector<int> >::iterator it;
387                 for(it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
388                         
389                         double withinGroup = 0;
390                         
391                         vector<int> samples = it->second;
392                         
393                         for(int i=0;i<samples.size();i++){
394                                 int row = samples[i];
395
396                                 for(int j=0;j<samples.size();j++){
397                                         int col = samples[j];
398
399                                         if(col < row){
400                                                 withinGroup += distanceMatrix[row][col];
401                                         }
402                                         
403                                 }
404                         }
405
406                         ssWithin += withinGroup / samples.size();
407                 }
408
409                 return ssWithin;
410         }
411         catch(exception& e) {
412                 m->errorOut(e, "AmovaCommand", "calcSSWithin");
413                 exit(1);
414         }
415 }
416
417 //**********************************************************************************************************************