5 * Created by westcott on 2/7/11.
6 * Copyright 2011 Schloss Lab. All rights reserved.
10 #include "amovacommand.h"
11 #include "readphylipvector.h"
15 //**********************************************************************************************************************
16 vector<string> AmovaCommand::setParameters(){
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);
25 vector<string> myArray;
26 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
30 m->errorOut(e, "AmovaCommand", "setParameters");
34 //**********************************************************************************************************************
35 string AmovaCommand::getHelpString(){
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).";
49 m->errorOut(e, "AmovaCommand", "getHelpString");
53 //**********************************************************************************************************************
54 AmovaCommand::AmovaCommand(){
56 abort = true; calledHelp = true;
58 vector<string> tempOutNames;
59 outputTypes["amova"] = tempOutNames;
62 m->errorOut(e, "AmovaCommand", "AmovaCommand");
66 //**********************************************************************************************************************
67 AmovaCommand::AmovaCommand(string option) {
69 abort = false; calledHelp = false;
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;}
76 vector<string> myArray = setParameters();
78 OptionParser parser(option);
79 map<string,string> parameters = parser.getParameters();
81 ValidParameters validParameter;
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; }
89 //initialize outputTypes
90 vector<string> tempOutNames;
91 outputTypes["amova"] = tempOutNames;
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 = ""; }
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 = ""; }
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; }
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; }
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); }
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); }
137 string temp = validParameter.validFile(parameters, "iters", false);
138 if (temp == "not found") { temp = "1000"; }
139 m->mothurConvert(temp, iters);
141 temp = validParameter.validFile(parameters, "alpha", false);
142 if (temp == "not found") { temp = "0.05"; }
143 m->mothurConvert(temp, experimentwiseAlpha);
146 catch(exception& e) {
147 m->errorOut(e, "AmovaCommand", "AmovaCommand");
151 //**********************************************************************************************************************
153 int AmovaCommand::execute(){
156 if (abort == true) { if (calledHelp) { return 0; } return 2; }
159 designMap = new GroupMap(designFileName);
160 designMap->readDesignMap();
162 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
164 //read in distance matrix and square it
165 ReadPhylipVector readMatrix(phylipFileName);
166 vector<string> sampleNames = readMatrix.read(distanceMatrix);
168 for(int i=0;i<distanceMatrix.size();i++){
169 for(int j=0;j<i;j++){
170 distanceMatrix[i][j] *= distanceMatrix[i][j];
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 string group = designMap->getGroup(sampleNames[i]);
179 if (group == "not found") {
180 m->mothurOut("[ERROR]: " + sampleNames[i] + " is not in your design file, please correct."); m->mothurOutEndLine(); m->control_pressed = true;
181 }else { origGroupSampleMap[group].push_back(i); }
184 int numGroups = origGroupSampleMap.size();
186 if (m->control_pressed) { delete designMap; return 0; }
188 //create a new filename
190 string AMOVAFileName = outputDir + m->getRootName(m->getSimpleName(phylipFileName)) + "amova";
191 m->openOutputFile(AMOVAFileName, AMOVAFile);
192 outputNames.push_back(AMOVAFileName); outputTypes["amova"].push_back(AMOVAFileName);
194 double fullANOVAPValue = runAMOVA(AMOVAFile, origGroupSampleMap, experimentwiseAlpha);
195 if(fullANOVAPValue <= experimentwiseAlpha && numGroups > 2){
197 int numCombos = numGroups * (numGroups-1) / 2;
198 double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
200 map<string, vector<int> >::iterator itA;
201 map<string, vector<int> >::iterator itB;
203 for(itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
205 for(itB;itB!=origGroupSampleMap.end();itB++){
207 map<string, vector<int> > pairwiseGroupSampleMap;
208 pairwiseGroupSampleMap[itA->first] = itA->second;
209 pairwiseGroupSampleMap[itB->first] = itB->second;
211 runAMOVA(AMOVAFile, pairwiseGroupSampleMap, pairwiseAlpha);
214 m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
215 m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
218 m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
220 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
225 m->mothurOutEndLine();
226 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
227 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
228 m->mothurOutEndLine();
232 catch(exception& e) {
233 m->errorOut(e, "AmovaCommand", "execute");
238 //**********************************************************************************************************************
240 double AmovaCommand::runAMOVA(ofstream& AMOVAFile, map<string, vector<int> > groupSampleMap, double alpha) {
242 map<string, vector<int> >::iterator it;
244 int numGroups = groupSampleMap.size();
245 int totalNumSamples = 0;
247 for(it = groupSampleMap.begin();it!=groupSampleMap.end();it++){
248 totalNumSamples += it->second.size();
251 double ssTotalOrig = calcSSTotal(groupSampleMap);
252 double ssWithinOrig = calcSSWithin(groupSampleMap);
253 double ssAmongOrig = ssTotalOrig - ssWithinOrig;
256 for(int i=0;i<iters;i++){
257 map<string, vector<int> > randomizedGroup = getRandomizedGroups(groupSampleMap);
258 double ssWithinRand = calcSSWithin(randomizedGroup);
259 if(ssWithinRand < ssWithinOrig){ counter++; }
262 double pValue = (double)counter / (double) iters;
264 if(pValue < 1/(double)iters){ pString = '<' + toString(1/(double)iters); }
265 else { pString = toString(pValue); }
269 it = groupSampleMap.begin();
270 AMOVAFile << it->first;
271 m->mothurOut(it->first);
273 for(it;it!=groupSampleMap.end();it++){
274 AMOVAFile << '-' << it->first;
275 m->mothurOut('-' + it->first);
278 AMOVAFile << "\tAmong\tWithin\tTotal" << endl;
279 m->mothurOut("\tAmong\tWithin\tTotal\n");
281 AMOVAFile << "SS\t" << ssAmongOrig << '\t' << ssWithinOrig << '\t' << ssTotalOrig << endl;
282 m->mothurOut("SS\t" + toString(ssAmongOrig) + '\t' + toString(ssWithinOrig) + '\t' + toString(ssTotalOrig) + '\n');
284 int dfAmong = numGroups - 1; double MSAmong = ssAmongOrig / (double) dfAmong;
285 int dfWithin = totalNumSamples - numGroups; double MSWithin = ssWithinOrig / (double) dfWithin;
286 int dfTotal = totalNumSamples - 1; double Fs = MSAmong / MSWithin;
288 AMOVAFile << "df\t" << dfAmong << '\t' << dfWithin << '\t' << dfTotal << endl;
289 m->mothurOut("df\t" + toString(dfAmong) + '\t' + toString(dfWithin) + '\t' + toString(dfTotal) + '\n');
291 AMOVAFile << "MS\t" << MSAmong << '\t' << MSWithin << endl << endl;
292 m->mothurOut("MS\t" + toString(MSAmong) + '\t' + toString(MSWithin) + "\n\n");
294 AMOVAFile << "Fs:\t" << Fs << endl;
295 m->mothurOut("Fs:\t" + toString(Fs) + '\n');
297 AMOVAFile << "p-value: " << pString;
298 m->mothurOut("p-value: " + pString);
304 AMOVAFile << endl << endl;
305 m->mothurOutEndLine();m->mothurOutEndLine();
309 catch(exception& e) {
310 m->errorOut(e, "AmovaCommand", "runAMOVA");
315 //**********************************************************************************************************************
317 map<string, vector<int> > AmovaCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
319 vector<int> sampleIndices;
320 vector<int> samplesPerGroup;
322 map<string, vector<int> >::iterator it;
323 for(it=origMapping.begin();it!=origMapping.end();it++){
324 vector<int> indices = it->second;
325 samplesPerGroup.push_back(indices.size());
326 sampleIndices.insert(sampleIndices.end(), indices.begin(), indices.end());
329 random_shuffle(sampleIndices.begin(), sampleIndices.end());
332 map<string, vector<int> > randomizedGroups = origMapping;
333 for(it=randomizedGroups.begin();it!=randomizedGroups.end();it++){
334 for(int i=0;i<it->second.size();i++){
335 it->second[i] = sampleIndices[index++];
339 return randomizedGroups;
341 catch (exception& e) {
342 m->errorOut(e, "AmovaCommand", "getRandomizedGroups");
347 //**********************************************************************************************************************
349 double AmovaCommand::calcSSTotal(map<string, vector<int> >& groupSampleMap) {
353 map<string, vector<int> >::iterator it;
354 for(it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
355 indices.insert(indices.end(), it->second.begin(), it->second.end());
357 sort(indices.begin(), indices.end());
359 int numIndices =indices.size();
360 double ssTotal = 0.0;
362 for(int i=1;i<numIndices;i++){
363 int row = indices[i];
365 for(int j=0;j<i;j++){
366 ssTotal += distanceMatrix[row][indices[j]];
369 ssTotal /= numIndices;
373 catch(exception& e) {
374 m->errorOut(e, "AmovaCommand", "calcSSTotal");
379 //**********************************************************************************************************************
381 double AmovaCommand::calcSSWithin(map<string, vector<int> >& groupSampleMap) {
384 double ssWithin = 0.0;
386 map<string, vector<int> >::iterator it;
387 for(it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
389 double withinGroup = 0;
391 vector<int> samples = it->second;
393 for(int i=0;i<samples.size();i++){
394 int row = samples[i];
396 for(int j=0;j<samples.size();j++){
397 int col = samples[j];
400 withinGroup += distanceMatrix[row][col];
406 ssWithin += withinGroup / samples.size();
411 catch(exception& e) {
412 m->errorOut(e, "AmovaCommand", "calcSSWithin");
417 //**********************************************************************************************************************