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; }
74 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
77 vector<string> myArray = setParameters();
79 OptionParser parser(option);
80 map<string,string> parameters = parser.getParameters();
82 ValidParameters validParameter;
84 //check to make sure all parameters are valid for command
85 map<string,string>::iterator it;
86 for (it = parameters.begin(); it != parameters.end(); it++) {
87 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
90 //initialize outputTypes
91 vector<string> tempOutNames;
92 outputTypes["anosim"] = tempOutNames;
94 //if the user changes the output directory command factory will send this info to us in the output parameter
95 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
97 //if the user changes the input directory command factory will send this info to us in the output parameter
98 string inputDir = validParameter.validFile(parameters, "inputdir", false);
99 if (inputDir == "not found"){ inputDir = ""; }
102 it = parameters.find("design");
103 //user has given a template file
104 if(it != parameters.end()){
105 path = m->hasPath(it->second);
106 //if the user has not given a path then, add inputdir. else leave path alone.
107 if (path == "") { parameters["design"] = inputDir + it->second; }
110 it = parameters.find("phylip");
111 //user has given a template file
112 if(it != parameters.end()){
113 path = m->hasPath(it->second);
114 //if the user has not given a path then, add inputdir. else leave path alone.
115 if (path == "") { parameters["phylip"] = inputDir + it->second; }
119 phylipFileName = validParameter.validFile(parameters, "phylip", true);
120 if (phylipFileName == "not open") { phylipFileName = ""; abort = true; }
121 else if (phylipFileName == "not found") {
122 //if there is a current phylip file, use it
123 phylipFileName = m->getPhylipFile();
124 if (phylipFileName != "") { m->mothurOut("Using " + phylipFileName + " as input file for the phylip parameter."); m->mothurOutEndLine(); }
125 else { m->mothurOut("You have no current phylip file and the phylip parameter is required."); m->mothurOutEndLine(); abort = true; }
127 }else { m->setPhylipFile(phylipFileName); }
129 //check for required parameters
130 designFileName = validParameter.validFile(parameters, "design", true);
131 if (designFileName == "not open") { designFileName = ""; abort = true; }
132 else if (designFileName == "not found") {
133 //if there is a current design file, use it
134 designFileName = m->getDesignFile();
135 if (designFileName != "") { m->mothurOut("Using " + designFileName + " as input file for the design parameter."); m->mothurOutEndLine(); }
136 else { m->mothurOut("You have no current design file and the design parameter is required."); m->mothurOutEndLine(); abort = true; }
137 }else { m->setDesignFile(designFileName); }
139 string temp = validParameter.validFile(parameters, "iters", false);
140 if (temp == "not found") { temp = "1000"; }
141 m->mothurConvert(temp, iters);
143 temp = validParameter.validFile(parameters, "alpha", false);
144 if (temp == "not found") { temp = "0.05"; }
145 m->mothurConvert(temp, experimentwiseAlpha);
149 catch(exception& e) {
150 m->errorOut(e, "AnosimCommand", "AnosimCommand");
154 //**********************************************************************************************************************
155 int AnosimCommand::execute(){
158 if (abort == true) { if (calledHelp) { return 0; } return 2; }
161 designMap = new GroupMap(designFileName);
162 designMap->readDesignMap();
164 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
166 //read in distance matrix and square it
167 ReadPhylipVector readMatrix(phylipFileName);
168 vector<string> sampleNames = readMatrix.read(distanceMatrix);
170 for(int i=0;i<distanceMatrix.size();i++){
171 for(int j=0;j<i;j++){
172 distanceMatrix[i][j] *= distanceMatrix[i][j];
176 //link designMap to rows/columns in distance matrix
177 map<string, vector<int> > origGroupSampleMap;
178 for(int i=0;i<sampleNames.size();i++){
179 string group = designMap->getGroup(sampleNames[i]);
181 if (group == "not found") {
182 m->mothurOut("[ERROR]: " + sampleNames[i] + " is not in your design file, please correct."); m->mothurOutEndLine(); m->control_pressed = true;
183 }else { origGroupSampleMap[group].push_back(i); }
185 int numGroups = origGroupSampleMap.size();
187 if (m->control_pressed) { delete designMap; return 0; }
189 //create a new filename
191 string ANOSIMFileName = outputDir + m->getRootName(m->getSimpleName(phylipFileName)) + "anosim";
192 m->openOutputFile(ANOSIMFileName, ANOSIMFile);
193 outputNames.push_back(ANOSIMFileName); outputTypes["anosim"].push_back(ANOSIMFileName);
194 m->mothurOut("\ncomparison\tR-value\tP-value\n");
195 ANOSIMFile << "comparison\tR-value\tP-value\n";
198 double fullANOSIMPValue = runANOSIM(ANOSIMFile, distanceMatrix, origGroupSampleMap, experimentwiseAlpha);
201 if(fullANOSIMPValue <= experimentwiseAlpha && numGroups > 2){
203 int numCombos = numGroups * (numGroups-1) / 2;
204 double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
206 for(map<string, vector<int> >::iterator itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
207 map<string, vector<int> >::iterator itB = itA;
209 for(itB;itB!=origGroupSampleMap.end();itB++){
211 map<string, vector<int> > subGroupSampleMap;
213 subGroupSampleMap[itA->first] = itA->second; string groupA = itA->first;
214 subGroupSampleMap[itB->first] = itB->second; string groupB = itB->first;
216 vector<int> subIndices;
217 for(map<string, vector<int> >::iterator it=subGroupSampleMap.begin();it!=subGroupSampleMap.end();it++){
218 subIndices.insert(subIndices.end(), it->second.begin(), it->second.end());
220 int subNumSamples = subIndices.size();
222 sort(subIndices.begin(), subIndices.end());
224 vector<vector<double> > subDistMatrix(distanceMatrix.size());
225 for(int i=0;i<distanceMatrix.size();i++){
226 subDistMatrix[i].assign(distanceMatrix.size(), -1);
229 for(int i=0;i<subNumSamples;i++){
230 for(int j=0;j<i;j++){
231 subDistMatrix[subIndices[i]][subIndices[j]] = distanceMatrix[subIndices[i]][subIndices[j]];
235 runANOSIM(ANOSIMFile, subDistMatrix, subGroupSampleMap, pairwiseAlpha);
240 m->mothurOut("\nExperiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
241 m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
244 m->mothurOut("\nExperiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
246 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
252 m->mothurOutEndLine();
253 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
254 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
255 m->mothurOutEndLine();
259 catch(exception& e) {
260 m->errorOut(e, "AnosimCommand", "execute");
264 //**********************************************************************************************************************
266 double AnosimCommand::runANOSIM(ofstream& ANOSIMFile, vector<vector<double> > dMatrix, map<string, vector<int> > groupSampleMap, double alpha) {
270 vector<vector<double> > rankMatrix = convertToRanks(dMatrix);
271 double RValue = calcR(rankMatrix, groupSampleMap);
274 for(int i=0;i<iters;i++){
275 map<string, vector<int> > randGroupSampleMap = getRandomizedGroups(groupSampleMap);
276 double RValueRand = calcR(rankMatrix, randGroupSampleMap);
277 if(RValue <= RValueRand){ pCount++; }
280 double pValue = (double)pCount / (double) iters;
282 if(pValue < 1/(double)iters){ pString = '<' + toString(1/(double)iters); }
283 else { pString = toString(pValue); }
286 map<string, vector<int> >::iterator it=groupSampleMap.begin();
287 m->mothurOut(it->first);
288 ANOSIMFile << it->first;
290 for(it;it!=groupSampleMap.end();it++){
291 m->mothurOut('-' + it->first);
292 ANOSIMFile << '-' << it->first;
295 m->mothurOut('\t' + toString(RValue) + '\t' + pString);
296 ANOSIMFile << '\t' << RValue << '\t' << pString;
303 m->mothurOutEndLine();
307 catch(exception& e) {
308 m->errorOut(e, "AnosimCommand", "calcAnisom");
313 //**********************************************************************************************************************
315 double AnosimCommand::calcR(vector<vector<double> > rankMatrix, map<string, vector<int> > groupSampleMap){
319 for(map<string, vector<int> >::iterator it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
320 numSamples += it->second.size();
325 int numWithinComps = 0;
327 for(map<string, vector<int> >::iterator it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
328 vector<int> indices = it->second;
329 for(int i=0;i<indices.size();i++){
330 for(int j=0;j<i;j++){
331 if(indices[i] > indices[j]) { within += rankMatrix[indices[i]][indices[j]]; }
332 else { within += rankMatrix[indices[j]][indices[i]]; }
338 within /= (float) numWithinComps;
340 double between = 0.0;
341 int numBetweenComps = 0;
343 map<string, vector<int> >::iterator itB;
345 for(map<string, vector<int> >::iterator itA=groupSampleMap.begin();itA!=groupSampleMap.end();itA++){
347 for(int i=0;i<itA->second.size();i++){
348 int A = itA->second[i];
349 map<string, vector<int> >::iterator itB = itA;
351 for(itB;itB!=groupSampleMap.end();itB++){
352 for(int j=0;j<itB->second.size();j++){
353 int B = itB->second[j];
354 if(A>B) { between += rankMatrix[A][B]; }
355 else { between += rankMatrix[B][A]; }
364 between /= (float) numBetweenComps;
366 double Rvalue = (between - within)/(numSamples * (numSamples-1) / 4.0);
370 catch(exception& e) {
371 m->errorOut(e, "AnosimCommand", "calcWithinBetween");
376 //**********************************************************************************************************************
378 vector<vector<double> > AnosimCommand::convertToRanks(vector<vector<double> > dist) {
380 vector<seqDist> cells;
381 vector<vector<double> > ranks = dist;
383 for (int i = 0; i < dist.size(); i++) {
384 for (int j = 0; j < i; j++) {
385 if(dist[i][j] != -1){
386 seqDist member(i, j, dist[i][j]);
387 cells.push_back(member);
394 sort(cells.begin(), cells.end(), compareSequenceDistance);
396 //find ranks of distances
399 for(int i=0;i<cells.size()-1;i++){
403 while(dist[cells[index].seq1][cells[index].seq2] == dist[cells[index+1].seq1][cells[index+1].seq2]){
405 indexSum += index + 1;
409 ranks[cells[i].seq1][cells[i].seq2] = i+1;
412 double aveIndex = (double)indexSum / (double)(index - i + 1);
413 for(int j=i;j<=index;j++){
414 ranks[cells[j].seq1][cells[j].seq2] = aveIndex;
420 if(indexSum == cells.size() - 1){
421 ranks[cells[cells.size()-1].seq1][cells[cells.size()-1].seq2] = indexSum + 1;
426 catch(exception& e) {
427 m->errorOut(e, "AnosimCommand", "convertToRanks");
432 //**********************************************************************************************************************
434 map<string, vector<int> > AnosimCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
436 vector<int> sampleIndices;
437 vector<int> samplesPerGroup;
439 map<string, vector<int> >::iterator it;
440 for(it=origMapping.begin();it!=origMapping.end();it++){
441 vector<int> indices = it->second;
442 samplesPerGroup.push_back(indices.size());
443 sampleIndices.insert(sampleIndices.end(), indices.begin(), indices.end());
446 random_shuffle(sampleIndices.begin(), sampleIndices.end());
449 map<string, vector<int> > randomizedGroups = origMapping;
450 for(it=randomizedGroups.begin();it!=randomizedGroups.end();it++){
451 for(int i=0;i<it->second.size();i++){
452 it->second[i] = sampleIndices[index++];
456 return randomizedGroups;
458 catch (exception& e) {
459 m->errorOut(e, "AnosimCommand", "randomizeGroups");
464 //**********************************************************************************************************************