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::getValidParameters(){
17 string Array[] = {"outputdir","iters","phylip","design", "alpha","inputdir"};
18 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
22 m->errorOut(e, "AnosimCommand", "getValidParameters");
26 //**********************************************************************************************************************
27 AnosimCommand::AnosimCommand(){
29 abort = true; calledHelp = true;
30 vector<string> tempOutNames;
31 outputTypes["anosim"] = tempOutNames;
34 m->errorOut(e, "AnosimCommand", "AnosimCommand");
38 //**********************************************************************************************************************
39 vector<string> AnosimCommand::getRequiredParameters(){
41 string Array[] = {"design"};
42 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
46 m->errorOut(e, "AnosimCommand", "getRequiredParameters");
50 //**********************************************************************************************************************
51 vector<string> AnosimCommand::getRequiredFiles(){
54 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
58 m->errorOut(e, "AnosimCommand", "getRequiredFiles");
62 //**********************************************************************************************************************
64 AnosimCommand::AnosimCommand(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[] = {"outputdir","iters","phylip","design", "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["anosim"] = 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);
139 catch(exception& e) {
140 m->errorOut(e, "AnosimCommand", "AnosimCommand");
145 //**********************************************************************************************************************
147 void AnosimCommand::help(){
149 m->mothurOut("Referenced: Clarke, K. R. (1993). Non-parametric multivariate analysis of changes in community structure. _Australian Journal of Ecology_ 18, 117-143.\n");
150 m->mothurOut("The anosim command outputs a .anosim file. \n");
151 m->mothurOut("The anosim command parameters are phylip, iters, and alpha. The phylip and design parameters are required.\n");
152 m->mothurOut("The design parameter allows you to assign your samples to groups when you are running anosim. It is required. \n");
153 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");
154 m->mothurOut("The iters parameter allows you to set number of randomization for the P value. The default is 1000. \n");
155 m->mothurOut("The anosim command should be in the following format: anosim(phylip=file.dist, design=file.design).\n");
156 m->mothurOut("Note: No spaces between parameter labels (i.e. iters), '=' and parameters (i.e. 1000).\n\n");
159 catch(exception& e) {
160 m->errorOut(e, "AnosimCommand", "help");
165 //**********************************************************************************************************************
167 AnosimCommand::~AnosimCommand(){}
169 //**********************************************************************************************************************
171 int AnosimCommand::execute(){
174 if (abort == true) { if (calledHelp) { return 0; } return 2; }
177 designMap = new GroupMap(designFileName);
178 designMap->readDesignMap();
180 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
182 //read in distance matrix and square it
183 ReadPhylipVector readMatrix(phylipFileName);
184 vector<string> sampleNames = readMatrix.read(distanceMatrix);
186 for(int i=0;i<distanceMatrix.size();i++){
187 for(int j=0;j<i;j++){
188 distanceMatrix[i][j] *= distanceMatrix[i][j];
192 //link designMap to rows/columns in distance matrix
193 map<string, vector<int> > origGroupSampleMap;
194 for(int i=0;i<sampleNames.size();i++){
195 origGroupSampleMap[designMap->getGroup(sampleNames[i])].push_back(i);
197 int numGroups = origGroupSampleMap.size();
199 //create a new filename
201 string ANOSIMFileName = outputDir + m->getRootName(m->getSimpleName(phylipFileName)) + "anosim";
202 m->openOutputFile(ANOSIMFileName, ANOSIMFile);
203 outputNames.push_back(ANOSIMFileName); outputTypes["anosim"].push_back(ANOSIMFileName);
204 m->mothurOut("\ncomparison\tR-value\tP-value\n");
205 ANOSIMFile << "comparison\tR-value\tP-value\n";
208 double fullANOSIMPValue = runANOSIM(ANOSIMFile, distanceMatrix, origGroupSampleMap, experimentwiseAlpha);
211 if(fullANOSIMPValue <= experimentwiseAlpha && numGroups > 2){
213 int numCombos = numGroups * (numGroups-1) / 2;
214 double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
216 for(map<string, vector<int> >::iterator itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
217 map<string, vector<int> >::iterator itB = itA;
219 for(itB;itB!=origGroupSampleMap.end();itB++){
221 map<string, vector<int> > subGroupSampleMap;
223 subGroupSampleMap[itA->first] = itA->second; string groupA = itA->first;
224 subGroupSampleMap[itB->first] = itB->second; string groupB = itB->first;
226 vector<int> subIndices;
227 for(map<string, vector<int> >::iterator it=subGroupSampleMap.begin();it!=subGroupSampleMap.end();it++){
228 subIndices.insert(subIndices.end(), it->second.begin(), it->second.end());
230 int subNumSamples = subIndices.size();
232 sort(subIndices.begin(), subIndices.end());
234 vector<vector<double> > subDistMatrix(distanceMatrix.size());
235 for(int i=0;i<distanceMatrix.size();i++){
236 subDistMatrix[i].assign(distanceMatrix.size(), -1);
239 for(int i=0;i<subNumSamples;i++){
240 for(int j=0;j<i;j++){
241 subDistMatrix[subIndices[i]][subIndices[j]] = distanceMatrix[subIndices[i]][subIndices[j]];
245 runANOSIM(ANOSIMFile, subDistMatrix, subGroupSampleMap, pairwiseAlpha);
250 m->mothurOut("\nExperiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
251 m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
254 m->mothurOut("\nExperiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
256 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
262 m->mothurOutEndLine();
263 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
264 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
265 m->mothurOutEndLine();
269 catch(exception& e) {
270 m->errorOut(e, "AnosimCommand", "execute");
274 //**********************************************************************************************************************
276 double AnosimCommand::runANOSIM(ofstream& ANOSIMFile, vector<vector<double> > dMatrix, map<string, vector<int> > groupSampleMap, double alpha) {
280 vector<vector<double> > rankMatrix = convertToRanks(dMatrix);
281 double RValue = calcR(rankMatrix, groupSampleMap);
284 for(int i=0;i<iters;i++){
285 map<string, vector<int> > randGroupSampleMap = getRandomizedGroups(groupSampleMap);
286 double RValueRand = calcR(rankMatrix, randGroupSampleMap);
287 if(RValue <= RValueRand){ pCount++; }
290 double pValue = (double)pCount / (double) iters;
292 if(pValue < 1/(double)iters){ pString = '<' + toString(1/(double)iters); }
293 else { pString = toString(pValue); }
296 map<string, vector<int> >::iterator it=groupSampleMap.begin();
297 m->mothurOut(it->first);
298 ANOSIMFile << it->first;
300 for(it;it!=groupSampleMap.end();it++){
301 m->mothurOut('-' + it->first);
302 ANOSIMFile << '-' << it->first;
305 m->mothurOut('\t' + toString(RValue) + '\t' + pString);
306 ANOSIMFile << '\t' << RValue << '\t' << pString;
313 m->mothurOutEndLine();
317 catch(exception& e) {
318 m->errorOut(e, "AnosimCommand", "calcAnisom");
323 //**********************************************************************************************************************
325 double AnosimCommand::calcR(vector<vector<double> > rankMatrix, map<string, vector<int> > groupSampleMap){
329 for(map<string, vector<int> >::iterator it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
330 numSamples += it->second.size();
335 int numWithinComps = 0;
337 for(map<string, vector<int> >::iterator it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
338 vector<int> indices = it->second;
339 for(int i=0;i<indices.size();i++){
340 for(int j=0;j<i;j++){
341 if(indices[i] > indices[j]) { within += rankMatrix[indices[i]][indices[j]]; }
342 else { within += rankMatrix[indices[j]][indices[i]]; }
348 within /= (float) numWithinComps;
350 double between = 0.0;
351 int numBetweenComps = 0;
353 map<string, vector<int> >::iterator itB;
355 for(map<string, vector<int> >::iterator itA=groupSampleMap.begin();itA!=groupSampleMap.end();itA++){
357 for(int i=0;i<itA->second.size();i++){
358 int A = itA->second[i];
359 map<string, vector<int> >::iterator itB = itA;
361 for(itB;itB!=groupSampleMap.end();itB++){
362 for(int j=0;j<itB->second.size();j++){
363 int B = itB->second[j];
364 if(A>B) { between += rankMatrix[A][B]; }
365 else { between += rankMatrix[B][A]; }
374 between /= (float) numBetweenComps;
376 double Rvalue = (between - within)/(numSamples * (numSamples-1) / 4.0);
380 catch(exception& e) {
381 m->errorOut(e, "AnosimCommand", "calcWithinBetween");
386 //**********************************************************************************************************************
388 vector<vector<double> > AnosimCommand::convertToRanks(vector<vector<double> > dist) {
390 vector<seqDist> cells;
391 vector<vector<double> > ranks = dist;
393 for (int i = 0; i < dist.size(); i++) {
394 for (int j = 0; j < i; j++) {
395 if(dist[i][j] != -1){
396 seqDist member(i, j, dist[i][j]);
397 cells.push_back(member);
404 sort(cells.begin(), cells.end(), compareSequenceDistance);
406 //find ranks of distances
409 for(int i=0;i<cells.size()-1;i++){
413 while(dist[cells[index].seq1][cells[index].seq2] == dist[cells[index+1].seq1][cells[index+1].seq2]){
415 indexSum += index + 1;
419 ranks[cells[i].seq1][cells[i].seq2] = i+1;
422 double aveIndex = (double)indexSum / (double)(index - i + 1);
423 for(int j=i;j<=index;j++){
424 ranks[cells[j].seq1][cells[j].seq2] = aveIndex;
430 if(indexSum == cells.size() - 1){
431 ranks[cells[cells.size()-1].seq1][cells[cells.size()-1].seq2] = indexSum + 1;
436 catch(exception& e) {
437 m->errorOut(e, "AnosimCommand", "convertToRanks");
442 //**********************************************************************************************************************
444 map<string, vector<int> > AnosimCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
446 vector<int> sampleIndices;
447 vector<int> samplesPerGroup;
449 map<string, vector<int> >::iterator it;
450 for(it=origMapping.begin();it!=origMapping.end();it++){
451 vector<int> indices = it->second;
452 samplesPerGroup.push_back(indices.size());
453 sampleIndices.insert(sampleIndices.end(), indices.begin(), indices.end());
456 random_shuffle(sampleIndices.begin(), sampleIndices.end());
459 map<string, vector<int> > randomizedGroups = origMapping;
460 for(it=randomizedGroups.begin();it!=randomizedGroups.end();it++){
461 for(int i=0;i<it->second.size();i++){
462 it->second[i] = sampleIndices[index++];
466 return randomizedGroups;
468 catch (exception& e) {
469 m->errorOut(e, "AnosimCommand", "randomizeGroups");
474 //**********************************************************************************************************************