2 // createdatabasecommand.cpp
5 // Created by Sarah Westcott on 3/28/12.
6 // Copyright (c) 2012 Schloss Lab. All rights reserved.
9 #include "createdatabasecommand.h"
10 #include "inputdata.h"
12 //**********************************************************************************************************************
13 vector<string> CreateDatabaseCommand::setParameters(){
15 CommandParameter pfasta("repfasta", "InputTypes", "", "", "none", "none", "none","database",false,true,true); parameters.push_back(pfasta);
16 CommandParameter pname("repname", "InputTypes", "", "", "none", "none", "none","",false,true,true); parameters.push_back(pname);
17 CommandParameter pcontaxonomy("contaxonomy", "InputTypes", "", "", "none", "none", "none","",false,true,true); parameters.push_back(pcontaxonomy);
18 CommandParameter plist("list", "InputTypes", "", "", "ListShared", "ListShared", "none","",false,false,true); parameters.push_back(plist);
19 CommandParameter pshared("shared", "InputTypes", "", "", "ListShared", "ListShared", "none","",false,false,true); parameters.push_back(pshared);
20 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none","",false,false); parameters.push_back(pgroup);
21 CommandParameter plabel("label", "String", "", "", "", "", "","",false,false); parameters.push_back(plabel);
22 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
23 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
25 vector<string> myArray;
26 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
30 m->errorOut(e, "CreateDatabaseCommand", "setParameters");
34 //**********************************************************************************************************************
35 string CreateDatabaseCommand::getHelpString(){
37 string helpString = "";
38 helpString += "The create.database command reads a list file or a shared file, *.cons.taxonomy, *.rep.fasta, *.rep.names and optional groupfile, and creates a database file.\n";
39 helpString += "The create.database command parameters are repfasta, list, shared, repname, contaxonomy, group and label. List, repfasta, repnames, and contaxonomy are required.\n";
40 helpString += "The repfasta file is fasta file outputted by get.oturep(fasta=yourFastaFile, list=yourListfile, column=yourDistFile, name=yourNameFile).\n";
41 helpString += "The repname file is the name file outputted by get.oturep(fasta=yourFastaFile, list=yourListfile, column=yourDistFile, name=yourNameFile).\n";
42 helpString += "The contaxonomy file is the taxonomy file outputted by classify.otu(list=yourListfile, taxonomy=yourTaxonomyFile).\n";
43 helpString += "The group file is optional and will just give you the abundance breakdown by group.\n";
44 helpString += "The label parameter allows you to specify a label to be used from your listfile.\n";
45 helpString += "NOTE: Make SURE the repfasta, repnames and contaxonomy are for the same label as the listfile.\n";
46 helpString += "The create.database command should be in the following format: \n";
47 helpString += "create.database(repfasta=yourFastaFileFromGetOTURep, repname=yourNameFileFromGetOTURep, contaxonomy=yourConTaxFileFromClassifyOTU, list=yourListFile) \n";
48 helpString += "Example: create.database(repfasta=final.an.0.03.rep.fasta, name=final.an.0.03.rep.names, list=fina.an.list, label=0.03, contaxonomy=final.an.0.03.cons.taxonomy) \n";
49 helpString += "Note: No spaces between parameter labels (i.e. repfasta), '=' and parameters (i.e.yourFastaFileFromGetOTURep).\n";
53 m->errorOut(e, "CreateDatabaseCommand", "getHelpString");
57 //**********************************************************************************************************************
58 string CreateDatabaseCommand::getOutputPattern(string type) {
62 if (type == "database") { pattern = "[filename],database"; }
63 else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true; }
68 m->errorOut(e, "CreateDatabaseCommand", "getOutputPattern");
72 //**********************************************************************************************************************
73 CreateDatabaseCommand::CreateDatabaseCommand(){
75 abort = true; calledHelp = true;
77 vector<string> tempOutNames;
78 outputTypes["database"] = tempOutNames;
81 m->errorOut(e, "CreateDatabaseCommand", "CreateDatabaseCommand");
86 //**********************************************************************************************************************
87 CreateDatabaseCommand::CreateDatabaseCommand(string option) {
89 abort = false; calledHelp = false;
91 //allow user to run help
92 if (option == "help") {
93 help(); abort = true; calledHelp = true;
94 }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;
102 map<string, string>::iterator it;
104 //check to make sure all parameters are valid for command
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["database"] = tempOutNames;
113 //if the user changes the input directory command factory will send this info to us in the output parameter
114 string inputDir = validParameter.validFile(parameters, "inputdir", false);
115 if (inputDir == "not found"){ inputDir = ""; }
118 it = parameters.find("list");
119 //user has given a template file
120 if(it != parameters.end()){
121 path = m->hasPath(it->second);
122 //if the user has not given a path then, add inputdir. else leave path alone.
123 if (path == "") { parameters["list"] = inputDir + it->second; }
126 it = parameters.find("repname");
127 //user has given a template file
128 if(it != parameters.end()){
129 path = m->hasPath(it->second);
130 //if the user has not given a path then, add inputdir. else leave path alone.
131 if (path == "") { parameters["repname"] = inputDir + it->second; }
134 it = parameters.find("contaxonomy");
135 //user has given a template file
136 if(it != parameters.end()){
137 path = m->hasPath(it->second);
138 //if the user has not given a path then, add inputdir. else leave path alone.
139 if (path == "") { parameters["contaxonomy"] = inputDir + it->second; }
142 it = parameters.find("repfasta");
143 //user has given a template file
144 if(it != parameters.end()){
145 path = m->hasPath(it->second);
146 //if the user has not given a path then, add inputdir. else leave path alone.
147 if (path == "") { parameters["repfasta"] = inputDir + it->second; }
150 it = parameters.find("group");
151 //user has given a template file
152 if(it != parameters.end()){
153 path = m->hasPath(it->second);
154 //if the user has not given a path then, add inputdir. else leave path alone.
155 if (path == "") { parameters["group"] = inputDir + it->second; }
158 it = parameters.find("shared");
159 //user has given a template file
160 if(it != parameters.end()){
161 path = m->hasPath(it->second);
162 //if the user has not given a path then, add inputdir. else leave path alone.
163 if (path == "") { parameters["shared"] = inputDir + it->second; }
168 //if the user changes the output directory command factory will send this info to us in the output parameter
169 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
171 //check for required parameters
172 listfile = validParameter.validFile(parameters, "list", true);
173 if (listfile == "not found") { listfile = ""; }
174 else if (listfile == "not open") { listfile = ""; abort = true; }
175 else { m->setListFile(listfile); }
177 sharedfile = validParameter.validFile(parameters, "shared", true);
178 if (sharedfile == "not found") { sharedfile = ""; }
179 else if (sharedfile == "not open") { sharedfile = ""; abort = true; }
180 else { m->setSharedFile(sharedfile); }
182 if ((sharedfile == "") && (listfile == "")) {
183 //is there are current file available for either of these?
184 //give priority to list, then shared
185 listfile = m->getListFile();
186 if (listfile != "") { m->mothurOut("Using " + listfile + " as input file for the list parameter."); m->mothurOutEndLine(); }
188 sharedfile = m->getSharedFile();
189 if (sharedfile != "") { m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
191 m->mothurOut("No valid current files. You must provide a shared or list file before you can use the create.database command."); m->mothurOutEndLine();
196 else if ((sharedfile != "") && (listfile != "")) { m->mothurOut("When executing a create.database command you must enter ONLY ONE of the following: shared or list."); m->mothurOutEndLine(); abort = true; }
198 if (sharedfile != "") { if (outputDir == "") { outputDir = m->hasPath(sharedfile); } }
199 else { if (outputDir == "") { outputDir = m->hasPath(listfile); } }
201 contaxonomyfile = validParameter.validFile(parameters, "contaxonomy", true);
202 if (contaxonomyfile == "not found") { //if there is a current list file, use it
203 contaxonomyfile = ""; m->mothurOut("The contaxonomy parameter is required, aborting."); m->mothurOutEndLine(); abort = true;
205 else if (contaxonomyfile == "not open") { contaxonomyfile = ""; abort = true; }
207 repfastafile = validParameter.validFile(parameters, "repfasta", true);
208 if (repfastafile == "not found") { //if there is a current list file, use it
209 repfastafile = ""; m->mothurOut("The repfasta parameter is required, aborting."); m->mothurOutEndLine(); abort = true;
211 else if (repfastafile == "not open") { repfastafile = ""; abort = true; }
213 repnamesfile = validParameter.validFile(parameters, "repname", true);
214 if (repnamesfile == "not found") { //if there is a current list file, use it
215 repnamesfile = ""; m->mothurOut("The repnames parameter is required, aborting."); m->mothurOutEndLine(); abort = true;
217 else if (repnamesfile == "not open") { repnamesfile = ""; abort = true; }
219 groupfile = validParameter.validFile(parameters, "group", true);
220 if (groupfile == "not open") { groupfile = ""; abort = true; }
221 else if (groupfile == "not found") { groupfile = ""; }
222 else { m->setGroupFile(groupfile); }
224 //check for optional parameter and set defaults
225 // ...at some point should added some additional type checking...
226 label = validParameter.validFile(parameters, "label", false);
227 if (label == "not found") { label = ""; m->mothurOut("You did not provide a label, I will use the first label in your listfile.\n");}
230 catch(exception& e) {
231 m->errorOut(e, "CreateDatabaseCommand", "CreateDatabaseCommand");
235 //**********************************************************************************************************************
236 int CreateDatabaseCommand::execute(){
239 if (abort == true) { if (calledHelp) { return 0; } return 2; }
241 //taxonomies holds the taxonomy info for each Otu
242 //classifyOtuSizes holds the size info of each Otu to help with error checking
243 vector<string> taxonomies;
244 vector<string> otuLabels;
245 vector<int> classifyOtuSizes = readTax(taxonomies, otuLabels);
247 if (m->control_pressed) { return 0; }
249 vector<Sequence> seqs;
250 vector<int> repOtusSizes = readFasta(seqs);
252 if (m->control_pressed) { return 0; }
254 //names redundants to uniques. backwards to how we normally do it, but each bin is the list file will be a key entry in the map.
255 map<string, string> repNames;
256 int numUniqueNamesFile = m->readNames(repnamesfile, repNames, 1);
258 //are there the same number of otus in the fasta and name files
259 if (repOtusSizes.size() != numUniqueNamesFile) { m->mothurOut("[ERROR]: you have " + toString(numUniqueNamesFile) + " unique seqs in your repname file, but " + toString(repOtusSizes.size()) + " seqs in your repfasta file. These should match.\n"); m->control_pressed = true; }
261 if (m->control_pressed) { return 0; }
263 //are there the same number of OTUs in the tax and fasta file
264 if (classifyOtuSizes.size() != repOtusSizes.size()) { m->mothurOut("[ERROR]: you have " + toString(classifyOtuSizes.size()) + " taxonomies in your contaxonomy file, but " + toString(repOtusSizes.size()) + " seqs in your repfasta file. These should match.\n"); m->control_pressed = true; }
266 if (m->control_pressed) { return 0; }
268 //at this point we have the same number of OTUs. Are the sizes we have found so far accurate?
269 for (int i = 0; i < classifyOtuSizes.size(); i++) {
270 if (classifyOtuSizes[i] != repOtusSizes[i]) {
271 m->mothurOut("[ERROR]: OTU size info does not match for bin " + toString(i+1) + ". The contaxonomy file indicated the OTU represented " + toString(classifyOtuSizes[i]) + " sequences, but the repfasta file had " + toString(repOtusSizes[i]) + ". These should match. Make sure you are using files for the same distance.\n"); m->control_pressed = true;
275 if (m->control_pressed) { return 0; }
278 map<string, string> variables;
279 if (listfile != "") { variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(listfile)); }
280 else { variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(sharedfile)); }
281 string outputFileName = getOutputFileName("database", variables);
282 outputNames.push_back(outputFileName); outputTypes["database"].push_back(outputFileName);
285 m->openOutputFile(outputFileName, out);
287 string header = "OTUNumber\tAbundance\t";
290 if (listfile != "") {
291 //at this point we are fairly sure the repfasta, repnames and contaxonomy files match so lets proceed with the listfile
292 ListVector* list = getList();
294 if (otuLabels.size() != list->getNumBins()) {
295 m->mothurOut("[ERROR]: you have " + toString(otuLabels.size()) + " otus in your contaxonomy file, but your list file has " + toString(list->getNumBins()) + " otus. These should match. Make sure you are using files for the same distance.\n"); m->control_pressed = true; }
297 if (m->control_pressed) { delete list; return 0; }
299 GroupMap* groupmap = NULL;
300 if (groupfile != "") {
301 groupmap = new GroupMap(groupfile);
305 if (m->control_pressed) { delete list; if (groupfile != "") { delete groupmap; } return 0; }
307 if (groupfile != "") {
308 header = "OTUNumber\t";
309 for (int i = 0; i < groupmap->getNamesOfGroups().size(); i++) { header += (groupmap->getNamesOfGroups())[i] + '\t'; }
311 header += "repSeqName\trepSeq\tOTUConTaxonomy";
312 out << header << endl;
314 for (int i = 0; i < list->getNumBins(); i++) {
316 if (m->control_pressed) { break; }
318 out << otuLabels[i] << '\t';
320 vector<string> binNames;
321 string bin = list->get(i);
323 map<string, string>::iterator it = repNames.find(bin);
324 if (it == repNames.end()) {
325 m->mothurOut("[ERROR: OTU " + otuLabels[i] + " is not in the repnames file. Make sure you are using files for the same distance.\n"); m->control_pressed = true; break;
328 m->splitAtComma(bin, binNames);
331 if (binNames.size() != classifyOtuSizes[i]) {
332 m->mothurOut("[ERROR: OTU " + otuLabels[i] + " contains " + toString(binNames.size()) + " sequence, but the rep and taxonomy files indicated this OTU should have " + toString(classifyOtuSizes[i]) + ". Make sure you are using files for the same distance.\n"); m->control_pressed = true; break;
336 if (groupfile != "") {
337 string groupAbunds = "";
338 map<string, int> counts;
339 //initialize counts to 0
340 for (int j = 0; j < groupmap->getNamesOfGroups().size(); j++) { counts[(groupmap->getNamesOfGroups())[j]] = 0; }
342 //find abundances by group
344 for (int j = 0; j < binNames.size(); j++) {
345 string group = groupmap->getGroup(binNames[j]);
346 if (group == "not found") {
347 m->mothurOut("[ERROR]: " + binNames[j] + " is not in your groupfile, please correct.\n");
349 }else { counts[group]++; }
353 for (int j = 0; j < groupmap->getNamesOfGroups().size(); j++) { out << counts[(groupmap->getNamesOfGroups())[j]] << '\t'; }
355 if (error) { m->control_pressed = true; }
356 }else { out << binNames.size() << '\t'; }
359 out << it->second << '\t' << seqs[i].getAligned() << '\t' << taxonomies[i] << endl;
364 if (groupfile != "") { delete groupmap; }
367 vector<SharedRAbundVector*> lookup = getShared();
369 header = "OTUNumber\t";
370 for (int i = 0; i < lookup.size(); i++) { header += lookup[i]->getGroup() + '\t'; }
371 header += "repSeqName\trepSeq\tOTUConTaxonomy";
372 out << header << endl;
374 for (int h = 0; h < lookup[0]->getNumBins(); h++) {
376 if (m->control_pressed) { break; }
378 int index = findIndex(otuLabels, m->currentBinLabels[h]);
379 if (index == -1) { m->mothurOut("[ERROR]: " + m->currentBinLabels[h] + " is not in your constaxonomy file, aborting.\n"); m->control_pressed = true; }
381 if (m->control_pressed) { break; }
383 out << otuLabels[index] << '\t';
386 for (int i = 0; i < lookup.size(); i++) {
387 int abund = lookup[i]->getAbundance(h);
389 out << abund << '\t';
393 if (totalAbund != classifyOtuSizes[index]) {
394 m->mothurOut("[WARNING]: OTU " + m->currentBinLabels[h] + " contains " + toString(totalAbund) + " sequence, but the rep and taxonomy files indicated this OTU should have " + toString(classifyOtuSizes[index]) + ". Make sure you are using files for the same distance.\n"); //m->control_pressed = true; break;
398 out << seqs[index].getName() << '\t' << seqs[index].getAligned() << '\t' << taxonomies[index] << endl;
402 if (m->control_pressed) { m->mothurRemove(outputFileName); return 0; }
404 m->mothurOutEndLine();
405 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
406 m->mothurOut(outputFileName); m->mothurOutEndLine();
407 m->mothurOutEndLine();
412 catch(exception& e) {
413 m->errorOut(e, "CreateDatabaseCommand", "execute");
417 //**********************************************************************************************************************
418 int CreateDatabaseCommand::findIndex(vector<string>& otuLabels, string label){
421 for (int i = 0; i < otuLabels.size(); i++) {
422 if (otuLabels[i] == label) { index = i; break; }
426 catch(exception& e) {
427 m->errorOut(e, "CreateDatabaseCommand", "findIndex");
431 //**********************************************************************************************************************
432 vector<int> CreateDatabaseCommand::readTax(vector<string>& taxonomies, vector<string>& otuLabels){
438 m->openInputFile(contaxonomyfile, in);
445 if (m->control_pressed) { break; }
447 string otu = ""; string tax = "unknown";
450 in >> otu >> size >> tax; m->gobble(in);
452 sizes.push_back(size);
453 taxonomies.push_back(tax);
454 otuLabels.push_back(otu);
460 catch(exception& e) {
461 m->errorOut(e, "CreateDatabaseCommand", "readTax");
465 //**********************************************************************************************************************
466 vector<int> CreateDatabaseCommand::readFasta(vector<Sequence>& seqs){
472 m->openInputFile(repfastafile, in);
476 if (m->control_pressed) { break; }
479 Sequence seq(in, binInfo, true); m->gobble(in);
481 //the binInfo should look like - binNumber|size ie. 1|200 if it is binNumber|size|group then the user gave us the wrong repfasta file
483 m->splitAtChar(binInfo, info, '|');
484 if (info.size() != 2) { m->mothurOut("[ERROR]: your repfasta file is not the right format. The create database command is designed to be used with the output from get.oturep. When running get.oturep you can not use a group file, because mothur is only expecting one representative sequence per OTU and when you use a group file with get.oturep a representative is found for each group.\n"); m->control_pressed = true; break;}
487 m->mothurConvert(info[1], size);
489 sizes.push_back(size);
496 catch(exception& e) {
497 m->errorOut(e, "CreateDatabaseCommand", "readFasta");
501 //**********************************************************************************************************************
502 ListVector* CreateDatabaseCommand::getList(){
504 InputData* input = new InputData(listfile, "list");
505 ListVector* list = input->getListVector();
506 string lastLabel = list->getLabel();
508 if (label == "") { label = lastLabel; delete input; return list; }
510 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
511 set<string> labels; labels.insert(label);
512 set<string> processedLabels;
513 set<string> userLabels = labels;
515 //as long as you are not at the end of the file or done wih the lines you want
516 while((list != NULL) && (userLabels.size() != 0)) {
517 if (m->control_pressed) { delete input; return list; }
519 if(labels.count(list->getLabel()) == 1){
520 processedLabels.insert(list->getLabel());
521 userLabels.erase(list->getLabel());
525 if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
526 string saveLabel = list->getLabel();
529 list = input->getListVector(lastLabel);
531 processedLabels.insert(list->getLabel());
532 userLabels.erase(list->getLabel());
534 //restore real lastlabel to save below
535 list->setLabel(saveLabel);
539 lastLabel = list->getLabel();
541 //get next line to process
542 //prevent memory leak
544 list = input->getListVector();
548 if (m->control_pressed) { delete input; return list; }
550 //output error messages about any remaining user labels
551 set<string>::iterator it;
552 bool needToRun = false;
553 for (it = userLabels.begin(); it != userLabels.end(); it++) {
554 m->mothurOut("Your file does not include the label " + *it);
555 if (processedLabels.count(lastLabel) != 1) {
556 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
559 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
563 //run last label if you need to
564 if (needToRun == true) {
566 list = input->getListVector(lastLabel);
573 catch(exception& e) {
574 m->errorOut(e, "CreateDatabaseCommand", "getList");
578 //**********************************************************************************************************************
579 vector<SharedRAbundVector*> CreateDatabaseCommand::getShared(){
581 InputData input(sharedfile, "sharedfile");
582 vector<SharedRAbundVector*> lookup = input.getSharedRAbundVectors();
583 string lastLabel = lookup[0]->getLabel();
585 if (label == "") { label = lastLabel; return lookup; }
587 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
588 set<string> labels; labels.insert(label);
589 set<string> processedLabels;
590 set<string> userLabels = labels;
592 //as long as you are not at the end of the file or done wih the lines you want
593 while((lookup[0] != NULL) && (userLabels.size() != 0)) {
594 if (m->control_pressed) { return lookup; }
596 if(labels.count(lookup[0]->getLabel()) == 1){
597 processedLabels.insert(lookup[0]->getLabel());
598 userLabels.erase(lookup[0]->getLabel());
602 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
603 string saveLabel = lookup[0]->getLabel();
605 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
606 lookup = input.getSharedRAbundVectors(lastLabel);
608 processedLabels.insert(lookup[0]->getLabel());
609 userLabels.erase(lookup[0]->getLabel());
611 //restore real lastlabel to save below
612 lookup[0]->setLabel(saveLabel);
616 lastLabel = lookup[0]->getLabel();
618 //get next line to process
619 //prevent memory leak
620 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
621 lookup = input.getSharedRAbundVectors();
625 if (m->control_pressed) { return lookup; }
627 //output error messages about any remaining user labels
628 set<string>::iterator it;
629 bool needToRun = false;
630 for (it = userLabels.begin(); it != userLabels.end(); it++) {
631 m->mothurOut("Your file does not include the label " + *it);
632 if (processedLabels.count(lastLabel) != 1) {
633 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
636 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
640 //run last label if you need to
641 if (needToRun == true) {
642 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
643 lookup = input.getSharedRAbundVectors(lastLabel);
648 catch(exception& e) {
649 m->errorOut(e, "CreateDatabaseCommand", "getList");
654 //**********************************************************************************************************************