]> git.donarmstrong.com Git - mothur.git/blob - amovacommand.cpp
working on current change
[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                         origGroupSampleMap[designMap->getGroup(sampleNames[i])].push_back(i);
178                 }
179                 int numGroups = origGroupSampleMap.size();
180                 
181                 //create a new filename
182                 ofstream AMOVAFile;
183                 string AMOVAFileName = outputDir + m->getRootName(m->getSimpleName(phylipFileName))  + "amova";                         
184                 m->openOutputFile(AMOVAFileName, AMOVAFile);
185                 outputNames.push_back(AMOVAFileName); outputTypes["amova"].push_back(AMOVAFileName);
186                 
187                 double fullANOVAPValue = runAMOVA(AMOVAFile, origGroupSampleMap, experimentwiseAlpha);
188                 if(fullANOVAPValue <= experimentwiseAlpha && numGroups > 2){
189                         
190                         int numCombos = numGroups * (numGroups-1) / 2;
191                         double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
192                         
193                         map<string, vector<int> >::iterator itA;
194                         map<string, vector<int> >::iterator itB;
195                         
196                         for(itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
197                                 itB = itA;itB++;
198                                 for(itB;itB!=origGroupSampleMap.end();itB++){
199                                         
200                                         map<string, vector<int> > pairwiseGroupSampleMap;
201                                         pairwiseGroupSampleMap[itA->first] = itA->second;
202                                         pairwiseGroupSampleMap[itB->first] = itB->second;
203                                         
204                                         runAMOVA(AMOVAFile, pairwiseGroupSampleMap, pairwiseAlpha);
205                                 }                       
206                         }
207                         m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
208                         m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
209                 }
210                 else{
211                         m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
212                 }
213                 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
214                 AMOVAFile.close();
215                 
216                 delete designMap;
217          
218                 m->mothurOutEndLine();
219                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
220                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
221                 m->mothurOutEndLine();
222                 
223                 return 0;
224         }
225         catch(exception& e) {
226                 m->errorOut(e, "AmovaCommand", "execute");
227                 exit(1);
228         }
229 }
230
231 //**********************************************************************************************************************
232
233 double AmovaCommand::runAMOVA(ofstream& AMOVAFile, map<string, vector<int> > groupSampleMap, double alpha) {
234         try {
235                 map<string, vector<int> >::iterator it;
236
237                 int numGroups = groupSampleMap.size();
238                 int totalNumSamples = 0;
239
240                 for(it = groupSampleMap.begin();it!=groupSampleMap.end();it++){
241                         totalNumSamples += it->second.size();                   
242                 }
243
244                 double ssTotalOrig = calcSSTotal(groupSampleMap);
245                 double ssWithinOrig = calcSSWithin(groupSampleMap);
246                 double ssAmongOrig = ssTotalOrig - ssWithinOrig;
247                 
248                 double counter = 0;
249                 for(int i=0;i<iters;i++){
250                         map<string, vector<int> > randomizedGroup = getRandomizedGroups(groupSampleMap);
251                         double ssWithinRand = calcSSWithin(randomizedGroup);
252                         if(ssWithinRand < ssWithinOrig){        counter++;      }
253                 }
254                 
255                 double pValue = (double)counter / (double) iters;
256                 string pString = "";
257                 if(pValue < 1/(double)iters){   pString = '<' + toString(1/(double)iters);      }
258                 else                                            {       pString = toString(pValue);                                     }
259                 
260                 
261                 //print anova table
262                 it = groupSampleMap.begin();
263                 AMOVAFile << it->first;
264                 m->mothurOut(it->first);
265                 it++;
266                 for(it;it!=groupSampleMap.end();it++){
267                         AMOVAFile << '-' << it->first;
268                         m->mothurOut('-' + it->first);
269                 }
270                 
271                 AMOVAFile << "\tAmong\tWithin\tTotal" << endl;
272                 m->mothurOut("\tAmong\tWithin\tTotal\n");
273                 
274                 AMOVAFile << "SS\t" << ssAmongOrig << '\t' << ssWithinOrig << '\t' << ssTotalOrig << endl;
275                 m->mothurOut("SS\t" + toString(ssAmongOrig) + '\t' + toString(ssWithinOrig) + '\t' + toString(ssTotalOrig) + '\n');
276                 
277                 int dfAmong = numGroups - 1;                            double MSAmong = ssAmongOrig / (double) dfAmong;
278                 int dfWithin = totalNumSamples - numGroups;     double MSWithin = ssWithinOrig / (double) dfWithin;
279                 int dfTotal = totalNumSamples - 1;                      double Fs = MSAmong / MSWithin;
280                 
281                 AMOVAFile << "df\t" << dfAmong << '\t' << dfWithin << '\t' << dfTotal << endl;
282                 m->mothurOut("df\t" + toString(dfAmong) + '\t' + toString(dfWithin) + '\t' + toString(dfTotal) + '\n');
283
284                 AMOVAFile << "MS\t" << MSAmong << '\t' << MSWithin << endl << endl;
285                 m->mothurOut("MS\t" + toString(MSAmong) + '\t' + toString(MSWithin) + "\n\n");
286
287                 AMOVAFile << "Fs:\t" << Fs << endl;
288                 m->mothurOut("Fs:\t" + toString(Fs) + '\n');
289                 
290                 AMOVAFile << "p-value: " << pString;
291                 m->mothurOut("p-value: " + pString);
292
293                 if(pValue < alpha){
294                         AMOVAFile << "*";
295                         m->mothurOut("*");
296                 }
297                 AMOVAFile << endl << endl;
298                 m->mothurOutEndLine();m->mothurOutEndLine();
299
300                 return pValue;
301         }
302         catch(exception& e) {
303                 m->errorOut(e, "AmovaCommand", "runAMOVA");
304                 exit(1);
305         }
306 }
307
308 //**********************************************************************************************************************
309
310 map<string, vector<int> > AmovaCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
311         try{
312                 vector<int> sampleIndices;
313                 vector<int> samplesPerGroup;
314                 
315                 map<string, vector<int> >::iterator it;
316                 for(it=origMapping.begin();it!=origMapping.end();it++){
317                         vector<int> indices = it->second;
318                         samplesPerGroup.push_back(indices.size());
319                         sampleIndices.insert(sampleIndices.end(), indices.begin(), indices.end());
320                 }
321                 
322                 random_shuffle(sampleIndices.begin(), sampleIndices.end());
323                 
324                 int index = 0;
325                 map<string, vector<int> > randomizedGroups = origMapping;
326                 for(it=randomizedGroups.begin();it!=randomizedGroups.end();it++){
327                         for(int i=0;i<it->second.size();i++){
328                                 it->second[i] = sampleIndices[index++];                         
329                         }
330                 }
331
332                 return randomizedGroups;                
333         }
334         catch (exception& e) {
335                 m->errorOut(e, "AmovaCommand", "getRandomizedGroups");
336                 exit(1);
337         }
338 }
339
340 //**********************************************************************************************************************
341
342 double AmovaCommand::calcSSTotal(map<string, vector<int> >& groupSampleMap) {
343         try {
344                 
345                 vector<int> indices;
346                 map<string, vector<int> >::iterator it;
347                 for(it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
348                         indices.insert(indices.end(), it->second.begin(), it->second.end());                    
349                 }
350                 sort(indices.begin(), indices.end());
351                         
352                 int numIndices =indices.size();
353                 double ssTotal = 0.0;
354                 
355                 for(int i=1;i<numIndices;i++){
356                         int row = indices[i];
357                         
358                         for(int j=0;j<i;j++){
359                                 ssTotal += distanceMatrix[row][indices[j]];
360                         }
361                 }
362                 ssTotal /= numIndices;
363                         
364                 return ssTotal;
365         }
366         catch(exception& e) {
367                 m->errorOut(e, "AmovaCommand", "calcSSTotal");
368                 exit(1);
369         }
370 }
371
372 //**********************************************************************************************************************
373
374 double AmovaCommand::calcSSWithin(map<string, vector<int> >& groupSampleMap) {
375         try {
376
377                 double ssWithin = 0.0;
378                 
379                 map<string, vector<int> >::iterator it;
380                 for(it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
381                         
382                         double withinGroup = 0;
383                         
384                         vector<int> samples = it->second;
385                         
386                         for(int i=0;i<samples.size();i++){
387                                 int row = samples[i];
388
389                                 for(int j=0;j<samples.size();j++){
390                                         int col = samples[j];
391
392                                         if(col < row){
393                                                 withinGroup += distanceMatrix[row][col];
394                                         }
395                                         
396                                 }
397                         }
398
399                         ssWithin += withinGroup / samples.size();
400                 }
401
402                 return ssWithin;
403         }
404         catch(exception& e) {
405                 m->errorOut(e, "AmovaCommand", "calcSSWithin");
406                 exit(1);
407         }
408 }
409
410 //**********************************************************************************************************************