5 * Created by westcott on 6/1/11.
6 * Copyright 2011 Schloss Lab. All rights reserved.
10 #include "countseqscommand.h"
12 #include "sharedutilities.h"
14 //**********************************************************************************************************************
15 vector<string> CountSeqsCommand::setParameters(){
17 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pname);
18 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pgroup);
19 CommandParameter plarge("large", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(plarge);
20 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
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, "CountSeqsCommand", "setParameters");
33 //**********************************************************************************************************************
34 string CountSeqsCommand::getHelpString(){
36 string helpString = "";
37 helpString += "The count.seqs aka. make.table command reads a name file and outputs a .count.table file. You may also provide a group file to get the counts broken down by group.\n";
38 helpString += "The groups parameter allows you to indicate which groups you want to include in the counts, by default all groups in your groupfile are used.\n";
39 helpString += "The large parameter indicates the name and group files are too large to fit in RAM.\n";
40 helpString += "When you use the groups parameter and a sequence does not represent any sequences from the groups you specify it is not included in the .count.summary file.\n";
41 helpString += "The count.seqs command should be in the following format: count.seqs(name=yourNameFile).\n";
42 helpString += "Example count.seqs(name=amazon.names) or make.table(name=amazon.names).\n";
43 helpString += "Note: No spaces between parameter labels (i.e. name), '=' and parameters (i.e.yourNameFile).\n";
47 m->errorOut(e, "CountSeqsCommand", "getHelpString");
51 //**********************************************************************************************************************
52 string CountSeqsCommand::getOutputFileNameTag(string type, string inputName=""){
54 string outputFileName = "";
55 map<string, vector<string> >::iterator it;
57 //is this a type this command creates
58 it = outputTypes.find(type);
59 if (it == outputTypes.end()) { m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
61 if (type == "counttable") { outputFileName = "count.table"; }
62 else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true; }
64 return outputFileName;
67 m->errorOut(e, "CountSeqsCommand", "getOutputFileNameTag");
71 //**********************************************************************************************************************
72 CountSeqsCommand::CountSeqsCommand(){
74 abort = true; calledHelp = true;
76 vector<string> tempOutNames;
77 outputTypes["counttable"] = tempOutNames;
80 m->errorOut(e, "CountSeqsCommand", "CountSeqsCommand");
84 //**********************************************************************************************************************
86 CountSeqsCommand::CountSeqsCommand(string option) {
88 abort = false; calledHelp = false;
90 //allow user to run help
91 if(option == "help") { help(); abort = true; calledHelp = true; }
92 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
94 vector<string> myArray = setParameters();
96 OptionParser parser(option);
97 map<string,string> parameters = parser.getParameters();
99 ValidParameters validParameter;
100 map<string,string>::iterator it;
102 //check to make sure all parameters are valid for command
103 for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) {
104 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
107 //initialize outputTypes
108 vector<string> tempOutNames;
109 outputTypes["counttable"] = tempOutNames;
112 //if the user changes the input directory command factory will send this info to us in the output parameter
113 string inputDir = validParameter.validFile(parameters, "inputdir", false);
114 if (inputDir == "not found"){ inputDir = ""; }
117 it = parameters.find("name");
118 //user has given a template file
119 if(it != parameters.end()){
120 path = m->hasPath(it->second);
121 //if the user has not given a path then, add inputdir. else leave path alone.
122 if (path == "") { parameters["name"] = inputDir + it->second; }
125 it = parameters.find("group");
126 //user has given a template file
127 if(it != parameters.end()){
128 path = m->hasPath(it->second);
129 //if the user has not given a path then, add inputdir. else leave path alone.
130 if (path == "") { parameters["group"] = inputDir + it->second; }
134 //check for required parameters
135 namefile = validParameter.validFile(parameters, "name", true);
136 if (namefile == "not open") { namefile = ""; abort = true; }
137 else if (namefile == "not found"){
138 namefile = m->getNameFile();
139 if (namefile != "") { m->mothurOut("Using " + namefile + " as input file for the name parameter."); m->mothurOutEndLine(); }
140 else { m->mothurOut("You have no current namefile and the name parameter is required."); m->mothurOutEndLine(); abort = true; }
141 }else { m->setNameFile(namefile); }
143 groupfile = validParameter.validFile(parameters, "group", true);
144 if (groupfile == "not open") { abort = true; }
145 else if (groupfile == "not found") { groupfile = ""; }
146 else { m->setGroupFile(groupfile); }
148 groups = validParameter.validFile(parameters, "groups", false);
149 if (groups == "not found") { groups = "all"; }
150 m->splitAtDash(groups, Groups);
152 string temp = validParameter.validFile(parameters, "large", false); if (temp == "not found") { temp = "F"; }
153 large = m->isTrue(temp);
155 //if the user changes the output directory command factory will send this info to us in the output parameter
156 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = m->hasPath(namefile); }
161 catch(exception& e) {
162 m->errorOut(e, "CountSeqsCommand", "CountSeqsCommand");
166 //**********************************************************************************************************************
168 int CountSeqsCommand::execute(){
171 if (abort == true) { if (calledHelp) { return 0; } return 2; }
173 string outputFileName = outputDir + m->getRootName(m->getSimpleName(namefile)) + getOutputFileNameTag("counttable");
176 if (!large) { total = processSmall(outputFileName); }
177 else { total = processLarge(outputFileName); }
179 if (m->control_pressed) { m->mothurRemove(outputFileName); return 0; }
181 //set rabund file as new current rabundfile
182 itTypes = outputTypes.find("counttable");
183 if (itTypes != outputTypes.end()) {
184 if ((itTypes->second).size() != 0) { string current = (itTypes->second)[0]; m->setCountTableFile(current); }
187 m->mothurOutEndLine();
188 m->mothurOut("Total number of sequences: " + toString(total)); m->mothurOutEndLine();
189 m->mothurOutEndLine();
190 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
191 m->mothurOut(outputFileName); m->mothurOutEndLine();
192 m->mothurOutEndLine();
197 catch(exception& e) {
198 m->errorOut(e, "CountSeqsCommand", "execute");
202 //**********************************************************************************************************************
204 int CountSeqsCommand::processSmall(string outputFileName){
207 m->openOutputFile(outputFileName, out); outputTypes["counttable"].push_back(outputFileName);
208 outputNames.push_back(outputFileName); outputTypes["counttable"].push_back(outputFileName);
209 out << "Representative_Sequence\ttotal\t";
212 if (groupfile != "") {
213 groupMap = new GroupMap(groupfile); groupMap->readMap();
215 //make sure groups are valid. takes care of user setting groupNames that are invalid or setting groups=all
216 SharedUtil* util = new SharedUtil();
217 vector<string> nameGroups = groupMap->getNamesOfGroups();
218 util->setGroups(Groups, nameGroups);
221 //sort groupNames so that the group title match the counts below, this is needed because the map object automatically sorts
222 sort(Groups.begin(), Groups.end());
225 for (int i = 0; i < Groups.size(); i++) {
226 out << Groups[i] << '\t';
233 m->openInputFile(namefile, in);
237 if (m->control_pressed) { break; }
239 string firstCol, secondCol;
240 in >> firstCol; m->gobble(in); in >> secondCol; m->gobble(in);
242 vector<string> names;
243 m->splitAtChar(secondCol, names, ',');
245 if (groupfile != "") {
247 map<string, int> groupCounts;
249 for (int i = 0; i < Groups.size(); i++) { groupCounts[Groups[i]] = 0; }
251 //get counts for each of the users groups
252 for (int i = 0; i < names.size(); i++) {
253 string group = groupMap->getGroup(names[i]);
255 if (group == "not found") { m->mothurOut("[ERROR]: " + names[i] + " is not in your groupfile, please correct."); m->mothurOutEndLine(); }
257 map<string, int>::iterator it = groupCounts.find(group);
259 //if not found, then this sequence is not from a group we care about
260 if (it != groupCounts.end()) {
268 out << firstCol << '\t' << total << '\t';
269 for (map<string, int>::iterator it = groupCounts.begin(); it != groupCounts.end(); it++) {
270 out << it->second << '\t';
275 out << firstCol << '\t' << names.size() << endl;
278 total += names.size();
283 if (groupfile != "") { delete groupMap; }
287 catch(exception& e) {
288 m->errorOut(e, "CountSeqsCommand", "processSmall");
292 //**********************************************************************************************************************
294 int CountSeqsCommand::processLarge(string outputFileName){
296 set<string> namesOfGroups;
297 map<string, int> initial;
298 for (set<string>::iterator it = namesOfGroups.begin(); it != namesOfGroups.end(); it++) { initial[(*it)] = 0; }
300 m->openOutputFile(outputFileName, out);
301 outputNames.push_back(outputFileName); outputTypes["counttable"].push_back(outputFileName);
302 out << "Representative_Sequence\ttotal\t";
303 if (groupfile == "") { out << endl; }
305 map<string, unsigned long long> namesToIndex;
306 string outfile = m->getRootName(groupfile) + "sorted.groups.temp";
307 string outName = m->getRootName(namefile) + "sorted.name.temp";
308 map<int, string> indexToName;
309 map<int, string> indexToGroup;
310 if (groupfile != "") {
311 time_t estart = time(NULL);
312 //convert name file to redundant -> unique. set unique name equal to index so we can use vectors, save name for later.
313 string newNameFile = m->getRootName(namefile) + ".name.temp";
314 string newGroupFile = m->getRootName(groupfile) + ".group.temp";
315 indexToName = processNameFile(newNameFile);
316 indexToGroup = getGroupNames(newGroupFile, namesOfGroups);
318 //sort file by first column so the names of sequences will be easier to find
320 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
321 string command = "sort -n " + newGroupFile + " -o " + outfile;
322 system(command.c_str());
323 command = "sort -n " + newNameFile + " -o " + outName;
324 system(command.c_str());
325 #else //sort using windows sort
326 string command = "sort " + newGroupFile + " /O " + outfile;
327 system(command.c_str());
328 command = "sort " + newNameFile + " /O " + outName;
329 system(command.c_str());
331 m->mothurRemove(newNameFile);
332 m->mothurRemove(newGroupFile);
334 m->mothurOut("It took " + toString(time(NULL) - estart) + " seconds to sort and index the group and name files. "); m->mothurOutEndLine();
335 }else { outName = namefile; }
337 time_t estart = time(NULL);
340 m->openInputFile(outName, in);
346 vector< vector<int> > nameMapCount;
347 if (groupfile != "") {
348 m->openInputFile(outfile, in2);
349 nameMapCount.resize(indexToName.size());
350 for (int i = 0; i < nameMapCount.size(); i++) {
351 nameMapCount[i].resize(indexToGroup.size(), 0);
356 if (m->control_pressed) { break; }
359 in >> firstCol; m->gobble(in);
361 if (groupfile != "") {
363 in >> uniqueIndex; m->gobble(in);
365 string name; int groupIndex;
366 in2 >> name >> groupIndex; m->gobble(in2);
368 if (name != firstCol) { m->mothurOut("[ERROR]: found " + name + " in your groupfile, but " + firstCol + " was in your namefile, please correct.\n"); m->control_pressed = true; }
370 nameMapCount[uniqueIndex][groupIndex]++;
374 in >> secondCol; m->gobble(in);
375 int num = m->getNumNames(secondCol);
376 out << firstCol << '\t' << num << endl;
382 if (groupfile != "") {
383 m->mothurRemove(outfile);
384 m->mothurRemove(outName);
386 for (map<int, string>::iterator it = indexToGroup.begin(); it != indexToGroup.end(); it++) { out << it->second << '\t'; }
388 for (int i = 0; i < nameMapCount.size(); i++) {
389 string totalsLine = "";
391 for (int j = 0; j < nameMapCount[i].size(); j++) {
392 seqTotal += nameMapCount[i][j];
393 totalsLine += toString(nameMapCount[i][j]) + '\t';
395 out << indexToName[i] << '\t' << seqTotal << '\t' << totalsLine << endl;
401 m->mothurOut("It took " + toString(time(NULL) - estart) + " seconds to create the count table file. "); m->mothurOutEndLine();
405 catch(exception& e) {
406 m->errorOut(e, "CountSeqsCommand", "processLarge");
410 /**************************************************************************************************/
411 map<int, string> CountSeqsCommand::processNameFile(string name) {
413 map<int, string> indexToNames;
416 m->openOutputFile(name, out);
420 m->openInputFile(namefile, in);
424 bool pairDone = false;
425 bool columnOne = true;
426 string firstCol, secondCol;
430 if (m->control_pressed) { break; }
432 in.read(buffer, 4096);
433 vector<string> pieces = m->splitWhiteSpace(rest, buffer, in.gcount());
435 for (int i = 0; i < pieces.size(); i++) {
436 if (columnOne) { firstCol = pieces[i]; columnOne=false; }
437 else { secondCol = pieces[i]; pairDone = true; columnOne=true; }
440 //parse names into vector
441 vector<string> theseNames;
442 m->splitAtComma(secondCol, theseNames);
443 for (int i = 0; i < theseNames.size(); i++) { out << theseNames[i] << '\t' << count << endl; }
444 indexToNames[count] = firstCol;
455 catch(exception& e) {
456 m->errorOut(e, "CountSeqsCommand", "processNameFile");
460 /**************************************************************************************************/
461 map<int, string> CountSeqsCommand::getGroupNames(string filename, set<string>& namesOfGroups) {
463 map<int, string> indexToGroups;
464 map<string, int> groupIndex;
465 map<string, int>::iterator it;
468 m->openOutputFile(filename, out);
472 m->openInputFile(groupfile, in);
476 bool pairDone = false;
477 bool columnOne = true;
478 string firstCol, secondCol;
482 if (m->control_pressed) { break; }
484 in.read(buffer, 4096);
485 vector<string> pieces = m->splitWhiteSpace(rest, buffer, in.gcount());
487 for (int i = 0; i < pieces.size(); i++) {
488 if (columnOne) { firstCol = pieces[i]; columnOne=false; }
489 else { secondCol = pieces[i]; pairDone = true; columnOne=true; }
492 it = groupIndex.find(secondCol);
493 if (it == groupIndex.end()) { //add group, assigning the group and number so we can use vectors above
494 groupIndex[secondCol] = count;
497 out << firstCol << '\t' << groupIndex[secondCol] << endl;
498 namesOfGroups.insert(secondCol);
506 for (it = groupIndex.begin(); it != groupIndex.end(); it++) { indexToGroups[it->second] = it->first; }
508 return indexToGroups;
510 catch(exception& e) {
511 m->errorOut(e, "CountSeqsCommand", "getGroupNames");
515 //**********************************************************************************************************************