2 // classifysharedcommand.cpp
5 // Created by Abu Zaher Md. Faridee on 8/13/12.
6 // Copyright (c) 2012 Schloss Lab. All rights reserved.
9 #include "classifysharedcommand.h"
10 #include "randomforest.hpp"
11 #include "decisiontree.hpp"
12 #include "rftreenode.hpp"
14 //**********************************************************************************************************************
15 vector<string> ClassifySharedCommand::setParameters(){
17 //CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
18 CommandParameter pshared("shared", "InputTypes", "", "", "none", "none", "none","summary",false,true,true); parameters.push_back(pshared);
19 CommandParameter pdesign("design", "InputTypes", "", "", "none", "none", "none","",false,true,true); parameters.push_back(pdesign);
20 CommandParameter potupersplit("otupersplit", "Multiple", "log2-squareroot", "log2", "", "", "","",false,false); parameters.push_back(potupersplit);
21 CommandParameter psplitcriteria("splitcriteria", "Multiple", "gainratio-infogain", "gainratio", "", "", "","",false,false); parameters.push_back(psplitcriteria);
22 CommandParameter pnumtrees("numtrees", "Number", "", "100", "", "", "","",false,false); parameters.push_back(pnumtrees);
24 // parameters related to pruning
25 CommandParameter pdopruning("prune", "Boolean", "", "T", "", "", "", "", false, false); parameters.push_back(pdopruning);
26 CommandParameter ppruneaggrns("pruneaggressiveness", "Number", "", "0.9", "", "", "", "", false, false); parameters.push_back(ppruneaggrns);
27 CommandParameter pdiscardhetrees("discarderrortrees", "Boolean", "", "T", "", "", "", "", false, false); parameters.push_back(pdiscardhetrees);
28 CommandParameter phetdiscardthreshold("errorthreshold", "Number", "", "0.4", "", "", "", "", false, false); parameters.push_back(phetdiscardthreshold);
29 CommandParameter psdthreshold("stdthreshold", "Number", "", "0.0", "", "", "", "", false, false); parameters.push_back(psdthreshold);
32 CommandParameter pgroups("groups", "String", "", "", "", "", "","",false,false); parameters.push_back(pgroups);
33 CommandParameter plabel("label", "String", "", "", "", "", "","",false,false); parameters.push_back(plabel);
34 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
35 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
37 vector<string> myArray;
38 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
42 m->errorOut(e, "ClassifySharedCommand", "setParameters");
46 //**********************************************************************************************************************
47 string ClassifySharedCommand::getHelpString(){
49 string helpString = "";
50 helpString += "The classify.shared command allows you to ....\n";
51 helpString += "The classify.shared command parameters are: shared, design, label, groups, otupersplit.\n";
52 helpString += "The label parameter is used to analyze specific labels in your input.\n";
53 helpString += "The groups parameter allows you to specify which of the groups in your designfile you would like analyzed.\n";
54 helpString += "The classify.shared should be in the following format: \n";
55 helpString += "classify.shared(shared=yourSharedFile, design=yourDesignFile)\n";
59 m->errorOut(e, "ClassifySharedCommand", "getHelpString");
63 //**********************************************************************************************************************
64 string ClassifySharedCommand::getOutputPattern(string type) {
68 if (type == "summary") { pattern = "[filename],[distance],summary"; } //makes file like: amazon.0.03.fasta
69 else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true; }
74 m->errorOut(e, "ClassifySharedCommand", "getOutputPattern");
78 //**********************************************************************************************************************
80 ClassifySharedCommand::ClassifySharedCommand() {
82 abort = true; calledHelp = true;
84 vector<string> tempOutNames;
85 outputTypes["summary"] = tempOutNames;
88 m->errorOut(e, "ClassifySharedCommand", "ClassifySharedCommand");
93 //**********************************************************************************************************************
94 ClassifySharedCommand::ClassifySharedCommand(string option) {
96 abort = false; calledHelp = false;
99 //allow user to run help
100 if(option == "help") { help(); abort = true; calledHelp = true; }
101 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
104 //valid paramters for this command
105 vector<string> myArray = setParameters();
107 OptionParser parser(option);
108 map<string,string> parameters = parser.getParameters();
110 ValidParameters validParameter;
111 map<string,string>::iterator it;
112 //check to make sure all parameters are valid for command
113 for (it = parameters.begin(); it != parameters.end(); it++) {
114 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
116 vector<string> tempOutNames;
117 outputTypes["summary"] = tempOutNames;
119 //if the user changes the input directory command factory will send this info to us in the output parameter
120 string inputDir = validParameter.validFile(parameters, "inputdir", false);
121 if (inputDir == "not found"){ inputDir = ""; }
124 it = parameters.find("shared");
125 //user has given a shared file
126 if(it != parameters.end()){
127 path = m->hasPath(it->second);
128 //if the user has not given a path then, add inputdir. else leave path alone.
129 if (path == "") { parameters["shared"] = inputDir + it->second; }
132 it = parameters.find("design");
133 //user has given a design file
134 if(it != parameters.end()){
135 path = m->hasPath(it->second);
136 //if the user has not given a path then, add inputdir. else leave path alone.
137 if (path == "") { parameters["design"] = inputDir + it->second; }
141 //check for parameters
142 //get shared file, it is required
143 sharedfile = validParameter.validFile(parameters, "shared", true);
144 if (sharedfile == "not open") { sharedfile = ""; abort = true; }
145 else if (sharedfile == "not found") {
146 //if there is a current shared file, use it
147 sharedfile = m->getSharedFile();
148 if (sharedfile != "") { m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
149 else { m->mothurOut("You have no current sharedfile and the shared parameter is required."); m->mothurOutEndLine(); abort = true; }
150 }else { m->setSharedFile(sharedfile); }
152 //get design file, it is required
153 designfile = validParameter.validFile(parameters, "design", true);
154 if (designfile == "not open") { sharedfile = ""; abort = true; }
155 else if (designfile == "not found") {
156 //if there is a current shared file, use it
157 designfile = m->getDesignFile();
158 if (designfile != "") { m->mothurOut("Using " + designfile + " as input file for the design parameter."); m->mothurOutEndLine(); }
159 else { m->mothurOut("You have no current designfile and the design parameter is required."); m->mothurOutEndLine(); abort = true; }
160 }else { m->setDesignFile(designfile); }
163 //if the user changes the output directory command factory will send this info to us in the output parameter
164 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
165 outputDir = m->hasPath(sharedfile); //if user entered a file with a path then preserve it
168 // NEW CODE for OTU per split selection criteria
169 string temp = validParameter.validFile(parameters, "splitcriteria", false);
170 if (temp == "not found") { temp = "gainratio"; }
171 if ((temp == "gainratio") || (temp == "infogain")) {
172 treeSplitCriterion = temp;
173 } else { m->mothurOut("Not a valid tree splitting criterio. Valid tree splitting criteria are 'gainratio' and 'infogain'.");
174 m->mothurOutEndLine();
178 temp = validParameter.validFile(parameters, "numtrees", false); if (temp == "not found"){ temp = "100"; }
179 m->mothurConvert(temp, numDecisionTrees);
181 // parameters for pruning
182 temp = validParameter.validFile(parameters, "prune", false);
183 if (temp == "not found") { temp = "f"; }
184 doPruning = m->isTrue(temp);
186 temp = validParameter.validFile(parameters, "pruneaggressiveness", false);
187 if (temp == "not found") { temp = "0.9"; }
188 m->mothurConvert(temp, pruneAggressiveness);
190 temp = validParameter.validFile(parameters, "discarderrortrees", false);
191 if (temp == "not found") { temp = "f"; }
192 discardHighErrorTrees = m->isTrue(temp);
194 temp = validParameter.validFile(parameters, "errorthreshold", false);
195 if (temp == "not found") { temp = "0.4"; }
196 m->mothurConvert(temp, highErrorTreeDiscardThreshold);
198 temp = validParameter.validFile(parameters, "otupersplit", false);
199 if (temp == "not found") { temp = "log2"; }
200 if ((temp == "squareroot") || (temp == "log2")) {
201 optimumFeatureSubsetSelectionCriteria = temp;
202 } else { m->mothurOut("Not a valid OTU per split selection method. Valid OTU per split selection methods are 'log2' and 'squareroot'.");
203 m->mothurOutEndLine();
207 temp = validParameter.validFile(parameters, "stdthreshold", false);
208 if (temp == "not found") { temp = "0.0"; }
209 m->mothurConvert(temp, featureStandardDeviationThreshold);
211 // end of pruning params
213 //Groups must be checked later to make sure they are valid. SharedUtilities has functions of check the validity, just make to so m->setGroups() after the checks. If you are using these with a shared file no need to check the SharedRAbundVector class will call SharedUtilites for you, kinda nice, huh?
214 string groups = validParameter.validFile(parameters, "groups", false);
215 if (groups == "not found") { groups = ""; }
216 else { m->splitAtDash(groups, Groups); }
217 m->setGroups(Groups);
219 //Commonly used to process list, rabund, sabund, shared and relabund files. Look at "smart distancing" examples below in the execute function.
220 string label = validParameter.validFile(parameters, "label", false);
221 if (label == "not found") { label = ""; }
223 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
224 else { allLines = 1; }
229 catch(exception& e) {
230 m->errorOut(e, "ClassifySharedCommand", "ClassifySharedCommand");
234 //**********************************************************************************************************************
235 int ClassifySharedCommand::execute() {
238 if (abort == true) { if (calledHelp) { return 0; } return 2; }
240 InputData input(sharedfile, "sharedfile");
241 vector<SharedRAbundVector*> lookup = input.getSharedRAbundVectors();
244 designMap.readDesignMap(designfile);
246 string lastLabel = lookup[0]->getLabel();
247 set<string> processedLabels;
248 set<string> userLabels = labels;
250 //as long as you are not at the end of the file or done wih the lines you want
251 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
253 if (m->control_pressed) { for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; } return 0; }
255 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
257 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
259 processSharedAndDesignData(lookup);
261 processedLabels.insert(lookup[0]->getLabel());
262 userLabels.erase(lookup[0]->getLabel());
265 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
266 string saveLabel = lookup[0]->getLabel();
268 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
269 lookup = input.getSharedRAbundVectors(lastLabel);
270 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
271 processSharedAndDesignData(lookup);
273 processedLabels.insert(lookup[0]->getLabel());
274 userLabels.erase(lookup[0]->getLabel());
276 //restore real lastlabel to save below
277 lookup[0]->setLabel(saveLabel);
280 lastLabel = lookup[0]->getLabel();
281 //prevent memory leak
282 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; }
284 if (m->control_pressed) { return 0; }
286 //get next line to process
287 lookup = input.getSharedRAbundVectors();
290 if (m->control_pressed) { return 0; }
292 //output error messages about any remaining user labels
293 set<string>::iterator it;
294 bool needToRun = false;
295 for (it = userLabels.begin(); it != userLabels.end(); it++) {
296 m->mothurOut("Your file does not include the label " + *it);
297 if (processedLabels.count(lastLabel) != 1) {
298 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
301 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
305 //run last label if you need to
306 if (needToRun == true) {
307 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
308 lookup = input.getSharedRAbundVectors(lastLabel);
310 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
312 processSharedAndDesignData(lookup);
314 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
318 m->mothurOutEndLine();
319 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
320 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
321 m->mothurOutEndLine();
326 catch(exception& e) {
327 m->errorOut(e, "ClassifySharedCommand", "execute");
331 //**********************************************************************************************************************
333 void ClassifySharedCommand::processSharedAndDesignData(vector<SharedRAbundVector*> lookup){
335 // for (int i = 0; i < designMap->getNamesOfGroups().size(); i++) {
336 // string groupName = designMap->getNamesOfGroups()[i];
337 // cout << groupName << endl;
340 // for (int i = 0; i < designMap->getNumSeqs(); i++) {
341 // string sharedGroupName = designMap->getNamesSeqs()[i];
342 // string treatmentName = designMap->getGroup(sharedGroupName);
343 // cout << sharedGroupName << " : " << treatmentName << endl;
346 map<string, int> treatmentToIntMap;
347 map<int, string> intToTreatmentMap;
348 for (int i = 0; i < designMap.getNumGroups(); i++) {
349 string treatmentName = designMap.getNamesOfGroups()[i];
350 treatmentToIntMap[treatmentName] = i;
351 intToTreatmentMap[i] = treatmentName;
354 int numSamples = lookup.size();
355 int numFeatures = lookup[0]->getNumBins();
357 int numRows = numSamples;
358 int numColumns = numFeatures + 1; // extra one space needed for the treatment/outcome
360 vector< vector<int> > dataSet(numRows, vector<int>(numColumns, 0));
362 for (int i = 0; i < lookup.size(); i++) {
363 string sharedGroupName = lookup[i]->getGroup();
364 string treatmentName = designMap.getGroup(sharedGroupName);
367 for (; j < lookup[i]->getNumBins(); j++) {
368 int otuCount = lookup[i]->getAbundance(j);
369 dataSet[i][j] = otuCount;
371 dataSet[i][j] = treatmentToIntMap[treatmentName];
374 RandomForest randomForest(dataSet, numDecisionTrees, treeSplitCriterion, doPruning, pruneAggressiveness, discardHighErrorTrees, highErrorTreeDiscardThreshold, optimumFeatureSubsetSelectionCriteria, featureStandardDeviationThreshold);
376 randomForest.populateDecisionTrees();
377 randomForest.calcForrestErrorRate();
379 map<string, string> variables;
380 variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(sharedfile));
381 variables["[distance]"] = lookup[0]->getLabel();
382 string filename = getOutputFileName("summary", variables);
383 outputNames.push_back(filename); outputTypes["summary"].push_back(filename);
385 randomForest.calcForrestVariableImportance(filename);
387 m->mothurOutEndLine();
389 catch(exception& e) {
390 m->errorOut(e, "ClassifySharedCommand", "processSharedAndDesignData");
394 //**********************************************************************************************************************