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