]> git.donarmstrong.com Git - mothur.git/blob - homovacommand.cpp
added getCommandInfoCommand for gui
[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 vector<string> HomovaCommand::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, "HomovaCommand", "setParameters");
30                 exit(1);
31         }
32 }
33 //**********************************************************************************************************************
34 string HomovaCommand::getHelpString(){  
35         try {
36                 string helpString = "";
37                 helpString += "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";
38                 helpString += "The homova command outputs a .homova file. \n";
39                 helpString += "The homova command parameters are phylip, iters, and alpha.  The phylip and design parameters are required, unless valid current files exist.\n";
40                 helpString += "The design parameter allows you to assign your samples to groups when you are running homova. 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 homova command should be in the following format: homova(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, "HomovaCommand", "getHelpString");
49                 exit(1);
50         }
51 }
52
53 //**********************************************************************************************************************
54
55 HomovaCommand::HomovaCommand(){ 
56         try {
57                 abort = true; calledHelp = true; 
58                 setParameters();
59                 vector<string> tempOutNames;
60                 outputTypes["homova"] = tempOutNames;
61         }
62         catch(exception& e) {
63                 m->errorOut(e, "HomovaCommand", "HomovaCommand");
64                 exit(1);
65         }
66 }
67 //**********************************************************************************************************************
68
69 HomovaCommand::HomovaCommand(string option) {
70         try {
71                 abort = false; calledHelp = false;   
72                 
73                 //allow user to run help
74                 if(option == "help") { help(); 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["homova"] = 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                         }       
128                         
129                         //check for required parameters
130                         designFileName = validParameter.validFile(parameters, "design", true);
131                         if (designFileName == "not open") { 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                         }       
138                         
139                         string temp = validParameter.validFile(parameters, "iters", false);
140                         if (temp == "not found") { temp = "1000"; }
141                         convert(temp, iters); 
142                         
143                         temp = validParameter.validFile(parameters, "alpha", false);
144                         if (temp == "not found") { temp = "0.05"; }
145                         convert(temp, experimentwiseAlpha); 
146                 }
147                 
148         }
149         catch(exception& e) {
150                 m->errorOut(e, "HomovaCommand", "HomovaCommand");
151                 exit(1);
152         }
153 }
154 //**********************************************************************************************************************
155
156 int HomovaCommand::execute(){
157         try {
158                 
159                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
160                 
161                 //read design file
162                 designMap = new GroupMap(designFileName);
163                 designMap->readDesignMap();
164                 
165                 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
166                 
167                 //read in distance matrix and square it
168                 ReadPhylipVector readMatrix(phylipFileName);
169                 vector<string> sampleNames = readMatrix.read(distanceMatrix);
170                 
171                 for(int i=0;i<distanceMatrix.size();i++){
172                         for(int j=0;j<i;j++){
173                                 distanceMatrix[i][j] *= distanceMatrix[i][j];   
174                         }
175                 }
176                 
177                 //link designMap to rows/columns in distance matrix
178                 map<string, vector<int> > origGroupSampleMap;
179                 for(int i=0;i<sampleNames.size();i++){
180                         origGroupSampleMap[designMap->getGroup(sampleNames[i])].push_back(i);
181                 }
182                 int numGroups = origGroupSampleMap.size();
183                 
184                 //create a new filename
185                 ofstream HOMOVAFile;
186                 string HOMOVAFileName = outputDir + m->getRootName(m->getSimpleName(phylipFileName))  + "homova";                               
187                 m->openOutputFile(HOMOVAFileName, HOMOVAFile);
188                 outputNames.push_back(HOMOVAFileName); outputTypes["homova"].push_back(HOMOVAFileName);
189                 
190                 HOMOVAFile << "HOMOVA\tBValue\tP-value\tSSwithin/(Ni-1)_values" << endl;
191                 m->mothurOut("HOMOVA\tBValue\tP-value\tSSwithin/(Ni-1)_values\n");
192                 
193                 double fullHOMOVAPValue = runHOMOVA(HOMOVAFile, origGroupSampleMap, experimentwiseAlpha);
194
195                 if(fullHOMOVAPValue <= experimentwiseAlpha && numGroups > 2){
196                         
197                         int numCombos = numGroups * (numGroups-1) / 2;
198                         double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
199                         
200                         map<string, vector<int> >::iterator itA;
201                         map<string, vector<int> >::iterator itB;
202                         
203                         for(itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
204                                 itB = itA;itB++;
205                                 for(;itB!=origGroupSampleMap.end();itB++){
206                                         map<string, vector<int> > pairwiseGroupSampleMap;
207                                         pairwiseGroupSampleMap[itA->first] = itA->second;
208                                         pairwiseGroupSampleMap[itB->first] = itB->second;
209                                         
210                                         runHOMOVA(HOMOVAFile, pairwiseGroupSampleMap, pairwiseAlpha);
211                                 }                       
212                         }
213                         HOMOVAFile << endl;
214                         m->mothurOutEndLine();
215                         
216                         m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
217                         m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
218                 }
219                 else{
220                         m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
221                 }
222                 
223                 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
224                 
225                 delete designMap;
226                 
227                 m->mothurOutEndLine();
228                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
229                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
230                 m->mothurOutEndLine();
231                 
232                 return 0;
233         }
234         catch(exception& e) {
235                 m->errorOut(e, "HomovaCommand", "execute");
236                 exit(1);
237         }
238 }
239
240 //**********************************************************************************************************************
241
242 double HomovaCommand::runHOMOVA(ofstream& HOMOVAFile, map<string, vector<int> > groupSampleMap, double alpha){
243         try {
244                 map<string, vector<int> >::iterator it;
245                 int numGroups = groupSampleMap.size();
246                 
247                 vector<double> ssWithinOrigVector;
248                 double bValueOrig = calcBValue(groupSampleMap, ssWithinOrigVector);
249                 
250                 double counter = 0;
251                 for(int i=0;i<iters;i++){
252                         vector<double> ssWithinRandVector;
253                         map<string, vector<int> > randomizedGroup = getRandomizedGroups(groupSampleMap);
254                         double bValueRand = calcBValue(randomizedGroup, ssWithinRandVector);
255                         if(bValueRand > bValueOrig){    counter++;      }
256                 }
257                 
258                 double pValue = (double) counter / (double) iters;
259                 string pString = "";
260                 if(pValue < 1/(double)iters){   pString = '<' + toString(1/(double)iters);      }
261                 else                                            {       pString = toString(pValue);                                     }
262                 
263                 
264                 //print homova table
265                 it = groupSampleMap.begin();
266                 HOMOVAFile << it->first;
267                 m->mothurOut(it->first);
268                 it++;
269                 for(;it!=groupSampleMap.end();it++){
270                         HOMOVAFile << '-' << it->first;
271                         m->mothurOut('-' + it->first);
272                 }
273
274                 HOMOVAFile << '\t' << bValueOrig << '\t' << pString;
275                 m->mothurOut('\t' + toString(bValueOrig) + '\t' + pString);
276                 
277                 if(pValue < alpha){
278                         HOMOVAFile << "*";
279                         m->mothurOut("*");
280                 }
281
282                 for(int i=0;i<numGroups;i++){
283                         HOMOVAFile << '\t' << ssWithinOrigVector[i];
284                         m->mothurOut('\t' + toString(ssWithinOrigVector[i]));
285                 }
286                 HOMOVAFile << endl;
287                 m->mothurOutEndLine();
288                 
289                 return pValue;  
290         }
291         catch(exception& e) {
292                 m->errorOut(e, "HomovaCommand", "runHOMOVA");
293                 exit(1);
294         }
295 }
296
297 //**********************************************************************************************************************
298
299 double HomovaCommand::calcSigleSSWithin(vector<int> sampleIndices) {
300         try {
301                 double ssWithin = 0.0;
302                 int numSamplesInGroup = sampleIndices.size();
303                 
304                 for(int i=0;i<numSamplesInGroup;i++){
305                         int row = sampleIndices[i];
306                         
307                         for(int j=0;j<numSamplesInGroup;j++){
308                                 int col = sampleIndices[j];
309                                 
310                                 if(col < row){
311                                         ssWithin += distanceMatrix[row][col];
312                                 }
313                                 
314                         }
315                 }
316                 
317                 ssWithin /= numSamplesInGroup;
318                 return ssWithin;
319         }
320         catch(exception& e) {
321                 m->errorOut(e, "HomovaCommand", "calcSigleSSWithin");
322                 exit(1);
323         }
324 }
325
326 //**********************************************************************************************************************
327
328 double HomovaCommand::calcBValue(map<string, vector<int> > groupSampleMap, vector<double>& ssWithinVector) {
329         try {
330
331                 map<string, vector<int> >::iterator it;
332                 
333                 double numGroups = (double)groupSampleMap.size();
334                 ssWithinVector.resize(numGroups, 0);
335                 
336                 double totalNumSamples = 0;
337                 double ssWithinFull;
338                 double secondTermSum = 0;
339                 double inverseOneMinusSum = 0;
340                 int index = 0;
341                 
342                 ssWithinVector.resize(numGroups, 0);
343                 for(it = groupSampleMap.begin();it!=groupSampleMap.end();it++){
344                         int numSamplesInGroup = it->second.size();
345                         totalNumSamples += numSamplesInGroup;
346                         
347                         ssWithinVector[index] = calcSigleSSWithin(it->second);
348                         ssWithinFull += ssWithinVector[index];
349                         
350                         secondTermSum += (numSamplesInGroup - 1) * log(ssWithinVector[index] / (double)(numSamplesInGroup - 1));
351                         inverseOneMinusSum += 1.0 / (double)(numSamplesInGroup - 1);
352                         
353                         ssWithinVector[index] /= (double)(numSamplesInGroup - 1); //this line is only for output purposes to scale SSw by the number of samples in the group
354                         index++;
355                 }
356                 
357                 double B = (totalNumSamples - numGroups) * log(ssWithinFull/(totalNumSamples-numGroups)) - secondTermSum;
358                 double denomintor = 1 + 1.0/(3.0 * (numGroups - 1.0)) * (inverseOneMinusSum - 1.0 / (double) (totalNumSamples - numGroups));
359                 B /= denomintor;
360                 
361                 return B;
362                 
363         }
364         catch(exception& e) {
365                 m->errorOut(e, "HomovaCommand", "calcBValue");
366                 exit(1);
367         }
368 }
369
370 //**********************************************************************************************************************
371
372 map<string, vector<int> > HomovaCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
373         try{
374                 vector<int> sampleIndices;
375                 vector<int> samplesPerGroup;
376                 
377                 map<string, vector<int> >::iterator it;
378                 for(it=origMapping.begin();it!=origMapping.end();it++){
379                         vector<int> indices = it->second;
380                         samplesPerGroup.push_back(indices.size());
381                         sampleIndices.insert(sampleIndices.end(), indices.begin(), indices.end());
382                 }
383                 
384                 random_shuffle(sampleIndices.begin(), sampleIndices.end());
385                 
386                 int index = 0;
387                 map<string, vector<int> > randomizedGroups = origMapping;
388                 for(it=randomizedGroups.begin();it!=randomizedGroups.end();it++){
389                         for(int i=0;i<it->second.size();i++){
390                                 it->second[i] = sampleIndices[index++];                         
391                         }
392                 }
393                 
394                 return randomizedGroups;                
395         }
396         catch (exception& e) {
397                 m->errorOut(e, "AmovaCommand", "randomizeGroups");
398                 exit(1);
399         }
400 }
401
402 //**********************************************************************************************************************
403
404