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