]> git.donarmstrong.com Git - mothur.git/blob - amovacommand.cpp
added set.current and get.current commands and modified existing commands to update...
[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") { 
119                                 phylipFileName = ""; 
120                         }       
121                         
122                         //check for required parameters
123                         designFileName = validParameter.validFile(parameters, "design", true);
124                         if (designFileName == "not open") { abort = true; }
125                         else if (designFileName == "not found") {
126                                 designFileName = "";
127                         }       
128
129                         string temp = validParameter.validFile(parameters, "iters", false);
130                         if (temp == "not found") { temp = "1000"; }
131                         convert(temp, iters); 
132                         
133                         temp = validParameter.validFile(parameters, "alpha", false);
134                         if (temp == "not found") { temp = "0.05"; }
135                         convert(temp, experimentwiseAlpha); 
136                 }
137         }
138         catch(exception& e) {
139                 m->errorOut(e, "AmovaCommand", "AmovaCommand");
140                 exit(1);
141         }
142 }
143
144 //**********************************************************************************************************************
145
146 void AmovaCommand::help(){
147         try {
148                 m->mothurOut("Referenced: Anderson MJ (2001). A new method for non-parametric multivariate analysis of variance. Austral Ecol 26: 32-46.\n");
149                 m->mothurOut("The amova command outputs a .amova file. \n");
150                 m->mothurOut("The amova command parameters are phylip, iters, and alpha.  The phylip and design parameters are required.\n");
151                 m->mothurOut("The design parameter allows you to assign your samples to groups when you are running amova. It is required. \n");
152                 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");
153                 m->mothurOut("The iters parameter allows you to set number of randomization for the P value.  The default is 1000. \n");
154                 m->mothurOut("The amova command should be in the following format: amova(phylip=file.dist, design=file.design).\n");
155                 m->mothurOut("Note: No spaces between parameter labels (i.e. iters), '=' and parameters (i.e. 1000).\n\n");
156         }
157         catch(exception& e) {
158                 m->errorOut(e, "AmovaCommand", "help");
159                 exit(1);
160         }
161 }
162
163 //**********************************************************************************************************************
164
165 AmovaCommand::~AmovaCommand(){}
166
167 //**********************************************************************************************************************
168
169 int AmovaCommand::execute(){
170         try {
171                 
172                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
173                 
174                 //read design file
175                 designMap = new GroupMap(designFileName);
176                 designMap->readDesignMap();
177
178                 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
179                                                 
180                 //read in distance matrix and square it
181                 ReadPhylipVector readMatrix(phylipFileName);
182                 vector<string> sampleNames = readMatrix.read(distanceMatrix);
183                 
184                 for(int i=0;i<distanceMatrix.size();i++){
185                         for(int j=0;j<i;j++){
186                                 distanceMatrix[i][j] *= distanceMatrix[i][j];   
187                         }
188                 }
189                 
190                 //link designMap to rows/columns in distance matrix
191                 map<string, vector<int> > origGroupSampleMap;
192                 for(int i=0;i<sampleNames.size();i++){
193                         origGroupSampleMap[designMap->getGroup(sampleNames[i])].push_back(i);
194                 }
195                 int numGroups = origGroupSampleMap.size();
196                 
197                 //create a new filename
198                 ofstream AMOVAFile;
199                 string AMOVAFileName = outputDir + m->getRootName(m->getSimpleName(phylipFileName))  + "amova";                         
200                 m->openOutputFile(AMOVAFileName, AMOVAFile);
201                 outputNames.push_back(AMOVAFileName); outputTypes["amova"].push_back(AMOVAFileName);
202                 
203                 double fullANOVAPValue = runAMOVA(AMOVAFile, origGroupSampleMap, experimentwiseAlpha);
204                 if(fullANOVAPValue <= experimentwiseAlpha && numGroups > 2){
205                         
206                         int numCombos = numGroups * (numGroups-1) / 2;
207                         double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
208                         
209                         map<string, vector<int> >::iterator itA;
210                         map<string, vector<int> >::iterator itB;
211                         
212                         for(itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
213                                 itB = itA;itB++;
214                                 for(itB;itB!=origGroupSampleMap.end();itB++){
215                                         
216                                         map<string, vector<int> > pairwiseGroupSampleMap;
217                                         pairwiseGroupSampleMap[itA->first] = itA->second;
218                                         pairwiseGroupSampleMap[itB->first] = itB->second;
219                                         
220                                         runAMOVA(AMOVAFile, pairwiseGroupSampleMap, pairwiseAlpha);
221                                 }                       
222                         }
223                         m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
224                         m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
225                 }
226                 else{
227                         m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
228                 }
229                 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
230                 AMOVAFile.close();
231                 
232                 delete designMap;
233          
234                 m->mothurOutEndLine();
235                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
236                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
237                 m->mothurOutEndLine();
238                 
239                 return 0;
240         }
241         catch(exception& e) {
242                 m->errorOut(e, "AmovaCommand", "execute");
243                 exit(1);
244         }
245 }
246
247 //**********************************************************************************************************************
248
249 double AmovaCommand::runAMOVA(ofstream& AMOVAFile, map<string, vector<int> > groupSampleMap, double alpha) {
250         try {
251                 map<string, vector<int> >::iterator it;
252
253                 int numGroups = groupSampleMap.size();
254                 int totalNumSamples = 0;
255
256                 for(it = groupSampleMap.begin();it!=groupSampleMap.end();it++){
257                         totalNumSamples += it->second.size();                   
258                 }
259
260                 double ssTotalOrig = calcSSTotal(groupSampleMap);
261                 double ssWithinOrig = calcSSWithin(groupSampleMap);
262                 double ssAmongOrig = ssTotalOrig - ssWithinOrig;
263                 
264                 double counter = 0;
265                 for(int i=0;i<iters;i++){
266                         map<string, vector<int> > randomizedGroup = getRandomizedGroups(groupSampleMap);
267                         double ssWithinRand = calcSSWithin(randomizedGroup);
268                         if(ssWithinRand < ssWithinOrig){        counter++;      }
269                 }
270                 
271                 double pValue = (double)counter / (double) iters;
272                 string pString = "";
273                 if(pValue < 1/(double)iters){   pString = '<' + toString(1/(double)iters);      }
274                 else                                            {       pString = toString(pValue);                                     }
275                 
276                 
277                 //print anova table
278                 it = groupSampleMap.begin();
279                 AMOVAFile << it->first;
280                 m->mothurOut(it->first);
281                 it++;
282                 for(it;it!=groupSampleMap.end();it++){
283                         AMOVAFile << '-' << it->first;
284                         m->mothurOut('-' + it->first);
285                 }
286                 
287                 AMOVAFile << "\tAmong\tWithin\tTotal" << endl;
288                 m->mothurOut("\tAmong\tWithin\tTotal\n");
289                 
290                 AMOVAFile << "SS\t" << ssAmongOrig << '\t' << ssWithinOrig << '\t' << ssTotalOrig << endl;
291                 m->mothurOut("SS\t" + toString(ssAmongOrig) + '\t' + toString(ssWithinOrig) + '\t' + toString(ssTotalOrig) + '\n');
292                 
293                 int dfAmong = numGroups - 1;                            double MSAmong = ssAmongOrig / (double) dfAmong;
294                 int dfWithin = totalNumSamples - numGroups;     double MSWithin = ssWithinOrig / (double) dfWithin;
295                 int dfTotal = totalNumSamples - 1;                      double Fs = MSAmong / MSWithin;
296                 
297                 AMOVAFile << "df\t" << dfAmong << '\t' << dfWithin << '\t' << dfTotal << endl;
298                 m->mothurOut("df\t" + toString(dfAmong) + '\t' + toString(dfWithin) + '\t' + toString(dfTotal) + '\n');
299
300                 AMOVAFile << "MS\t" << MSAmong << '\t' << MSWithin << endl << endl;
301                 m->mothurOut("MS\t" + toString(MSAmong) + '\t' + toString(MSWithin) + "\n\n");
302
303                 AMOVAFile << "Fs:\t" << Fs << endl;
304                 m->mothurOut("Fs:\t" + toString(Fs) + '\n');
305                 
306                 AMOVAFile << "p-value: " << pString;
307                 m->mothurOut("p-value: " + pString);
308
309                 if(pValue < alpha){
310                         AMOVAFile << "*";
311                         m->mothurOut("*");
312                 }
313                 AMOVAFile << endl << endl;
314                 m->mothurOutEndLine();m->mothurOutEndLine();
315
316                 return pValue;
317         }
318         catch(exception& e) {
319                 m->errorOut(e, "AmovaCommand", "runAMOVA");
320                 exit(1);
321         }
322 }
323
324 //**********************************************************************************************************************
325
326 map<string, vector<int> > AmovaCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
327         try{
328                 vector<int> sampleIndices;
329                 vector<int> samplesPerGroup;
330                 
331                 map<string, vector<int> >::iterator it;
332                 for(it=origMapping.begin();it!=origMapping.end();it++){
333                         vector<int> indices = it->second;
334                         samplesPerGroup.push_back(indices.size());
335                         sampleIndices.insert(sampleIndices.end(), indices.begin(), indices.end());
336                 }
337                 
338                 random_shuffle(sampleIndices.begin(), sampleIndices.end());
339                 
340                 int index = 0;
341                 map<string, vector<int> > randomizedGroups = origMapping;
342                 for(it=randomizedGroups.begin();it!=randomizedGroups.end();it++){
343                         for(int i=0;i<it->second.size();i++){
344                                 it->second[i] = sampleIndices[index++];                         
345                         }
346                 }
347
348                 return randomizedGroups;                
349         }
350         catch (exception& e) {
351                 m->errorOut(e, "AmovaCommand", "getRandomizedGroups");
352                 exit(1);
353         }
354 }
355
356 //**********************************************************************************************************************
357
358 double AmovaCommand::calcSSTotal(map<string, vector<int> >& groupSampleMap) {
359         try {
360                 
361                 vector<int> indices;
362                 map<string, vector<int> >::iterator it;
363                 for(it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
364                         indices.insert(indices.end(), it->second.begin(), it->second.end());                    
365                 }
366                 sort(indices.begin(), indices.end());
367                         
368                 int numIndices =indices.size();
369                 double ssTotal = 0.0;
370                 
371                 for(int i=1;i<numIndices;i++){
372                         int row = indices[i];
373                         
374                         for(int j=0;j<i;j++){
375                                 ssTotal += distanceMatrix[row][indices[j]];
376                         }
377                 }
378                 ssTotal /= numIndices;
379                         
380                 return ssTotal;
381         }
382         catch(exception& e) {
383                 m->errorOut(e, "AmovaCommand", "calcSSTotal");
384                 exit(1);
385         }
386 }
387
388 //**********************************************************************************************************************
389
390 double AmovaCommand::calcSSWithin(map<string, vector<int> >& groupSampleMap) {
391         try {
392
393                 double ssWithin = 0.0;
394                 
395                 map<string, vector<int> >::iterator it;
396                 for(it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
397                         
398                         double withinGroup = 0;
399                         
400                         vector<int> samples = it->second;
401                         
402                         for(int i=0;i<samples.size();i++){
403                                 int row = samples[i];
404
405                                 for(int j=0;j<samples.size();j++){
406                                         int col = samples[j];
407
408                                         if(col < row){
409                                                 withinGroup += distanceMatrix[row][col];
410                                         }
411                                         
412                                 }
413                         }
414
415                         ssWithin += withinGroup / samples.size();
416                 }
417
418                 return ssWithin;
419         }
420         catch(exception& e) {
421                 m->errorOut(e, "AmovaCommand", "calcSSWithin");
422                 exit(1);
423         }
424 }
425
426 //**********************************************************************************************************************