]> git.donarmstrong.com Git - mothur.git/blob - splitgroupscommand.cpp
220c7cc680b1729880001c5bf94ad1fc284a85e9
[mothur.git] / splitgroupscommand.cpp
1 /*
2  *  splitgroupscommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 9/20/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "splitgroupscommand.h"
11 #include "sharedutilities.h"
12
13 //**********************************************************************************************************************
14 vector<string> SplitGroupCommand::setParameters(){      
15         try {           
16                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
17                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
18                 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pgroup);
19                 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
20                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
21                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
22                 
23                 vector<string> myArray;
24                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
25                 return myArray;
26         }
27         catch(exception& e) {
28                 m->errorOut(e, "SplitGroupCommand", "setParameters");
29                 exit(1);
30         }
31 }
32 //**********************************************************************************************************************
33 string SplitGroupCommand::getHelpString(){      
34         try {
35                 string helpString = "";
36                 helpString += "The split.group command reads a group file, and parses your fasta and names files by groups. \n";
37                 helpString += "The split.group command parameters are fasta, name, group and groups.\n";
38                 helpString += "The fasta and group parameters are required.\n";
39                 helpString += "The groups parameter allows you to select groups to create files for.  \n";
40                 helpString += "For example if you set groups=A-B-C, you will get a .A.fasta, .A.names, .B.fasta, .B.names, .C.fasta, .C.names files.  \n";
41                 helpString += "If you want .fasta and .names files for all groups, set groups=all.  \n";
42                 helpString += "The split.group command should be used in the following format: split.group(fasta=yourFasta, group=yourGroupFile).\n";
43                 helpString += "Example: split.group(fasta=abrecovery.fasta, group=abrecovery.groups).\n";
44                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
45                 return helpString;
46         }
47         catch(exception& e) {
48                 m->errorOut(e, "SplitGroupCommand", "getHelpString");
49                 exit(1);
50         }
51 }
52 //**********************************************************************************************************************
53 SplitGroupCommand::SplitGroupCommand(){ 
54         try {
55                 abort = true; calledHelp = true; 
56                 setParameters();
57                 vector<string> tempOutNames;
58                 outputTypes["fasta"] = tempOutNames;
59                 outputTypes["name"] = tempOutNames;
60         }
61         catch(exception& e) {
62                 m->errorOut(e, "SplitGroupCommand", "SplitGroupCommand");
63                 exit(1);
64         }
65 }
66 //**********************************************************************************************************************
67 SplitGroupCommand::SplitGroupCommand(string option)  {
68         try {
69                 abort = false; calledHelp = false;   
70                         
71                 //allow user to run help
72                 if(option == "help") { help(); abort = true; calledHelp = true; }
73                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
74                 
75                 else {
76                         vector<string> myArray = setParameters();
77                         
78                         OptionParser parser(option);
79                         map<string, string> parameters = parser.getParameters();
80                         
81                         ValidParameters validParameter;
82                         map<string, string>::iterator it;
83                 
84                         //check to make sure all parameters are valid for command
85                         for (it = parameters.begin(); it != parameters.end(); it++) { 
86                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
87                         }
88                         
89                         //initialize outputTypes
90                         vector<string> tempOutNames;
91                         outputTypes["fasta"] = tempOutNames;
92                         outputTypes["name"] = tempOutNames;
93                 
94                         //if the user changes the input directory command factory will send this info to us in the output parameter 
95                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
96                         if (inputDir == "not found"){   inputDir = "";          }
97                         else {
98                                 string path;
99                                 it = parameters.find("group");
100                                 //user has given a template file
101                                 if(it != parameters.end()){ 
102                                         path = m->hasPath(it->second);
103                                         //if the user has not given a path then, add inputdir. else leave path alone.
104                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
105                                 }
106                                 
107                                 it = parameters.find("fasta");
108                                 //user has given a template file
109                                 if(it != parameters.end()){ 
110                                         path = m->hasPath(it->second);
111                                         //if the user has not given a path then, add inputdir. else leave path alone.
112                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
113                                 }
114                                 
115                                 it = parameters.find("name");
116                                 //user has given a template file
117                                 if(it != parameters.end()){ 
118                                         path = m->hasPath(it->second);
119                                         //if the user has not given a path then, add inputdir. else leave path alone.
120                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
121                                 }
122
123                         }
124
125                         
126                         namefile = validParameter.validFile(parameters, "name", true);
127                         if (namefile == "not open") { abort = true; }
128                         else if (namefile == "not found") { namefile = ""; }    
129                 
130                         fastafile = validParameter.validFile(parameters, "fasta", true);
131                         if (fastafile == "not open") { abort = true; }
132                         else if (fastafile == "not found") {                    
133                                 fastafile = m->getFastaFile(); 
134                                 if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
135                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
136                         }       
137                         
138                         groupfile = validParameter.validFile(parameters, "group", true);
139                         if (groupfile == "not open") {  groupfile = ""; abort = true; } 
140                         else if (groupfile == "not found") {                    
141                                 groupfile = m->getGroupFile(); 
142                                 if (groupfile != "") { m->mothurOut("Using " + groupfile + " as input file for the group parameter."); m->mothurOutEndLine(); }
143                                 else {  m->mothurOut("You have no current groupfile and the group parameter is required."); m->mothurOutEndLine(); abort = true; }
144                         }
145                         
146                         groups = validParameter.validFile(parameters, "groups", false);         
147                         if (groups == "not found") { groups = ""; }
148                         else { m->splitAtDash(groups, Groups);  }
149                                                 
150                         //if the user changes the output directory command factory will send this info to us in the output parameter 
151                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = m->hasPath(groupfile);      }
152                 }
153
154         }
155         catch(exception& e) {
156                 m->errorOut(e, "SplitGroupCommand", "SplitAbundCommand");
157                 exit(1);
158         }
159 }
160 //**********************************************************************************************************************
161 int SplitGroupCommand::execute(){
162         try {
163         
164                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
165                 
166                 groupMap = new GroupMap(groupfile);
167                 groupMap->readMap();
168                 
169                 SharedUtil util;  util.setGroups(Groups, groupMap->namesOfGroups);  
170                 
171                 if (namefile != "") {  readNames();  }
172                 splitFasta();
173                 
174                 delete groupMap;
175                 
176                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str()); } return 0; }
177                 
178                 string current = "";
179                 itTypes = outputTypes.find("fasta");
180                 if (itTypes != outputTypes.end()) {
181                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
182                 }
183                 
184                 itTypes = outputTypes.find("name");
185                 if (itTypes != outputTypes.end()) {
186                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
187                 }
188                 
189                 m->mothurOutEndLine();
190                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
191                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
192                 m->mothurOutEndLine();
193                 
194                 return 0;
195         }
196         catch(exception& e) {
197                 m->errorOut(e, "SplitGroupCommand", "execute");
198                 exit(1);
199         }
200 }
201 /**********************************************************************************************************************/
202 int SplitGroupCommand::readNames() { 
203         try {
204                 //open input file
205                 ifstream in;
206                 m->openInputFile(namefile, in);
207                 
208                 while (!in.eof()) {
209                         if (m->control_pressed) { break; }
210                         
211                         string firstCol, secondCol;
212                         in >> firstCol >> secondCol; m->gobble(in);
213                         
214                         vector<string> names;
215                         m->splitAtComma(secondCol, names);
216                         
217                         nameMap[firstCol] = names;
218                 }
219                 in.close();
220                                 
221                 return 0;
222
223         }
224         catch(exception& e) {
225                 m->errorOut(e, "SplitGroupCommand", "readNames");
226                 exit(1);
227         }
228 }
229
230 /**********************************************************************************************************************/
231 int SplitGroupCommand::splitFasta() { 
232         try {
233                 
234                 string filerootFasta =  outputDir + m->getRootName(m->getSimpleName(fastafile));
235                 string filerootName =  outputDir + m->getRootName(m->getSimpleName(namefile));
236                 ofstream* temp;
237                 ofstream* temp2;
238                 map<string, ofstream*> filehandles;
239                 map<string, ofstream*>::iterator it3;
240
241                 for (int i=0; i<Groups.size(); i++) {
242                         temp = new ofstream;
243                         filehandles[Groups[i]+"fasta"] = temp;
244                         m->openOutputFile(filerootFasta + Groups[i] + ".fasta", *(filehandles[Groups[i]+"fasta"]));
245                         outputNames.push_back(filerootFasta + Groups[i] + ".fasta"); outputTypes["fasta"].push_back(filerootFasta + Groups[i] + ".fasta");
246                         
247                         if (namefile != "") {
248                                 temp2 = new ofstream;
249                                 filehandles[Groups[i]+"name"] = temp2;
250                                 m->openOutputFile(filerootName + Groups[i] + ".names", *(filehandles[Groups[i]+"name"]));
251                                 outputNames.push_back(filerootName + Groups[i] + ".names"); outputTypes["name"].push_back(filerootFasta + Groups[i] + ".names");
252                         }
253                 }
254                         
255                 //open input file
256                 ifstream in;
257                 m->openInputFile(fastafile, in);
258         
259                 while (!in.eof()) {
260                         if (m->control_pressed) { break; }
261                 
262                         Sequence seq(in); m->gobble(in);
263                                 
264                         if (seq.getName() != "") { 
265                                 
266                                 itNames = nameMap.find(seq.getName());
267                                 
268                                 if (itNames == nameMap.end()) {
269                                         if (namefile != "") {  m->mothurOut(seq.getName() + " is not in your namesfile, ignoring."); m->mothurOutEndLine();  }
270                                         else { //no names file given
271                                                 string group = groupMap->getGroup(seq.getName());
272                                                 
273                                                 if (m->inUsersGroups(group, Groups)) { //only add if this is in a group we want
274                                                         seq.printSequence(*(filehandles[group+"fasta"]));
275                                                 }else if(group == "not found") {
276                                                         m->mothurOut(seq.getName() + " is not in your groupfile. Ignoring."); m->mothurOutEndLine();
277                                                 }
278                                         }
279                                 }else{
280                                         vector<string> names = itNames->second;
281                                         map<string, string> group2Names;
282                                         map<string, string>::iterator it;
283                                         
284                                         for (int i = 0; i < names.size(); i++) {  //build strings for new group names file, will select rep below
285                                                 string group = groupMap->getGroup(names[i]);
286                                                 
287                                                 if (m->inUsersGroups(group, Groups)) { //only add if this is in a group we want
288                                                         it = group2Names.find(group);
289                                                         if (it == group2Names.end()) {
290                                                                 group2Names[group] = names[i] + ",";
291                                                         }else{
292                                                                 group2Names[group] += names[i] + ",";
293                                                         }
294                                                 }else if(group == "not found") {
295                                                         m->mothurOut(names[i] + " is not in your groupfile. Ignoring."); m->mothurOutEndLine();
296                                                 }
297                                         }
298                                 
299                                         for (map<string, string>::iterator itGroups = group2Names.begin(); itGroups != group2Names.end(); itGroups++) {
300                                                 //edit names string, by grabbing the first guy as the rep and removing the last comma
301                                                 string newNames = itGroups->second;
302                                                 newNames = newNames.substr(0, newNames.length()-1); 
303                                                 string repName = "";
304                                                 
305                                                 int pos = newNames.find_first_of(',');
306                                                 if (pos == newNames.npos) { //only one sequence so it represents itself
307                                                         repName = newNames;
308                                                 }else{
309                                                         repName = newNames.substr(0, pos);
310                                                 }
311                                                 
312                                                 *(filehandles[itGroups->first+"name"]) << repName << '\t' << newNames << endl;
313                                                 *(filehandles[itGroups->first+"fasta"]) << ">" << repName << endl << seq.getAligned() << endl;
314                                         }
315                                 }
316                         }
317                 }
318                         
319                 in.close();
320                         
321                 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) { 
322                         (*(filehandles[it3->first])).close();
323                         delete it3->second;
324                 }
325                 
326                 vector<string> newOutputNames;
327                 //remove blank files
328                 for (int i = 0; i < outputNames.size(); i++) {
329                         if (m->isBlank(outputNames[i])) {
330                                 remove(outputNames[i].c_str());
331                         }else { newOutputNames.push_back(outputNames[i]); }
332                 }
333                 outputNames = newOutputNames;
334                                 
335                 return 0;
336
337         }
338         catch(exception& e) {
339                 m->errorOut(e, "SplitGroupCommand", "splitFasta");
340                 exit(1);
341         }
342 }
343 /**********************************************************************************************************************/
344