5 * Created by westcott on 2/8/11.
6 * Copyright 2011 Schloss Lab. All rights reserved.
10 #include "homovacommand.h"
12 #include "readphylipvector.h"
14 //**********************************************************************************************************************
15 vector<string> HomovaCommand::setParameters(){
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);
24 vector<string> myArray;
25 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
29 m->errorOut(e, "HomovaCommand", "setParameters");
33 //**********************************************************************************************************************
34 string HomovaCommand::getHelpString(){
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";
48 m->errorOut(e, "HomovaCommand", "getHelpString");
52 //**********************************************************************************************************************
53 string HomovaCommand::getOutputFileNameTag(string type, string inputName=""){
55 string outputFileName = "";
56 map<string, vector<string> >::iterator it;
58 //is this a type this command creates
59 it = outputTypes.find(type);
60 if (it == outputTypes.end()) { m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
62 if (type == "homova") { outputFileName = "homova"; }
63 else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true; }
65 return outputFileName;
68 m->errorOut(e, "HomovaCommand", "getOutputFileNameTag");
72 //**********************************************************************************************************************
73 HomovaCommand::HomovaCommand(){
75 abort = true; calledHelp = true;
77 vector<string> tempOutNames;
78 outputTypes["homova"] = tempOutNames;
81 m->errorOut(e, "HomovaCommand", "HomovaCommand");
85 //**********************************************************************************************************************
87 HomovaCommand::HomovaCommand(string option) {
89 abort = false; calledHelp = false;
91 //allow user to run help
92 if(option == "help") { help(); abort = true; calledHelp = true; }
93 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
96 vector<string> myArray = setParameters();
98 OptionParser parser(option);
99 map<string,string> parameters = parser.getParameters();
101 ValidParameters validParameter;
103 //check to make sure all parameters are valid for command
104 map<string,string>::iterator it;
105 for (it = parameters.begin(); it != parameters.end(); it++) {
106 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
109 //initialize outputTypes
110 vector<string> tempOutNames;
111 outputTypes["homova"] = tempOutNames;
113 //if the user changes the output directory command factory will send this info to us in the output parameter
114 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
116 //if the user changes the input directory command factory will send this info to us in the output parameter
117 string inputDir = validParameter.validFile(parameters, "inputdir", false);
118 if (inputDir == "not found"){ inputDir = ""; }
121 it = parameters.find("design");
122 //user has given a template file
123 if(it != parameters.end()){
124 path = m->hasPath(it->second);
125 //if the user has not given a path then, add inputdir. else leave path alone.
126 if (path == "") { parameters["design"] = inputDir + it->second; }
129 it = parameters.find("phylip");
130 //user has given a template file
131 if(it != parameters.end()){
132 path = m->hasPath(it->second);
133 //if the user has not given a path then, add inputdir. else leave path alone.
134 if (path == "") { parameters["phylip"] = inputDir + it->second; }
138 phylipFileName = validParameter.validFile(parameters, "phylip", true);
139 if (phylipFileName == "not open") { phylipFileName = ""; abort = true; }
140 else if (phylipFileName == "not found") {
141 //if there is a current phylip file, use it
142 phylipFileName = m->getPhylipFile();
143 if (phylipFileName != "") { m->mothurOut("Using " + phylipFileName + " as input file for the phylip parameter."); m->mothurOutEndLine(); }
144 else { m->mothurOut("You have no current phylip file and the phylip parameter is required."); m->mothurOutEndLine(); abort = true; }
146 }else { m->setPhylipFile(phylipFileName); }
148 //check for required parameters
149 designFileName = validParameter.validFile(parameters, "design", true);
150 if (designFileName == "not open") { abort = true; }
151 else if (designFileName == "not found") {
152 //if there is a current design file, use it
153 designFileName = m->getDesignFile();
154 if (designFileName != "") { m->mothurOut("Using " + designFileName + " as input file for the design parameter."); m->mothurOutEndLine(); }
155 else { m->mothurOut("You have no current design file and the design parameter is required."); m->mothurOutEndLine(); abort = true; }
156 }else { m->setDesignFile(designFileName); }
158 string temp = validParameter.validFile(parameters, "iters", false);
159 if (temp == "not found") { temp = "1000"; }
160 m->mothurConvert(temp, iters);
162 temp = validParameter.validFile(parameters, "alpha", false);
163 if (temp == "not found") { temp = "0.05"; }
164 m->mothurConvert(temp, experimentwiseAlpha);
168 catch(exception& e) {
169 m->errorOut(e, "HomovaCommand", "HomovaCommand");
173 //**********************************************************************************************************************
175 int HomovaCommand::execute(){
178 if (abort == true) { if (calledHelp) { return 0; } return 2; }
181 designMap = new GroupMap(designFileName);
182 designMap->readDesignMap();
184 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
186 //read in distance matrix and square it
187 ReadPhylipVector readMatrix(phylipFileName);
188 vector<string> sampleNames = readMatrix.read(distanceMatrix);
190 for(int i=0;i<distanceMatrix.size();i++){
191 for(int j=0;j<i;j++){
192 distanceMatrix[i][j] *= distanceMatrix[i][j];
196 //link designMap to rows/columns in distance matrix
197 map<string, vector<int> > origGroupSampleMap;
198 for(int i=0;i<sampleNames.size();i++){
199 string group = designMap->getGroup(sampleNames[i]);
201 if (group == "not found") {
202 m->mothurOut("[ERROR]: " + sampleNames[i] + " is not in your design file, please correct."); m->mothurOutEndLine(); m->control_pressed = true;
203 }else { origGroupSampleMap[group].push_back(i); }
205 int numGroups = origGroupSampleMap.size();
207 if (m->control_pressed) { delete designMap; return 0; }
209 //create a new filename
211 string HOMOVAFileName = outputDir + m->getRootName(m->getSimpleName(phylipFileName)) + getOutputFileNameTag("homova");
212 m->openOutputFile(HOMOVAFileName, HOMOVAFile);
213 outputNames.push_back(HOMOVAFileName); outputTypes["homova"].push_back(HOMOVAFileName);
215 HOMOVAFile << "HOMOVA\tBValue\tP-value\tSSwithin/(Ni-1)_values" << endl;
216 m->mothurOut("HOMOVA\tBValue\tP-value\tSSwithin/(Ni-1)_values\n");
218 double fullHOMOVAPValue = runHOMOVA(HOMOVAFile, origGroupSampleMap, experimentwiseAlpha);
220 if(fullHOMOVAPValue <= experimentwiseAlpha && numGroups > 2){
222 int numCombos = numGroups * (numGroups-1) / 2;
223 double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
225 map<string, vector<int> >::iterator itA;
226 map<string, vector<int> >::iterator itB;
228 for(itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
230 for(;itB!=origGroupSampleMap.end();itB++){
231 map<string, vector<int> > pairwiseGroupSampleMap;
232 pairwiseGroupSampleMap[itA->first] = itA->second;
233 pairwiseGroupSampleMap[itB->first] = itB->second;
235 runHOMOVA(HOMOVAFile, pairwiseGroupSampleMap, pairwiseAlpha);
239 m->mothurOutEndLine();
241 m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
242 m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
245 m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
248 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
252 m->mothurOutEndLine();
253 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
254 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
255 m->mothurOutEndLine();
259 catch(exception& e) {
260 m->errorOut(e, "HomovaCommand", "execute");
265 //**********************************************************************************************************************
267 double HomovaCommand::runHOMOVA(ofstream& HOMOVAFile, map<string, vector<int> > groupSampleMap, double alpha){
269 map<string, vector<int> >::iterator it;
270 int numGroups = groupSampleMap.size();
272 vector<double> ssWithinOrigVector;
273 double bValueOrig = calcBValue(groupSampleMap, ssWithinOrigVector);
276 for(int i=0;i<iters;i++){
277 vector<double> ssWithinRandVector;
278 map<string, vector<int> > randomizedGroup = getRandomizedGroups(groupSampleMap);
279 double bValueRand = calcBValue(randomizedGroup, ssWithinRandVector);
280 if(bValueRand > bValueOrig){ counter++; }
283 double pValue = (double) counter / (double) iters;
285 if(pValue < 1/(double)iters){ pString = '<' + toString(1/(double)iters); }
286 else { pString = toString(pValue); }
290 it = groupSampleMap.begin();
291 HOMOVAFile << it->first;
292 m->mothurOut(it->first);
294 for(;it!=groupSampleMap.end();it++){
295 HOMOVAFile << '-' << it->first;
296 m->mothurOut('-' + it->first);
299 HOMOVAFile << '\t' << bValueOrig << '\t' << pString;
300 m->mothurOut('\t' + toString(bValueOrig) + '\t' + pString);
307 for(int i=0;i<numGroups;i++){
308 HOMOVAFile << '\t' << ssWithinOrigVector[i];
309 m->mothurOut('\t' + toString(ssWithinOrigVector[i]));
312 m->mothurOutEndLine();
316 catch(exception& e) {
317 m->errorOut(e, "HomovaCommand", "runHOMOVA");
322 //**********************************************************************************************************************
324 double HomovaCommand::calcSigleSSWithin(vector<int> sampleIndices) {
326 double ssWithin = 0.0;
327 int numSamplesInGroup = sampleIndices.size();
329 for(int i=0;i<numSamplesInGroup;i++){
330 int row = sampleIndices[i];
332 for(int j=0;j<numSamplesInGroup;j++){
333 int col = sampleIndices[j];
336 ssWithin += distanceMatrix[row][col];
342 ssWithin /= numSamplesInGroup;
345 catch(exception& e) {
346 m->errorOut(e, "HomovaCommand", "calcSigleSSWithin");
351 //**********************************************************************************************************************
353 double HomovaCommand::calcBValue(map<string, vector<int> > groupSampleMap, vector<double>& ssWithinVector) {
356 map<string, vector<int> >::iterator it;
358 double numGroups = (double)groupSampleMap.size();
359 ssWithinVector.resize(numGroups, 0);
361 double totalNumSamples = 0;
363 double secondTermSum = 0;
364 double inverseOneMinusSum = 0;
367 ssWithinVector.resize(numGroups, 0);
368 for(it = groupSampleMap.begin();it!=groupSampleMap.end();it++){
369 int numSamplesInGroup = it->second.size();
370 totalNumSamples += numSamplesInGroup;
372 ssWithinVector[index] = calcSigleSSWithin(it->second);
373 ssWithinFull += ssWithinVector[index];
375 secondTermSum += (numSamplesInGroup - 1) * log(ssWithinVector[index] / (double)(numSamplesInGroup - 1));
376 inverseOneMinusSum += 1.0 / (double)(numSamplesInGroup - 1);
378 ssWithinVector[index] /= (double)(numSamplesInGroup - 1); //this line is only for output purposes to scale SSw by the number of samples in the group
382 double B = (totalNumSamples - numGroups) * log(ssWithinFull/(totalNumSamples-numGroups)) - secondTermSum;
383 double denomintor = 1 + 1.0/(3.0 * (numGroups - 1.0)) * (inverseOneMinusSum - 1.0 / (double) (totalNumSamples - numGroups));
389 catch(exception& e) {
390 m->errorOut(e, "HomovaCommand", "calcBValue");
395 //**********************************************************************************************************************
397 map<string, vector<int> > HomovaCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
399 vector<int> sampleIndices;
400 vector<int> samplesPerGroup;
402 map<string, vector<int> >::iterator it;
403 for(it=origMapping.begin();it!=origMapping.end();it++){
404 vector<int> indices = it->second;
405 samplesPerGroup.push_back(indices.size());
406 sampleIndices.insert(sampleIndices.end(), indices.begin(), indices.end());
409 random_shuffle(sampleIndices.begin(), sampleIndices.end());
412 map<string, vector<int> > randomizedGroups = origMapping;
413 for(it=randomizedGroups.begin();it!=randomizedGroups.end();it++){
414 for(int i=0;i<it->second.size();i++){
415 it->second[i] = sampleIndices[index++];
419 return randomizedGroups;
421 catch (exception& e) {
422 m->errorOut(e, "AmovaCommand", "randomizeGroups");
427 //**********************************************************************************************************************