]> git.donarmstrong.com Git - mothur.git/blob - chimeraslayercommand.cpp
added blastlocation to chimera.slayer and fixed issue with clearcut getting current...
[mothur.git] / chimeraslayercommand.cpp
1 /*
2  *  chimeraslayercommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 3/31/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "chimeraslayercommand.h"
11 #include "chimeraslayer.h"
12 #include "deconvolutecommand.h"
13 #include "referencedb.h"
14
15 //**********************************************************************************************************************
16 vector<string> ChimeraSlayerCommand::setParameters(){   
17         try {
18                 CommandParameter ptemplate("reference", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(ptemplate);
19                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
20                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
21                 CommandParameter pwindow("window", "Number", "", "50", "", "", "",false,false); parameters.push_back(pwindow);
22                 CommandParameter pksize("ksize", "Number", "", "7", "", "", "",false,false); parameters.push_back(pksize);
23                 CommandParameter pmatch("match", "Number", "", "5.0", "", "", "",false,false); parameters.push_back(pmatch);
24                 CommandParameter pmismatch("mismatch", "Number", "", "-4.0", "", "", "",false,false); parameters.push_back(pmismatch);
25                 CommandParameter pminsim("minsim", "Number", "", "90", "", "", "",false,false); parameters.push_back(pminsim);
26                 CommandParameter pmincov("mincov", "Number", "", "70", "", "", "",false,false); parameters.push_back(pmincov);
27                 CommandParameter pminsnp("minsnp", "Number", "", "10", "", "", "",false,false); parameters.push_back(pminsnp);
28                 CommandParameter pminbs("minbs", "Number", "", "90", "", "", "",false,false); parameters.push_back(pminbs);
29                 CommandParameter psearch("search", "Multiple", "kmer-blast", "blast", "", "", "",false,false); parameters.push_back(psearch);
30                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
31                 CommandParameter prealign("realign", "Boolean", "", "T", "", "", "",false,false); parameters.push_back(prealign);
32                 CommandParameter ptrim("trim", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(ptrim);
33                 CommandParameter psplit("split", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psplit);
34                 CommandParameter pnumwanted("numwanted", "Number", "", "15", "", "", "",false,false); parameters.push_back(pnumwanted);
35                 CommandParameter piters("iters", "Number", "", "1000", "", "", "",false,false); parameters.push_back(piters);
36                 CommandParameter pdivergence("divergence", "Number", "", "1.007", "", "", "",false,false); parameters.push_back(pdivergence);
37                 CommandParameter pparents("parents", "Number", "", "3", "", "", "",false,false); parameters.push_back(pparents);
38                 CommandParameter pincrement("increment", "Number", "", "5", "", "", "",false,false); parameters.push_back(pincrement);
39                 CommandParameter pblastlocation("blastlocation", "String", "", "", "", "", "",false,false); parameters.push_back(pblastlocation);
40                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
41                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
42                 CommandParameter psave("save", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psave);
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, "ChimeraSlayerCommand", "setParameters");
50                 exit(1);
51         }
52 }
53 //**********************************************************************************************************************
54 string ChimeraSlayerCommand::getHelpString(){   
55         try {
56                 string helpString = "";
57                 helpString += "The chimera.slayer command reads a fastafile and referencefile and outputs potentially chimeric sequences.\n";
58                 helpString += "This command was modeled after the chimeraSlayer written by the Broad Institute.\n";
59                 helpString += "The chimera.slayer command parameters are fasta, name, template, processors, trim, ksize, window, match, mismatch, divergence. minsim, mincov, minbs, minsnp, parents, search, iters, increment, numwanted, blastlocation and realign.\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 reference=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 #ifdef USE_MPI
66                 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
67 #endif
68                 helpString += "The trim parameter allows you to output a new fasta file containing your sequences with the chimeric ones trimmed to include only their longest piece, default=F. \n";
69                 helpString += "The split parameter allows you to check both pieces of non-chimeric sequence for chimeras, thus looking for trimeras and quadmeras. default=F. \n";
70                 helpString += "The window parameter allows you to specify the window size for searching for chimeras, default=50. \n";
71                 helpString += "The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default=5.\n";
72                 helpString += "The numwanted parameter allows you to specify how many sequences you would each query sequence compared with, default=15.\n";
73                 helpString += "The ksize parameter allows you to input kmersize, default is 7, used if search is kmer. \n";
74                 helpString += "The match parameter allows you to reward matched bases in blast search, default is 5. \n";
75                 helpString += "The parents parameter allows you to select the number of potential parents to investigate from the numwanted best matches after rating them, default is 3. \n";
76                 helpString += "The mismatch parameter allows you to penalize mismatched bases in blast search, default is -4. \n";
77                 helpString += "The divergence parameter allows you to set a cutoff for chimera determination, default is 1.007. \n";
78                 helpString += "The iters parameter allows you to specify the number of bootstrap iters to do with the chimeraslayer method, default=1000.\n";
79                 helpString += "The minsim parameter allows you to specify a minimum similarity with the parent fragments, default=90. \n";
80                 helpString += "The mincov parameter allows you to specify minimum coverage by closest matches found in template. Default is 70, meaning 70%. \n";
81                 helpString += "The minbs parameter allows you to specify minimum bootstrap support for calling a sequence chimeric. Default is 90, meaning 90%. \n";
82                 helpString += "The minsnp parameter allows you to specify percent of SNPs to sample on each side of breakpoint for computing bootstrap support (default: 10) \n";
83                 helpString += "The search parameter allows you to specify search method for finding the closest parent. Choices are blast, and kmer, default blast. \n";
84                 helpString += "The realign parameter allows you to realign the query to the potential parents. Choices are true or false, default true.  \n";
85                 helpString += "The blastlocation parameter allows you to specify the location of your blast executable. By default mothur will look in ./blast/bin relative to mothur's executable.  \n";
86                 helpString += "If the save parameter is set to true the reference sequences will be saved in memory, to clear them later you can use the clear.memory command. Default=f.";
87                 helpString += "The chimera.slayer command should be in the following format: \n";
88                 helpString += "chimera.slayer(fasta=yourFastaFile, reference=yourTemplate, search=yourSearch) \n";
89                 helpString += "Example: chimera.slayer(fasta=AD.align, reference=core_set_aligned.imputed.fasta, search=kmer) \n";
90                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";       
91                 return helpString;
92         }
93         catch(exception& e) {
94                 m->errorOut(e, "ChimeraSlayerCommand", "getHelpString");
95                 exit(1);
96         }
97 }
98 //**********************************************************************************************************************
99 ChimeraSlayerCommand::ChimeraSlayerCommand(){   
100         try {
101                 abort = true; calledHelp = true;
102                 setParameters();
103                 vector<string> tempOutNames;
104                 outputTypes["chimera"] = tempOutNames;
105                 outputTypes["accnos"] = tempOutNames;
106                 outputTypes["fasta"] = tempOutNames;
107         }
108         catch(exception& e) {
109                 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
110                 exit(1);
111         }
112 }
113 //***************************************************************************************************************
114 ChimeraSlayerCommand::ChimeraSlayerCommand(string option)  {
115         try {
116                 abort = false; calledHelp = false;   
117                 ReferenceDB* rdb = ReferenceDB::getInstance();
118                 
119                 //allow user to run help
120                 if(option == "help") { help(); abort = true; calledHelp = true; }
121                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
122                 
123                 else {
124                         vector<string> myArray = setParameters();
125                         
126                         OptionParser parser(option);
127                         map<string,string> parameters = parser.getParameters();
128                         
129                         ValidParameters validParameter("chimera.slayer");
130                         map<string,string>::iterator it;
131                         
132                         //check to make sure all parameters are valid for command
133                         for (it = parameters.begin(); it != parameters.end(); it++) { 
134                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
135                         }
136                         
137                         vector<string> tempOutNames;
138                         outputTypes["chimera"] = tempOutNames;
139                         outputTypes["accnos"] = tempOutNames;
140                         outputTypes["fasta"] = tempOutNames;
141                 
142                         //if the user changes the input directory command factory will send this info to us in the output parameter 
143                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
144                         if (inputDir == "not found"){   inputDir = "";          }
145                                                 
146                         //check for required parameters
147                         fastafile = validParameter.validFile(parameters, "fasta", false);
148                         if (fastafile == "not found") {                                 
149                                 //if there is a current fasta file, use it
150                                 string filename = m->getFastaFile(); 
151                                 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
152                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
153                         }else { 
154                                 m->splitAtDash(fastafile, fastaFileNames);
155                                 
156                                 //go through files and make sure they are good, if not, then disregard them
157                                 for (int i = 0; i < fastaFileNames.size(); i++) {
158                                         
159                                         bool ignore = false;
160                                         if (fastaFileNames[i] == "current") { 
161                                                 fastaFileNames[i] = m->getFastaFile(); 
162                                                 if (fastaFileNames[i] != "") {  m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
163                                                 else {  
164                                                         m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
165                                                         //erase from file list
166                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
167                                                         i--;
168                                                 }
169                                         }
170                                         
171                                         if (!ignore) {
172                                                 
173                                                 if (inputDir != "") {
174                                                         string path = m->hasPath(fastaFileNames[i]);
175                                                         //if the user has not given a path then, add inputdir. else leave path alone.
176                                                         if (path == "") {       fastaFileNames[i] = inputDir + fastaFileNames[i];               }
177                                                 }
178                 
179                                                 int ableToOpen;
180                                                 ifstream in;
181                                                 
182                                                 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
183                                         
184                                                 //if you can't open it, try default location
185                                                 if (ableToOpen == 1) {
186                                                         if (m->getDefaultPath() != "") { //default path is set
187                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
188                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
189                                                                 ifstream in2;
190                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
191                                                                 in2.close();
192                                                                 fastaFileNames[i] = tryPath;
193                                                         }
194                                                 }
195                                                 
196                                                 if (ableToOpen == 1) {
197                                                         if (m->getOutputDir() != "") { //default path is set
198                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
199                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
200                                                                 ifstream in2;
201                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
202                                                                 in2.close();
203                                                                 fastaFileNames[i] = tryPath;
204                                                         }
205                                                 }
206                                                 
207                                                 in.close();
208                                                 
209                                                 if (ableToOpen == 1) { 
210                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
211                                                         //erase from file list
212                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
213                                                         i--;
214                                                 }else {
215                                                         m->setFastaFile(fastaFileNames[i]);
216                                                 }
217                                         }
218                                 }
219                                 
220                                 //make sure there is at least one valid file left
221                                 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
222                         }
223                         
224                         
225                         //check for required parameters
226                         bool hasName = true;
227                         namefile = validParameter.validFile(parameters, "name", false);
228                         if (namefile == "not found") { namefile = "";  hasName = false; }
229                         else { 
230                                 m->splitAtDash(namefile, nameFileNames);
231                                 
232                                 //go through files and make sure they are good, if not, then disregard them
233                                 for (int i = 0; i < nameFileNames.size(); i++) {
234                                         
235                                         bool ignore = false;
236                                         if (nameFileNames[i] == "current") { 
237                                                 nameFileNames[i] = m->getNameFile(); 
238                                                 if (nameFileNames[i] != "") {  m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
239                                                 else {  
240                                                         m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
241                                                         //erase from file list
242                                                         nameFileNames.erase(nameFileNames.begin()+i);
243                                                         i--;
244                                                 }
245                                         }
246                                         
247                                         if (!ignore) {
248                                                 
249                                                 if (inputDir != "") {
250                                                         string path = m->hasPath(nameFileNames[i]);
251                                                         //if the user has not given a path then, add inputdir. else leave path alone.
252                                                         if (path == "") {       nameFileNames[i] = inputDir + nameFileNames[i];         }
253                                                 }
254                                                 
255                                                 int ableToOpen;
256                                                 ifstream in;
257                                                 
258                                                 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
259                                                 
260                                                 //if you can't open it, try default location
261                                                 if (ableToOpen == 1) {
262                                                         if (m->getDefaultPath() != "") { //default path is set
263                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
264                                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
265                                                                 ifstream in2;
266                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
267                                                                 in2.close();
268                                                                 nameFileNames[i] = tryPath;
269                                                         }
270                                                 }
271                                                 
272                                                 if (ableToOpen == 1) {
273                                                         if (m->getOutputDir() != "") { //default path is set
274                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
275                                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
276                                                                 ifstream in2;
277                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
278                                                                 in2.close();
279                                                                 nameFileNames[i] = tryPath;
280                                                         }
281                                                 }
282                                                 
283                                                 in.close();
284                                                 
285                                                 if (ableToOpen == 1) { 
286                                                         m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
287                                                         //erase from file list
288                                                         nameFileNames.erase(nameFileNames.begin()+i);
289                                                         i--;
290                                                 }else {
291                                                         m->setNameFile(nameFileNames[i]);
292                                                 }
293                                         }
294                                 }
295                                 
296                                 //make sure there is at least one valid file left
297                                 if (nameFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid name files."); m->mothurOutEndLine(); abort = true; }
298                         }
299                         
300                         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; }
301                         
302                         //if the user changes the output directory command factory will send this info to us in the output parameter 
303                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
304                         
305                         string temp = validParameter.validFile(parameters, "processors", false);        if (temp == "not found"){       temp = m->getProcessors();      }
306                         m->setProcessors(temp);
307                         convert(temp, processors);
308                         
309                         temp = validParameter.validFile(parameters, "save", false);                     if (temp == "not found"){       temp = "f";                             }
310                         save = m->isTrue(temp); 
311                         rdb->save = save; 
312                         if (save) { //clear out old references
313                                 rdb->clearMemory();     
314                         }
315                         
316                         string path;
317                         it = parameters.find("reference");
318                         //user has given a template file
319                         if(it != parameters.end()){ 
320                                 if (it->second == "self") { 
321                                         templatefile = "self"; 
322                                         if (save) {
323                                                 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save."); 
324                                                 m->mothurOutEndLine();
325                                                 save = false;
326                                         }
327                                 }
328                                 else {
329                                         path = m->hasPath(it->second);
330                                         //if the user has not given a path then, add inputdir. else leave path alone.
331                                         if (path == "") {       parameters["reference"] = inputDir + it->second;                }
332                                         
333                                         templatefile = validParameter.validFile(parameters, "reference", true);
334                                         if (templatefile == "not open") { abort = true; }
335                                         else if (templatefile == "not found") { //check for saved reference sequences
336                                                 if (rdb->referenceSeqs.size() != 0) {
337                                                         templatefile = "saved";
338                                                 }else {
339                                                         m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required."); 
340                                                         m->mothurOutEndLine();
341                                                         abort = true; 
342                                                 }
343                                         }else { if (save) {     rdb->setSavedReference(templatefile);   }       }       
344                                 }
345                         }else if (hasName) {  templatefile = "self"; 
346                                 if (save) {
347                                         m->mothurOut("[WARNING]: You can't save reference=self, ignoring save."); 
348                                         m->mothurOutEndLine();
349                                         save = false;
350                                 }
351                         }
352                         else { 
353                                 if (rdb->referenceSeqs.size() != 0) {
354                                         templatefile = "saved";
355                                 }else {
356                                         m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required."); 
357                                         m->mothurOutEndLine();
358                                         templatefile = ""; abort = true; 
359                                 } 
360                         }
361                         
362                         
363                         
364                         temp = validParameter.validFile(parameters, "ksize", false);                    if (temp == "not found") { temp = "7"; }
365                         convert(temp, ksize);
366                                                 
367                         temp = validParameter.validFile(parameters, "window", false);                   if (temp == "not found") { temp = "50"; }                       
368                         convert(temp, window);
369                         
370                         temp = validParameter.validFile(parameters, "match", false);                    if (temp == "not found") { temp = "5"; }
371                         convert(temp, match);
372                         
373                         temp = validParameter.validFile(parameters, "mismatch", false);                 if (temp == "not found") { temp = "-4"; }
374                         convert(temp, mismatch);
375                         
376                         temp = validParameter.validFile(parameters, "divergence", false);               if (temp == "not found") { temp = "1.007"; }
377                         convert(temp, divR);
378                         
379                         temp = validParameter.validFile(parameters, "minsim", false);                   if (temp == "not found") { temp = "90"; }
380                         convert(temp, minSimilarity);
381                         
382                         temp = validParameter.validFile(parameters, "mincov", false);                   if (temp == "not found") { temp = "70"; }
383                         convert(temp, minCoverage);
384                         
385                         temp = validParameter.validFile(parameters, "minbs", false);                    if (temp == "not found") { temp = "90"; }
386                         convert(temp, minBS);
387                         
388                         temp = validParameter.validFile(parameters, "minsnp", false);                   if (temp == "not found") { temp = "10"; }
389                         convert(temp, minSNP);
390
391                         temp = validParameter.validFile(parameters, "parents", false);                  if (temp == "not found") { temp = "3"; }
392                         convert(temp, parents); 
393                         
394                         temp = validParameter.validFile(parameters, "realign", false);                  if (temp == "not found") { temp = "t"; }
395                         realign = m->isTrue(temp); 
396                         
397                         temp = validParameter.validFile(parameters, "trim", false);                             if (temp == "not found") { temp = "f"; }
398                         trim = m->isTrue(temp); 
399                         
400                         temp = validParameter.validFile(parameters, "split", false);                    if (temp == "not found") { temp = "f"; }
401                         trimera = m->isTrue(temp); 
402                         
403                         search = validParameter.validFile(parameters, "search", false);                 if (search == "not found") { search = "blast"; }
404                         
405                         temp = validParameter.validFile(parameters, "iters", false);                    if (temp == "not found") { temp = "1000"; }             
406                         convert(temp, iters); 
407                          
408                         temp = validParameter.validFile(parameters, "increment", false);                if (temp == "not found") { temp = "5"; }
409                         convert(temp, increment);
410                         
411                         temp = validParameter.validFile(parameters, "numwanted", false);                if (temp == "not found") { temp = "15"; }               
412                         convert(temp, numwanted);
413                         
414                         blastlocation = validParameter.validFile(parameters, "blastlocation", false);   
415                         if (blastlocation == "not found") { blastlocation = ""; }
416                         else {
417                                 //add / to name if needed
418                                 string lastChar = blastlocation.substr(blastlocation.length()-1);
419 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
420                                 if (lastChar != "/") { blastlocation += "/"; }
421 #else
422                                 if (lastChar != "\\") { blastlocation += "\\"; }        
423 #endif
424                                 blastlocation = m->getFullPathName(blastlocation);
425                                 string formatdbCommand = "";
426 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
427                                 formatdbCommand = blastlocation + "formatdb";   
428 #else
429                                 formatdbCommand = blastlocation + "formatdb.exe";
430 #endif
431                                 
432                                 //test to make sure formatdb exists
433                                 ifstream in;
434                                 formatdbCommand = m->getFullPathName(formatdbCommand);
435                                 int ableToOpen = m->openInputFile(formatdbCommand, in, "no error"); in.close();
436                                 if(ableToOpen == 1) {   m->mothurOut("[ERROR]: " + formatdbCommand + " file does not exist. mothur requires formatdb.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
437                                 
438                                 string blastCommand = "";
439 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
440                                 blastCommand = blastlocation + "megablast";     
441 #else
442                                 blastCommand = blastlocation + "megablast.exe";
443 #endif
444                                 //test to make sure formatdb exists
445                                 ifstream in2;
446                                 blastCommand = m->getFullPathName(blastCommand);
447                                 ableToOpen = m->openInputFile(blastCommand, in2, "no error"); in2.close();
448                                 if(ableToOpen == 1) {   m->mothurOut("[ERROR]: " + blastCommand + " file does not exist. mothur requires blastall.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
449                         }
450
451                         if ((search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true;  }
452                         
453                         if (hasName && (templatefile != "self")) { m->mothurOut("You have provided a namefile and the reference parameter is not set to self. I am not sure what reference you are trying to use, aborting."); m->mothurOutEndLine(); abort=true; }
454                 }
455         }
456         catch(exception& e) {
457                 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
458                 exit(1);
459         }
460 }
461 //***************************************************************************************************************
462
463 int ChimeraSlayerCommand::execute(){
464         try{
465                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
466                         
467                 for (int s = 0; s < fastaFileNames.size(); s++) {
468                                 
469                         m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
470                 
471                         int start = time(NULL); 
472                         
473                         if (templatefile != "self") { //you want to run slayer with a refernce template
474                                 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation);      
475                         }else {
476                                 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
477                                 string nameFile = "";
478                                 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
479                                         nameFile = nameFileNames[s];
480                                 }else {
481                                         m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
482                                         
483                                         //use unique.seqs to create new name and fastafile
484                                         string inputString = "fasta=" + fastaFileNames[s];
485                                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
486                                         m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
487                                                                  
488                                         Command* uniqueCommand = new DeconvoluteCommand(inputString);
489                                         uniqueCommand->execute();
490                                         
491                                         map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
492                                         
493                                         delete uniqueCommand;
494                                         
495                                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
496                                         
497                                         nameFile = filenames["name"][0];
498                                         fastaFileNames[s] = filenames["fasta"][0];
499                                 }
500                                 
501                                 //sort fastafile by abundance, returns new sorted fastafile name
502                                 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush(); 
503                                 map<string, int> priority = sortFastaFile(fastaFileNames[s], nameFile);
504                                 m->mothurOut("Done."); m->mothurOutEndLine();
505                                 
506                                 if (m->control_pressed) {  for (int j = 0; j < outputNames.size(); j++) {       m->mothurRemove(outputNames[j]);        }  return 0;    }
507
508                                 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation);    
509                         }
510                                 
511                         if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]);  }//if user entered a file with a path then preserve it                               
512                         string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimera";
513                         string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "slayer.accnos";
514                         string trimFastaFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "slayer.fasta";
515                         
516                         if (m->control_pressed) { delete chimera; for (int j = 0; j < outputNames.size(); j++) {        m->mothurRemove(outputNames[j]);        }  return 0;    }
517                         
518                         if (chimera->getUnaligned()) { 
519                                 m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); 
520                                 delete chimera;
521                                 return 0; 
522                         }
523                         templateSeqsLength = chimera->getLength();
524                         
525                 #ifdef USE_MPI  
526                         int pid, numSeqsPerProcessor; 
527                                 int tag = 2001;
528                                 vector<unsigned long int> MPIPos;
529                                 
530                                 MPI_Status status; 
531                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
532                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
533
534                                 MPI_File inMPI;
535                                 MPI_File outMPI;
536                                 MPI_File outMPIAccnos;
537                                 MPI_File outMPIFasta;
538                                 
539                                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
540                                 int inMode=MPI_MODE_RDONLY; 
541                                 
542                                 char outFilename[1024];
543                                 strcpy(outFilename, outputFileName.c_str());
544                                 
545                                 char outAccnosFilename[1024];
546                                 strcpy(outAccnosFilename, accnosFileName.c_str());
547                         
548                                 char outFastaFilename[1024];
549                                 strcpy(outFastaFilename, trimFastaFileName.c_str());
550                                 
551                                 char inFileName[1024];
552                                 strcpy(inFileName, fastaFileNames[s].c_str());
553
554                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
555                                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
556                                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
557                                 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
558
559                         if (m->control_pressed) { outputTypes.clear();  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) {  MPI_File_close(&outMPIFasta);  } MPI_File_close(&outMPIAccnos); for (int j = 0; j < outputNames.size(); j++) {   m->mothurRemove(outputNames[j]);        }   delete chimera; return 0;  }
560                         
561                                 if (pid == 0) { //you are the root process 
562                                         m->mothurOutEndLine();
563                                         m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
564                                         m->mothurOutEndLine();
565                 
566                                         string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
567                                         
568                                         //print header
569                                         int length = outTemp.length();
570                                         char* buf2 = new char[length];
571                                         memcpy(buf2, outTemp.c_str(), length);
572
573                                         MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
574                                         delete buf2;
575
576                                         MPIPos = m->setFilePosFasta(fastaFileNames[s], numSeqs); //fills MPIPos, returns numSeqs
577                                         
578                                         if (templatefile != "self") { //if template=self we can only use 1 processor
579                                                 //send file positions to all processes
580                                                 for(int i = 1; i < processors; i++) { 
581                                                         MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
582                                                         MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
583                                                 }
584                                         }
585                                         //figure out how many sequences you have to align
586                                         numSeqsPerProcessor = numSeqs / processors;
587                                         int startIndex =  pid * numSeqsPerProcessor;
588                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
589                                         
590                                         if (templatefile == "self") { //if template=self we can only use 1 processor
591                                                 startIndex = 0;
592                                                 numSeqsPerProcessor = numSeqs;
593                                         }
594                                         
595                                         //do your part
596                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
597                                         
598                                         int numNoParents = chimera->getNumNoParents();
599                                         int temp;
600                                         for(int i = 1; i < processors; i++) { 
601                                                 MPI_Recv(&temp, 1, MPI_INT, 1, tag, MPI_COMM_WORLD, &status);
602                                                 numNoParents += temp;
603                                         }
604                                         
605                                         
606                                         if (numSeqs == numNoParents) {  m->mothurOut("[WARNING]: megablast returned 0 potential parents for all your sequences. This could be due to formatdb.exe not being setup properly, please check formatdb.log for errors."); m->mothurOutEndLine(); }
607                                         
608                                         if (m->control_pressed) { outputTypes.clear();  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); }  MPI_File_close(&outMPIAccnos);  for (int j = 0; j < outputNames.size(); j++) {   m->mothurRemove(outputNames[j]);        }  m->mothurRemove(outputFileName);  m->mothurRemove(accnosFileName);  delete chimera; return 0;  }
609
610                                 }else{ //you are a child process
611                                         if (templatefile != "self") { //if template=self we can only use 1 processor
612                                                 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
613                                                 MPIPos.resize(numSeqs+1);
614                                                 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
615                                         
616                                                 //figure out how many sequences you have to align
617                                                 numSeqsPerProcessor = numSeqs / processors;
618                                                 int startIndex =  pid * numSeqsPerProcessor;
619                                                 if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
620                                         
621                                                 //do your part
622                                                 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
623                                                 
624                                                 int numNoParents = chimera->getNumNoParents();
625                                                 MPI_Send(&numNoParents, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
626                                         
627                                                 if (m->control_pressed) { outputTypes.clear();  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); }  MPI_File_close(&outMPIAccnos);  for (int j = 0; j < outputNames.size(); j++) {   m->mothurRemove(outputNames[j]);        }  delete chimera; return 0;  }
628                                 
629                                         }
630                                 }
631                                 
632                                 //close files 
633                                 MPI_File_close(&inMPI);
634                                 MPI_File_close(&outMPI);
635                                 MPI_File_close(&outMPIAccnos); 
636                                 if (trim) { MPI_File_close(&outMPIFasta); }
637                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
638                                 
639                 #else
640                         ofstream outHeader;
641                         string tempHeader = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimeras.tempHeader";
642                         m->openOutputFile(tempHeader, outHeader);
643                         
644                         chimera->printHeader(outHeader);
645                         outHeader.close();
646                         
647                         vector<unsigned long int> positions = m->divideFile(fastaFileNames[s], processors);
648                                 
649                         for (int i = 0; i < (positions.size()-1); i++) {
650                                 lines.push_back(new linePair(positions[i], positions[(i+1)]));
651                         }       
652
653                         //break up file
654                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
655                                 if(processors == 1){
656                                         numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
657                                         
658                                         int numNoParents = chimera->getNumNoParents();
659                                         if (numNoParents == numSeqs) { m->mothurOut("[WARNING]: megablast returned 0 potential parents for all your sequences. This could be due to formatdb.exe not being setup properly, please check formatdb.log for errors."); m->mothurOutEndLine(); }
660                                         
661                                         if (m->control_pressed) { outputTypes.clear(); if (trim) { m->mothurRemove(trimFastaFileName); } m->mothurRemove(outputFileName); m->mothurRemove(tempHeader); m->mothurRemove(accnosFileName); for (int j = 0; j < outputNames.size(); j++) {  m->mothurRemove(outputNames[j]);        } for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear(); delete chimera; return 0; }
662                                         
663                                 }else{
664                                         processIDS.resize(0);
665                                         
666                                         numSeqs = createProcesses(outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName); 
667                                 
668                                         rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
669                                         rename((accnosFileName + toString(processIDS[0]) + ".temp").c_str(), accnosFileName.c_str());
670                                         if (trim) {  rename((trimFastaFileName + toString(processIDS[0]) + ".temp").c_str(), trimFastaFileName.c_str()); }
671                                                 
672                                         //append output files
673                                         for(int i=1;i<processors;i++){
674                                                 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
675                                                 m->mothurRemove((outputFileName + toString(processIDS[i]) + ".temp"));
676                                         }
677                                         
678                                         //append output files
679                                         for(int i=1;i<processors;i++){
680                                                 m->appendFiles((accnosFileName + toString(processIDS[i]) + ".temp"), accnosFileName);
681                                                 m->mothurRemove((accnosFileName + toString(processIDS[i]) + ".temp"));
682                                         }
683                                         
684                                         if (trim) {
685                                                 for(int i=1;i<processors;i++){
686                                                         m->appendFiles((trimFastaFileName + toString(processIDS[i]) + ".temp"), trimFastaFileName);
687                                                         m->mothurRemove((trimFastaFileName + toString(processIDS[i]) + ".temp"));
688                                                 }
689                                         }
690                                         
691                                         if (m->control_pressed) { outputTypes.clear(); if (trim) { m->mothurRemove(trimFastaFileName); } m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); for (int j = 0; j < outputNames.size(); j++) {       m->mothurRemove(outputNames[j]);        } for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear(); delete chimera; return 0; }
692                                 }
693
694                         #else
695                                 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
696                                 
697                                 int numNoParents = chimera->getNumNoParents();
698                                 if (numNoParents == numSeqs) { m->mothurOut("[WARNING]: megablast returned 0 potential parents for all your sequences. This could be due to formatdb.exe not being setup properly, please check formatdb.log for errors."); m->mothurOutEndLine(); }
699
700                                 
701                                 if (m->control_pressed) { outputTypes.clear(); if (trim) { m->mothurRemove(trimFastaFileName); } m->mothurRemove(outputFileName); m->mothurRemove(tempHeader); m->mothurRemove(accnosFileName); for (int j = 0; j < outputNames.size(); j++) {  m->mothurRemove(outputNames[j]);        } for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear(); delete chimera; return 0; }
702                                 
703                         #endif
704                         
705                         m->appendFiles(outputFileName, tempHeader);
706                 
707                         m->mothurRemove(outputFileName);
708                         rename(tempHeader.c_str(), outputFileName.c_str());
709                         
710                 #endif
711                         delete chimera;
712                         
713                         
714                         for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
715                         
716                         outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
717                         outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
718                         if (trim) {  outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }
719                         
720                         m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
721                 }
722                 
723                 //set accnos file as new current accnosfile
724                 string current = "";
725                 itTypes = outputTypes.find("accnos");
726                 if (itTypes != outputTypes.end()) {
727                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
728                 }
729                 
730                 if (trim) {
731                         itTypes = outputTypes.find("fasta");
732                         if (itTypes != outputTypes.end()) {
733                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
734                         }
735                 }
736                 
737                 m->mothurOutEndLine();
738                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
739                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
740                 m->mothurOutEndLine();
741
742                 return 0;
743                 
744         }
745         catch(exception& e) {
746                 m->errorOut(e, "ChimeraSlayerCommand", "execute");
747                 exit(1);
748         }
749 }
750 //**********************************************************************************************************************
751
752 int ChimeraSlayerCommand::driver(linePair* filePos, string outputFName, string filename, string accnos, string fasta){
753         try {
754                 ofstream out;
755                 m->openOutputFile(outputFName, out);
756                 
757                 ofstream out2;
758                 m->openOutputFile(accnos, out2);
759                 
760                 ofstream out3;
761                 if (trim) {  m->openOutputFile(fasta, out3); }
762                 
763                 ifstream inFASTA;
764                 m->openInputFile(filename, inFASTA);
765
766                 inFASTA.seekg(filePos->start);
767
768                 bool done = false;
769                 int count = 0;
770         
771                 while (!done) {
772                 
773                         if (m->control_pressed) {       out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1;       }
774                 
775                         Sequence* candidateSeq = new Sequence(inFASTA);  m->gobble(inFASTA);
776                         string candidateAligned = candidateSeq->getAligned();
777                         
778                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
779                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
780                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
781                                 }else{
782                                         //find chimeras
783                                         chimera->getChimeras(candidateSeq);
784                                         
785                                         if (m->control_pressed) {       delete candidateSeq; return 1;  }
786                                                 
787                                         //if you are not chimeric, then check each half
788                                         data_results wholeResults = chimera->getResults();
789                                         
790                                         //determine if we need to split
791                                         bool isChimeric = false;
792                                         
793                                         if (wholeResults.flag == "yes") {
794                                                 string chimeraFlag = "no";
795                                                 if(  (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
796                                                    ||
797                                                    (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
798                                                 
799                                                 
800                                                 if (chimeraFlag == "yes") {     
801                                                         if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
802                                                 }
803                                         }
804                                         
805                                         if ((!isChimeric) && trimera) {
806                                                 
807                                                 //split sequence in half by bases
808                                                 string leftQuery, rightQuery;
809                                                 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
810                                                 divideInHalf(tempSeq, leftQuery, rightQuery);
811                                                 
812                                                 //run chimeraSlayer on each piece
813                                                 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
814                                                 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
815                                                 
816                                                 //find chimeras
817                                                 chimera->getChimeras(left);
818                                                 data_results leftResults = chimera->getResults();
819                                                 
820                                                 chimera->getChimeras(right);
821                                                 data_results rightResults = chimera->getResults();
822                                                 
823                                                 //if either piece is chimeric then report
824                                                 Sequence trimmed = chimera->print(out, out2, leftResults, rightResults);
825                                                 if (trim) { trimmed.printSequence(out3);  }
826                                                 
827                                                 delete left; delete right;
828                                                 
829                                         }else { //already chimeric
830                                                 //print results
831                                                 Sequence trimmed = chimera->print(out, out2);
832                                                 if (trim) { trimmed.printSequence(out3);  }
833                                         }
834                                         
835                                         
836                                 }
837                                 count++;
838                         }
839                         
840                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
841                                 unsigned long int pos = inFASTA.tellg();
842                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
843                         #else
844                                 if (inFASTA.eof()) { break; }
845                         #endif
846                         
847                         delete candidateSeq;
848                         //report progress
849                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
850                 }
851                 //report progress
852                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
853                 
854                 out.close();
855                 out2.close();
856                 if (trim) { out3.close(); }
857                 inFASTA.close();
858                                 
859                 return count;
860         }
861         catch(exception& e) {
862                 m->errorOut(e, "ChimeraSlayerCommand", "driver");
863                 exit(1);
864         }
865 }
866 //**********************************************************************************************************************
867 #ifdef USE_MPI
868 int ChimeraSlayerCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, MPI_File& outFastaMPI, vector<unsigned long int>& MPIPos){
869         try {                           
870                 MPI_Status status; 
871                 int pid;
872                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
873                 
874                 for(int i=0;i<num;i++){
875                         
876                         if (m->control_pressed) {       return 1;       }
877                         
878                         //read next sequence
879                         int length = MPIPos[start+i+1] - MPIPos[start+i];
880
881                         char* buf4 = new char[length];
882                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
883         
884                         string tempBuf = buf4;
885                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
886                         istringstream iss (tempBuf,istringstream::in);
887
888                         delete buf4;
889
890                         Sequence* candidateSeq = new Sequence(iss);  m->gobble(iss);
891                         string candidateAligned = candidateSeq->getAligned();
892                 
893                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
894                                 
895                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
896                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
897                                 }else{
898                 
899                                         //find chimeras
900                                         chimera->getChimeras(candidateSeq);
901                         
902                                         if (m->control_pressed) {       delete candidateSeq; return 1;  }
903                                         
904                                         //if you are not chimeric, then check each half
905                                         data_results wholeResults = chimera->getResults();
906                                         
907                                         //determine if we need to split
908                                         bool isChimeric = false;
909                                         
910                                         if (wholeResults.flag == "yes") {
911                                                 string chimeraFlag = "no";
912                                                 if(  (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
913                                                    ||
914                                                    (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
915                                                 
916                                                 
917                                                 if (chimeraFlag == "yes") {     
918                                                         if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
919                                                 }
920                                         }
921                                         
922                                         if ((!isChimeric) && trimera) {                                                 
923                                                 //split sequence in half by bases
924                                                 string leftQuery, rightQuery;
925                                                 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
926                                                 divideInHalf(tempSeq, leftQuery, rightQuery);
927                                                 
928                                                 //run chimeraSlayer on each piece
929                                                 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
930                                                 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
931                                                 
932                                                 //find chimeras
933                                                 chimera->getChimeras(left);
934                                                 data_results leftResults = chimera->getResults();
935                                                 
936                                                 chimera->getChimeras(right);
937                                                 data_results rightResults = chimera->getResults();
938                                                 
939                                                 //if either piece is chimeric then report
940                                                 Sequence trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults);
941                                                 if (trim) {  
942                                                         string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
943                                                         
944                                                         //write to accnos file
945                                                         int length = outputString.length();
946                                                         char* buf2 = new char[length];
947                                                         memcpy(buf2, outputString.c_str(), length);
948                                                         
949                                                         MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
950                                                         delete buf2;
951                                                 }
952                                                 
953                                                 delete left; delete right;
954                                                 
955                                         }else { 
956                                                 //print results
957                                                 Sequence trimmed = chimera->print(outMPI, outAccMPI);
958                                                 
959                                                 if (trim) {  
960                                                         string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
961                                                         
962                                                         //write to accnos file
963                                                         int length = outputString.length();
964                                                         char* buf2 = new char[length];
965                                                         memcpy(buf2, outputString.c_str(), length);
966                                                         
967                                                         MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
968                                                         delete buf2;
969                                                 }
970                                         }
971                                         
972                                 }
973                         }
974                         delete candidateSeq;
975                         
976                         //report progress
977                         if((i+1) % 100 == 0){  cout << "Processing sequence: " << (i+1) << endl;        m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n");          }
978                 }
979                 //report progress
980                 if(num % 100 != 0){             cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n");  }
981                 
982                                 
983                 return 0;
984         }
985         catch(exception& e) {
986                 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
987                 exit(1);
988         }
989 }
990 #endif
991
992 /**************************************************************************************************/
993
994 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta) {
995         try {
996 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
997                 int process = 0;
998                 int num = 0;
999                 
1000                 //loop through and create all the processes you want
1001                 while (process != processors) {
1002                         int pid = fork();
1003                         
1004                         if (pid > 0) {
1005                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
1006                                 process++;
1007                         }else if (pid == 0){
1008                                 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp");
1009                                 
1010                                 //pass numSeqs to parent
1011                                 ofstream out;
1012                                 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
1013                                 m->openOutputFile(tempFile, out);
1014                                 out << num << '\t' << chimera->getNumNoParents() << endl;
1015                                 out.close();
1016                                 exit(0);
1017                         }else { 
1018                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
1019                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1020                                 exit(0);
1021                         }
1022                 }
1023                 
1024                 //force parent to wait until all the processes are done
1025                 for (int i=0;i<processors;i++) { 
1026                         int temp = processIDS[i];
1027                         wait(&temp);
1028                 }
1029                 
1030                 int numNoParents = 0;
1031                 for (int i = 0; i < processIDS.size(); i++) {
1032                         ifstream in;
1033                         string tempFile =  outputFileName + toString(processIDS[i]) + ".num.temp";
1034                         m->openInputFile(tempFile, in);
1035                         if (!in.eof()) { int tempNum = 0; int tempNumParents = 0; in >> tempNum >> tempNumParents; num += tempNum; numNoParents += tempNumParents; }
1036                         in.close(); m->mothurRemove(tempFile);
1037                 }
1038                 
1039                 if (num == numNoParents) {  m->mothurOut("[WARNING]: megablast returned 0 potential parents for all your sequences. This could be due to formatdb.exe not being setup properly, please check formatdb.log for errors."); m->mothurOutEndLine(); }
1040                 
1041                 return num;
1042 #endif          
1043         }
1044         catch(exception& e) {
1045                 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
1046                 exit(1);
1047         }
1048 }
1049
1050 /**************************************************************************************************/
1051
1052 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
1053         try {
1054                 
1055                 string queryUnAligned = querySeq.getUnaligned();
1056                 int numBases = int(queryUnAligned.length() * 0.5);
1057                 
1058                 string queryAligned = querySeq.getAligned();
1059                 leftQuery = querySeq.getAligned();
1060                 rightQuery = querySeq.getAligned();
1061                 
1062                 int baseCount = 0;
1063                 int leftSpot = 0;
1064                 for (int i = 0; i < queryAligned.length(); i++) {
1065                         //if you are a base
1066                         if (isalpha(queryAligned[i])) {         
1067                                 baseCount++; 
1068                         }
1069                         
1070                         //if you have half
1071                         if (baseCount >= numBases) {  leftSpot = i; break; } //first half
1072                 }
1073                 
1074                 //blank out right side
1075                 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
1076                 
1077                 //blank out left side
1078                 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
1079                 
1080                 return 0;
1081                 
1082         }
1083         catch(exception& e) {
1084                 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
1085                 exit(1);
1086         }
1087 }
1088 /**************************************************************************************************/
1089 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
1090         try {
1091                 map<string, int> nameAbund;
1092                 
1093                 //read through fastafile and store info
1094                 map<string, string> seqs;
1095                 ifstream in;
1096                 m->openInputFile(fastaFile, in);
1097                 
1098                 while (!in.eof()) {
1099                         
1100                         if (m->control_pressed) { in.close(); return nameAbund; }
1101                         
1102                         Sequence seq(in); m->gobble(in);
1103                         seqs[seq.getName()] = seq.getAligned();
1104                 }
1105                 
1106                 in.close();
1107                 
1108                 //read namefile
1109                 vector<seqPriorityNode> nameMapCount;
1110                 int error = m->readNames(nameFile, nameMapCount, seqs);
1111                 
1112                 if (m->control_pressed) { return nameAbund; }
1113                 
1114                 if (error == 1) { m->control_pressed = true; return nameAbund; }
1115                 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(); m->control_pressed = true; return nameAbund; }
1116
1117                 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
1118                 
1119                 string newFasta = fastaFile + ".temp";
1120                 ofstream out;
1121                 m->openOutputFile(newFasta, out);
1122                 
1123                 //print new file in order of
1124                 for (int i = 0; i < nameMapCount.size(); i++) {
1125                         out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
1126                         nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
1127                 }
1128                 out.close();
1129                 
1130                 rename(newFasta.c_str(), fastaFile.c_str());
1131                                 
1132                 return nameAbund;
1133                 
1134         }
1135         catch(exception& e) {
1136                 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
1137                 exit(1);
1138         }
1139 }
1140
1141 /**************************************************************************************************/
1142