5 * Created by westcott on 2/14/11.
6 * Copyright 2011 Schloss Lab. All rights reserved.
10 #include "anosimcommand.h"
11 #include "inputdata.h"
12 #include "readphylipvector.h"
14 //**********************************************************************************************************************
15 vector<string> AnosimCommand::setParameters(){
17 CommandParameter pdesign("design", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pdesign);
18 CommandParameter pphylip("phylip", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pphylip);
19 CommandParameter piters("iters", "Number", "", "1000", "", "", "",false,false); parameters.push_back(piters);
20 CommandParameter palpha("alpha", "Number", "", "0.05", "", "", "",false,false); parameters.push_back(palpha);
21 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
22 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
24 vector<string> myArray;
25 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
29 m->errorOut(e, "AnosimCommand", "setParameters");
33 //**********************************************************************************************************************
34 string AnosimCommand::getHelpString(){
36 string helpString = "";
37 helpString += "Referenced: Clarke, K. R. (1993). Non-parametric multivariate analysis of changes in community structure. _Australian Journal of Ecology_ 18, 117-143.\n";
38 helpString += "The anosim command outputs a .anosim file. \n";
39 helpString += "The anosim command parameters are phylip, iters, and alpha. The phylip and design parameters are required, unless you have valid current files.\n";
40 helpString += "The design parameter allows you to assign your samples to groups when you are running anosim. It is required. \n";
41 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.\n";
42 helpString += "The iters parameter allows you to set number of randomization for the P value. The default is 1000. \n";
43 helpString += "The anosim command should be in the following format: anosim(phylip=file.dist, design=file.design).\n";
44 helpString += "Note: No spaces between parameter labels (i.e. iters), '=' and parameters (i.e. 1000).\n";
48 m->errorOut(e, "AnosimCommand", "getHelpString");
53 //**********************************************************************************************************************
54 AnosimCommand::AnosimCommand(){
56 abort = true; calledHelp = true;
58 vector<string> tempOutNames;
59 outputTypes["anosim"] = tempOutNames;
62 m->errorOut(e, "AnosimCommand", "AnosimCommand");
66 //**********************************************************************************************************************
68 AnosimCommand::AnosimCommand(string option) {
70 abort = false; calledHelp = false;
72 //allow user to run help
73 if(option == "help") { help(); 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["anosim"] = 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; }
128 //check for required parameters
129 designFileName = validParameter.validFile(parameters, "design", true);
130 if (designFileName == "not open") { abort = true; }
131 else if (designFileName == "not found") {
132 //if there is a current design file, use it
133 designFileName = m->getDesignFile();
134 if (designFileName != "") { m->mothurOut("Using " + designFileName + " as input file for the design parameter."); m->mothurOutEndLine(); }
135 else { m->mothurOut("You have no current design file and the design parameter is required."); m->mothurOutEndLine(); abort = true; }
138 string temp = validParameter.validFile(parameters, "iters", false);
139 if (temp == "not found") { temp = "1000"; }
140 convert(temp, iters);
142 temp = validParameter.validFile(parameters, "alpha", false);
143 if (temp == "not found") { temp = "0.05"; }
144 convert(temp, experimentwiseAlpha);
148 catch(exception& e) {
149 m->errorOut(e, "AnosimCommand", "AnosimCommand");
153 //**********************************************************************************************************************
154 int AnosimCommand::execute(){
157 if (abort == true) { if (calledHelp) { return 0; } return 2; }
160 designMap = new GroupMap(designFileName);
161 designMap->readDesignMap();
163 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
165 //read in distance matrix and square it
166 ReadPhylipVector readMatrix(phylipFileName);
167 vector<string> sampleNames = readMatrix.read(distanceMatrix);
169 for(int i=0;i<distanceMatrix.size();i++){
170 for(int j=0;j<i;j++){
171 distanceMatrix[i][j] *= distanceMatrix[i][j];
175 //link designMap to rows/columns in distance matrix
176 map<string, vector<int> > origGroupSampleMap;
177 for(int i=0;i<sampleNames.size();i++){
178 origGroupSampleMap[designMap->getGroup(sampleNames[i])].push_back(i);
180 int numGroups = origGroupSampleMap.size();
182 //create a new filename
184 string ANOSIMFileName = outputDir + m->getRootName(m->getSimpleName(phylipFileName)) + "anosim";
185 m->openOutputFile(ANOSIMFileName, ANOSIMFile);
186 outputNames.push_back(ANOSIMFileName); outputTypes["anosim"].push_back(ANOSIMFileName);
187 m->mothurOut("\ncomparison\tR-value\tP-value\n");
188 ANOSIMFile << "comparison\tR-value\tP-value\n";
191 double fullANOSIMPValue = runANOSIM(ANOSIMFile, distanceMatrix, origGroupSampleMap, experimentwiseAlpha);
194 if(fullANOSIMPValue <= experimentwiseAlpha && numGroups > 2){
196 int numCombos = numGroups * (numGroups-1) / 2;
197 double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
199 for(map<string, vector<int> >::iterator itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
200 map<string, vector<int> >::iterator itB = itA;
202 for(itB;itB!=origGroupSampleMap.end();itB++){
204 map<string, vector<int> > subGroupSampleMap;
206 subGroupSampleMap[itA->first] = itA->second; string groupA = itA->first;
207 subGroupSampleMap[itB->first] = itB->second; string groupB = itB->first;
209 vector<int> subIndices;
210 for(map<string, vector<int> >::iterator it=subGroupSampleMap.begin();it!=subGroupSampleMap.end();it++){
211 subIndices.insert(subIndices.end(), it->second.begin(), it->second.end());
213 int subNumSamples = subIndices.size();
215 sort(subIndices.begin(), subIndices.end());
217 vector<vector<double> > subDistMatrix(distanceMatrix.size());
218 for(int i=0;i<distanceMatrix.size();i++){
219 subDistMatrix[i].assign(distanceMatrix.size(), -1);
222 for(int i=0;i<subNumSamples;i++){
223 for(int j=0;j<i;j++){
224 subDistMatrix[subIndices[i]][subIndices[j]] = distanceMatrix[subIndices[i]][subIndices[j]];
228 runANOSIM(ANOSIMFile, subDistMatrix, subGroupSampleMap, pairwiseAlpha);
233 m->mothurOut("\nExperiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
234 m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
237 m->mothurOut("\nExperiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
239 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
245 m->mothurOutEndLine();
246 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
247 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
248 m->mothurOutEndLine();
252 catch(exception& e) {
253 m->errorOut(e, "AnosimCommand", "execute");
257 //**********************************************************************************************************************
259 double AnosimCommand::runANOSIM(ofstream& ANOSIMFile, vector<vector<double> > dMatrix, map<string, vector<int> > groupSampleMap, double alpha) {
263 vector<vector<double> > rankMatrix = convertToRanks(dMatrix);
264 double RValue = calcR(rankMatrix, groupSampleMap);
267 for(int i=0;i<iters;i++){
268 map<string, vector<int> > randGroupSampleMap = getRandomizedGroups(groupSampleMap);
269 double RValueRand = calcR(rankMatrix, randGroupSampleMap);
270 if(RValue <= RValueRand){ pCount++; }
273 double pValue = (double)pCount / (double) iters;
275 if(pValue < 1/(double)iters){ pString = '<' + toString(1/(double)iters); }
276 else { pString = toString(pValue); }
279 map<string, vector<int> >::iterator it=groupSampleMap.begin();
280 m->mothurOut(it->first);
281 ANOSIMFile << it->first;
283 for(it;it!=groupSampleMap.end();it++){
284 m->mothurOut('-' + it->first);
285 ANOSIMFile << '-' << it->first;
288 m->mothurOut('\t' + toString(RValue) + '\t' + pString);
289 ANOSIMFile << '\t' << RValue << '\t' << pString;
296 m->mothurOutEndLine();
300 catch(exception& e) {
301 m->errorOut(e, "AnosimCommand", "calcAnisom");
306 //**********************************************************************************************************************
308 double AnosimCommand::calcR(vector<vector<double> > rankMatrix, map<string, vector<int> > groupSampleMap){
312 for(map<string, vector<int> >::iterator it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
313 numSamples += it->second.size();
318 int numWithinComps = 0;
320 for(map<string, vector<int> >::iterator it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
321 vector<int> indices = it->second;
322 for(int i=0;i<indices.size();i++){
323 for(int j=0;j<i;j++){
324 if(indices[i] > indices[j]) { within += rankMatrix[indices[i]][indices[j]]; }
325 else { within += rankMatrix[indices[j]][indices[i]]; }
331 within /= (float) numWithinComps;
333 double between = 0.0;
334 int numBetweenComps = 0;
336 map<string, vector<int> >::iterator itB;
338 for(map<string, vector<int> >::iterator itA=groupSampleMap.begin();itA!=groupSampleMap.end();itA++){
340 for(int i=0;i<itA->second.size();i++){
341 int A = itA->second[i];
342 map<string, vector<int> >::iterator itB = itA;
344 for(itB;itB!=groupSampleMap.end();itB++){
345 for(int j=0;j<itB->second.size();j++){
346 int B = itB->second[j];
347 if(A>B) { between += rankMatrix[A][B]; }
348 else { between += rankMatrix[B][A]; }
357 between /= (float) numBetweenComps;
359 double Rvalue = (between - within)/(numSamples * (numSamples-1) / 4.0);
363 catch(exception& e) {
364 m->errorOut(e, "AnosimCommand", "calcWithinBetween");
369 //**********************************************************************************************************************
371 vector<vector<double> > AnosimCommand::convertToRanks(vector<vector<double> > dist) {
373 vector<seqDist> cells;
374 vector<vector<double> > ranks = dist;
376 for (int i = 0; i < dist.size(); i++) {
377 for (int j = 0; j < i; j++) {
378 if(dist[i][j] != -1){
379 seqDist member(i, j, dist[i][j]);
380 cells.push_back(member);
387 sort(cells.begin(), cells.end(), compareSequenceDistance);
389 //find ranks of distances
392 for(int i=0;i<cells.size()-1;i++){
396 while(dist[cells[index].seq1][cells[index].seq2] == dist[cells[index+1].seq1][cells[index+1].seq2]){
398 indexSum += index + 1;
402 ranks[cells[i].seq1][cells[i].seq2] = i+1;
405 double aveIndex = (double)indexSum / (double)(index - i + 1);
406 for(int j=i;j<=index;j++){
407 ranks[cells[j].seq1][cells[j].seq2] = aveIndex;
413 if(indexSum == cells.size() - 1){
414 ranks[cells[cells.size()-1].seq1][cells[cells.size()-1].seq2] = indexSum + 1;
419 catch(exception& e) {
420 m->errorOut(e, "AnosimCommand", "convertToRanks");
425 //**********************************************************************************************************************
427 map<string, vector<int> > AnosimCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
429 vector<int> sampleIndices;
430 vector<int> samplesPerGroup;
432 map<string, vector<int> >::iterator it;
433 for(it=origMapping.begin();it!=origMapping.end();it++){
434 vector<int> indices = it->second;
435 samplesPerGroup.push_back(indices.size());
436 sampleIndices.insert(sampleIndices.end(), indices.begin(), indices.end());
439 random_shuffle(sampleIndices.begin(), sampleIndices.end());
442 map<string, vector<int> > randomizedGroups = origMapping;
443 for(it=randomizedGroups.begin();it!=randomizedGroups.end();it++){
444 for(int i=0;i<it->second.size();i++){
445 it->second[i] = sampleIndices[index++];
449 return randomizedGroups;
451 catch (exception& e) {
452 m->errorOut(e, "AnosimCommand", "randomizeGroups");
457 //**********************************************************************************************************************