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") { phylipFileName = ""; }
119 else if (designFileName == "not found") {
121 m->mothurOut("You must provide an phylip file.");
122 m->mothurOutEndLine();
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") {
131 m->mothurOut("You must provide an design file.");
132 m->mothurOutEndLine();
136 string temp = validParameter.validFile(parameters, "iters", false);
137 if (temp == "not found") { temp = "1000"; }
138 convert(temp, iters);
140 temp = validParameter.validFile(parameters, "alpha", false);
141 if (temp == "not found") { temp = "0.05"; }
142 convert(temp, experimentwiseAlpha);
145 catch(exception& e) {
146 m->errorOut(e, "AmovaCommand", "AmovaCommand");
151 //**********************************************************************************************************************
153 void AmovaCommand::help(){
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");
164 catch(exception& e) {
165 m->errorOut(e, "AmovaCommand", "help");
170 //**********************************************************************************************************************
172 AmovaCommand::~AmovaCommand(){}
174 //**********************************************************************************************************************
176 int AmovaCommand::execute(){
179 if (abort == true) { if (calledHelp) { return 0; } return 2; }
182 designMap = new GroupMap(designFileName);
183 designMap->readDesignMap();
185 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
187 //read in distance matrix and square it
188 ReadPhylipVector readMatrix(phylipFileName);
189 vector<string> sampleNames = readMatrix.read(distanceMatrix);
191 for(int i=0;i<distanceMatrix.size();i++){
192 for(int j=0;j<i;j++){
193 distanceMatrix[i][j] *= distanceMatrix[i][j];
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);
202 int numGroups = origGroupSampleMap.size();
204 //create a new filename
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);
210 double fullANOVAPValue = runAMOVA(AMOVAFile, origGroupSampleMap, experimentwiseAlpha);
211 if(fullANOVAPValue <= experimentwiseAlpha && numGroups > 2){
213 int numCombos = numGroups * (numGroups-1) / 2;
214 double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
216 map<string, vector<int> >::iterator itA;
217 map<string, vector<int> >::iterator itB;
219 for(itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
221 for(itB;itB!=origGroupSampleMap.end();itB++){
223 map<string, vector<int> > pairwiseGroupSampleMap;
224 pairwiseGroupSampleMap[itA->first] = itA->second;
225 pairwiseGroupSampleMap[itB->first] = itB->second;
227 runAMOVA(AMOVAFile, pairwiseGroupSampleMap, pairwiseAlpha);
230 m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
231 m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
234 m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
236 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
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();
248 catch(exception& e) {
249 m->errorOut(e, "AmovaCommand", "execute");
254 //**********************************************************************************************************************
256 double AmovaCommand::runAMOVA(ofstream& AMOVAFile, map<string, vector<int> > groupSampleMap, double alpha) {
258 map<string, vector<int> >::iterator it;
260 int numGroups = groupSampleMap.size();
261 int totalNumSamples = 0;
263 for(it = groupSampleMap.begin();it!=groupSampleMap.end();it++){
264 totalNumSamples += it->second.size();
267 double ssTotalOrig = calcSSTotal(groupSampleMap);
268 double ssWithinOrig = calcSSWithin(groupSampleMap);
269 double ssAmongOrig = ssTotalOrig - ssWithinOrig;
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++; }
278 double pValue = (double)counter / (double) iters;
280 if(pValue < 1/(double)iters){ pString = '<' + toString(1/(double)iters); }
281 else { pString = toString(pValue); }
285 it = groupSampleMap.begin();
286 AMOVAFile << it->first;
287 m->mothurOut(it->first);
289 for(it;it!=groupSampleMap.end();it++){
290 AMOVAFile << '-' << it->first;
291 m->mothurOut('-' + it->first);
294 AMOVAFile << "\tAmong\tWithin\tTotal" << endl;
295 m->mothurOut("\tAmong\tWithin\tTotal\n");
297 AMOVAFile << "SS\t" << ssAmongOrig << '\t' << ssWithinOrig << '\t' << ssTotalOrig << endl;
298 m->mothurOut("SS\t" + toString(ssAmongOrig) + '\t' + toString(ssWithinOrig) + '\t' + toString(ssTotalOrig) + '\n');
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;
304 AMOVAFile << "df\t" << dfAmong << '\t' << dfWithin << '\t' << dfTotal << endl;
305 m->mothurOut("df\t" + toString(dfAmong) + '\t' + toString(dfWithin) + '\t' + toString(dfTotal) + '\n');
307 AMOVAFile << "MS\t" << MSAmong << '\t' << MSWithin << endl << endl;
308 m->mothurOut("MS\t" + toString(MSAmong) + '\t' + toString(MSWithin) + "\n\n");
310 AMOVAFile << "Fs:\t" << Fs << endl;
311 m->mothurOut("Fs:\t" + toString(Fs) + '\n');
313 AMOVAFile << "p-value: " << pString;
314 m->mothurOut("p-value: " + pString);
320 AMOVAFile << endl << endl;
321 m->mothurOutEndLine();m->mothurOutEndLine();
325 catch(exception& e) {
326 m->errorOut(e, "AmovaCommand", "runAMOVA");
331 //**********************************************************************************************************************
333 map<string, vector<int> > AmovaCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
335 vector<int> sampleIndices;
336 vector<int> samplesPerGroup;
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());
345 random_shuffle(sampleIndices.begin(), sampleIndices.end());
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++];
355 return randomizedGroups;
357 catch (exception& e) {
358 m->errorOut(e, "AmovaCommand", "getRandomizedGroups");
363 //**********************************************************************************************************************
365 double AmovaCommand::calcSSTotal(map<string, vector<int> >& groupSampleMap) {
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());
373 sort(indices.begin(), indices.end());
375 int numIndices =indices.size();
376 double ssTotal = 0.0;
378 for(int i=1;i<numIndices;i++){
379 int row = indices[i];
381 for(int j=0;j<i;j++){
382 ssTotal += distanceMatrix[row][indices[j]];
385 ssTotal /= numIndices;
389 catch(exception& e) {
390 m->errorOut(e, "AmovaCommand", "calcSSTotal");
395 //**********************************************************************************************************************
397 double AmovaCommand::calcSSWithin(map<string, vector<int> >& groupSampleMap) {
400 double ssWithin = 0.0;
402 map<string, vector<int> >::iterator it;
403 for(it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
405 double withinGroup = 0;
407 vector<int> samples = it->second;
409 for(int i=0;i<samples.size();i++){
410 int row = samples[i];
412 for(int j=0;j<samples.size();j++){
413 int col = samples[j];
416 withinGroup += distanceMatrix[row][col];
422 ssWithin += withinGroup / samples.size();
427 catch(exception& e) {
428 m->errorOut(e, "AmovaCommand", "calcSSWithin");
433 //**********************************************************************************************************************