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") { 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(){
224 string errorOff = "no error";
227 //if user provided an order file containing the order the shared file should be in read it
228 if (ordergroupfile != "") { readOrderFile(); }
230 input = new InputData(listfile, "shared");
231 SharedList = input->getSharedListVector();
232 string lastLabel = SharedList->getLabel();
233 vector<SharedRAbundVector*> lookup;
235 if (m->control_pressed) {
236 delete input; delete SharedList; delete groupMap;
237 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
238 out.close(); remove(filename.c_str());
239 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
243 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
244 m->mothurOut("Your group file contains " + toString(groupMap->getNumSeqs()) + " sequences and list file contains " + toString(SharedList->getNumSeqs()) + " sequences. Please correct."); m->mothurOutEndLine();
247 remove(filename.c_str()); //remove blank shared file you made
249 createMisMatchFile();
252 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) {
256 delete input; delete SharedList; delete groupMap;
261 //if user has specified groups make new groupfile for them
262 if (m->Groups.size() != 0) { //make new group file
264 if (m->Groups.size() < 4) {
265 for (int i = 0; i < m->Groups.size(); i++) {
266 groups += m->Groups[i] + ".";
268 }else { groups = "merge"; }
270 string newGroupFile = outputDir + m->getRootName(m->getSimpleName(listfile)) + groups + "groups";
272 m->openOutputFile(newGroupFile, outGroups);
274 vector<string> names = groupMap->getNamesSeqs();
276 for (int i = 0; i < names.size(); i++) {
277 groupName = groupMap->getGroup(names[i]);
278 if (isValidGroup(groupName, m->Groups)) {
279 outGroups << names[i] << '\t' << groupName << endl;
285 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
286 set<string> processedLabels;
287 set<string> userLabels = labels;
289 while((SharedList != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
290 if (m->control_pressed) {
291 delete input; delete SharedList; delete groupMap;
292 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
293 out.close(); remove(filename.c_str());
294 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
298 if(allLines == 1 || labels.count(SharedList->getLabel()) == 1){
300 lookup = SharedList->getSharedRAbundVector();
302 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
303 if (pickedGroups) { //check for otus with no seqs in them
304 eliminateZeroOTUS(lookup);
307 if (m->control_pressed) {
308 delete input; delete SharedList; delete groupMap;
309 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
310 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
311 out.close(); remove(filename.c_str());
312 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
316 printSharedData(lookup); //prints info to the .shared file
317 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
319 processedLabels.insert(SharedList->getLabel());
320 userLabels.erase(SharedList->getLabel());
323 if ((m->anyLabelsToProcess(SharedList->getLabel(), userLabels, errorOff) == true) && (processedLabels.count(lastLabel) != 1)) {
324 string saveLabel = SharedList->getLabel();
327 SharedList = input->getSharedListVector(lastLabel); //get new list vector to process
329 lookup = SharedList->getSharedRAbundVector();
330 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
331 if (pickedGroups) { //check for otus with no seqs in them
332 eliminateZeroOTUS(lookup);
336 if (m->control_pressed) {
337 delete input; delete SharedList; delete groupMap;
338 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
339 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
340 out.close(); remove(filename.c_str());
341 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
345 printSharedData(lookup); //prints info to the .shared file
346 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
348 processedLabels.insert(SharedList->getLabel());
349 userLabels.erase(SharedList->getLabel());
351 //restore real lastlabel to save below
352 SharedList->setLabel(saveLabel);
356 lastLabel = SharedList->getLabel();
359 SharedList = input->getSharedListVector(); //get new list vector to process
362 //output error messages about any remaining user labels
363 set<string>::iterator it;
364 bool needToRun = false;
365 for (it = userLabels.begin(); it != userLabels.end(); it++) {
366 if (processedLabels.count(lastLabel) != 1) {
371 //run last label if you need to
372 if (needToRun == true) {
373 if (SharedList != NULL) { delete SharedList; }
374 SharedList = input->getSharedListVector(lastLabel); //get new list vector to process
376 lookup = SharedList->getSharedRAbundVector();
377 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
378 if (pickedGroups) { //check for otus with no seqs in them
379 eliminateZeroOTUS(lookup);
382 if (m->control_pressed) {
383 delete input; delete groupMap;
384 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { delete it3->second; }
385 out.close(); remove(filename.c_str());
386 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
390 printSharedData(lookup); //prints info to the .shared file
391 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
397 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) {
401 delete input; delete groupMap;
403 if (m->control_pressed) {
404 remove(filename.c_str());
405 for (int i=0; i<Groups.size(); i++) { remove((fileroot + Groups[i] + ".rabund").c_str()); }
409 //set rabund file as new current rabundfile
411 itTypes = outputTypes.find("rabund");
412 if (itTypes != outputTypes.end()) {
413 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRabundFile(current); }
416 itTypes = outputTypes.find("shared");
417 if (itTypes != outputTypes.end()) {
418 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSharedFile(current); }
421 m->mothurOutEndLine();
422 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
423 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
424 m->mothurOut(filename); m->mothurOutEndLine();
425 m->mothurOutEndLine();
429 catch(exception& e) {
430 m->errorOut(e, "SharedCommand", "execute");
434 //**********************************************************************************************************************
435 void SharedCommand::printSharedData(vector<SharedRAbundVector*> thislookup) {
438 if (order.size() == 0) { //user has not specified an order so do aplabetically
439 sort(thislookup.begin(), thislookup.end(), compareSharedRabunds);
443 //initialize bin values
444 for (int i = 0; i < thislookup.size(); i++) {
445 out << thislookup[i]->getLabel() << '\t' << thislookup[i]->getGroup() << '\t';
446 thislookup[i]->print(out);
448 m->Groups.push_back(thislookup[i]->getGroup());
450 RAbundVector rav = thislookup[i]->getRAbundVector();
451 m->openOutputFileAppend(fileroot + thislookup[i]->getGroup() + ".rabund", *(filehandles[thislookup[i]->getGroup()]));
452 rav.print(*(filehandles[thislookup[i]->getGroup()]));
453 (*(filehandles[thislookup[i]->getGroup()])).close();
456 //create a map from groupName to each sharedrabund
457 map<string, SharedRAbundVector*> myMap;
458 map<string, SharedRAbundVector*>::iterator myIt;
460 for (int i = 0; i < thislookup.size(); i++) {
461 myMap[thislookup[i]->getGroup()] = thislookup[i];
466 //loop through ordered list and print the rabund
467 for (int i = 0; i < order.size(); i++) {
468 myIt = myMap.find(order[i]);
470 if(myIt != myMap.end()) { //we found it
471 out << (myIt->second)->getLabel() << '\t' << (myIt->second)->getGroup() << '\t';
472 (myIt->second)->print(out);
474 m->Groups.push_back((myIt->second)->getGroup());
476 RAbundVector rav = (myIt->second)->getRAbundVector();
477 m->openOutputFileAppend(fileroot + (myIt->second)->getGroup() + ".rabund", *(filehandles[(myIt->second)->getGroup()]));
478 rav.print(*(filehandles[(myIt->second)->getGroup()]));
479 (*(filehandles[(myIt->second)->getGroup()])).close();
481 m->mothurOut("Can't find shared info for " + order[i] + ", skipping."); m->mothurOutEndLine();
488 catch(exception& e) {
489 m->errorOut(e, "SharedCommand", "printSharedData");
493 //**********************************************************************************************************************
494 int SharedCommand::eliminateZeroOTUS(vector<SharedRAbundVector*>& thislookup) {
497 vector<SharedRAbundVector*> newLookup;
498 for (int i = 0; i < thislookup.size(); i++) {
499 SharedRAbundVector* temp = new SharedRAbundVector();
500 temp->setLabel(thislookup[i]->getLabel());
501 temp->setGroup(thislookup[i]->getGroup());
502 newLookup.push_back(temp);
506 for (int i = 0; i < thislookup[0]->getNumBins(); i++) {
507 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
509 //look at each sharedRabund and make sure they are not all zero
511 for (int j = 0; j < thislookup.size(); j++) {
512 if (thislookup[j]->getAbundance(i) != 0) { allZero = false; break; }
515 //if they are not all zero add this bin
517 for (int j = 0; j < thislookup.size(); j++) {
518 newLookup[j]->push_back(thislookup[j]->getAbundance(i), thislookup[j]->getGroup());
521 //else{ cout << "bin # " << i << " is all zeros" << endl; }
524 for (int j = 0; j < thislookup.size(); j++) { delete thislookup[j]; }
525 thislookup = newLookup;
530 catch(exception& e) {
531 m->errorOut(e, "SharedCommand", "eliminateZeroOTUS");
535 //**********************************************************************************************************************
536 int SharedCommand::createMisMatchFile() {
538 ofstream outMisMatch;
539 string outputMisMatchName = outputDir + m->getRootName(m->getSimpleName(listfile));
541 //you have sequences in your list file that are not in your group file
542 if (SharedList->getNumSeqs() > groupMap->getNumSeqs()) {
543 outputMisMatchName += "missing.group";
544 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();
546 m->openOutputFile(outputMisMatchName, outMisMatch);
548 map<string, string> listNames;
549 map<string, string>::iterator itList;
551 //go through list and if group returns "not found" output it
552 for (int i = 0; i < SharedList->getNumBins(); i++) {
553 if (m->control_pressed) { outMisMatch.close(); remove(outputMisMatchName.c_str()); return 0; }
555 string names = SharedList->get(i);
557 while (names.find_first_of(',') != -1) {
558 string name = names.substr(0,names.find_first_of(','));
559 names = names.substr(names.find_first_of(',')+1, names.length());
560 string group = groupMap->getGroup(name);
562 if(group == "not found") { outMisMatch << name << endl; }
564 itList = listNames.find(name);
565 if (itList != listNames.end()) { m->mothurOut(name + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
566 else { listNames[name] = name; }
570 string group = groupMap->getGroup(names);
571 if(group == "not found") { outMisMatch << names << endl; }
573 itList = listNames.find(names);
574 if (itList != listNames.end()) { m->mothurOut(names + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
575 else { listNames[names] = names; }
582 }else {//you have sequences in your group file that are not in you list file
584 outputMisMatchName += "missing.name";
585 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();
587 map<string, string> namesInList;
588 map<string, string>::iterator itList;
590 //go through listfile and get names
591 for (int i = 0; i < SharedList->getNumBins(); i++) {
592 if (m->control_pressed) { return 0; }
595 string names = SharedList->get(i);
597 while (names.find_first_of(',') != -1) {
598 string name = names.substr(0,names.find_first_of(','));
599 names = names.substr(names.find_first_of(',')+1, names.length());
601 itList = namesInList.find(name);
602 if (itList != namesInList.end()) { m->mothurOut(name + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
604 namesInList[name] = name;
608 itList = namesInList.find(names);
609 if (itList != namesInList.end()) { m->mothurOut(names + " is in your list file more than once. Sequence names must be unique. please correct."); m->mothurOutEndLine(); }
612 namesInList[names] = names;
615 //get names of sequences in groupfile
616 vector<string> seqNames = groupMap->getNamesSeqs();
618 map<string, string>::iterator itMatch;
620 m->openOutputFile(outputMisMatchName, outMisMatch);
622 //loop through names in seqNames and if they aren't in namesIn list output them
623 for (int i = 0; i < seqNames.size(); i++) {
624 if (m->control_pressed) { outMisMatch.close(); remove(outputMisMatchName.c_str()); return 0; }
626 itMatch = namesInList.find(seqNames[i]);
628 if (itMatch == namesInList.end()) {
630 outMisMatch << seqNames[i] << endl;
638 catch(exception& e) {
639 m->errorOut(e, "SharedCommand", "createMisMatchFile");
644 //**********************************************************************************************************************
646 SharedCommand::~SharedCommand(){
651 //**********************************************************************************************************************
652 int SharedCommand::readOrderFile() {
658 m->openInputFile(ordergroupfile, in);
662 in >> thisGroup; m->gobble(in);
664 order.push_back(thisGroup);
666 if (m->control_pressed) { order.clear(); break; }
672 catch(exception& e) {
673 m->errorOut(e, "SharedCommand", "readOrderFile");
677 //**********************************************************************************************************************
679 bool SharedCommand::isValidGroup(string groupname, vector<string> groups) {
681 for (int i = 0; i < groups.size(); i++) {
682 if (groupname == groups[i]) { return true; }
687 catch(exception& e) {
688 m->errorOut(e, "SharedCommand", "isValidGroup");
692 /************************************************************/