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;
61 outputTypes["group"] = tempOutNames;
64 m->errorOut(e, "SharedCommand", "SharedCommand");
68 //**********************************************************************************************************************
69 SharedCommand::SharedCommand(string option) {
71 abort = false; calledHelp = false;
74 //allow user to run help
75 if(option == "help") { help(); abort = true; calledHelp = true; }
76 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
80 vector<string> myArray = setParameters();
82 OptionParser parser(option);
83 map<string, string> parameters = parser.getParameters();
85 ValidParameters validParameter;
86 map<string, string>::iterator it;
88 //check to make sure all parameters are valid for command
89 for (it = parameters.begin(); it != parameters.end(); it++) {
90 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
93 //if the user changes the input directory command factory will send this info to us in the output parameter
94 string inputDir = validParameter.validFile(parameters, "inputdir", false);
95 if (inputDir == "not found"){ inputDir = ""; }
98 it = parameters.find("list");
99 //user has given a template file
100 if(it != parameters.end()){
101 path = m->hasPath(it->second);
102 //if the user has not given a path then, add inputdir. else leave path alone.
103 if (path == "") { parameters["list"] = inputDir + it->second; }
106 it = parameters.find("group");
107 //user has given a template file
108 if(it != parameters.end()){
109 path = m->hasPath(it->second);
110 //if the user has not given a path then, add inputdir. else leave path alone.
111 if (path == "") { parameters["group"] = inputDir + it->second; }
114 it = parameters.find("ordergroup");
115 //user has given a template file
116 if(it != parameters.end()){
117 path = m->hasPath(it->second);
118 //if the user has not given a path then, add inputdir. else leave path alone.
119 if (path == "") { parameters["ordergroup"] = inputDir + it->second; }
124 //if the user changes the output directory command factory will send this info to us in the output parameter
125 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
127 //check for required parameters
128 listfile = validParameter.validFile(parameters, "list", true);
129 if (listfile == "not open") { listfile = ""; abort = true; }
130 else if (listfile == "not found") {
131 listfile = m->getListFile();
132 if (listfile != "") { m->mothurOut("Using " + listfile + " as input file for the list parameter."); m->mothurOutEndLine(); }
133 else { m->mothurOut("You have no current list file and the list parameter is required."); m->mothurOutEndLine(); abort = true; }
136 ordergroupfile = validParameter.validFile(parameters, "ordergroup", true);
137 if (ordergroupfile == "not open") { abort = true; }
138 else if (ordergroupfile == "not found") { ordergroupfile = ""; }
140 groupfile = validParameter.validFile(parameters, "group", true);
141 if (groupfile == "not open") { groupfile = ""; abort = true; }
142 else if (groupfile == "not found") {
143 groupfile = m->getGroupFile();
144 if (groupfile != "") {
145 m->mothurOut("Using " + groupfile + " as input file for the group parameter."); m->mothurOutEndLine();
146 groupMap = new GroupMap(groupfile);
148 int error = groupMap->readMap();
149 if (error == 1) { abort = true; }
150 m->namesOfGroups = groupMap->namesOfGroups;
152 else { m->mothurOut("You have no current group file and the group parameter is required."); m->mothurOutEndLine(); abort = true; }
154 groupMap = new GroupMap(groupfile);
156 int error = groupMap->readMap();
157 if (error == 1) { abort = true; }
158 m->namesOfGroups = groupMap->namesOfGroups;
159 m->setGroupFile(groupfile);
162 string groups = validParameter.validFile(parameters, "groups", false);
163 if (groups == "not found") { groups = ""; }
165 m->splitAtDash(groups, Groups);
169 //check for optional parameter and set defaults
170 // ...at some point should added some additional type checking...
171 string label = validParameter.validFile(parameters, "label", false);
172 if (label == "not found") { label = ""; }
174 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
175 else { allLines = 1; }
180 catch(exception& e) {
181 m->errorOut(e, "SharedCommand", "SharedCommand");
185 //**********************************************************************************************************************
187 int SharedCommand::execute(){
190 if (abort == true) { if (calledHelp) { return 0; } return 2; }
192 //getting output filename
195 if (outputDir == "") { outputDir += m->hasPath(filename); }
197 filename = outputDir + m->getRootName(m->getSimpleName(filename));
198 filename = filename + "shared";
199 outputTypes["shared"].push_back(filename);
201 m->openOutputFile(filename, out);
202 pickedGroups = false;
204 //if hte user has not specified any groups then use them all
205 if (Groups.size() == 0) {
206 Groups = groupMap->namesOfGroups; m->Groups = Groups;
207 }else { pickedGroups = true; }
209 //fill filehandles with neccessary ofstreams
212 for (i=0; i<Groups.size(); i++) {
214 filehandles[Groups[i]] = temp;
218 fileroot = outputDir + m->getRootName(m->getSimpleName(listfile));
220 //clears file before we start to write to it below
221 for (int i=0; i<Groups.size(); i++) {
222 remove((fileroot + Groups[i] + ".rabund").c_str());
223 outputNames.push_back((fileroot + Groups[i] + ".rabund"));
224 outputTypes["rabund"].push_back((fileroot + Groups[i] + ".rabund"));
228 string errorOff = "no error";
231 //if user provided an order file containing the order the shared file should be in read it
232 if (ordergroupfile != "") { readOrderFile(); }
234 input = new InputData(listfile, "shared");
235 SharedList = input->getSharedListVector();
236 string lastLabel = SharedList->getLabel();
237 vector<SharedRAbundVector*> lookup;
239 if (m->control_pressed) {
240 delete input; delete SharedList; delete groupMap;
241 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
242 out.close(); remove(filename.c_str());
243 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
247 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
248 m->mothurOut("Your group file contains " + toString(groupMap->getNumSeqs()) + " sequences and list file contains " + toString(SharedList->getNumSeqs()) + " sequences. Please correct."); m->mothurOutEndLine();
251 remove(filename.c_str()); //remove blank shared file you made
253 createMisMatchFile();
256 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) {
260 delete input; delete SharedList; delete groupMap;
265 //if user has specified groups make new groupfile for them
266 if (pickedGroups) { //make new group file
268 if (m->Groups.size() < 4) {
269 for (int i = 0; i < m->Groups.size(); i++) {
270 groups += m->Groups[i] + ".";
272 }else { groups = "merge"; }
274 string newGroupFile = outputDir + m->getRootName(m->getSimpleName(listfile)) + groups + "groups";
275 outputTypes["group"].push_back(newGroupFile);
276 outputNames.push_back(newGroupFile);
278 m->openOutputFile(newGroupFile, outGroups);
280 vector<string> names = groupMap->getNamesSeqs();
282 for (int i = 0; i < names.size(); i++) {
283 groupName = groupMap->getGroup(names[i]);
284 if (isValidGroup(groupName, m->Groups)) {
285 outGroups << names[i] << '\t' << groupName << endl;
291 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
292 set<string> processedLabels;
293 set<string> userLabels = labels;
295 while((SharedList != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
296 if (m->control_pressed) {
297 delete input; delete SharedList; delete groupMap;
298 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
299 out.close(); remove(filename.c_str());
300 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
304 if(allLines == 1 || labels.count(SharedList->getLabel()) == 1){
306 lookup = SharedList->getSharedRAbundVector();
308 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
309 if (pickedGroups) { //check for otus with no seqs in them
310 eliminateZeroOTUS(lookup);
313 if (m->control_pressed) {
314 delete input; delete SharedList; delete groupMap;
315 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
316 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
317 out.close(); remove(filename.c_str());
318 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
322 printSharedData(lookup); //prints info to the .shared file
323 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
325 processedLabels.insert(SharedList->getLabel());
326 userLabels.erase(SharedList->getLabel());
329 if ((m->anyLabelsToProcess(SharedList->getLabel(), userLabels, errorOff) == true) && (processedLabels.count(lastLabel) != 1)) {
330 string saveLabel = SharedList->getLabel();
333 SharedList = input->getSharedListVector(lastLabel); //get new list vector to process
335 lookup = SharedList->getSharedRAbundVector();
336 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
337 if (pickedGroups) { //check for otus with no seqs in them
338 eliminateZeroOTUS(lookup);
342 if (m->control_pressed) {
343 delete input; delete SharedList; delete groupMap;
344 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
345 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
346 out.close(); remove(filename.c_str());
347 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
351 printSharedData(lookup); //prints info to the .shared file
352 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
354 processedLabels.insert(SharedList->getLabel());
355 userLabels.erase(SharedList->getLabel());
357 //restore real lastlabel to save below
358 SharedList->setLabel(saveLabel);
362 lastLabel = SharedList->getLabel();
365 SharedList = input->getSharedListVector(); //get new list vector to process
368 //output error messages about any remaining user labels
369 set<string>::iterator it;
370 bool needToRun = false;
371 for (it = userLabels.begin(); it != userLabels.end(); it++) {
372 if (processedLabels.count(lastLabel) != 1) {
377 //run last label if you need to
378 if (needToRun == true) {
379 if (SharedList != NULL) { delete SharedList; }
380 SharedList = input->getSharedListVector(lastLabel); //get new list vector to process
382 lookup = SharedList->getSharedRAbundVector();
383 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
384 if (pickedGroups) { //check for otus with no seqs in them
385 eliminateZeroOTUS(lookup);
388 if (m->control_pressed) {
389 delete input; delete groupMap;
390 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
391 out.close(); remove(filename.c_str());
392 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
396 printSharedData(lookup); //prints info to the .shared file
397 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
403 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) {
407 delete input; delete groupMap;
409 if (m->control_pressed) {
410 remove(filename.c_str());
411 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
415 //set rabund file as new current rabundfile
417 itTypes = outputTypes.find("rabund");
418 if (itTypes != outputTypes.end()) {
419 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRabundFile(current); }
422 itTypes = outputTypes.find("shared");
423 if (itTypes != outputTypes.end()) {
424 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSharedFile(current); }
427 itTypes = outputTypes.find("group");
428 if (itTypes != outputTypes.end()) {
429 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
432 m->mothurOutEndLine();
433 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
434 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
435 m->mothurOut(filename); m->mothurOutEndLine();
436 m->mothurOutEndLine();
440 catch(exception& e) {
441 m->errorOut(e, "SharedCommand", "execute");
445 //**********************************************************************************************************************
446 void SharedCommand::printSharedData(vector<SharedRAbundVector*> thislookup) {
449 if (order.size() == 0) { //user has not specified an order so do aplabetically
450 sort(thislookup.begin(), thislookup.end(), compareSharedRabunds);
454 //initialize bin values
455 for (int i = 0; i < thislookup.size(); i++) {
456 out << thislookup[i]->getLabel() << '\t' << thislookup[i]->getGroup() << '\t';
457 thislookup[i]->print(out);
459 m->Groups.push_back(thislookup[i]->getGroup());
461 RAbundVector rav = thislookup[i]->getRAbundVector();
462 m->openOutputFileAppend(fileroot + thislookup[i]->getGroup() + ".rabund", *(filehandles[thislookup[i]->getGroup()]));
463 rav.print(*(filehandles[thislookup[i]->getGroup()]));
464 (*(filehandles[thislookup[i]->getGroup()])).close();
467 //create a map from groupName to each sharedrabund
468 map<string, SharedRAbundVector*> myMap;
469 map<string, SharedRAbundVector*>::iterator myIt;
471 for (int i = 0; i < thislookup.size(); i++) {
472 myMap[thislookup[i]->getGroup()] = thislookup[i];
477 //loop through ordered list and print the rabund
478 for (int i = 0; i < order.size(); i++) {
479 myIt = myMap.find(order[i]);
481 if(myIt != myMap.end()) { //we found it
482 out << (myIt->second)->getLabel() << '\t' << (myIt->second)->getGroup() << '\t';
483 (myIt->second)->print(out);
485 m->Groups.push_back((myIt->second)->getGroup());
487 RAbundVector rav = (myIt->second)->getRAbundVector();
488 m->openOutputFileAppend(fileroot + (myIt->second)->getGroup() + ".rabund", *(filehandles[(myIt->second)->getGroup()]));
489 rav.print(*(filehandles[(myIt->second)->getGroup()]));
490 (*(filehandles[(myIt->second)->getGroup()])).close();
492 m->mothurOut("Can't find shared info for " + order[i] + ", skipping."); m->mothurOutEndLine();
499 catch(exception& e) {
500 m->errorOut(e, "SharedCommand", "printSharedData");
504 //**********************************************************************************************************************
505 int SharedCommand::eliminateZeroOTUS(vector<SharedRAbundVector*>& thislookup) {
508 vector<SharedRAbundVector*> newLookup;
509 for (int i = 0; i < thislookup.size(); i++) {
510 SharedRAbundVector* temp = new SharedRAbundVector();
511 temp->setLabel(thislookup[i]->getLabel());
512 temp->setGroup(thislookup[i]->getGroup());
513 newLookup.push_back(temp);
517 for (int i = 0; i < thislookup[0]->getNumBins(); i++) {
518 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
520 //look at each sharedRabund and make sure they are not all zero
522 for (int j = 0; j < thislookup.size(); j++) {
523 if (thislookup[j]->getAbundance(i) != 0) { allZero = false; break; }
526 //if they are not all zero add this bin
528 for (int j = 0; j < thislookup.size(); j++) {
529 newLookup[j]->push_back(thislookup[j]->getAbundance(i), thislookup[j]->getGroup());
532 //else{ cout << "bin # " << i << " is all zeros" << endl; }
535 for (int j = 0; j < thislookup.size(); j++) { delete thislookup[j]; }
536 thislookup = newLookup;
541 catch(exception& e) {
542 m->errorOut(e, "SharedCommand", "eliminateZeroOTUS");
546 //**********************************************************************************************************************
547 int SharedCommand::createMisMatchFile() {
549 ofstream outMisMatch;
550 string outputMisMatchName = outputDir + m->getRootName(m->getSimpleName(listfile));
552 //you have sequences in your list file that are not in your group file
553 if (SharedList->getNumSeqs() > groupMap->getNumSeqs()) {
554 outputMisMatchName += "missing.group";
555 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();
557 m->openOutputFile(outputMisMatchName, outMisMatch);
559 map<string, string> listNames;
560 map<string, string>::iterator itList;
562 //go through list and if group returns "not found" output it
563 for (int i = 0; i < SharedList->getNumBins(); i++) {
564 if (m->control_pressed) { outMisMatch.close(); remove(outputMisMatchName.c_str()); return 0; }
566 string names = SharedList->get(i);
568 while (names.find_first_of(',') != -1) {
569 string name = names.substr(0,names.find_first_of(','));
570 names = names.substr(names.find_first_of(',')+1, names.length());
571 string group = groupMap->getGroup(name);
573 if(group == "not found") { outMisMatch << name << endl; }
575 itList = listNames.find(name);
576 if (itList != listNames.end()) { m->mothurOut(name + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
577 else { listNames[name] = name; }
581 string group = groupMap->getGroup(names);
582 if(group == "not found") { outMisMatch << names << endl; }
584 itList = listNames.find(names);
585 if (itList != listNames.end()) { m->mothurOut(names + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
586 else { listNames[names] = names; }
593 }else {//you have sequences in your group file that are not in you list file
595 outputMisMatchName += "missing.name";
596 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();
598 map<string, string> namesInList;
599 map<string, string>::iterator itList;
601 //go through listfile and get names
602 for (int i = 0; i < SharedList->getNumBins(); i++) {
603 if (m->control_pressed) { return 0; }
606 string names = SharedList->get(i);
608 while (names.find_first_of(',') != -1) {
609 string name = names.substr(0,names.find_first_of(','));
610 names = names.substr(names.find_first_of(',')+1, names.length());
612 itList = namesInList.find(name);
613 if (itList != namesInList.end()) { m->mothurOut(name + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
615 namesInList[name] = name;
619 itList = namesInList.find(names);
620 if (itList != namesInList.end()) { m->mothurOut(names + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
623 namesInList[names] = names;
626 //get names of sequences in groupfile
627 vector<string> seqNames = groupMap->getNamesSeqs();
629 map<string, string>::iterator itMatch;
631 m->openOutputFile(outputMisMatchName, outMisMatch);
633 //loop through names in seqNames and if they aren't in namesIn list output them
634 for (int i = 0; i < seqNames.size(); i++) {
635 if (m->control_pressed) { outMisMatch.close(); remove(outputMisMatchName.c_str()); return 0; }
637 itMatch = namesInList.find(seqNames[i]);
639 if (itMatch == namesInList.end()) {
641 outMisMatch << seqNames[i] << endl;
649 catch(exception& e) {
650 m->errorOut(e, "SharedCommand", "createMisMatchFile");
655 //**********************************************************************************************************************
657 SharedCommand::~SharedCommand(){
662 //**********************************************************************************************************************
663 int SharedCommand::readOrderFile() {
669 m->openInputFile(ordergroupfile, in);
673 in >> thisGroup; m->gobble(in);
675 order.push_back(thisGroup);
677 if (m->control_pressed) { order.clear(); break; }
683 catch(exception& e) {
684 m->errorOut(e, "SharedCommand", "readOrderFile");
688 //**********************************************************************************************************************
690 bool SharedCommand::isValidGroup(string groupname, vector<string> groups) {
692 for (int i = 0; i < groups.size(); i++) {
693 if (groupname == groups[i]) { return true; }
698 catch(exception& e) {
699 m->errorOut(e, "SharedCommand", "isValidGroup");
703 /************************************************************/