]> git.donarmstrong.com Git - mothur.git/blob - anosimcommand.cpp
1.23.0
[mothur.git] / anosimcommand.cpp
1 /*
2  *  anosimcommand.cpp
3  *  mothur
4  *
5  *  Created by westcott on 2/14/11.
6  *  Copyright 2011 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "anosimcommand.h"
11 #include "inputdata.h"
12 #include "readphylipvector.h"
13
14 //**********************************************************************************************************************
15 vector<string> AnosimCommand::setParameters(){  
16         try {
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);
23
24                 vector<string> myArray;
25                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
26                 return myArray;
27         }
28         catch(exception& e) {
29                 m->errorOut(e, "AnosimCommand", "setParameters");
30                 exit(1);
31         }
32 }
33 //**********************************************************************************************************************
34 string AnosimCommand::getHelpString(){  
35         try {
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";
45                 return helpString;
46         }
47         catch(exception& e) {
48                 m->errorOut(e, "AnosimCommand", "getHelpString");
49                 exit(1);
50         }
51 }
52
53 //**********************************************************************************************************************
54 AnosimCommand::AnosimCommand(){ 
55         try {
56                 abort = true; calledHelp = true;
57                 setParameters();
58                 vector<string> tempOutNames;
59                 outputTypes["anosim"] = tempOutNames;
60         }
61         catch(exception& e) {
62                 m->errorOut(e, "AnosimCommand", "AnosimCommand");
63                 exit(1);
64         }
65 }
66 //**********************************************************************************************************************
67
68 AnosimCommand::AnosimCommand(string option) {
69         try {
70                 abort = false; calledHelp = false;   
71                 
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;}
75                 
76                 else {
77                         vector<string> myArray = setParameters();
78                         
79                         OptionParser parser(option);
80                         map<string,string> parameters = parser.getParameters();
81                         
82                         ValidParameters validParameter;
83                         
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;  }
88                         }
89                         
90                         //initialize outputTypes
91                         vector<string> tempOutNames;
92                         outputTypes["anosim"] = tempOutNames;
93                         
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 = ""; }
96                         
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 = "";          }
100                         else {
101                                 string path;
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;           }
108                                 }
109                                 
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;           }
116                                 }
117                         }
118                         
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; }
126                                 
127                         }else { m->setPhylipFile(phylipFileName); }     
128                         
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); }     
138                         
139                         string temp = validParameter.validFile(parameters, "iters", false);
140                         if (temp == "not found") { temp = "1000"; }
141                         m->mothurConvert(temp, iters); 
142                         
143                         temp = validParameter.validFile(parameters, "alpha", false);
144                         if (temp == "not found") { temp = "0.05"; }
145                         m->mothurConvert(temp, experimentwiseAlpha); 
146                 }
147                 
148         }
149         catch(exception& e) {
150                 m->errorOut(e, "AnosimCommand", "AnosimCommand");
151                 exit(1);
152         }
153 }
154 //**********************************************************************************************************************
155 int AnosimCommand::execute(){
156         try {
157                 
158                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
159                 
160                 //read design file
161                 designMap = new GroupMap(designFileName);
162                 designMap->readDesignMap();
163                 
164                 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
165                 
166                 //read in distance matrix and square it
167                 ReadPhylipVector readMatrix(phylipFileName);
168                 vector<string> sampleNames = readMatrix.read(distanceMatrix);
169                 
170                 for(int i=0;i<distanceMatrix.size();i++){
171                         for(int j=0;j<i;j++){
172                                 distanceMatrix[i][j] *= distanceMatrix[i][j];   
173                         }
174                 }
175                 
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]);
180                         
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); }
184                 }
185                 int numGroups = origGroupSampleMap.size();
186                 
187                 if (m->control_pressed) { delete designMap; return 0; }
188                 
189                 //create a new filename
190                 ofstream ANOSIMFile;
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";
196                 
197                 
198                 double fullANOSIMPValue = runANOSIM(ANOSIMFile, distanceMatrix, origGroupSampleMap, experimentwiseAlpha);
199                 
200                 
201                 if(fullANOSIMPValue <= experimentwiseAlpha && numGroups > 2){
202
203                         int numCombos = numGroups * (numGroups-1) / 2;
204                         double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
205
206                         for(map<string, vector<int> >::iterator itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
207                                 map<string, vector<int> >::iterator itB = itA;
208                                 itB++;
209                                 for(itB;itB!=origGroupSampleMap.end();itB++){
210                                         
211                                         map<string, vector<int> > subGroupSampleMap;
212                                         
213                                         subGroupSampleMap[itA->first] = itA->second;    string groupA = itA->first;
214                                         subGroupSampleMap[itB->first] = itB->second;    string groupB = itB->first;
215                         
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());
219                                         }
220                                         int subNumSamples = subIndices.size();
221
222                                         sort(subIndices.begin(), subIndices.end());             
223                                         
224                                         vector<vector<double> > subDistMatrix(distanceMatrix.size());
225                                         for(int i=0;i<distanceMatrix.size();i++){
226                                                 subDistMatrix[i].assign(distanceMatrix.size(), -1);
227                                         }
228
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]];
232                                                 }
233                                         }
234
235                                         runANOSIM(ANOSIMFile, subDistMatrix, subGroupSampleMap, pairwiseAlpha);
236
237                                 }
238                         }
239                         
240                         m->mothurOut("\nExperiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
241                         m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
242                 }
243                 else{
244                         m->mothurOut("\nExperiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
245                 }
246                 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
247                 ANOSIMFile.close();
248                 
249                         
250                 delete designMap;
251                                 
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();
256                 
257                 return 0;
258         }
259         catch(exception& e) {
260                 m->errorOut(e, "AnosimCommand", "execute");
261                 exit(1);
262         }
263 }
264 //**********************************************************************************************************************
265
266 double AnosimCommand::runANOSIM(ofstream& ANOSIMFile, vector<vector<double> > dMatrix, map<string, vector<int> > groupSampleMap, double alpha) {
267         try {
268
269                 
270                 vector<vector<double> > rankMatrix = convertToRanks(dMatrix);
271                 double RValue = calcR(rankMatrix, groupSampleMap);
272                 
273                 int pCount = 0;
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++;       }
278                 }
279
280                 double pValue = (double)pCount / (double) iters;
281                 string pString = "";
282                 if(pValue < 1/(double)iters){   pString = '<' + toString(1/(double)iters);      }
283                 else                                            {       pString = toString(pValue);                                     }
284                 
285                 
286                 map<string, vector<int> >::iterator it=groupSampleMap.begin();
287                 m->mothurOut(it->first);
288                 ANOSIMFile << it->first;
289                 it++;
290                 for(it;it!=groupSampleMap.end();it++){
291                         m->mothurOut('-' + it->first);
292                         ANOSIMFile << '-' << it->first;
293                 
294                 }
295                 m->mothurOut('\t' + toString(RValue) + '\t' + pString);
296                 ANOSIMFile << '\t' << RValue << '\t' << pString;
297
298                 if(pValue < alpha){
299                         ANOSIMFile << "*";
300                         m->mothurOut("*");
301                 }
302                 ANOSIMFile << endl;
303                 m->mothurOutEndLine();
304                 
305                 return pValue;
306         }
307         catch(exception& e) {
308                 m->errorOut(e, "AnosimCommand", "calcAnisom");
309                 exit(1);
310         }
311 }
312
313 //**********************************************************************************************************************
314
315 double AnosimCommand::calcR(vector<vector<double> > rankMatrix, map<string, vector<int> > groupSampleMap){
316         try {
317
318                 int numSamples = 0;
319                 for(map<string, vector<int> >::iterator it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
320                         numSamples += it->second.size();
321                 }
322                 
323                 
324                 double within = 0.0;
325                 int numWithinComps = 0;         
326                 
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]];   }
333                                         numWithinComps++;
334                                 }
335                         }
336                 }
337                 
338                 within /= (float) numWithinComps;
339                 
340                 double between = 0.0;
341                 int numBetweenComps = 0;
342
343                 map<string, vector<int> >::iterator itB;
344                 
345                 for(map<string, vector<int> >::iterator itA=groupSampleMap.begin();itA!=groupSampleMap.end();itA++){
346
347                         for(int i=0;i<itA->second.size();i++){
348                                 int A = itA->second[i];
349                                 map<string, vector<int> >::iterator itB = itA;
350                                 itB++;
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];    }
356                                                 numBetweenComps++;
357                                         }                                       
358                                 }
359                                 
360                         }
361                 }
362                 
363                 
364                 between /= (float) numBetweenComps;
365                 
366                 double Rvalue = (between - within)/(numSamples * (numSamples-1) / 4.0);
367                                 
368                 return Rvalue;
369         }
370         catch(exception& e) {
371                 m->errorOut(e, "AnosimCommand", "calcWithinBetween");
372                 exit(1);
373         }
374 }
375
376 //**********************************************************************************************************************
377
378 vector<vector<double> > AnosimCommand::convertToRanks(vector<vector<double> > dist) {
379         try {
380                 vector<seqDist> cells;
381                 vector<vector<double> > ranks = dist;
382                 
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);
388                                 }
389                         }
390                 }
391                 
392                 
393                 //sort distances
394                 sort(cells.begin(), cells.end(), compareSequenceDistance);      
395
396                 //find ranks of distances
397                 int index = 0;
398                 int indexSum = 0;
399                 for(int i=0;i<cells.size()-1;i++){
400
401                         index = i;
402                         indexSum = i + 1;
403                         while(dist[cells[index].seq1][cells[index].seq2] == dist[cells[index+1].seq1][cells[index+1].seq2]){
404                                 index++;                                
405                                 indexSum += index + 1;
406                         }
407                         
408                         if(index == i){
409                                 ranks[cells[i].seq1][cells[i].seq2] = i+1;
410                         }
411                         else{
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;
415                                 }                                       
416                                 i = index;
417                         }
418                 }
419                 
420                 if(indexSum == cells.size() - 1){
421                         ranks[cells[cells.size()-1].seq1][cells[cells.size()-1].seq2] = indexSum + 1;
422                 }
423
424                 return ranks;
425         }
426         catch(exception& e) {
427                 m->errorOut(e, "AnosimCommand", "convertToRanks");
428                 exit(1);
429         }
430 }
431
432 //**********************************************************************************************************************
433
434 map<string, vector<int> > AnosimCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
435         try{
436                 vector<int> sampleIndices;
437                 vector<int> samplesPerGroup;
438                 
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());
444                 }
445                 
446                 random_shuffle(sampleIndices.begin(), sampleIndices.end());
447                 
448                 int index = 0;
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++];                         
453                         }
454                 }
455                 
456                 return randomizedGroups;                
457         }
458         catch (exception& e) {
459                 m->errorOut(e, "AnosimCommand", "randomizeGroups");
460                 exit(1);
461         }
462 }
463
464 //**********************************************************************************************************************
465
466
467