]> git.donarmstrong.com Git - mothur.git/blob - anosimcommand.cpp
removed read.dist, read.otu, read.tree and globaldata. added current to defaults...
[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\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                 
75                 else {
76                         vector<string> myArray = setParameters();
77                         
78                         OptionParser parser(option);
79                         map<string,string> parameters = parser.getParameters();
80                         
81                         ValidParameters validParameter;
82                         
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;  }
87                         }
88                         
89                         //initialize outputTypes
90                         vector<string> tempOutNames;
91                         outputTypes["anosim"] = tempOutNames;
92                         
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 = ""; }
95                         
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 = "";          }
99                         else {
100                                 string path;
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;           }
107                                 }
108                                 
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;           }
115                                 }
116                         }
117                         
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                                 
126                         }       
127                         
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; }                                                           
136                         }       
137                         
138                         string temp = validParameter.validFile(parameters, "iters", false);
139                         if (temp == "not found") { temp = "1000"; }
140                         convert(temp, iters); 
141                         
142                         temp = validParameter.validFile(parameters, "alpha", false);
143                         if (temp == "not found") { temp = "0.05"; }
144                         convert(temp, experimentwiseAlpha); 
145                 }
146                 
147         }
148         catch(exception& e) {
149                 m->errorOut(e, "AnosimCommand", "AnosimCommand");
150                 exit(1);
151         }
152 }
153 //**********************************************************************************************************************
154 int AnosimCommand::execute(){
155         try {
156                 
157                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
158                 
159                 //read design file
160                 designMap = new GroupMap(designFileName);
161                 designMap->readDesignMap();
162                 
163                 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
164                 
165                 //read in distance matrix and square it
166                 ReadPhylipVector readMatrix(phylipFileName);
167                 vector<string> sampleNames = readMatrix.read(distanceMatrix);
168                 
169                 for(int i=0;i<distanceMatrix.size();i++){
170                         for(int j=0;j<i;j++){
171                                 distanceMatrix[i][j] *= distanceMatrix[i][j];   
172                         }
173                 }
174                 
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);
179                 }
180                 int numGroups = origGroupSampleMap.size();
181                 
182                 //create a new filename
183                 ofstream ANOSIMFile;
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";
189                 
190                 
191                 double fullANOSIMPValue = runANOSIM(ANOSIMFile, distanceMatrix, origGroupSampleMap, experimentwiseAlpha);
192                 
193                 
194                 if(fullANOSIMPValue <= experimentwiseAlpha && numGroups > 2){
195
196                         int numCombos = numGroups * (numGroups-1) / 2;
197                         double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
198
199                         for(map<string, vector<int> >::iterator itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
200                                 map<string, vector<int> >::iterator itB = itA;
201                                 itB++;
202                                 for(itB;itB!=origGroupSampleMap.end();itB++){
203                                         
204                                         map<string, vector<int> > subGroupSampleMap;
205                                         
206                                         subGroupSampleMap[itA->first] = itA->second;    string groupA = itA->first;
207                                         subGroupSampleMap[itB->first] = itB->second;    string groupB = itB->first;
208                         
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());
212                                         }
213                                         int subNumSamples = subIndices.size();
214
215                                         sort(subIndices.begin(), subIndices.end());             
216                                         
217                                         vector<vector<double> > subDistMatrix(distanceMatrix.size());
218                                         for(int i=0;i<distanceMatrix.size();i++){
219                                                 subDistMatrix[i].assign(distanceMatrix.size(), -1);
220                                         }
221
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]];
225                                                 }
226                                         }
227
228                                         runANOSIM(ANOSIMFile, subDistMatrix, subGroupSampleMap, pairwiseAlpha);
229
230                                 }
231                         }
232                         
233                         m->mothurOut("\nExperiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
234                         m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
235                 }
236                 else{
237                         m->mothurOut("\nExperiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
238                 }
239                 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
240                 ANOSIMFile.close();
241                 
242                         
243                 delete designMap;
244                                 
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();
249                 
250                 return 0;
251         }
252         catch(exception& e) {
253                 m->errorOut(e, "AnosimCommand", "execute");
254                 exit(1);
255         }
256 }
257 //**********************************************************************************************************************
258
259 double AnosimCommand::runANOSIM(ofstream& ANOSIMFile, vector<vector<double> > dMatrix, map<string, vector<int> > groupSampleMap, double alpha) {
260         try {
261
262                 
263                 vector<vector<double> > rankMatrix = convertToRanks(dMatrix);
264                 double RValue = calcR(rankMatrix, groupSampleMap);
265                 
266                 int pCount = 0;
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++;       }
271                 }
272
273                 double pValue = (double)pCount / (double) iters;
274                 string pString = "";
275                 if(pValue < 1/(double)iters){   pString = '<' + toString(1/(double)iters);      }
276                 else                                            {       pString = toString(pValue);                                     }
277                 
278                 
279                 map<string, vector<int> >::iterator it=groupSampleMap.begin();
280                 m->mothurOut(it->first);
281                 ANOSIMFile << it->first;
282                 it++;
283                 for(it;it!=groupSampleMap.end();it++){
284                         m->mothurOut('-' + it->first);
285                         ANOSIMFile << '-' << it->first;
286                 
287                 }
288                 m->mothurOut('\t' + toString(RValue) + '\t' + pString);
289                 ANOSIMFile << '\t' << RValue << '\t' << pString;
290
291                 if(pValue < alpha){
292                         ANOSIMFile << "*";
293                         m->mothurOut("*");
294                 }
295                 ANOSIMFile << endl;
296                 m->mothurOutEndLine();
297                 
298                 return pValue;
299         }
300         catch(exception& e) {
301                 m->errorOut(e, "AnosimCommand", "calcAnisom");
302                 exit(1);
303         }
304 }
305
306 //**********************************************************************************************************************
307
308 double AnosimCommand::calcR(vector<vector<double> > rankMatrix, map<string, vector<int> > groupSampleMap){
309         try {
310
311                 int numSamples = 0;
312                 for(map<string, vector<int> >::iterator it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
313                         numSamples += it->second.size();
314                 }
315                 
316                 
317                 double within = 0.0;
318                 int numWithinComps = 0;         
319                 
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]];   }
326                                         numWithinComps++;
327                                 }
328                         }
329                 }
330                 
331                 within /= (float) numWithinComps;
332                 
333                 double between = 0.0;
334                 int numBetweenComps = 0;
335
336                 map<string, vector<int> >::iterator itB;
337                 
338                 for(map<string, vector<int> >::iterator itA=groupSampleMap.begin();itA!=groupSampleMap.end();itA++){
339
340                         for(int i=0;i<itA->second.size();i++){
341                                 int A = itA->second[i];
342                                 map<string, vector<int> >::iterator itB = itA;
343                                 itB++;
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];    }
349                                                 numBetweenComps++;
350                                         }                                       
351                                 }
352                                 
353                         }
354                 }
355                 
356                 
357                 between /= (float) numBetweenComps;
358                 
359                 double Rvalue = (between - within)/(numSamples * (numSamples-1) / 4.0);
360                                 
361                 return Rvalue;
362         }
363         catch(exception& e) {
364                 m->errorOut(e, "AnosimCommand", "calcWithinBetween");
365                 exit(1);
366         }
367 }
368
369 //**********************************************************************************************************************
370
371 vector<vector<double> > AnosimCommand::convertToRanks(vector<vector<double> > dist) {
372         try {
373                 vector<seqDist> cells;
374                 vector<vector<double> > ranks = dist;
375                 
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);
381                                 }
382                         }
383                 }
384                 
385                 
386                 //sort distances
387                 sort(cells.begin(), cells.end(), compareSequenceDistance);      
388
389                 //find ranks of distances
390                 int index = 0;
391                 int indexSum = 0;
392                 for(int i=0;i<cells.size()-1;i++){
393
394                         index = i;
395                         indexSum = i + 1;
396                         while(dist[cells[index].seq1][cells[index].seq2] == dist[cells[index+1].seq1][cells[index+1].seq2]){
397                                 index++;                                
398                                 indexSum += index + 1;
399                         }
400                         
401                         if(index == i){
402                                 ranks[cells[i].seq1][cells[i].seq2] = i+1;
403                         }
404                         else{
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;
408                                 }                                       
409                                 i = index;
410                         }
411                 }
412                 
413                 if(indexSum == cells.size() - 1){
414                         ranks[cells[cells.size()-1].seq1][cells[cells.size()-1].seq2] = indexSum + 1;
415                 }
416
417                 return ranks;
418         }
419         catch(exception& e) {
420                 m->errorOut(e, "AnosimCommand", "convertToRanks");
421                 exit(1);
422         }
423 }
424
425 //**********************************************************************************************************************
426
427 map<string, vector<int> > AnosimCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
428         try{
429                 vector<int> sampleIndices;
430                 vector<int> samplesPerGroup;
431                 
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());
437                 }
438                 
439                 random_shuffle(sampleIndices.begin(), sampleIndices.end());
440                 
441                 int index = 0;
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++];                         
446                         }
447                 }
448                 
449                 return randomizedGroups;                
450         }
451         catch (exception& e) {
452                 m->errorOut(e, "AnosimCommand", "randomizeGroups");
453                 exit(1);
454         }
455 }
456
457 //**********************************************************************************************************************
458
459
460