]> git.donarmstrong.com Git - mothur.git/blob - anosimcommand.cpp
added set.current and get.current commands and modified existing commands to update...
[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::getValidParameters(){     
16         try {
17                 string Array[] =  {"outputdir","iters","phylip","design", "alpha","inputdir"};
18                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
19                 return myArray;
20         }
21         catch(exception& e) {
22                 m->errorOut(e, "AnosimCommand", "getValidParameters");
23                 exit(1);
24         }
25 }
26 //**********************************************************************************************************************
27 AnosimCommand::AnosimCommand(){ 
28         try {
29                 abort = true; calledHelp = true; 
30                 vector<string> tempOutNames;
31                 outputTypes["anosim"] = tempOutNames;
32         }
33         catch(exception& e) {
34                 m->errorOut(e, "AnosimCommand", "AnosimCommand");
35                 exit(1);
36         }
37 }
38 //**********************************************************************************************************************
39 vector<string> AnosimCommand::getRequiredParameters(){  
40         try {
41                 string Array[] =  {"design"};
42                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
43                 return myArray;
44         }
45         catch(exception& e) {
46                 m->errorOut(e, "AnosimCommand", "getRequiredParameters");
47                 exit(1);
48         }
49 }
50 //**********************************************************************************************************************
51 vector<string> AnosimCommand::getRequiredFiles(){       
52         try {
53                 string Array[] =  {};
54                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
55                 return myArray;
56         }
57         catch(exception& e) {
58                 m->errorOut(e, "AnosimCommand", "getRequiredFiles");
59                 exit(1);
60         }
61 }
62 //**********************************************************************************************************************
63
64 AnosimCommand::AnosimCommand(string option) {
65         try {
66                 abort = false; calledHelp = false;   
67                 
68                 //allow user to run help
69                 if(option == "help") { help(); abort = true; calledHelp = true; }
70                 
71                 else {
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)));
75                         
76                         OptionParser parser(option);
77                         map<string,string> parameters = parser.getParameters();
78                         
79                         ValidParameters validParameter;
80                         
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;  }
85                         }
86                         
87                         //initialize outputTypes
88                         vector<string> tempOutNames;
89                         outputTypes["anosim"] = tempOutNames;
90                         
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 = ""; }
93                         
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 = "";          }
97                         else {
98                                 string path;
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;           }
105                                 }
106                                 
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;           }
113                                 }
114                         }
115                         
116                         phylipFileName = validParameter.validFile(parameters, "phylip", true);
117                         if (phylipFileName == "not open") { phylipFileName = ""; abort = true; }
118                         else if (phylipFileName == "not found") { 
119                                 phylipFileName = "";    
120                         }       
121                         
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") {
126                                 designFileName = "";
127                         }       
128                         
129                         string temp = validParameter.validFile(parameters, "iters", false);
130                         if (temp == "not found") { temp = "1000"; }
131                         convert(temp, iters); 
132                         
133                         temp = validParameter.validFile(parameters, "alpha", false);
134                         if (temp == "not found") { temp = "0.05"; }
135                         convert(temp, experimentwiseAlpha); 
136                 }
137                 
138         }
139         catch(exception& e) {
140                 m->errorOut(e, "AnosimCommand", "AnosimCommand");
141                 exit(1);
142         }
143 }
144
145 //**********************************************************************************************************************
146
147 void AnosimCommand::help(){
148         try {
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");
157                 
158         }
159         catch(exception& e) {
160                 m->errorOut(e, "AnosimCommand", "help");
161                 exit(1);
162         }
163 }
164
165 //**********************************************************************************************************************
166
167 AnosimCommand::~AnosimCommand(){}
168
169 //**********************************************************************************************************************
170
171 int AnosimCommand::execute(){
172         try {
173                 
174                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
175                 
176                 //read design file
177                 designMap = new GroupMap(designFileName);
178                 designMap->readDesignMap();
179                 
180                 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
181                 
182                 //read in distance matrix and square it
183                 ReadPhylipVector readMatrix(phylipFileName);
184                 vector<string> sampleNames = readMatrix.read(distanceMatrix);
185                 
186                 for(int i=0;i<distanceMatrix.size();i++){
187                         for(int j=0;j<i;j++){
188                                 distanceMatrix[i][j] *= distanceMatrix[i][j];   
189                         }
190                 }
191                 
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);
196                 }
197                 int numGroups = origGroupSampleMap.size();
198                 
199                 //create a new filename
200                 ofstream ANOSIMFile;
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";
206                 
207                 
208                 double fullANOSIMPValue = runANOSIM(ANOSIMFile, distanceMatrix, origGroupSampleMap, experimentwiseAlpha);
209                 
210                 
211                 if(fullANOSIMPValue <= experimentwiseAlpha && numGroups > 2){
212
213                         int numCombos = numGroups * (numGroups-1) / 2;
214                         double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
215
216                         for(map<string, vector<int> >::iterator itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
217                                 map<string, vector<int> >::iterator itB = itA;
218                                 itB++;
219                                 for(itB;itB!=origGroupSampleMap.end();itB++){
220                                         
221                                         map<string, vector<int> > subGroupSampleMap;
222                                         
223                                         subGroupSampleMap[itA->first] = itA->second;    string groupA = itA->first;
224                                         subGroupSampleMap[itB->first] = itB->second;    string groupB = itB->first;
225                         
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());
229                                         }
230                                         int subNumSamples = subIndices.size();
231
232                                         sort(subIndices.begin(), subIndices.end());             
233                                         
234                                         vector<vector<double> > subDistMatrix(distanceMatrix.size());
235                                         for(int i=0;i<distanceMatrix.size();i++){
236                                                 subDistMatrix[i].assign(distanceMatrix.size(), -1);
237                                         }
238
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]];
242                                                 }
243                                         }
244
245                                         runANOSIM(ANOSIMFile, subDistMatrix, subGroupSampleMap, pairwiseAlpha);
246
247                                 }
248                         }
249                         
250                         m->mothurOut("\nExperiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
251                         m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
252                 }
253                 else{
254                         m->mothurOut("\nExperiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
255                 }
256                 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
257                 ANOSIMFile.close();
258                 
259                         
260                 delete designMap;
261                                 
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();
266                 
267                 return 0;
268         }
269         catch(exception& e) {
270                 m->errorOut(e, "AnosimCommand", "execute");
271                 exit(1);
272         }
273 }
274 //**********************************************************************************************************************
275
276 double AnosimCommand::runANOSIM(ofstream& ANOSIMFile, vector<vector<double> > dMatrix, map<string, vector<int> > groupSampleMap, double alpha) {
277         try {
278
279                 
280                 vector<vector<double> > rankMatrix = convertToRanks(dMatrix);
281                 double RValue = calcR(rankMatrix, groupSampleMap);
282                 
283                 int pCount = 0;
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++;       }
288                 }
289
290                 double pValue = (double)pCount / (double) iters;
291                 string pString = "";
292                 if(pValue < 1/(double)iters){   pString = '<' + toString(1/(double)iters);      }
293                 else                                            {       pString = toString(pValue);                                     }
294                 
295                 
296                 map<string, vector<int> >::iterator it=groupSampleMap.begin();
297                 m->mothurOut(it->first);
298                 ANOSIMFile << it->first;
299                 it++;
300                 for(it;it!=groupSampleMap.end();it++){
301                         m->mothurOut('-' + it->first);
302                         ANOSIMFile << '-' << it->first;
303                 
304                 }
305                 m->mothurOut('\t' + toString(RValue) + '\t' + pString);
306                 ANOSIMFile << '\t' << RValue << '\t' << pString;
307
308                 if(pValue < alpha){
309                         ANOSIMFile << "*";
310                         m->mothurOut("*");
311                 }
312                 ANOSIMFile << endl;
313                 m->mothurOutEndLine();
314                 
315                 return pValue;
316         }
317         catch(exception& e) {
318                 m->errorOut(e, "AnosimCommand", "calcAnisom");
319                 exit(1);
320         }
321 }
322
323 //**********************************************************************************************************************
324
325 double AnosimCommand::calcR(vector<vector<double> > rankMatrix, map<string, vector<int> > groupSampleMap){
326         try {
327
328                 int numSamples = 0;
329                 for(map<string, vector<int> >::iterator it=groupSampleMap.begin();it!=groupSampleMap.end();it++){
330                         numSamples += it->second.size();
331                 }
332                 
333                 
334                 double within = 0.0;
335                 int numWithinComps = 0;         
336                 
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]];   }
343                                         numWithinComps++;
344                                 }
345                         }
346                 }
347                 
348                 within /= (float) numWithinComps;
349                 
350                 double between = 0.0;
351                 int numBetweenComps = 0;
352
353                 map<string, vector<int> >::iterator itB;
354                 
355                 for(map<string, vector<int> >::iterator itA=groupSampleMap.begin();itA!=groupSampleMap.end();itA++){
356
357                         for(int i=0;i<itA->second.size();i++){
358                                 int A = itA->second[i];
359                                 map<string, vector<int> >::iterator itB = itA;
360                                 itB++;
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];    }
366                                                 numBetweenComps++;
367                                         }                                       
368                                 }
369                                 
370                         }
371                 }
372                 
373                 
374                 between /= (float) numBetweenComps;
375                 
376                 double Rvalue = (between - within)/(numSamples * (numSamples-1) / 4.0);
377                                 
378                 return Rvalue;
379         }
380         catch(exception& e) {
381                 m->errorOut(e, "AnosimCommand", "calcWithinBetween");
382                 exit(1);
383         }
384 }
385
386 //**********************************************************************************************************************
387
388 vector<vector<double> > AnosimCommand::convertToRanks(vector<vector<double> > dist) {
389         try {
390                 vector<seqDist> cells;
391                 vector<vector<double> > ranks = dist;
392                 
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);
398                                 }
399                         }
400                 }
401                 
402                 
403                 //sort distances
404                 sort(cells.begin(), cells.end(), compareSequenceDistance);      
405
406                 //find ranks of distances
407                 int index = 0;
408                 int indexSum = 0;
409                 for(int i=0;i<cells.size()-1;i++){
410
411                         index = i;
412                         indexSum = i + 1;
413                         while(dist[cells[index].seq1][cells[index].seq2] == dist[cells[index+1].seq1][cells[index+1].seq2]){
414                                 index++;                                
415                                 indexSum += index + 1;
416                         }
417                         
418                         if(index == i){
419                                 ranks[cells[i].seq1][cells[i].seq2] = i+1;
420                         }
421                         else{
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;
425                                 }                                       
426                                 i = index;
427                         }
428                 }
429                 
430                 if(indexSum == cells.size() - 1){
431                         ranks[cells[cells.size()-1].seq1][cells[cells.size()-1].seq2] = indexSum + 1;
432                 }
433
434                 return ranks;
435         }
436         catch(exception& e) {
437                 m->errorOut(e, "AnosimCommand", "convertToRanks");
438                 exit(1);
439         }
440 }
441
442 //**********************************************************************************************************************
443
444 map<string, vector<int> > AnosimCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
445         try{
446                 vector<int> sampleIndices;
447                 vector<int> samplesPerGroup;
448                 
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());
454                 }
455                 
456                 random_shuffle(sampleIndices.begin(), sampleIndices.end());
457                 
458                 int index = 0;
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++];                         
463                         }
464                 }
465                 
466                 return randomizedGroups;                
467         }
468         catch (exception& e) {
469                 m->errorOut(e, "AnosimCommand", "randomizeGroups");
470                 exit(1);
471         }
472 }
473
474 //**********************************************************************************************************************
475
476
477