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; }
79 vector<string> myArray = setParameters();
81 OptionParser parser(option);
82 map<string, string> parameters = parser.getParameters();
84 ValidParameters validParameter;
85 map<string, string>::iterator it;
87 //check to make sure all parameters are valid for command
88 for (it = parameters.begin(); it != parameters.end(); it++) {
89 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
92 //if the user changes the input directory command factory will send this info to us in the output parameter
93 string inputDir = validParameter.validFile(parameters, "inputdir", false);
94 if (inputDir == "not found"){ inputDir = ""; }
97 it = parameters.find("list");
98 //user has given a template file
99 if(it != parameters.end()){
100 path = m->hasPath(it->second);
101 //if the user has not given a path then, add inputdir. else leave path alone.
102 if (path == "") { parameters["list"] = inputDir + it->second; }
105 it = parameters.find("group");
106 //user has given a template file
107 if(it != parameters.end()){
108 path = m->hasPath(it->second);
109 //if the user has not given a path then, add inputdir. else leave path alone.
110 if (path == "") { parameters["group"] = inputDir + it->second; }
113 it = parameters.find("ordergroup");
114 //user has given a template file
115 if(it != parameters.end()){
116 path = m->hasPath(it->second);
117 //if the user has not given a path then, add inputdir. else leave path alone.
118 if (path == "") { parameters["ordergroup"] = inputDir + it->second; }
123 //if the user changes the output directory command factory will send this info to us in the output parameter
124 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
126 //check for required parameters
127 listfile = validParameter.validFile(parameters, "list", true);
128 if (listfile == "not open") { listfile = ""; abort = true; }
129 else if (listfile == "not found") {
130 listfile = m->getListFile();
131 if (listfile != "") { m->mothurOut("Using " + listfile + " as input file for the list parameter."); m->mothurOutEndLine(); }
132 else { m->mothurOut("You have no current list file and the list parameter is required."); m->mothurOutEndLine(); abort = true; }
135 ordergroupfile = validParameter.validFile(parameters, "ordergroup", true);
136 if (ordergroupfile == "not open") { abort = true; }
137 else if (ordergroupfile == "not found") { ordergroupfile = ""; }
139 groupfile = validParameter.validFile(parameters, "group", true);
140 if (groupfile == "not open") { groupfile = ""; abort = true; }
141 else if (groupfile == "not found") {
142 groupfile = m->getGroupFile();
143 if (groupfile != "") {
144 m->mothurOut("Using " + groupfile + " as input file for the group parameter."); m->mothurOutEndLine();
145 groupMap = new GroupMap(groupfile);
147 int error = groupMap->readMap();
148 if (error == 1) { abort = true; }
149 m->namesOfGroups = groupMap->namesOfGroups;
151 else { m->mothurOut("You have no current group file and the group parameter is required."); m->mothurOutEndLine(); abort = true; }
153 groupMap = new GroupMap(groupfile);
155 int error = groupMap->readMap();
156 if (error == 1) { abort = true; }
157 m->namesOfGroups = groupMap->namesOfGroups;
158 m->setGroupFile(groupfile);
161 string groups = validParameter.validFile(parameters, "groups", false);
162 if (groups == "not found") { groups = ""; }
164 m->splitAtDash(groups, Groups);
168 //check for optional parameter and set defaults
169 // ...at some point should added some additional type checking...
170 string label = validParameter.validFile(parameters, "label", false);
171 if (label == "not found") { label = ""; }
173 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
174 else { allLines = 1; }
179 catch(exception& e) {
180 m->errorOut(e, "SharedCommand", "SharedCommand");
184 //**********************************************************************************************************************
186 int SharedCommand::execute(){
189 if (abort == true) { if (calledHelp) { return 0; } return 2; }
191 //getting output filename
194 if (outputDir == "") { outputDir += m->hasPath(filename); }
196 filename = outputDir + m->getRootName(m->getSimpleName(filename));
197 filename = filename + "shared";
198 outputTypes["shared"].push_back(filename);
200 m->openOutputFile(filename, out);
201 pickedGroups = false;
203 //if hte user has not specified any groups then use them all
204 if (Groups.size() == 0) {
205 Groups = groupMap->namesOfGroups; m->Groups = Groups;
206 }else { pickedGroups = true; }
208 //fill filehandles with neccessary ofstreams
211 for (i=0; i<Groups.size(); i++) {
213 filehandles[Groups[i]] = temp;
217 fileroot = outputDir + m->getRootName(m->getSimpleName(listfile));
219 //clears file before we start to write to it below
220 for (int i=0; i<Groups.size(); i++) {
221 remove((fileroot + Groups[i] + ".rabund").c_str());
222 outputNames.push_back((fileroot + Groups[i] + ".rabund"));
223 outputTypes["rabund"].push_back((fileroot + Groups[i] + ".rabund"));
227 string errorOff = "no error";
230 //if user provided an order file containing the order the shared file should be in read it
231 if (ordergroupfile != "") { readOrderFile(); }
233 input = new InputData(listfile, "shared");
234 SharedList = input->getSharedListVector();
235 string lastLabel = SharedList->getLabel();
236 vector<SharedRAbundVector*> lookup;
238 if (m->control_pressed) {
239 delete input; delete SharedList; delete groupMap;
240 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
241 out.close(); remove(filename.c_str());
242 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
246 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
247 m->mothurOut("Your group file contains " + toString(groupMap->getNumSeqs()) + " sequences and list file contains " + toString(SharedList->getNumSeqs()) + " sequences. Please correct."); m->mothurOutEndLine();
250 remove(filename.c_str()); //remove blank shared file you made
252 createMisMatchFile();
255 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) {
259 delete input; delete SharedList; delete groupMap;
264 //if user has specified groups make new groupfile for them
265 if (pickedGroups) { //make new group file
267 if (m->Groups.size() < 4) {
268 for (int i = 0; i < m->Groups.size(); i++) {
269 groups += m->Groups[i] + ".";
271 }else { groups = "merge"; }
273 string newGroupFile = outputDir + m->getRootName(m->getSimpleName(listfile)) + groups + "groups";
274 outputTypes["group"].push_back(newGroupFile);
275 outputNames.push_back(newGroupFile);
277 m->openOutputFile(newGroupFile, outGroups);
279 vector<string> names = groupMap->getNamesSeqs();
281 for (int i = 0; i < names.size(); i++) {
282 groupName = groupMap->getGroup(names[i]);
283 if (isValidGroup(groupName, m->Groups)) {
284 outGroups << names[i] << '\t' << groupName << endl;
290 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
291 set<string> processedLabels;
292 set<string> userLabels = labels;
294 while((SharedList != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
295 if (m->control_pressed) {
296 delete input; delete SharedList; delete groupMap;
297 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
298 out.close(); remove(filename.c_str());
299 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
303 if(allLines == 1 || labels.count(SharedList->getLabel()) == 1){
305 lookup = SharedList->getSharedRAbundVector();
307 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
308 if (pickedGroups) { //check for otus with no seqs in them
309 eliminateZeroOTUS(lookup);
312 if (m->control_pressed) {
313 delete input; delete SharedList; delete groupMap;
314 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
315 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
316 out.close(); remove(filename.c_str());
317 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
321 printSharedData(lookup); //prints info to the .shared file
322 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
324 processedLabels.insert(SharedList->getLabel());
325 userLabels.erase(SharedList->getLabel());
328 if ((m->anyLabelsToProcess(SharedList->getLabel(), userLabels, errorOff) == true) && (processedLabels.count(lastLabel) != 1)) {
329 string saveLabel = SharedList->getLabel();
332 SharedList = input->getSharedListVector(lastLabel); //get new list vector to process
334 lookup = SharedList->getSharedRAbundVector();
335 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
336 if (pickedGroups) { //check for otus with no seqs in them
337 eliminateZeroOTUS(lookup);
341 if (m->control_pressed) {
342 delete input; delete SharedList; delete groupMap;
343 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
344 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
345 out.close(); remove(filename.c_str());
346 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
350 printSharedData(lookup); //prints info to the .shared file
351 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
353 processedLabels.insert(SharedList->getLabel());
354 userLabels.erase(SharedList->getLabel());
356 //restore real lastlabel to save below
357 SharedList->setLabel(saveLabel);
361 lastLabel = SharedList->getLabel();
364 SharedList = input->getSharedListVector(); //get new list vector to process
367 //output error messages about any remaining user labels
368 set<string>::iterator it;
369 bool needToRun = false;
370 for (it = userLabels.begin(); it != userLabels.end(); it++) {
371 if (processedLabels.count(lastLabel) != 1) {
376 //run last label if you need to
377 if (needToRun == true) {
378 if (SharedList != NULL) { delete SharedList; }
379 SharedList = input->getSharedListVector(lastLabel); //get new list vector to process
381 lookup = SharedList->getSharedRAbundVector();
382 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
383 if (pickedGroups) { //check for otus with no seqs in them
384 eliminateZeroOTUS(lookup);
387 if (m->control_pressed) {
388 delete input; delete groupMap;
389 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
390 out.close(); remove(filename.c_str());
391 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
395 printSharedData(lookup); //prints info to the .shared file
396 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
402 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) {
406 delete input; delete groupMap;
408 if (m->control_pressed) {
409 remove(filename.c_str());
410 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
414 //set rabund file as new current rabundfile
416 itTypes = outputTypes.find("rabund");
417 if (itTypes != outputTypes.end()) {
418 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRabundFile(current); }
421 itTypes = outputTypes.find("shared");
422 if (itTypes != outputTypes.end()) {
423 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSharedFile(current); }
426 itTypes = outputTypes.find("group");
427 if (itTypes != outputTypes.end()) {
428 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
431 m->mothurOutEndLine();
432 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
433 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
434 m->mothurOut(filename); m->mothurOutEndLine();
435 m->mothurOutEndLine();
439 catch(exception& e) {
440 m->errorOut(e, "SharedCommand", "execute");
444 //**********************************************************************************************************************
445 void SharedCommand::printSharedData(vector<SharedRAbundVector*> thislookup) {
448 if (order.size() == 0) { //user has not specified an order so do aplabetically
449 sort(thislookup.begin(), thislookup.end(), compareSharedRabunds);
453 //initialize bin values
454 for (int i = 0; i < thislookup.size(); i++) {
455 out << thislookup[i]->getLabel() << '\t' << thislookup[i]->getGroup() << '\t';
456 thislookup[i]->print(out);
458 m->Groups.push_back(thislookup[i]->getGroup());
460 RAbundVector rav = thislookup[i]->getRAbundVector();
461 m->openOutputFileAppend(fileroot + thislookup[i]->getGroup() + ".rabund", *(filehandles[thislookup[i]->getGroup()]));
462 rav.print(*(filehandles[thislookup[i]->getGroup()]));
463 (*(filehandles[thislookup[i]->getGroup()])).close();
466 //create a map from groupName to each sharedrabund
467 map<string, SharedRAbundVector*> myMap;
468 map<string, SharedRAbundVector*>::iterator myIt;
470 for (int i = 0; i < thislookup.size(); i++) {
471 myMap[thislookup[i]->getGroup()] = thislookup[i];
476 //loop through ordered list and print the rabund
477 for (int i = 0; i < order.size(); i++) {
478 myIt = myMap.find(order[i]);
480 if(myIt != myMap.end()) { //we found it
481 out << (myIt->second)->getLabel() << '\t' << (myIt->second)->getGroup() << '\t';
482 (myIt->second)->print(out);
484 m->Groups.push_back((myIt->second)->getGroup());
486 RAbundVector rav = (myIt->second)->getRAbundVector();
487 m->openOutputFileAppend(fileroot + (myIt->second)->getGroup() + ".rabund", *(filehandles[(myIt->second)->getGroup()]));
488 rav.print(*(filehandles[(myIt->second)->getGroup()]));
489 (*(filehandles[(myIt->second)->getGroup()])).close();
491 m->mothurOut("Can't find shared info for " + order[i] + ", skipping."); m->mothurOutEndLine();
498 catch(exception& e) {
499 m->errorOut(e, "SharedCommand", "printSharedData");
503 //**********************************************************************************************************************
504 int SharedCommand::eliminateZeroOTUS(vector<SharedRAbundVector*>& thislookup) {
507 vector<SharedRAbundVector*> newLookup;
508 for (int i = 0; i < thislookup.size(); i++) {
509 SharedRAbundVector* temp = new SharedRAbundVector();
510 temp->setLabel(thislookup[i]->getLabel());
511 temp->setGroup(thislookup[i]->getGroup());
512 newLookup.push_back(temp);
516 for (int i = 0; i < thislookup[0]->getNumBins(); i++) {
517 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
519 //look at each sharedRabund and make sure they are not all zero
521 for (int j = 0; j < thislookup.size(); j++) {
522 if (thislookup[j]->getAbundance(i) != 0) { allZero = false; break; }
525 //if they are not all zero add this bin
527 for (int j = 0; j < thislookup.size(); j++) {
528 newLookup[j]->push_back(thislookup[j]->getAbundance(i), thislookup[j]->getGroup());
531 //else{ cout << "bin # " << i << " is all zeros" << endl; }
534 for (int j = 0; j < thislookup.size(); j++) { delete thislookup[j]; }
535 thislookup = newLookup;
540 catch(exception& e) {
541 m->errorOut(e, "SharedCommand", "eliminateZeroOTUS");
545 //**********************************************************************************************************************
546 int SharedCommand::createMisMatchFile() {
548 ofstream outMisMatch;
549 string outputMisMatchName = outputDir + m->getRootName(m->getSimpleName(listfile));
551 //you have sequences in your list file that are not in your group file
552 if (SharedList->getNumSeqs() > groupMap->getNumSeqs()) {
553 outputMisMatchName += "missing.group";
554 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();
556 m->openOutputFile(outputMisMatchName, outMisMatch);
558 map<string, string> listNames;
559 map<string, string>::iterator itList;
561 //go through list and if group returns "not found" output it
562 for (int i = 0; i < SharedList->getNumBins(); i++) {
563 if (m->control_pressed) { outMisMatch.close(); remove(outputMisMatchName.c_str()); return 0; }
565 string names = SharedList->get(i);
567 while (names.find_first_of(',') != -1) {
568 string name = names.substr(0,names.find_first_of(','));
569 names = names.substr(names.find_first_of(',')+1, names.length());
570 string group = groupMap->getGroup(name);
572 if(group == "not found") { outMisMatch << name << endl; }
574 itList = listNames.find(name);
575 if (itList != listNames.end()) { m->mothurOut(name + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
576 else { listNames[name] = name; }
580 string group = groupMap->getGroup(names);
581 if(group == "not found") { outMisMatch << names << endl; }
583 itList = listNames.find(names);
584 if (itList != listNames.end()) { m->mothurOut(names + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
585 else { listNames[names] = names; }
592 }else {//you have sequences in your group file that are not in you list file
594 outputMisMatchName += "missing.name";
595 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();
597 map<string, string> namesInList;
598 map<string, string>::iterator itList;
600 //go through listfile and get names
601 for (int i = 0; i < SharedList->getNumBins(); i++) {
602 if (m->control_pressed) { return 0; }
605 string names = SharedList->get(i);
607 while (names.find_first_of(',') != -1) {
608 string name = names.substr(0,names.find_first_of(','));
609 names = names.substr(names.find_first_of(',')+1, names.length());
611 itList = namesInList.find(name);
612 if (itList != namesInList.end()) { m->mothurOut(name + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
614 namesInList[name] = name;
618 itList = namesInList.find(names);
619 if (itList != namesInList.end()) { m->mothurOut(names + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
622 namesInList[names] = names;
625 //get names of sequences in groupfile
626 vector<string> seqNames = groupMap->getNamesSeqs();
628 map<string, string>::iterator itMatch;
630 m->openOutputFile(outputMisMatchName, outMisMatch);
632 //loop through names in seqNames and if they aren't in namesIn list output them
633 for (int i = 0; i < seqNames.size(); i++) {
634 if (m->control_pressed) { outMisMatch.close(); remove(outputMisMatchName.c_str()); return 0; }
636 itMatch = namesInList.find(seqNames[i]);
638 if (itMatch == namesInList.end()) {
640 outMisMatch << seqNames[i] << endl;
648 catch(exception& e) {
649 m->errorOut(e, "SharedCommand", "createMisMatchFile");
654 //**********************************************************************************************************************
656 SharedCommand::~SharedCommand(){
661 //**********************************************************************************************************************
662 int SharedCommand::readOrderFile() {
668 m->openInputFile(ordergroupfile, in);
672 in >> thisGroup; m->gobble(in);
674 order.push_back(thisGroup);
676 if (m->control_pressed) { order.clear(); break; }
682 catch(exception& e) {
683 m->errorOut(e, "SharedCommand", "readOrderFile");
687 //**********************************************************************************************************************
689 bool SharedCommand::isValidGroup(string groupname, vector<string> groups) {
691 for (int i = 0; i < groups.size(); i++) {
692 if (groupname == groups[i]) { return true; }
697 catch(exception& e) {
698 m->errorOut(e, "SharedCommand", "isValidGroup");
702 /************************************************************/