5 * Created by westcott on 2/7/11.
6 * Copyright 2011 Schloss Lab. All rights reserved.
10 #include "amovacommand.h"
11 #include "readphylipvector.h"
14 //**********************************************************************************************************************
15 vector<string> AmovaCommand::getValidParameters(){
17 string Array[] = {"outputdir","iters","phylip","design","alpha", "inputdir"};
18 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
22 m->errorOut(e, "AmovaCommand", "getValidParameters");
26 //**********************************************************************************************************************
27 AmovaCommand::AmovaCommand(){
29 abort = true; calledHelp = true;
30 vector<string> tempOutNames;
31 outputTypes["amova"] = tempOutNames;
34 m->errorOut(e, "AmovaCommand", "AmovaCommand");
38 //**********************************************************************************************************************
39 vector<string> AmovaCommand::getRequiredParameters(){
41 string Array[] = {"design"};
42 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
46 m->errorOut(e, "AmovaCommand", "getRequiredParameters");
50 //**********************************************************************************************************************
51 vector<string> AmovaCommand::getRequiredFiles(){
54 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
58 m->errorOut(e, "AmovaCommand", "getRequiredFiles");
62 //**********************************************************************************************************************
64 AmovaCommand::AmovaCommand(string option) {
66 abort = false; calledHelp = false;
68 //allow user to run help
69 if(option == "help") { help(); abort = true; calledHelp = true; }
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)));
76 OptionParser parser(option);
77 map<string,string> parameters = parser.getParameters();
79 ValidParameters validParameter;
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; }
87 //initialize outputTypes
88 vector<string> tempOutNames;
89 outputTypes["amova"] = tempOutNames;
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 = ""; }
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 = ""; }
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; }
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; }
116 phylipFileName = validParameter.validFile(parameters, "phylip", true);
117 if (phylipFileName == "not open") { phylipFileName = ""; abort = true; }
118 else if (phylipFileName == "not found") {
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") {
129 string temp = validParameter.validFile(parameters, "iters", false);
130 if (temp == "not found") { temp = "1000"; }
131 convert(temp, iters);
133 temp = validParameter.validFile(parameters, "alpha", false);
134 if (temp == "not found") { temp = "0.05"; }
135 convert(temp, experimentwiseAlpha);
138 catch(exception& e) {
139 m->errorOut(e, "AmovaCommand", "AmovaCommand");
144 //**********************************************************************************************************************
146 void AmovaCommand::help(){
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");
157 catch(exception& e) {
158 m->errorOut(e, "AmovaCommand", "help");
163 //**********************************************************************************************************************
165 AmovaCommand::~AmovaCommand(){}
167 //**********************************************************************************************************************
169 int AmovaCommand::execute(){
172 if (abort == true) { if (calledHelp) { return 0; } return 2; }
175 designMap = new GroupMap(designFileName);
176 designMap->readDesignMap();
178 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
180 //read in distance matrix and square it
181 ReadPhylipVector readMatrix(phylipFileName);
182 vector<string> sampleNames = readMatrix.read(distanceMatrix);
184 for(int i=0;i<distanceMatrix.size();i++){
185 for(int j=0;j<i;j++){
186 distanceMatrix[i][j] *= distanceMatrix[i][j];
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);
195 int numGroups = origGroupSampleMap.size();
197 //create a new filename
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);
203 double fullANOVAPValue = runAMOVA(AMOVAFile, origGroupSampleMap, experimentwiseAlpha);
204 if(fullANOVAPValue <= experimentwiseAlpha && numGroups > 2){
206 int numCombos = numGroups * (numGroups-1) / 2;
207 double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
209 map<string, vector<int> >::iterator itA;
210 map<string, vector<int> >::iterator itB;
212 for(itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
214 for(itB;itB!=origGroupSampleMap.end();itB++){
216 map<string, vector<int> > pairwiseGroupSampleMap;
217 pairwiseGroupSampleMap[itA->first] = itA->second;
218 pairwiseGroupSampleMap[itB->first] = itB->second;
220 runAMOVA(AMOVAFile, pairwiseGroupSampleMap, pairwiseAlpha);
223 m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
224 m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
227 m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
229 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
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();
241 catch(exception& e) {
242 m->errorOut(e, "AmovaCommand", "execute");
247 //**********************************************************************************************************************
249 double AmovaCommand::runAMOVA(ofstream& AMOVAFile, map<string, vector<int> > groupSampleMap, double alpha) {
251 map<string, vector<int> >::iterator it;
253 int numGroups = groupSampleMap.size();
254 int totalNumSamples = 0;
256 for(it = groupSampleMap.begin();it!=groupSampleMap.end();it++){
257 totalNumSamples += it->second.size();
260 double ssTotalOrig = calcSSTotal(groupSampleMap);
261 double ssWithinOrig = calcSSWithin(groupSampleMap);
262 double ssAmongOrig = ssTotalOrig - ssWithinOrig;
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++; }
271 double pValue = (double)counter / (double) iters;
273 if(pValue < 1/(double)iters){ pString = '<' + toString(1/(double)iters); }
274 else { pString = toString(pValue); }
278 it = groupSampleMap.begin();
279 AMOVAFile << it->first;
280 m->mothurOut(it->first);
282 for(it;it!=groupSampleMap.end();it++){
283 AMOVAFile << '-' << it->first;
284 m->mothurOut('-' + it->first);
287 AMOVAFile << "\tAmong\tWithin\tTotal" << endl;
288 m->mothurOut("\tAmong\tWithin\tTotal\n");
290 AMOVAFile << "SS\t" << ssAmongOrig << '\t' << ssWithinOrig << '\t' << ssTotalOrig << endl;
291 m->mothurOut("SS\t" + toString(ssAmongOrig) + '\t' + toString(ssWithinOrig) + '\t' + toString(ssTotalOrig) + '\n');
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;
297 AMOVAFile << "df\t" << dfAmong << '\t' << dfWithin << '\t' << dfTotal << endl;
298 m->mothurOut("df\t" + toString(dfAmong) + '\t' + toString(dfWithin) + '\t' + toString(dfTotal) + '\n');
300 AMOVAFile << "MS\t" << MSAmong << '\t' << MSWithin << endl << endl;
301 m->mothurOut("MS\t" + toString(MSAmong) + '\t' + toString(MSWithin) + "\n\n");
303 AMOVAFile << "Fs:\t" << Fs << endl;
304 m->mothurOut("Fs:\t" + toString(Fs) + '\n');
306 AMOVAFile << "p-value: " << pString;
307 m->mothurOut("p-value: " + pString);
313 AMOVAFile << endl << endl;
314 m->mothurOutEndLine();m->mothurOutEndLine();
318 catch(exception& e) {
319 m->errorOut(e, "AmovaCommand", "runAMOVA");
324 //**********************************************************************************************************************
326 map<string, vector<int> > AmovaCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
328 vector<int> sampleIndices;
329 vector<int> samplesPerGroup;
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());
338 random_shuffle(sampleIndices.begin(), sampleIndices.end());
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++];
348 return randomizedGroups;
350 catch (exception& e) {
351 m->errorOut(e, "AmovaCommand", "getRandomizedGroups");
356 //**********************************************************************************************************************
358 double AmovaCommand::calcSSTotal(map<string, vector<int> >& groupSampleMap) {
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());
366 sort(indices.begin(), indices.end());
368 int numIndices =indices.size();
369 double ssTotal = 0.0;
371 for(int i=1;i<numIndices;i++){
372 int row = indices[i];
374 for(int j=0;j<i;j++){
375 ssTotal += distanceMatrix[row][indices[j]];
378 ssTotal /= numIndices;
382 catch(exception& e) {
383 m->errorOut(e, "AmovaCommand", "calcSSTotal");
388 //**********************************************************************************************************************
390 double AmovaCommand::calcSSWithin(map<string, vector<int> >& groupSampleMap) {
393 double ssWithin = 0.0;
395 map<string, vector<int> >::iterator it;
396 for(it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
398 double withinGroup = 0;
400 vector<int> samples = it->second;
402 for(int i=0;i<samples.size();i++){
403 int row = samples[i];
405 for(int j=0;j<samples.size();j++){
406 int col = samples[j];
409 withinGroup += distanceMatrix[row][col];
415 ssWithin += withinGroup / samples.size();
420 catch(exception& e) {
421 m->errorOut(e, "AmovaCommand", "calcSSWithin");
426 //**********************************************************************************************************************