]> git.donarmstrong.com Git - mothur.git/blob - chimerauchimecommand.cpp
added count.seqs command and made some modifcations to the uchime code to allow it...
[mothur.git] / chimerauchimecommand.cpp
1 /*
2  *  chimerauchimecommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 5/13/11.
6  *  Copyright 2011 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "chimerauchimecommand.h"
11 #include "deconvolutecommand.h"
12 #include "uc.h"
13 #include "sequence.hpp"
14
15
16 //**********************************************************************************************************************
17 vector<string> ChimeraUchimeCommand::setParameters(){   
18         try {
19                 CommandParameter ptemplate("reference", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(ptemplate);
20                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
21                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
22                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
23                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
24                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
25                 CommandParameter pabskew("abskew", "Number", "", "1.9", "", "", "",false,false); parameters.push_back(pabskew);
26                 CommandParameter pchimealns("chimealns", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(pchimealns);
27                 CommandParameter pminh("minh", "Number", "", "0.3", "", "", "",false,false); parameters.push_back(pminh);
28                 CommandParameter pmindiv("mindiv", "Number", "", "0.5", "", "", "",false,false); parameters.push_back(pmindiv);
29                 CommandParameter pxn("xn", "Number", "", "8.0", "", "", "",false,false); parameters.push_back(pxn);
30                 CommandParameter pdn("dn", "Number", "", "1.4", "", "", "",false,false); parameters.push_back(pdn);
31                 CommandParameter pxa("xa", "Number", "", "1", "", "", "",false,false); parameters.push_back(pxa);
32                 CommandParameter pchunks("chunks", "Number", "", "4", "", "", "",false,false); parameters.push_back(pchunks);
33                 CommandParameter pminchunk("minchunk", "Number", "", "64", "", "", "",false,false); parameters.push_back(pminchunk);
34                 CommandParameter pidsmoothwindow("idsmoothwindow", "Number", "", "32", "", "", "",false,false); parameters.push_back(pidsmoothwindow);
35                 CommandParameter pminsmoothid("minsmoothid", "Number", "", "0.95", "", "", "",false,false); parameters.push_back(pminsmoothid);
36                 CommandParameter pmaxp("maxp", "Number", "", "2", "", "", "",false,false); parameters.push_back(pmaxp);
37                 CommandParameter pskipgaps("skipgaps", "Boolean", "", "T", "", "", "",false,false); parameters.push_back(pskipgaps);
38                 CommandParameter pskipgaps2("skipgaps2", "Boolean", "", "T", "", "", "",false,false); parameters.push_back(pskipgaps2);
39                 CommandParameter pminlen("minlen", "Number", "", "10", "", "", "",false,false); parameters.push_back(pminlen);
40                 CommandParameter pmaxlen("maxlen", "Number", "", "10000", "", "", "",false,false); parameters.push_back(pmaxlen);
41                 CommandParameter pucl("ucl", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(pucl);
42                 CommandParameter pqueryfract("queryfract", "Number", "", "0.5", "", "", "",false,false); parameters.push_back(pqueryfract);
43                 
44                 vector<string> myArray;
45                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
46                 return myArray;
47         }
48         catch(exception& e) {
49                 m->errorOut(e, "ChimeraUchimeCommand", "setParameters");
50                 exit(1);
51         }
52 }
53 //**********************************************************************************************************************
54 string ChimeraUchimeCommand::getHelpString(){   
55         try {
56                 string helpString = "";
57                 helpString += "The chimera.uchime command reads a fastafile and referencefile and outputs potentially chimeric sequences.\n";
58                 helpString += "This command is a wrapper for uchime written by Robert C. Edgar.\n";
59                 helpString += "The chimera.uchime command parameters are fasta, name, reference, processors, abskew, chimealns, minh, mindiv, xn, dn, xa, chunks, minchunk, idsmoothwindow, minsmoothid, maxp, skipgaps, skipgaps2, minlen, maxlen, ucl and queryfact.\n";
60                 helpString += "The fasta parameter allows you to enter the fasta file containing your potentially chimeric sequences, and is required, unless you have a valid current fasta file. \n";
61                 helpString += "The name parameter allows you to provide a name file, if you are using template=self. \n";
62                 helpString += "You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n";
63                 helpString += "The reference parameter allows you to enter a reference file containing known non-chimeric sequences, and is required. You may also set template=self, in this case the abundant sequences will be used as potential parents. \n";
64                 helpString += "The processors parameter allows you to specify how many processors you would like to use.  The default is 1. \n";
65                 helpString += "The abskew parameter can only be used with template=self. Minimum abundance skew. Default 1.9. Abundance skew is: min [ abund(parent1), abund(parent2) ] / abund(query).\n";
66                 helpString += "The chimealns parameter allows you to indicate you would like a file containing multiple alignments of query sequences to parents in human readable format. Alignments show columns with differences that support or contradict a chimeric model.\n";
67                 helpString += "The minh parameter - mininum score to report chimera. Default 0.3. Values from 0.1 to 5 might be reasonable. Lower values increase sensitivity but may report more false positives. If you decrease xn you may need to increase minh, and vice versa.\n";
68                 helpString += "The mindiv parameter - minimum divergence ratio, default 0.5. Div ratio is 100%% - %%identity between query sequence and the closest candidate for being a parent. If you don't care about very close chimeras, then you could increase mindiv to, say, 1.0 or 2.0, and also decrease --min h, say to 0.1, to increase sensitivity. How well this works will depend on your data. Best is to tune parameters on a good benchmark.\n";
69                 helpString += "The xn parameter - weight of a no vote. Default 8.0. Decreasing this weight to around 3 or 4 may give better performance on denoised data.\n";
70                 helpString += "The dn parameter - pseudo-count prior on number of no votes. Default 1.4. Probably no good reason to change this unless you can retune to a good benchmark for your data. Reasonable values are probably in the range from 0.2 to 2.\n";
71                 helpString += "The xa parameter - weight of an abstain vote. Default 1. So far, results do not seem to be very sensitive to this parameter, but if you have a good training set might be worth trying. Reasonable values might range from 0.1 to 2.\n";
72                 helpString += "The chunks parameter is the number of chunks to extract from the query sequence when searching for parents. Default 4.\n";
73                 helpString += "The minchunk parameter is the minimum length of a chunk. Default 64.\n";
74                 helpString += "The idsmoothwindow parameter is the length of id smoothing window. Default 32.\n";
75                 helpString += "The minsmoothid parameter - minimum factional identity over smoothed window of candidate parent. Default 0.95.\n";
76                 helpString += "The maxp parameter - maximum number of candidate parents to consider. Default 2. In tests so far, increasing maxp gives only a very small improvement in sensivity but tends to increase the error rate quite a bit.\n";
77                 helpString += "The skipgaps parameter controls how gapped columns affect counting of diffs. If skipgaps is set to T, columns containing gaps do not found as diffs. Default = T.\n";
78                 helpString += "The skipgaps2 parameter controls how gapped columns affect counting of diffs. If skipgaps2 is set to T, if column is immediately adjacent to a column containing a gap, it is not counted as a diff. Default = T.\n";
79                 helpString += "The minlen parameter is the minimum unaligned sequence length. Defaults 10. Applies to both query and reference sequences.\n";
80                 helpString += "The maxlen parameter is the maximum unaligned sequence length. Defaults 10000. Applies to both query and reference sequences.\n";
81                 helpString += "The ucl parameter - use local-X alignments. Default is global-X or false. On tests so far, global-X is always better; this option is retained because it just might work well on some future type of data.\n";
82                 helpString += "The queryfract parameter - minimum fraction of the query sequence that must be covered by a local-X alignment. Default 0.5. Applies only when ucl is true.\n";
83 #ifdef USE_MPI
84                 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
85 #endif
86                 helpString += "The chimera.uchime command should be in the following format: \n";
87                 helpString += "chimera.uchime(fasta=yourFastaFile, reference=yourTemplate) \n";
88                 helpString += "Example: chimera.uchime(fasta=AD.align, reference=silva.gold.align) \n";
89                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";       
90                 return helpString;
91         }
92         catch(exception& e) {
93                 m->errorOut(e, "ChimeraUchimeCommand", "getHelpString");
94                 exit(1);
95         }
96 }
97 //**********************************************************************************************************************
98 ChimeraUchimeCommand::ChimeraUchimeCommand(){   
99         try {
100                 abort = true; calledHelp = true;
101                 setParameters();
102                 vector<string> tempOutNames;
103                 outputTypes["chimera"] = tempOutNames;
104                 outputTypes["accnos"] = tempOutNames;
105                 outputTypes["alns"] = tempOutNames;
106         }
107         catch(exception& e) {
108                 m->errorOut(e, "ChimeraUchimeCommand", "ChimeraUchimeCommand");
109                 exit(1);
110         }
111 }
112 //***************************************************************************************************************
113 ChimeraUchimeCommand::ChimeraUchimeCommand(string option)  {
114         try {
115                 abort = false; calledHelp = false;   
116                 
117                 //allow user to run help
118                 if(option == "help") { help(); abort = true; calledHelp = true; }
119                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
120                 
121                 else {
122                         vector<string> myArray = setParameters();
123                         
124                         OptionParser parser(option);
125                         map<string,string> parameters = parser.getParameters();
126                         
127                         ValidParameters validParameter("chimera.uchime");
128                         map<string,string>::iterator it;
129                         
130                         //check to make sure all parameters are valid for command
131                         for (it = parameters.begin(); it != parameters.end(); it++) { 
132                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
133                         }
134                         
135                         vector<string> tempOutNames;
136                         outputTypes["chimera"] = tempOutNames;
137                         outputTypes["accnos"] = tempOutNames;
138                         outputTypes["alns"] = tempOutNames;
139                         
140                         //if the user changes the input directory command factory will send this info to us in the output parameter 
141                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
142                         if (inputDir == "not found"){   inputDir = "";          }
143                         
144                         //check for required parameters
145                         fastafile = validParameter.validFile(parameters, "fasta", false);
146                         if (fastafile == "not found") {                                 
147                                 //if there is a current fasta file, use it
148                                 string filename = m->getFastaFile(); 
149                                 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
150                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
151                         }else { 
152                                 m->splitAtDash(fastafile, fastaFileNames);
153                                 
154                                 //go through files and make sure they are good, if not, then disregard them
155                                 for (int i = 0; i < fastaFileNames.size(); i++) {
156                                         
157                                         bool ignore = false;
158                                         if (fastaFileNames[i] == "current") { 
159                                                 fastaFileNames[i] = m->getFastaFile(); 
160                                                 if (fastaFileNames[i] != "") {  m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
161                                                 else {  
162                                                         m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
163                                                         //erase from file list
164                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
165                                                         i--;
166                                                 }
167                                         }
168                                         
169                                         if (!ignore) {
170                                                 
171                                                 if (inputDir != "") {
172                                                         string path = m->hasPath(fastaFileNames[i]);
173                                                         //if the user has not given a path then, add inputdir. else leave path alone.
174                                                         if (path == "") {       fastaFileNames[i] = inputDir + fastaFileNames[i];               }
175                                                 }
176                                                 
177                                                 int ableToOpen;
178                                                 ifstream in;
179                                                 
180                                                 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
181                                                 
182                                                 //if you can't open it, try default location
183                                                 if (ableToOpen == 1) {
184                                                         if (m->getDefaultPath() != "") { //default path is set
185                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
186                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
187                                                                 ifstream in2;
188                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
189                                                                 in2.close();
190                                                                 fastaFileNames[i] = tryPath;
191                                                         }
192                                                 }
193                                                 
194                                                 if (ableToOpen == 1) {
195                                                         if (m->getOutputDir() != "") { //default path is set
196                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
197                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
198                                                                 ifstream in2;
199                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
200                                                                 in2.close();
201                                                                 fastaFileNames[i] = tryPath;
202                                                         }
203                                                 }
204                                                 
205                                                 in.close();
206                                                 
207                                                 if (ableToOpen == 1) { 
208                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
209                                                         //erase from file list
210                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
211                                                         i--;
212                                                 }
213                                         }
214                                 }
215                                 
216                                 //make sure there is at least one valid file left
217                                 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
218                         }
219                         
220                         
221                         //check for required parameters
222                         bool hasName = true;
223                         namefile = validParameter.validFile(parameters, "name", false);
224                         if (namefile == "not found") { namefile = "";  hasName = false; }
225                         else { 
226                                 m->splitAtDash(namefile, nameFileNames);
227                                 
228                                 //go through files and make sure they are good, if not, then disregard them
229                                 for (int i = 0; i < nameFileNames.size(); i++) {
230                                         
231                                         bool ignore = false;
232                                         if (nameFileNames[i] == "current") { 
233                                                 nameFileNames[i] = m->getNameFile(); 
234                                                 if (nameFileNames[i] != "") {  m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
235                                                 else {  
236                                                         m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
237                                                         //erase from file list
238                                                         nameFileNames.erase(nameFileNames.begin()+i);
239                                                         i--;
240                                                 }
241                                         }
242                                         
243                                         if (!ignore) {
244                                                 
245                                                 if (inputDir != "") {
246                                                         string path = m->hasPath(nameFileNames[i]);
247                                                         //if the user has not given a path then, add inputdir. else leave path alone.
248                                                         if (path == "") {       nameFileNames[i] = inputDir + nameFileNames[i];         }
249                                                 }
250                                                 
251                                                 int ableToOpen;
252                                                 ifstream in;
253                                                 
254                                                 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
255                                                 
256                                                 //if you can't open it, try default location
257                                                 if (ableToOpen == 1) {
258                                                         if (m->getDefaultPath() != "") { //default path is set
259                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
260                                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
261                                                                 ifstream in2;
262                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
263                                                                 in2.close();
264                                                                 nameFileNames[i] = tryPath;
265                                                         }
266                                                 }
267                                                 
268                                                 if (ableToOpen == 1) {
269                                                         if (m->getOutputDir() != "") { //default path is set
270                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
271                                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
272                                                                 ifstream in2;
273                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
274                                                                 in2.close();
275                                                                 nameFileNames[i] = tryPath;
276                                                         }
277                                                 }
278                                                 
279                                                 in.close();
280                                                 
281                                                 if (ableToOpen == 1) { 
282                                                         m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
283                                                         //erase from file list
284                                                         nameFileNames.erase(nameFileNames.begin()+i);
285                                                         i--;
286                                                 }
287                                         }
288                                 }
289                                 
290                                 //make sure there is at least one valid file left
291                                 if (nameFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid name files."); m->mothurOutEndLine(); abort = true; }
292                         }
293                         
294                         if (hasName && (nameFileNames.size() != fastaFileNames.size())) { m->mothurOut("[ERROR]: The number of namefiles does not match the number of fastafiles, please correct."); m->mothurOutEndLine(); abort=true; }
295                         
296                         //if the user changes the output directory command factory will send this info to us in the output parameter 
297                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
298                         
299                         
300                         string path;
301                         it = parameters.find("reference");
302                         //user has given a template file
303                         if(it != parameters.end()){ 
304                                 if (it->second == "self") { templatefile = "self"; }
305                                 else {
306                                         path = m->hasPath(it->second);
307                                         //if the user has not given a path then, add inputdir. else leave path alone.
308                                         if (path == "") {       parameters["reference"] = inputDir + it->second;                }
309                                         
310                                         templatefile = validParameter.validFile(parameters, "reference", true);
311                                         if (templatefile == "not open") { abort = true; }
312                                         else if (templatefile == "not found") { templatefile = "";  m->mothurOut("reference is a required parameter for the chimera.uchime command."); m->mothurOutEndLine(); abort = true;  }  
313                                 }
314                         }else if (hasName) {  templatefile = "self"; }
315                         else { templatefile = "";  m->mothurOut("reference is a required parameter for the chimera.uchime command, unless you have a namefile."); m->mothurOutEndLine(); abort = true;  }       
316
317                         
318                         string temp = validParameter.validFile(parameters, "processors", false);        if (temp == "not found"){       temp = m->getProcessors();      }
319                         m->setProcessors(temp);
320                         convert(temp, processors);
321                         
322                         abskew = validParameter.validFile(parameters, "abskew", false); if (abskew == "not found"){     useAbskew = false;  abskew = "1.9";     }else{  useAbskew = true;  }
323                         if (useAbskew && templatefile != "self") { m->mothurOut("The abskew parameter is only valid with template=self, ignoring."); m->mothurOutEndLine(); useAbskew = false; }
324                         
325                         temp = validParameter.validFile(parameters, "chimealns", false);                        if (temp == "not found") { temp = "f"; }
326                         chimealns = m->isTrue(temp); 
327                         
328                         minh = validParameter.validFile(parameters, "minh", false);                                             if (minh == "not found")                        { useMinH = false; minh = "0.3";                                        }       else{ useMinH = true;                   }
329                         mindiv = validParameter.validFile(parameters, "mindiv", false);                                 if (mindiv == "not found")                      { useMindiv = false; mindiv = "0.5";                            }       else{ useMindiv = true;                 }
330                         xn = validParameter.validFile(parameters, "xn", false);                                                 if (xn == "not found")                          { useXn = false; xn = "8.0";                                            }       else{ useXn = true;                             }
331                         dn = validParameter.validFile(parameters, "dn", false);                                                 if (dn == "not found")                          { useDn = false; dn = "1.4";                                            }       else{ useDn = true;                             }
332                         xa = validParameter.validFile(parameters, "xa", false);                                                 if (xa == "not found")                          { useXa = false; xa = "1";                                                      }       else{ useXa = true;                             }
333                         chunks = validParameter.validFile(parameters, "chunks", false);                                 if (chunks == "not found")                      { useChunks = false; chunks = "4";                                      }       else{ useChunks = true;                 }
334                         minchunk = validParameter.validFile(parameters, "minchunk", false);                             if (minchunk == "not found")            { useMinchunk = false; minchunk = "64";                         }       else{ useMinchunk = true;               }
335                         idsmoothwindow = validParameter.validFile(parameters, "idsmoothwindow", false); if (idsmoothwindow == "not found")      { useIdsmoothwindow = false; idsmoothwindow = "32";     }       else{ useIdsmoothwindow = true; }
336                         minsmoothid = validParameter.validFile(parameters, "minsmoothid", false);               if (minsmoothid == "not found")         { useMinsmoothid = false; minsmoothid = "0.95";         }       else{ useMinsmoothid = true;    }
337                         maxp = validParameter.validFile(parameters, "maxp", false);                                             if (maxp == "not found")                        { useMaxp = false; maxp = "2";                                          }       else{ useMaxp = true;                   }
338                         minlen = validParameter.validFile(parameters, "minlen", false);                                 if (minlen == "not found")                      { useMinlen = false; minlen = "10";                                     }       else{ useMinlen = true;                 }
339                         maxlen = validParameter.validFile(parameters, "maxlen", false);                                 if (maxlen == "not found")                      { useMaxlen = false; maxlen = "10000";                          }       else{ useMaxlen = true;                 }
340                         
341                         temp = validParameter.validFile(parameters, "ucl", false);                                              if (temp == "not found") { temp = "f"; }
342                         ucl = m->isTrue(temp);
343                         
344                         queryfract = validParameter.validFile(parameters, "queryfract", false);                 if (queryfract == "not found")          { useQueryfract = false; queryfract = "0.5";            }       else{ useQueryfract = true;             }
345                         if (!ucl && useQueryfract) { m->mothurOut("queryfact may only be used when ucl=t, ignoring."); m->mothurOutEndLine(); useQueryfract = false; }
346                         
347                         temp = validParameter.validFile(parameters, "skipgaps", false);                                 if (temp == "not found") { temp = "t"; }
348                         skipgaps = m->isTrue(temp); 
349
350                         temp = validParameter.validFile(parameters, "skipgaps2", false);                                if (temp == "not found") { temp = "t"; }
351                         skipgaps2 = m->isTrue(temp); 
352
353                 }
354         }
355         catch(exception& e) {
356                 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
357                 exit(1);
358         }
359 }
360 //***************************************************************************************************************
361
362 int ChimeraUchimeCommand::execute(){
363         try{
364                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
365                 
366                 m->mothurOut("\nuchime by Robert C. Edgar\nhttp://drive5.com/uchime\nThis code is donated to the public domain.\n\n");
367                 
368                 for (int s = 0; s < fastaFileNames.size(); s++) {
369                         
370                         m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
371                         
372                         int start = time(NULL); 
373                         string nameFile = "";
374                         
375                         if (templatefile == "self") { //you want to run uchime with a refernce template
376                                 
377                                 #ifdef USE_MPI  
378                                         int pid; 
379                                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
380                                         if (pid == 0) { //you are the root process 
381                                 #endif  
382                                 
383                                 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
384                                 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
385                                         nameFile = nameFileNames[s];
386                                 }else {
387                                         m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
388                                         
389                                         //use unique.seqs to create new name and fastafile
390                                         string inputString = "fasta=" + fastaFileNames[s];
391                                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
392                                         m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
393                                         
394                                         Command* uniqueCommand = new DeconvoluteCommand(inputString);
395                                         uniqueCommand->execute();
396                                         
397                                         map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
398                                         
399                                         delete uniqueCommand;
400                                         
401                                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
402                                         
403                                         nameFile = filenames["name"][0];
404                                         fastaFileNames[s] = filenames["fasta"][0];
405                                 }
406                                 
407                                 //create input file for uchime
408                                 //read through fastafile and store info
409                                 map<string, string> seqs;
410                                 ifstream in;
411                                 m->openInputFile(fastaFileNames[s], in);
412                                 
413                                 while (!in.eof()) {
414                                         
415                                         if (m->control_pressed) { in.close(); for (int j = 0; j < outputNames.size(); j++) {    remove(outputNames[j].c_str()); }  return 0; }
416                                         
417                                         Sequence seq(in); m->gobble(in);
418                                         seqs[seq.getName()] = seq.getAligned();
419                                 }
420                                 in.close();
421                                 
422                                 //read namefile
423                                 vector<seqPriorityNode> nameMapCount;
424                                 int error = m->readNames(nameFile, nameMapCount, seqs);
425                                 
426                                 if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) {        remove(outputNames[j].c_str()); }  return 0; }
427                                 
428                                 if (error == 1) { for (int j = 0; j < outputNames.size(); j++) {        remove(outputNames[j].c_str()); }  return 0; }
429                                 if (seqs.size() != nameMapCount.size()) { m->mothurOut( "The number of sequences in your fastafile does not match the number of sequences in your namefile, aborting."); m->mothurOutEndLine(); for (int j = 0; j < outputNames.size(); j++) {  remove(outputNames[j].c_str()); }  return 0; }
430                                 
431                                 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
432                                 
433                                 string newFasta = fastaFileNames[s] + ".temp";
434                                 ofstream out;
435                                 m->openOutputFile(newFasta, out);
436                                 
437                                 //print new file in order of
438                                 for (int i = 0; i < nameMapCount.size(); i++) {
439                                         out << ">" << nameMapCount[i].name  << "/ab=" << nameMapCount[i].numIdentical << "/" << endl << nameMapCount[i].seq << endl;
440                                 }
441                                 out.close();
442                                 
443                                 fastaFileNames[s] = newFasta;
444                                                 
445                                 #ifdef USE_MPI  
446                                         }
447                                 #endif
448                                 if (m->control_pressed) {  for (int j = 0; j < outputNames.size(); j++) {       remove(outputNames[j].c_str()); }  return 0;    }                               
449                         }
450                         
451                         if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]);  }//if user entered a file with a path then preserve it                               
452                         string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "uchime.chimera";
453                         string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "uchime.accnos";
454                         string alnsFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "uchime.alns";
455                         
456                         if (m->control_pressed) {  for (int j = 0; j < outputNames.size(); j++) {       remove(outputNames[j].c_str()); }  return 0;    }
457                         
458                         int numSeqs = 0;
459 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
460                         if(processors == 1){ numSeqs = driver(outputFileName, fastaFileNames[s], accnosFileName, alnsFileName); }
461                         else{   numSeqs = createProcesses(outputFileName, fastaFileNames[s], accnosFileName, alnsFileName); }
462 #else
463                         numSeqs = driver(outputFileName, fastaFileNames[s], accnosFileName, alnsFileName);
464 #endif
465                         if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) {        remove(outputNames[j].c_str()); } return 0; }
466                         
467                         //remove file made for uchime
468                         if (templatefile == "self") {  remove(fastaFileNames[s].c_str()); }
469                         
470                         outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
471                         outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
472                         if (chimealns) { outputNames.push_back(alnsFileName); outputTypes["alns"].push_back(alnsFileName); }
473                         
474                         m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
475                 }
476                 
477                 //set accnos file as new current accnosfile
478                 string current = "";
479                 itTypes = outputTypes.find("accnos");
480                 if (itTypes != outputTypes.end()) {
481                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
482                 }
483                 
484                 m->mothurOutEndLine();
485                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
486                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
487                 m->mothurOutEndLine();
488                 
489                 return 0;
490                 
491         }
492         catch(exception& e) {
493                 m->errorOut(e, "ChimeraUchimeCommand", "execute");
494                 exit(1);
495         }
496 }
497 //**********************************************************************************************************************
498
499 int ChimeraUchimeCommand::driver(string outputFName, string filename, string accnos, string alns){
500         try {
501                 
502                 vector<char*> cPara;
503                 
504                 char* tempUchime = new char[8];  
505                 strcpy(tempUchime, "./uchime "); 
506                 cPara.push_back(tempUchime);
507                 
508                 char* tempIn = new char[7];  
509                 strcpy(tempIn, "--input"); 
510                 cPara.push_back(tempIn);
511                 char* temp = new char[filename.length()];
512                 strcpy(temp, filename.c_str());
513                 cPara.push_back(temp);
514                 
515                 //are you using a reference file
516                 if (templatefile != "self") {
517                                                 
518                         //add reference file
519                         char* tempRef = new char[4]; 
520                         strcpy(tempRef, "--db"); 
521                         cPara.push_back(tempRef);  
522                         char* tempR = new char[templatefile.length()];
523                         strcpy(tempR, templatefile.c_str());
524                         cPara.push_back(tempR);
525                 }
526                 
527                 char* tempO = new char[11]; 
528                 strcpy(tempO, "--uchimeout"); 
529                 cPara.push_back(tempO);
530                 char* tempout = new char[outputFName.length()];
531                 strcpy(tempout, outputFName.c_str());
532                 cPara.push_back(tempout);
533                 
534                 if (chimealns) {
535                         char* tempA = new char[12]; 
536                         strcpy(tempA, "--uchimealns"); 
537                         cPara.push_back(tempA);
538                         char* tempa = new char[alns.length()];
539                         strcpy(tempa, alns.c_str());
540                         cPara.push_back(tempa);
541                 }
542                 
543                 if (useAbskew) {
544                         char* tempskew = new char[8]; 
545                         strcpy(tempskew, "--abskew"); 
546                         cPara.push_back(tempskew);
547                         char* tempSkew = new char[abskew.length()];
548                         strcpy(tempSkew, abskew.c_str());
549                         cPara.push_back(tempSkew);
550                 }
551                 
552                 if (useMinH) {
553                         char* tempminh = new char[6]; 
554                         strcpy(tempminh, "--minh"); 
555                         cPara.push_back(tempminh);
556                         char* tempMinH = new char[minh.length()];
557                         strcpy(tempMinH, minh.c_str());
558                         cPara.push_back(tempMinH);
559                 }
560                 
561                 if (useMindiv) {
562                         char* tempmindiv = new char[8]; 
563                         strcpy(tempmindiv, "--mindiv"); 
564                         cPara.push_back(tempmindiv);
565                         char* tempMindiv = new char[mindiv.length()];
566                         strcpy(tempMindiv, mindiv.c_str());
567                         cPara.push_back(tempMindiv);
568                 }
569                 
570                 if (useXn) {
571                         char* tempxn = new char[4]; 
572                         strcpy(tempxn, "--xn"); 
573                         cPara.push_back(tempxn);
574                         char* tempXn = new char[xn.length()];
575                         strcpy(tempXn, xn.c_str());
576                         cPara.push_back(tempXn);
577                 }
578                 
579                 if (useDn) {
580                         char* tempdn = new char[4]; 
581                         strcpy(tempdn, "--dn"); 
582                         cPara.push_back(tempdn);
583                         char* tempDn = new char[dn.length()];
584                         strcpy(tempDn, dn.c_str());
585                         cPara.push_back(tempDn);
586                 }
587                 
588                 if (useXa) {
589                         char* tempxa = new char[4]; 
590                         strcpy(tempxa, "--xa"); 
591                         cPara.push_back(tempxa);
592                         char* tempXa = new char[xa.length()];
593                         strcpy(tempXa, xa.c_str());
594                         cPara.push_back(tempXa);
595                 }
596                 
597                 if (useChunks) {
598                         char* tempchunks = new char[8]; 
599                         strcpy(tempchunks, "--chunks"); 
600                         cPara.push_back(tempchunks);
601                         char* tempChunks = new char[chunks.length()];
602                         strcpy(tempChunks, chunks.c_str());
603                         cPara.push_back(tempChunks);
604                 }
605                 
606                 if (useMinchunk) {
607                         char* tempminchunk = new char[10]; 
608                         strcpy(tempminchunk, "--minchunk"); 
609                         cPara.push_back(tempminchunk);
610                         char* tempMinchunk = new char[minchunk.length()];
611                         strcpy(tempMinchunk, minchunk.c_str());
612                         cPara.push_back(tempMinchunk);
613                 }
614                 
615                 if (useIdsmoothwindow) {
616                         char* tempidsmoothwindow = new char[16]; 
617                         strcpy(tempidsmoothwindow, "--idsmoothwindow"); 
618                         cPara.push_back(tempidsmoothwindow);
619                         char* tempIdsmoothwindow = new char[idsmoothwindow.length()];
620                         strcpy(tempIdsmoothwindow, idsmoothwindow.c_str());
621                         cPara.push_back(tempIdsmoothwindow);
622                 }
623                 
624                 if (useMinsmoothid) {
625                         char* tempminsmoothid = new char[13]; 
626                         strcpy(tempminsmoothid, "--minsmoothid"); 
627                         cPara.push_back(tempminsmoothid);
628                         char* tempMinsmoothid = new char[minsmoothid.length()];
629                         strcpy(tempMinsmoothid, minsmoothid.c_str());
630                         cPara.push_back(tempMinsmoothid);
631                 }
632                 
633                 if (useMaxp) {
634                         char* tempmaxp = new char[6]; 
635                         strcpy(tempmaxp, "--maxp"); 
636                         cPara.push_back(tempmaxp);
637                         char* tempMaxp = new char[maxp.length()];
638                         strcpy(tempMaxp, maxp.c_str());
639                         cPara.push_back(tempMaxp);
640                 }
641                 
642                 if (!skipgaps) {
643                         char* tempskipgaps = new char[14]; 
644                         strcpy(tempskipgaps, "--[no]skipgaps"); 
645                         cPara.push_back(tempskipgaps);
646                 }
647                 
648                 if (!skipgaps2) {
649                         char* tempskipgaps2 = new char[15]; 
650                         strcpy(tempskipgaps2, "--[no]skipgaps2"); 
651                         cPara.push_back(tempskipgaps2);
652                 }
653                 
654                 if (useMinlen) {
655                         char* tempminlen = new char[8]; 
656                         strcpy(tempminlen, "--minlen"); 
657                         cPara.push_back(tempminlen);
658                         char* tempMinlen = new char[minlen.length()];
659                         strcpy(tempMinlen, minlen.c_str());
660                         cPara.push_back(tempMinlen);
661                 }
662                 
663                 if (useMaxlen) {
664                         char* tempmaxlen = new char[8]; 
665                         strcpy(tempmaxlen, "--maxlen"); 
666                         cPara.push_back(tempmaxlen);
667                         char* tempMaxlen = new char[maxlen.length()];
668                         strcpy(tempMaxlen, maxlen.c_str());
669                         cPara.push_back(tempMaxlen);
670                 }
671                 
672                 if (ucl) {
673                         char* tempucl = new char[5]; 
674                         strcpy(tempucl, "--ucl"); 
675                         cPara.push_back(tempucl);
676                 }
677                 
678                 if (useQueryfract) {
679                         char* tempqueryfract = new char[12]; 
680                         strcpy(tempqueryfract, "--queryfract"); 
681                         cPara.push_back(tempqueryfract);
682                         char* tempQueryfract = new char[queryfract.length()];
683                         strcpy(tempQueryfract, queryfract.c_str());
684                         cPara.push_back(tempQueryfract);
685                 }
686                 
687                 
688                 char** uchimeParameters;
689                 uchimeParameters = new char*[cPara.size()];
690                 for (int i = 0; i < cPara.size(); i++) {  uchimeParameters[i] = cPara[i];  } 
691                 int numArgs = cPara.size();
692                 
693                 uchime_main(numArgs, uchimeParameters); 
694                 
695                 //free memory
696                 for(int i = 0; i < cPara.size(); i++)  {  delete[] cPara[i];  }
697                 delete[] uchimeParameters; 
698                 
699                 if (m->control_pressed) { return 0; }
700                 
701                 //create accnos file from uchime results
702                 ifstream in; 
703                 m->openInputFile(outputFName, in);
704                 
705                 ofstream out;
706                 m->openOutputFile(accnos, out);
707                 
708                 int num = 0;
709                 while(!in.eof()) {
710                         
711                         if (m->control_pressed) { break; }
712                         
713                         string name = "";
714                         string chimeraFlag = "";
715                         in >> chimeraFlag >> name;
716                         
717                         //fix name if needed
718                         if (templatefile == "self") { 
719                                 name = name.substr(0, name.length()-1); //rip off last /
720                                 name = name.substr(0, name.find_last_of('/'));
721                         }
722                         
723                         for (int i = 0; i < 15; i++) {  in >> chimeraFlag; }
724                         m->gobble(in);
725                         
726                         if (chimeraFlag == "Y") {  out << name << endl; }
727                         num++;
728                 }
729                 in.close();
730                 out.close();
731                 
732                 return num;
733         }
734         catch(exception& e) {
735                 m->errorOut(e, "ChimeraUchimeCommand", "driver");
736                 exit(1);
737         }
738 }
739 /**************************************************************************************************/
740
741 int ChimeraUchimeCommand::createProcesses(string outputFileName, string filename, string accnos, string alns) {
742         try {
743                 
744                 processIDS.clear();
745                 int process = 1;
746                 int num = 0;
747 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)           
748                 //break up file into multiple files
749                 vector<string> files;
750                 m->divideFile(filename, processors, files);
751                 
752                 if (m->control_pressed) {  return 0;  }
753                 
754 #ifdef USE_MPI  
755                 int pid, numSeqsPerProcessor; 
756                 int tag = 2001;
757                 
758                 MPI_Status status; 
759                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
760                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
761                                 
762                 if (pid == 0) { //you are the root process 
763                         num = driver(outputFileName, files[0], accnos, alns);
764                         
765                         if (templatefile != "self") {
766                                 //wait on chidren
767                                 for(int j = 1; j < processors; j++) { 
768                                         int temp;
769                                         MPI_Recv(&temp, 1, MPI_INT, j, tag, MPI_COMM_WORLD, &status);
770                                         num += temp;
771                                         
772                                         m->appendFiles((outputFileName + toString(j) + ".temp"), outputFileName);
773                                         remove((outputFileName + toString(j) + ".temp").c_str());
774                                         
775                                         m->appendFiles((accnos + toString(j) + ".temp"), accnos);
776                                         remove((accnos + toString(j) + ".temp").c_str());
777                                         
778                                         if (chimealns) {
779                                                 m->appendFiles((alns + toString(j) + ".temp"), alns);
780                                                 remove((alns + toString(j) + ".temp").c_str());
781                                         }
782                                 }
783                         }
784                 }else{ //you are a child process
785                         if (templatefile != "self") { //if template=self we can only use 1 processor
786                                 num = driver(outputFileName+toString(pid) + ".temp", files[pid], accnos+toString(pid) + ".temp", alns+toString(pid) + ".temp"); 
787                                 
788                                 //send numSeqs to parent
789                                 MPI_Send(&num, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
790                         }
791                 }
792
793                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
794 #else
795                 
796                 //loop through and create all the processes you want
797                 while (process != processors) {
798                         int pid = fork();
799                         
800                         if (pid > 0) {
801                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
802                                 process++;
803                         }else if (pid == 0){
804                                 num = driver(outputFileName + toString(getpid()) + ".temp", files[process], accnos + toString(getpid()) + ".temp", alns + toString(getpid()) + ".temp");
805                                 
806                                 //pass numSeqs to parent
807                                 ofstream out;
808                                 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
809                                 m->openOutputFile(tempFile, out);
810                                 out << num << endl;
811                                 out.close();
812                                 
813                                 exit(0);
814                         }else { 
815                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
816                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
817                                 exit(0);
818                         }
819                 }
820                 
821                 //do my part
822                 num = driver(outputFileName, files[0], accnos, alns);
823                 
824                 //force parent to wait until all the processes are done
825                 for (int i=0;i<processIDS.size();i++) { 
826                         int temp = processIDS[i];
827                         wait(&temp);
828                 }
829                 
830                 for (int i = 0; i < processIDS.size(); i++) {
831                         ifstream in;
832                         string tempFile =  outputFileName + toString(processIDS[i]) + ".num.temp";
833                         m->openInputFile(tempFile, in);
834                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
835                         in.close(); remove(tempFile.c_str());
836                 }
837                 
838                 
839                 //append output files
840                 for(int i=0;i<processIDS[i];i++){
841                         m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
842                         remove((outputFileName + toString(processIDS[i]) + ".temp").c_str());
843                         
844                         m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
845                         remove((accnos + toString(processIDS[i]) + ".temp").c_str());
846                         
847                         if (chimealns) {
848                                 m->appendFiles((alns + toString(processIDS[i]) + ".temp"), alns);
849                                 remove((alns + toString(processIDS[i]) + ".temp").c_str());
850                         }
851                 }
852 #endif          
853                 //get rid of the file pieces.
854                 for (int i = 0; i < files.size(); i++) { remove(files[i].c_str()); }
855 #endif          
856                 return num;     
857         }
858         catch(exception& e) {
859                 m->errorOut(e, "ChimeraUchimeCommand", "createProcesses");
860                 exit(1);
861         }
862 }
863
864 /**************************************************************************************************/
865