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");
53 //**********************************************************************************************************************
55 HomovaCommand::HomovaCommand(){
57 abort = true; calledHelp = true;
59 vector<string> tempOutNames;
60 outputTypes["homova"] = tempOutNames;
63 m->errorOut(e, "HomovaCommand", "HomovaCommand");
67 //**********************************************************************************************************************
69 HomovaCommand::HomovaCommand(string option) {
71 abort = false; calledHelp = false;
73 //allow user to run help
74 if(option == "help") { help(); abort = true; calledHelp = true; }
77 vector<string> myArray = setParameters();
79 OptionParser parser(option);
80 map<string,string> parameters = parser.getParameters();
82 ValidParameters validParameter;
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; }
90 //initialize outputTypes
91 vector<string> tempOutNames;
92 outputTypes["homova"] = tempOutNames;
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 = ""; }
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 = ""; }
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; }
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; }
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; }
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; }
139 string temp = validParameter.validFile(parameters, "iters", false);
140 if (temp == "not found") { temp = "1000"; }
141 convert(temp, iters);
143 temp = validParameter.validFile(parameters, "alpha", false);
144 if (temp == "not found") { temp = "0.05"; }
145 convert(temp, experimentwiseAlpha);
149 catch(exception& e) {
150 m->errorOut(e, "HomovaCommand", "HomovaCommand");
154 //**********************************************************************************************************************
156 int HomovaCommand::execute(){
159 if (abort == true) { if (calledHelp) { return 0; } return 2; }
162 designMap = new GroupMap(designFileName);
163 designMap->readDesignMap();
165 if (outputDir == "") { outputDir = m->hasPath(phylipFileName); }
167 //read in distance matrix and square it
168 ReadPhylipVector readMatrix(phylipFileName);
169 vector<string> sampleNames = readMatrix.read(distanceMatrix);
171 for(int i=0;i<distanceMatrix.size();i++){
172 for(int j=0;j<i;j++){
173 distanceMatrix[i][j] *= distanceMatrix[i][j];
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);
182 int numGroups = origGroupSampleMap.size();
184 //create a new filename
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);
190 HOMOVAFile << "HOMOVA\tBValue\tP-value\tSSwithin/(Ni-1)_values" << endl;
191 m->mothurOut("HOMOVA\tBValue\tP-value\tSSwithin/(Ni-1)_values\n");
193 double fullHOMOVAPValue = runHOMOVA(HOMOVAFile, origGroupSampleMap, experimentwiseAlpha);
195 if(fullHOMOVAPValue <= experimentwiseAlpha && numGroups > 2){
197 int numCombos = numGroups * (numGroups-1) / 2;
198 double pairwiseAlpha = experimentwiseAlpha / (double) numCombos;
200 map<string, vector<int> >::iterator itA;
201 map<string, vector<int> >::iterator itB;
203 for(itA=origGroupSampleMap.begin();itA!=origGroupSampleMap.end();itA++){
205 for(;itB!=origGroupSampleMap.end();itB++){
206 map<string, vector<int> > pairwiseGroupSampleMap;
207 pairwiseGroupSampleMap[itA->first] = itA->second;
208 pairwiseGroupSampleMap[itB->first] = itB->second;
210 runHOMOVA(HOMOVAFile, pairwiseGroupSampleMap, pairwiseAlpha);
214 m->mothurOutEndLine();
216 m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
217 m->mothurOut("Pair-wise error rate (Bonferroni): " + toString(pairwiseAlpha) + '\n');
220 m->mothurOut("Experiment-wise error rate: " + toString(experimentwiseAlpha) + '\n');
223 m->mothurOut("If you have borderline P-values, you should try increasing the number of iterations\n");
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();
234 catch(exception& e) {
235 m->errorOut(e, "HomovaCommand", "execute");
240 //**********************************************************************************************************************
242 double HomovaCommand::runHOMOVA(ofstream& HOMOVAFile, map<string, vector<int> > groupSampleMap, double alpha){
244 map<string, vector<int> >::iterator it;
245 int numGroups = groupSampleMap.size();
247 vector<double> ssWithinOrigVector;
248 double bValueOrig = calcBValue(groupSampleMap, ssWithinOrigVector);
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++; }
258 double pValue = (double) counter / (double) iters;
260 if(pValue < 1/(double)iters){ pString = '<' + toString(1/(double)iters); }
261 else { pString = toString(pValue); }
265 it = groupSampleMap.begin();
266 HOMOVAFile << it->first;
267 m->mothurOut(it->first);
269 for(;it!=groupSampleMap.end();it++){
270 HOMOVAFile << '-' << it->first;
271 m->mothurOut('-' + it->first);
274 HOMOVAFile << '\t' << bValueOrig << '\t' << pString;
275 m->mothurOut('\t' + toString(bValueOrig) + '\t' + pString);
282 for(int i=0;i<numGroups;i++){
283 HOMOVAFile << '\t' << ssWithinOrigVector[i];
284 m->mothurOut('\t' + toString(ssWithinOrigVector[i]));
287 m->mothurOutEndLine();
291 catch(exception& e) {
292 m->errorOut(e, "HomovaCommand", "runHOMOVA");
297 //**********************************************************************************************************************
299 double HomovaCommand::calcSigleSSWithin(vector<int> sampleIndices) {
301 double ssWithin = 0.0;
302 int numSamplesInGroup = sampleIndices.size();
304 for(int i=0;i<numSamplesInGroup;i++){
305 int row = sampleIndices[i];
307 for(int j=0;j<numSamplesInGroup;j++){
308 int col = sampleIndices[j];
311 ssWithin += distanceMatrix[row][col];
317 ssWithin /= numSamplesInGroup;
320 catch(exception& e) {
321 m->errorOut(e, "HomovaCommand", "calcSigleSSWithin");
326 //**********************************************************************************************************************
328 double HomovaCommand::calcBValue(map<string, vector<int> > groupSampleMap, vector<double>& ssWithinVector) {
331 map<string, vector<int> >::iterator it;
333 double numGroups = (double)groupSampleMap.size();
334 ssWithinVector.resize(numGroups, 0);
336 double totalNumSamples = 0;
338 double secondTermSum = 0;
339 double inverseOneMinusSum = 0;
342 ssWithinVector.resize(numGroups, 0);
343 for(it = groupSampleMap.begin();it!=groupSampleMap.end();it++){
344 int numSamplesInGroup = it->second.size();
345 totalNumSamples += numSamplesInGroup;
347 ssWithinVector[index] = calcSigleSSWithin(it->second);
348 ssWithinFull += ssWithinVector[index];
350 secondTermSum += (numSamplesInGroup - 1) * log(ssWithinVector[index] / (double)(numSamplesInGroup - 1));
351 inverseOneMinusSum += 1.0 / (double)(numSamplesInGroup - 1);
353 ssWithinVector[index] /= (double)(numSamplesInGroup - 1); //this line is only for output purposes to scale SSw by the number of samples in the group
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));
364 catch(exception& e) {
365 m->errorOut(e, "HomovaCommand", "calcBValue");
370 //**********************************************************************************************************************
372 map<string, vector<int> > HomovaCommand::getRandomizedGroups(map<string, vector<int> > origMapping){
374 vector<int> sampleIndices;
375 vector<int> samplesPerGroup;
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());
384 random_shuffle(sampleIndices.begin(), sampleIndices.end());
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++];
394 return randomizedGroups;
396 catch (exception& e) {
397 m->errorOut(e, "AmovaCommand", "randomizeGroups");
402 //**********************************************************************************************************************