]> git.donarmstrong.com Git - mothur.git/blob - homovacommand.cpp
reworked amova / homova / anosim
[mothur.git] / homovacommand.cpp
1 /*
2  *  homovacommand.cpp
3  *  mothur
4  *
5  *  Created by westcott on 2/8/11.
6  *  Copyright 2011 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "homovacommand.h"
11 #include "groupmap.h"
12 #include "readphylipvector.h"
13
14 //**********************************************************************************************************************
15
16 vector<string> HomovaCommand::getValidParameters(){     
17         try {
18                 string Array[] =  {"outputdir","iters","phylip","design","alpha", "inputdir"};
19                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
20                 return myArray;
21         }
22         catch(exception& e) {
23                 m->errorOut(e, "HomovaCommand", "getValidParameters");
24                 exit(1);
25         }
26 }
27
28 //**********************************************************************************************************************
29
30 HomovaCommand::HomovaCommand(){ 
31         try {
32                 abort = true; calledHelp = true; 
33                 vector<string> tempOutNames;
34                 outputTypes["homova"] = tempOutNames;
35         }
36         catch(exception& e) {
37                 m->errorOut(e, "HomovaCommand", "HomovaCommand");
38                 exit(1);
39         }
40 }
41
42 //**********************************************************************************************************************
43
44 vector<string> HomovaCommand::getRequiredParameters(){  
45         try {
46                 string Array[] =  {"design"};
47                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
48                 return myArray;
49         }
50         catch(exception& e) {
51                 m->errorOut(e, "HomovaCommand", "getRequiredParameters");
52                 exit(1);
53         }
54 }
55
56 //**********************************************************************************************************************
57
58 vector<string> HomovaCommand::getRequiredFiles(){       
59         try {
60                 string Array[] =  {};
61                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
62                 return myArray;
63         }
64         catch(exception& e) {
65                 m->errorOut(e, "HomovaCommand", "getRequiredFiles");
66                 exit(1);
67         }
68 }
69
70 //**********************************************************************************************************************
71
72 HomovaCommand::HomovaCommand(string option) {
73         try {
74                 abort = false; calledHelp = false;   
75                 
76                 //allow user to run help
77                 if(option == "help") { help(); abort = true; calledHelp = true; }
78                 
79                 else {
80                         //valid paramters for this command
81                         string AlignArray[] =  {"design","outputdir","iters","phylip","alpha", "inputdir"};
82                         vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
83                         
84                         OptionParser parser(option);
85                         map<string,string> parameters = parser.getParameters();
86                         
87                         ValidParameters validParameter;
88                         
89                         //check to make sure all parameters are valid for command
90                         map<string,string>::iterator it;
91                         for (it = parameters.begin(); it != parameters.end(); it++) { 
92                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
93                         }
94                         
95                         //initialize outputTypes
96                         vector<string> tempOutNames;
97                         outputTypes["homova"] = tempOutNames;
98                         
99                         //if the user changes the output directory command factory will send this info to us in the output parameter 
100                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
101                         
102                         //if the user changes the input directory command factory will send this info to us in the output parameter 
103                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
104                         if (inputDir == "not found"){   inputDir = "";          }
105                         else {
106                                 string path;
107                                 it = parameters.find("design");
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["design"] = inputDir + it->second;           }
113                                 }
114                                 
115                                 it = parameters.find("phylip");
116                                 //user has given a template file
117                                 if(it != parameters.end()){ 
118                                         path = m->hasPath(it->second);
119                                         //if the user has not given a path then, add inputdir. else leave path alone.
120                                         if (path == "") {       parameters["phylip"] = inputDir + it->second;           }
121                                 }
122                         }
123                         
124                         phylipFileName = validParameter.validFile(parameters, "phylip", true);
125                         if (phylipFileName == "not open") { phylipFileName = ""; abort = true; }
126                         else if (phylipFileName == "not found") { phylipFileName = ""; }        
127                         else if (designFileName == "not found") {
128                                 designFileName = "";
129                                 m->mothurOut("You must provide an phylip file.");
130                                 m->mothurOutEndLine();
131                                 abort = true;
132                         }       
133                         
134                         //check for required parameters
135                         designFileName = validParameter.validFile(parameters, "design", true);
136                         if (designFileName == "not open") { abort = true; }
137                         else if (designFileName == "not found") {
138                                 designFileName = "";
139                                 m->mothurOut("You must provide an design file.");
140                                 m->mothurOutEndLine();
141                                 abort = true;
142                         }       
143                         
144                         string temp = validParameter.validFile(parameters, "iters", false);
145                         if (temp == "not found") { temp = "1000"; }
146                         convert(temp, iters); 
147                         
148                         temp = validParameter.validFile(parameters, "alpha", false);
149                         if (temp == "not found") { temp = "0.05"; }
150                         convert(temp, experimentwiseAlpha); 
151                 }
152                 
153         }
154         catch(exception& e) {
155                 m->errorOut(e, "HomovaCommand", "HomovaCommand");
156                 exit(1);
157         }
158 }
159
160 //**********************************************************************************************************************
161
162 void HomovaCommand::help(){
163         try {
164                 m->mothurOut("Referenced: Stewart CN, Excoffier L (1996). Assessing population genetic structure and variability with RAPD data: Application to Vaccinium macrocarpon (American Cranberry). J Evol Biol 9: 153-71.\n");
165                 m->mothurOut("The homova command outputs a .homova file. \n");
166                 m->mothurOut("The homova command parameters are phylip, iters, and alpha.  The phylip and design parameters are required.\n");
167                 m->mothurOut("The design parameter allows you to assign your samples to groups when you are running homova. It is required. \n");
168                 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");
169                 m->mothurOut("The iters parameter allows you to set number of randomization for the P value.  The default is 1000. \n");
170                 m->mothurOut("The homova command should be in the following format: homova(phylip=file.dist, design=file.design).\n");
171                 m->mothurOut("Note: No spaces between parameter labels (i.e. iters), '=' and parameters (i.e. 1000).\n\n");
172         }
173         catch(exception& e) {
174                 m->errorOut(e, "HomovaCommand", "help");
175                 exit(1);
176         }
177 }
178
179 //**********************************************************************************************************************
180
181 HomovaCommand::~HomovaCommand(){}
182
183 //**********************************************************************************************************************
184
185 int HomovaCommand::execute(){
186         try {
187                 
188                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
189                 
190                 //read design file
191                 designMap = new GroupMap(designFileName);
192                 designMap->readDesignMap();
193                 
194                 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
195                 
196                 //read in distance matrix and square it
197                 ReadPhylipVector readMatrix(phylipFileName);
198                 vector<string> sampleNames = readMatrix.read(distanceMatrix);
199                 
200                 for(int i=0;i<distanceMatrix.size();i++){
201                         for(int j=0;j<i;j++){
202                                 distanceMatrix[i][j] *= distanceMatrix[i][j];   
203                         }
204                 }
205                 
206                 //link designMap to rows/columns in distance matrix
207                 map<string, vector<int> > origGroupSampleMap;
208                 for(int i=0;i<sampleNames.size();i++){
209                         origGroupSampleMap[designMap->getGroup(sampleNames[i])].push_back(i);
210                 }
211                 int numGroups = origGroupSampleMap.size();
212                 
213                 //create a new filename
214                 ofstream HOMOVAFile;
215                 string HOMOVAFileName = outputDir + m->getRootName(m->getSimpleName(phylipFileName))  + "homova";                               
216                 m->openOutputFile(HOMOVAFileName, HOMOVAFile);
217                 outputNames.push_back(HOMOVAFileName); outputTypes["homova"].push_back(HOMOVAFileName);
218                 
219                 HOMOVAFile << "HOMOVA\tBValue\tP-value\tSSwithin_values" << endl;
220                 m->mothurOut("HOMOVA\tBValue\tP-value\tSSwithin_values\n");
221                 
222                 double fullHOMOVAPValue = runHOMOVA(HOMOVAFile, origGroupSampleMap, experimentwiseAlpha);
223
224                 if(fullHOMOVAPValue <= experimentwiseAlpha && numGroups > 2){
225                         
226                         int numCombos = numGroups * (numGroups-1) / 2;
227                         double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
228                         
229                         map<string, vector<int> >::iterator itA;
230                         map<string, vector<int> >::iterator itB;
231                         
232                         for(itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
233                                 itB = itA;itB++;
234                                 for(itB;itB!=origGroupSampleMap.end();itB++){
235                                         
236                                         map<string, vector<int> > pairwiseGroupSampleMap;
237                                         pairwiseGroupSampleMap[itA->first] = itA->second;
238                                         pairwiseGroupSampleMap[itB->first] = itB->second;
239                                         
240                                         runHOMOVA(HOMOVAFile, pairwiseGroupSampleMap, pairwiseAlpha);
241                                 }                       
242                         }
243                         HOMOVAFile << endl;
244                         m->mothurOutEndLine();
245                         
246                         m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
247                         m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
248                 }
249                 else{
250                         m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
251                 }
252                 
253                 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
254                 
255                 delete designMap;
256                 
257                 m->mothurOutEndLine();
258                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
259                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
260                 m->mothurOutEndLine();
261                 
262                 return 0;
263         }
264         catch(exception& e) {
265                 m->errorOut(e, "HomovaCommand", "execute");
266                 exit(1);
267         }
268 }
269
270 //**********************************************************************************************************************
271
272 double HomovaCommand::runHOMOVA(ofstream& HOMOVAFile, map<string, vector<int> > groupSampleMap, double alpha){
273         try {
274                 map<string, vector<int> >::iterator it;
275                 int numGroups = groupSampleMap.size();
276                 
277                 vector<double> ssWithinOrigVector;
278                 double bValueOrig = calcBValue(groupSampleMap, ssWithinOrigVector);
279                 
280                 double counter = 0;
281                 for(int i=0;i<iters;i++){
282                         vector<double> ssWithinRandVector;
283                         map<string, vector<int> > randomizedGroup = getRandomizedGroups(groupSampleMap);
284                         double bValueRand = calcBValue(randomizedGroup, ssWithinRandVector);
285                         if(bValueRand > bValueOrig){    counter++;      }
286                 }
287                 
288                 double pValue = (double) counter / (double) iters;
289                 string pString = "";
290                 if(pValue < 1/(double)iters){   pString = '<' + toString(1/(double)iters);      }
291                 else                                            {       pString = toString(pValue);                                     }
292                 
293                 
294                 //print homova table
295                 it = groupSampleMap.begin();
296                 HOMOVAFile << it->first;
297                 m->mothurOut(it->first);
298                 it++;
299                 for(it;it!=groupSampleMap.end();it++){
300                         HOMOVAFile << '-' << it->first;
301                         m->mothurOut('-' + it->first);
302                 }
303
304                 HOMOVAFile << '\t' << bValueOrig << '\t' << pString;
305                 m->mothurOut('\t' + toString(bValueOrig) + '\t' + pString);
306                 
307                 if(pValue < alpha){
308                         HOMOVAFile << "*";
309                         m->mothurOut("*");
310                 }
311
312                 for(int i=0;i<numGroups;i++){
313                         HOMOVAFile << '\t' << ssWithinOrigVector[i];
314                         m->mothurOut('\t' + toString(ssWithinOrigVector[i]));
315                 }
316                 HOMOVAFile << endl;
317                 m->mothurOutEndLine();
318                 
319                 return pValue;  
320         }
321         catch(exception& e) {
322                 m->errorOut(e, "HomovaCommand", "runHOMOVA");
323                 exit(1);
324         }
325 }
326
327 //**********************************************************************************************************************
328
329 double HomovaCommand::calcSigleSSWithin(vector<int> sampleIndices) {
330         try {
331                 double ssWithin = 0.0;
332                 int numSamplesInGroup = sampleIndices.size();
333                 
334                 for(int i=0;i<numSamplesInGroup;i++){
335                         int row = sampleIndices[i];
336                         
337                         for(int j=0;j<numSamplesInGroup;j++){
338                                 int col = sampleIndices[j];
339                                 
340                                 if(col < row){
341                                         ssWithin += distanceMatrix[row][col];
342                                 }
343                                 
344                         }
345                 }
346                 
347                 ssWithin /= numSamplesInGroup;
348                 return ssWithin;
349         }
350         catch(exception& e) {
351                 m->errorOut(e, "HomovaCommand", "calcSigleSSWithin");
352                 exit(1);
353         }
354 }
355
356 //**********************************************************************************************************************
357
358 double HomovaCommand::calcBValue(map<string, vector<int> > groupSampleMap, vector<double>& ssWithinVector) {
359         try {
360
361                 map<string, vector<int> >::iterator it;
362                 
363                 double numGroups = (double)groupSampleMap.size();
364                 ssWithinVector.resize(numGroups, 0);
365                 
366                 double totalNumSamples = 0;
367                 double ssWithinFull;
368                 double secondTermSum = 0;
369                 double inverseOneMinusSum = 0;
370                 int index = 0;
371                 
372                 ssWithinVector.resize(numGroups, 0);
373                 for(it = groupSampleMap.begin();it!=groupSampleMap.end();it++){
374                         int numSamplesInGroup = it->second.size();
375                         totalNumSamples += numSamplesInGroup;
376                         
377                         ssWithinVector[index] = calcSigleSSWithin(it->second);
378                         ssWithinFull += ssWithinVector[index];
379                         
380                         secondTermSum += (numSamplesInGroup - 1) * log(ssWithinVector[index] / (double)(numSamplesInGroup - 1));
381                         inverseOneMinusSum += 1.0 / (double)(numSamplesInGroup - 1);
382                         index++;
383                 }
384                 
385                 double B = (totalNumSamples - numGroups) * log(ssWithinFull/(totalNumSamples-numGroups)) - secondTermSum;
386                 double denomintor = 1 + 1.0/(3.0 * (numGroups - 1.0)) * (inverseOneMinusSum - 1.0 / (double) (totalNumSamples - numGroups));
387                 B /= denomintor;
388                 
389                 return B;
390                 
391         }
392         catch(exception& e) {
393                 m->errorOut(e, "HomovaCommand", "calcBValue");
394                 exit(1);
395         }
396 }
397
398 //**********************************************************************************************************************
399
400 map<string, vector<int> > HomovaCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
401         try{
402                 vector<int> sampleIndices;
403                 vector<int> samplesPerGroup;
404                 
405                 map<string, vector<int> >::iterator it;
406                 for(it=origMapping.begin();it!=origMapping.end();it++){
407                         vector<int> indices = it->second;
408                         samplesPerGroup.push_back(indices.size());
409                         sampleIndices.insert(sampleIndices.end(), indices.begin(), indices.end());
410                 }
411                 
412                 random_shuffle(sampleIndices.begin(), sampleIndices.end());
413                 
414                 int index = 0;
415                 map<string, vector<int> > randomizedGroups = origMapping;
416                 for(it=randomizedGroups.begin();it!=randomizedGroups.end();it++){
417                         for(int i=0;i<it->second.size();i++){
418                                 it->second[i] = sampleIndices[index++];                         
419                         }
420                 }
421                 
422                 return randomizedGroups;                
423         }
424         catch (exception& e) {
425                 m->errorOut(e, "AmovaCommand", "randomizeGroups");
426                 exit(1);
427         }
428 }
429
430 //**********************************************************************************************************************
431
432