5 * Created by Sarah Westcott on 1/2/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
10 #include "sharedcommand.h"
11 //********************************************************************************************************************
12 //sorts lowest to highest
13 inline bool compareSharedRabunds(SharedRAbundVector* left, SharedRAbundVector* right){
14 return (left->getGroup() < right->getGroup());
16 //**********************************************************************************************************************
17 vector<string> SharedCommand::setParameters(){
19 CommandParameter plist("list", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(plist);
20 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pgroup);
21 CommandParameter pordergroup("ordergroup", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pordergroup);
22 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
23 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
24 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
25 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
27 vector<string> myArray;
28 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
32 m->errorOut(e, "SharedCommand", "setParameters");
36 //**********************************************************************************************************************
37 string SharedCommand::getHelpString(){
39 string helpString = "";
40 helpString += "The make.shared command reads a list and group file and creates a shared file, as well as a rabund file for each group.\n";
41 helpString += "The make.shared command parameters are list, group, ordergroup, groups and label. list and group are required unless a current file is available.\n";
42 helpString += "The groups parameter allows you to indicate which groups you want to include, group names should be separated by dashes. ex. groups=A-B-C. Default is all groups in your groupfile.\n";
43 helpString += "The label parameter allows you to indicate which labels you want to include, label names should be separated by dashes. Default is all labels in your list file.\n";
44 helpString += "The ordergroup parameter allows you to indicate the order of the groups in the sharedfile, by default the groups are listed alphabetically.\n";
48 m->errorOut(e, "SharedCommand", "getHelpString");
52 //**********************************************************************************************************************
53 SharedCommand::SharedCommand(){
55 abort = true; calledHelp = true;
57 //initialize outputTypes
58 vector<string> tempOutNames;
59 outputTypes["rabund"] = tempOutNames;
60 outputTypes["shared"] = tempOutNames;
63 m->errorOut(e, "SharedCommand", "SharedCommand");
67 //**********************************************************************************************************************
68 SharedCommand::SharedCommand(string option) {
70 abort = false; calledHelp = false;
73 //allow user to run help
74 if(option == "help") { help(); abort = true; calledHelp = true; }
78 vector<string> myArray = setParameters();
80 OptionParser parser(option);
81 map<string, string> parameters = parser.getParameters();
83 ValidParameters validParameter;
84 map<string, string>::iterator it;
86 //check to make sure all parameters are valid for command
87 for (it = parameters.begin(); it != parameters.end(); it++) {
88 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
91 //if the user changes the input directory command factory will send this info to us in the output parameter
92 string inputDir = validParameter.validFile(parameters, "inputdir", false);
93 if (inputDir == "not found"){ inputDir = ""; }
96 it = parameters.find("list");
97 //user has given a template file
98 if(it != parameters.end()){
99 path = m->hasPath(it->second);
100 //if the user has not given a path then, add inputdir. else leave path alone.
101 if (path == "") { parameters["list"] = inputDir + it->second; }
104 it = parameters.find("group");
105 //user has given a template file
106 if(it != parameters.end()){
107 path = m->hasPath(it->second);
108 //if the user has not given a path then, add inputdir. else leave path alone.
109 if (path == "") { parameters["group"] = inputDir + it->second; }
112 it = parameters.find("ordergroup");
113 //user has given a template file
114 if(it != parameters.end()){
115 path = m->hasPath(it->second);
116 //if the user has not given a path then, add inputdir. else leave path alone.
117 if (path == "") { parameters["ordergroup"] = inputDir + it->second; }
122 //if the user changes the output directory command factory will send this info to us in the output parameter
123 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
125 //check for required parameters
126 listfile = validParameter.validFile(parameters, "list", true);
127 if (listfile == "not open") { listfile = ""; abort = true; }
128 else if (listfile == "not found") {
129 listfile = m->getListFile();
130 if (listfile != "") { m->mothurOut("Using " + listfile + " as input file for the list parameter."); m->mothurOutEndLine(); }
131 else { m->mothurOut("You have no current list file and the list parameter is required."); m->mothurOutEndLine(); abort = true; }
134 ordergroupfile = validParameter.validFile(parameters, "ordergroup", true);
135 if (ordergroupfile == "not open") { abort = true; }
136 else if (ordergroupfile == "not found") { ordergroupfile = ""; }
138 groupfile = validParameter.validFile(parameters, "group", true);
139 if (groupfile == "not open") { abort = true; }
140 else if (groupfile == "not found") {
141 groupfile = m->getGroupFile();
142 if (groupfile != "") {
143 m->mothurOut("Using " + groupfile + " as input file for the group parameter."); m->mothurOutEndLine();
144 groupMap = new GroupMap(groupfile);
146 int error = groupMap->readMap();
147 if (error == 1) { abort = true; }
148 m->namesOfGroups = groupMap->namesOfGroups;
150 else { m->mothurOut("You have no current group file and the group parameter is required."); m->mothurOutEndLine(); abort = true; }
152 groupMap = new GroupMap(groupfile);
154 int error = groupMap->readMap();
155 if (error == 1) { abort = true; }
156 m->namesOfGroups = groupMap->namesOfGroups;
157 m->setGroupFile(groupfile);
160 string groups = validParameter.validFile(parameters, "groups", false);
161 if (groups == "not found") { groups = ""; }
163 m->splitAtDash(groups, Groups);
167 //check for optional parameter and set defaults
168 // ...at some point should added some additional type checking...
169 string label = validParameter.validFile(parameters, "label", false);
170 if (label == "not found") { label = ""; }
172 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
173 else { allLines = 1; }
176 //getting output filename
178 if (outputDir == "") { outputDir += m->hasPath(filename); }
180 filename = outputDir + m->getRootName(m->getSimpleName(filename));
181 filename = filename + "shared";
182 outputTypes["shared"].push_back(filename);
184 m->openOutputFile(filename, out);
185 pickedGroups = false;
187 //if hte user has not specified any groups then use them all
188 if (Groups.size() == 0) {
189 Groups = groupMap->namesOfGroups; m->Groups = Groups;
192 //fill filehandles with neccessary ofstreams
195 for (i=0; i<Groups.size(); i++) {
197 filehandles[Groups[i]] = temp;
201 fileroot = outputDir + m->getRootName(m->getSimpleName(listfile));
203 //clears file before we start to write to it below
204 for (int i=0; i<Groups.size(); i++) {
205 remove((fileroot + Groups[i] + ".rabund").c_str());
206 outputNames.push_back((fileroot + Groups[i] + ".rabund"));
207 outputTypes["rabund"].push_back((fileroot + Groups[i] + ".rabund"));
213 catch(exception& e) {
214 m->errorOut(e, "SharedCommand", "SharedCommand");
218 //**********************************************************************************************************************
220 int SharedCommand::execute(){
223 if (abort == true) { if (calledHelp) { return 0; } return 2; }
226 string errorOff = "no error";
229 //if user provided an order file containing the order the shared file should be in read it
230 if (ordergroupfile != "") { readOrderFile(); }
232 input = new InputData(listfile, "shared");
233 SharedList = input->getSharedListVector();
234 string lastLabel = SharedList->getLabel();
235 vector<SharedRAbundVector*> lookup;
237 if (m->control_pressed) {
238 delete input; delete SharedList; delete groupMap;
239 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
240 out.close(); remove(filename.c_str());
241 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
245 if ((m->Groups.size() == 0) && (SharedList->getNumSeqs() != groupMap->getNumSeqs())) { //if the user has not specified any groups and their files don't match exit with error
246 m->mothurOut("Your group file contains " + toString(groupMap->getNumSeqs()) + " sequences and list file contains " + toString(SharedList->getNumSeqs()) + " sequences. Please correct."); m->mothurOutEndLine();
249 remove(filename.c_str()); //remove blank shared file you made
251 createMisMatchFile();
254 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) {
258 delete input; delete SharedList; delete groupMap;
263 //if user has specified groups make new groupfile for them
264 if (m->Groups.size() != 0) { //make new group file
266 if (m->Groups.size() < 4) {
267 for (int i = 0; i < m->Groups.size(); i++) {
268 groups += m->Groups[i] + ".";
270 }else { groups = "merge"; }
272 string newGroupFile = outputDir + m->getRootName(m->getSimpleName(listfile)) + groups + "groups";
274 m->openOutputFile(newGroupFile, outGroups);
276 vector<string> names = groupMap->getNamesSeqs();
278 for (int i = 0; i < names.size(); i++) {
279 groupName = groupMap->getGroup(names[i]);
280 if (isValidGroup(groupName, m->Groups)) {
281 outGroups << names[i] << '\t' << groupName << endl;
287 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
288 set<string> processedLabels;
289 set<string> userLabels = labels;
291 while((SharedList != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
292 if (m->control_pressed) {
293 delete input; delete SharedList; delete groupMap;
294 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
295 out.close(); remove(filename.c_str());
296 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
300 if(allLines == 1 || labels.count(SharedList->getLabel()) == 1){
302 lookup = SharedList->getSharedRAbundVector();
304 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
305 if (pickedGroups) { //check for otus with no seqs in them
306 eliminateZeroOTUS(lookup);
309 if (m->control_pressed) {
310 delete input; delete SharedList; delete groupMap;
311 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
312 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
313 out.close(); remove(filename.c_str());
314 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
318 printSharedData(lookup); //prints info to the .shared file
319 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
321 processedLabels.insert(SharedList->getLabel());
322 userLabels.erase(SharedList->getLabel());
325 if ((m->anyLabelsToProcess(SharedList->getLabel(), userLabels, errorOff) == true) && (processedLabels.count(lastLabel) != 1)) {
326 string saveLabel = SharedList->getLabel();
329 SharedList = input->getSharedListVector(lastLabel); //get new list vector to process
331 lookup = SharedList->getSharedRAbundVector();
332 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
333 if (pickedGroups) { //check for otus with no seqs in them
334 eliminateZeroOTUS(lookup);
338 if (m->control_pressed) {
339 delete input; delete SharedList; delete groupMap;
340 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
341 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
342 out.close(); remove(filename.c_str());
343 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
347 printSharedData(lookup); //prints info to the .shared file
348 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
350 processedLabels.insert(SharedList->getLabel());
351 userLabels.erase(SharedList->getLabel());
353 //restore real lastlabel to save below
354 SharedList->setLabel(saveLabel);
358 lastLabel = SharedList->getLabel();
361 SharedList = input->getSharedListVector(); //get new list vector to process
364 //output error messages about any remaining user labels
365 set<string>::iterator it;
366 bool needToRun = false;
367 for (it = userLabels.begin(); it != userLabels.end(); it++) {
368 if (processedLabels.count(lastLabel) != 1) {
373 //run last label if you need to
374 if (needToRun == true) {
375 if (SharedList != NULL) { delete SharedList; }
376 SharedList = input->getSharedListVector(lastLabel); //get new list vector to process
378 lookup = SharedList->getSharedRAbundVector();
379 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
380 if (pickedGroups) { //check for otus with no seqs in them
381 eliminateZeroOTUS(lookup);
384 if (m->control_pressed) {
385 delete input; delete groupMap;
386 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
387 out.close(); remove(filename.c_str());
388 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
392 printSharedData(lookup); //prints info to the .shared file
393 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
399 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) {
403 delete input; delete groupMap;
405 if (m->control_pressed) {
406 remove(filename.c_str());
407 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
411 //set rabund file as new current rabundfile
413 itTypes = outputTypes.find("rabund");
414 if (itTypes != outputTypes.end()) {
415 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRabundFile(current); }
418 itTypes = outputTypes.find("shared");
419 if (itTypes != outputTypes.end()) {
420 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSharedFile(current); }
423 m->mothurOutEndLine();
424 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
425 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
426 m->mothurOut(filename); m->mothurOutEndLine();
427 m->mothurOutEndLine();
431 catch(exception& e) {
432 m->errorOut(e, "SharedCommand", "execute");
436 //**********************************************************************************************************************
437 void SharedCommand::printSharedData(vector<SharedRAbundVector*> thislookup) {
440 if (order.size() == 0) { //user has not specified an order so do aplabetically
441 sort(thislookup.begin(), thislookup.end(), compareSharedRabunds);
445 //initialize bin values
446 for (int i = 0; i < thislookup.size(); i++) {
447 out << thislookup[i]->getLabel() << '\t' << thislookup[i]->getGroup() << '\t';
448 thislookup[i]->print(out);
450 m->Groups.push_back(thislookup[i]->getGroup());
452 RAbundVector rav = thislookup[i]->getRAbundVector();
453 m->openOutputFileAppend(fileroot + thislookup[i]->getGroup() + ".rabund", *(filehandles[thislookup[i]->getGroup()]));
454 rav.print(*(filehandles[thislookup[i]->getGroup()]));
455 (*(filehandles[thislookup[i]->getGroup()])).close();
458 //create a map from groupName to each sharedrabund
459 map<string, SharedRAbundVector*> myMap;
460 map<string, SharedRAbundVector*>::iterator myIt;
462 for (int i = 0; i < thislookup.size(); i++) {
463 myMap[thislookup[i]->getGroup()] = thislookup[i];
468 //loop through ordered list and print the rabund
469 for (int i = 0; i < order.size(); i++) {
470 myIt = myMap.find(order[i]);
472 if(myIt != myMap.end()) { //we found it
473 out << (myIt->second)->getLabel() << '\t' << (myIt->second)->getGroup() << '\t';
474 (myIt->second)->print(out);
476 m->Groups.push_back((myIt->second)->getGroup());
478 RAbundVector rav = (myIt->second)->getRAbundVector();
479 m->openOutputFileAppend(fileroot + (myIt->second)->getGroup() + ".rabund", *(filehandles[(myIt->second)->getGroup()]));
480 rav.print(*(filehandles[(myIt->second)->getGroup()]));
481 (*(filehandles[(myIt->second)->getGroup()])).close();
483 m->mothurOut("Can't find shared info for " + order[i] + ", skipping."); m->mothurOutEndLine();
490 catch(exception& e) {
491 m->errorOut(e, "SharedCommand", "printSharedData");
495 //**********************************************************************************************************************
496 int SharedCommand::eliminateZeroOTUS(vector<SharedRAbundVector*>& thislookup) {
499 vector<SharedRAbundVector*> newLookup;
500 for (int i = 0; i < thislookup.size(); i++) {
501 SharedRAbundVector* temp = new SharedRAbundVector();
502 temp->setLabel(thislookup[i]->getLabel());
503 temp->setGroup(thislookup[i]->getGroup());
504 newLookup.push_back(temp);
508 for (int i = 0; i < thislookup[0]->getNumBins(); i++) {
509 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
511 //look at each sharedRabund and make sure they are not all zero
513 for (int j = 0; j < thislookup.size(); j++) {
514 if (thislookup[j]->getAbundance(i) != 0) { allZero = false; break; }
517 //if they are not all zero add this bin
519 for (int j = 0; j < thislookup.size(); j++) {
520 newLookup[j]->push_back(thislookup[j]->getAbundance(i), thislookup[j]->getGroup());
523 //else{ cout << "bin # " << i << " is all zeros" << endl; }
526 for (int j = 0; j < thislookup.size(); j++) { delete thislookup[j]; }
527 thislookup = newLookup;
532 catch(exception& e) {
533 m->errorOut(e, "SharedCommand", "eliminateZeroOTUS");
537 //**********************************************************************************************************************
538 int SharedCommand::createMisMatchFile() {
540 ofstream outMisMatch;
541 string outputMisMatchName = outputDir + m->getRootName(m->getSimpleName(listfile));
543 //you have sequences in your list file that are not in your group file
544 if (SharedList->getNumSeqs() > groupMap->getNumSeqs()) {
545 outputMisMatchName += "missing.group";
546 m->mothurOut("For a list of names that are in your list file and not in your group file, please refer to " + outputMisMatchName + "."); m->mothurOutEndLine();
548 m->openOutputFile(outputMisMatchName, outMisMatch);
550 map<string, string> listNames;
551 map<string, string>::iterator itList;
553 //go through list and if group returns "not found" output it
554 for (int i = 0; i < SharedList->getNumBins(); i++) {
555 if (m->control_pressed) { outMisMatch.close(); remove(outputMisMatchName.c_str()); return 0; }
557 string names = SharedList->get(i);
559 while (names.find_first_of(',') != -1) {
560 string name = names.substr(0,names.find_first_of(','));
561 names = names.substr(names.find_first_of(',')+1, names.length());
562 string group = groupMap->getGroup(name);
564 if(group == "not found") { outMisMatch << name << endl; }
566 itList = listNames.find(name);
567 if (itList != listNames.end()) { m->mothurOut(name + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
568 else { listNames[name] = name; }
572 string group = groupMap->getGroup(names);
573 if(group == "not found") { outMisMatch << names << endl; }
575 itList = listNames.find(names);
576 if (itList != listNames.end()) { m->mothurOut(names + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
577 else { listNames[names] = names; }
584 }else {//you have sequences in your group file that are not in you list file
586 outputMisMatchName += "missing.name";
587 m->mothurOut("For a list of names that are in your group file and not in your list file, please refer to " + outputMisMatchName + "."); m->mothurOutEndLine();
589 map<string, string> namesInList;
590 map<string, string>::iterator itList;
592 //go through listfile and get names
593 for (int i = 0; i < SharedList->getNumBins(); i++) {
594 if (m->control_pressed) { return 0; }
597 string names = SharedList->get(i);
599 while (names.find_first_of(',') != -1) {
600 string name = names.substr(0,names.find_first_of(','));
601 names = names.substr(names.find_first_of(',')+1, names.length());
603 itList = namesInList.find(name);
604 if (itList != namesInList.end()) { m->mothurOut(name + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
606 namesInList[name] = name;
610 itList = namesInList.find(names);
611 if (itList != namesInList.end()) { m->mothurOut(names + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
614 namesInList[names] = names;
617 //get names of sequences in groupfile
618 vector<string> seqNames = groupMap->getNamesSeqs();
620 map<string, string>::iterator itMatch;
622 m->openOutputFile(outputMisMatchName, outMisMatch);
624 //loop through names in seqNames and if they aren't in namesIn list output them
625 for (int i = 0; i < seqNames.size(); i++) {
626 if (m->control_pressed) { outMisMatch.close(); remove(outputMisMatchName.c_str()); return 0; }
628 itMatch = namesInList.find(seqNames[i]);
630 if (itMatch == namesInList.end()) {
632 outMisMatch << seqNames[i] << endl;
640 catch(exception& e) {
641 m->errorOut(e, "SharedCommand", "createMisMatchFile");
646 //**********************************************************************************************************************
648 SharedCommand::~SharedCommand(){
653 //**********************************************************************************************************************
654 int SharedCommand::readOrderFile() {
660 m->openInputFile(ordergroupfile, in);
664 in >> thisGroup; m->gobble(in);
666 order.push_back(thisGroup);
668 if (m->control_pressed) { order.clear(); break; }
674 catch(exception& e) {
675 m->errorOut(e, "SharedCommand", "readOrderFile");
679 //**********************************************************************************************************************
681 bool SharedCommand::isValidGroup(string groupname, vector<string> groups) {
683 for (int i = 0; i < groups.size(); i++) {
684 if (groupname == groups[i]) { return true; }
689 catch(exception& e) {
690 m->errorOut(e, "SharedCommand", "isValidGroup");
694 /************************************************************/