]> git.donarmstrong.com Git - mothur.git/blob - chimeraslayercommand.cpp
added [ERROR] flag if command aborts
[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
14 //**********************************************************************************************************************
15 vector<string> ChimeraSlayerCommand::getValidParameters(){      
16         try {
17                 string AlignArray[] =  {"fasta", "processors","trim", "name","window", "include","template","numwanted", "ksize", "match","mismatch", 
18                         "divergence", "minsim","mincov","minbs", "minsnp","parents", "iters","outputdir","inputdir", "search","realign" };
19                 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
20                 return myArray;
21         }
22         catch(exception& e) {
23                 m->errorOut(e, "ChimeraSlayerCommand", "getValidParameters");
24                 exit(1);
25         }
26 }
27 //**********************************************************************************************************************
28 ChimeraSlayerCommand::ChimeraSlayerCommand(){   
29         try {
30                 abort = true; calledHelp = true;
31                 vector<string> tempOutNames;
32                 outputTypes["chimera"] = tempOutNames;
33                 outputTypes["accnos"] = tempOutNames;
34                 outputTypes["fasta"] = tempOutNames;
35         }
36         catch(exception& e) {
37                 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
38                 exit(1);
39         }
40 }
41 //**********************************************************************************************************************
42 vector<string> ChimeraSlayerCommand::getRequiredParameters(){   
43         try {
44                 string AlignArray[] =  {"template","fasta"};
45                 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
46                 return myArray;
47         }
48         catch(exception& e) {
49                 m->errorOut(e, "ChimeraSlayerCommand", "getRequiredParameters");
50                 exit(1);
51         }
52 }
53 //**********************************************************************************************************************
54 vector<string> ChimeraSlayerCommand::getRequiredFiles(){        
55         try {
56                 vector<string> myArray;
57                 return myArray;
58         }
59         catch(exception& e) {
60                 m->errorOut(e, "ChimeraSlayerCommand", "getRequiredFiles");
61                 exit(1);
62         }
63 }
64 //***************************************************************************************************************
65 ChimeraSlayerCommand::ChimeraSlayerCommand(string option)  {
66         try {
67                 abort = false; calledHelp = false;   
68                 
69                 //allow user to run help
70                 if(option == "help") { help(); abort = true; calledHelp = true; }
71                 
72                 else {
73                         //valid paramters for this command
74                         string Array[] =  {"fasta", "processors","name", "include","trim", "window", "template","numwanted", "ksize", "match","mismatch", 
75                         "divergence", "minsim","mincov","minbs", "minsnp","parents", "iters","outputdir","inputdir", "search","realign" };
76                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
77                         
78                         OptionParser parser(option);
79                         map<string,string> parameters = parser.getParameters();
80                         
81                         ValidParameters validParameter("chimera.slayer");
82                         map<string,string>::iterator it;
83                         
84                         //check to make sure all parameters are valid for command
85                         for (it = parameters.begin(); it != parameters.end(); it++) { 
86                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
87                         }
88                         
89                         vector<string> tempOutNames;
90                         outputTypes["chimera"] = tempOutNames;
91                         outputTypes["accnos"] = tempOutNames;
92                         outputTypes["fasta"] = tempOutNames;
93                 
94                         //if the user changes the input directory command factory will send this info to us in the output parameter 
95                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
96                         if (inputDir == "not found"){   inputDir = "";          }
97                                                 
98                         //check for required parameters
99                         fastafile = validParameter.validFile(parameters, "fasta", false);
100                         if (fastafile == "not found") { fastafile = ""; m->mothurOut("[ERROR]: fasta is a required parameter for the chimera.slayer command."); m->mothurOutEndLine(); abort = true;  }
101                         else { 
102                                 m->splitAtDash(fastafile, fastaFileNames);
103                                 
104                                 //go through files and make sure they are good, if not, then disregard them
105                                 for (int i = 0; i < fastaFileNames.size(); i++) {
106                                         if (inputDir != "") {
107                                                 string path = m->hasPath(fastaFileNames[i]);
108                                                 //if the user has not given a path then, add inputdir. else leave path alone.
109                                                 if (path == "") {       fastaFileNames[i] = inputDir + fastaFileNames[i];               }
110                                         }
111         
112                                         int ableToOpen;
113                                         ifstream in;
114                                         
115                                         ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
116                                 
117                                         //if you can't open it, try default location
118                                         if (ableToOpen == 1) {
119                                                 if (m->getDefaultPath() != "") { //default path is set
120                                                         string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
121                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
122                                                         ifstream in2;
123                                                         ableToOpen = m->openInputFile(tryPath, in2, "noerror");
124                                                         in2.close();
125                                                         fastaFileNames[i] = tryPath;
126                                                 }
127                                         }
128                                         
129                                         if (ableToOpen == 1) {
130                                                 if (m->getOutputDir() != "") { //default path is set
131                                                         string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
132                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
133                                                         ifstream in2;
134                                                         ableToOpen = m->openInputFile(tryPath, in2, "noerror");
135                                                         in2.close();
136                                                         fastaFileNames[i] = tryPath;
137                                                 }
138                                         }
139                                         
140                                         in.close();
141                                         
142                                         if (ableToOpen == 1) { 
143                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
144                                                 //erase from file list
145                                                 fastaFileNames.erase(fastaFileNames.begin()+i);
146                                                 i--;
147                                         }
148                                 }
149                                 
150                                 //make sure there is at least one valid file left
151                                 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
152                         }
153                         
154                         
155                         //check for required parameters
156                         bool hasName = true;
157                         namefile = validParameter.validFile(parameters, "name", false);
158                         if (namefile == "not found") { namefile = "";  hasName = false; }
159                         else { 
160                                 m->splitAtDash(namefile, nameFileNames);
161                                 
162                                 //go through files and make sure they are good, if not, then disregard them
163                                 for (int i = 0; i < nameFileNames.size(); i++) {
164                                         if (inputDir != "") {
165                                                 string path = m->hasPath(nameFileNames[i]);
166                                                 //if the user has not given a path then, add inputdir. else leave path alone.
167                                                 if (path == "") {       nameFileNames[i] = inputDir + nameFileNames[i];         }
168                                         }
169                                         
170                                         int ableToOpen;
171                                         ifstream in;
172                                         
173                                         ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
174                                         
175                                         //if you can't open it, try default location
176                                         if (ableToOpen == 1) {
177                                                 if (m->getDefaultPath() != "") { //default path is set
178                                                         string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
179                                                         m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
180                                                         ifstream in2;
181                                                         ableToOpen = m->openInputFile(tryPath, in2, "noerror");
182                                                         in2.close();
183                                                         nameFileNames[i] = tryPath;
184                                                 }
185                                         }
186                                         
187                                         if (ableToOpen == 1) {
188                                                 if (m->getOutputDir() != "") { //default path is set
189                                                         string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
190                                                         m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
191                                                         ifstream in2;
192                                                         ableToOpen = m->openInputFile(tryPath, in2, "noerror");
193                                                         in2.close();
194                                                         nameFileNames[i] = tryPath;
195                                                 }
196                                         }
197                                         
198                                         in.close();
199                                         
200                                         if (ableToOpen == 1) { 
201                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
202                                                 //erase from file list
203                                                 nameFileNames.erase(nameFileNames.begin()+i);
204                                                 i--;
205                                         }
206                                 }
207                                 
208                                 //make sure there is at least one valid file left
209                                 if (nameFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid name files."); m->mothurOutEndLine(); abort = true; }
210                         }
211                         
212                         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; }
213                         
214                         //if the user changes the output directory command factory will send this info to us in the output parameter 
215                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
216                         
217                         
218                         string path;
219                         it = parameters.find("template");
220                         //user has given a template file
221                         if(it != parameters.end()){ 
222                                 if (it->second == "self") { templatefile = "self"; }
223                                 else {
224                                         path = m->hasPath(it->second);
225                                         //if the user has not given a path then, add inputdir. else leave path alone.
226                                         if (path == "") {       parameters["template"] = inputDir + it->second;         }
227                                         
228                                         templatefile = validParameter.validFile(parameters, "template", true);
229                                         if (templatefile == "not open") { abort = true; }
230                                         else if (templatefile == "not found") { templatefile = "";  m->mothurOut("template is a required parameter for the chimera.slayer command."); m->mothurOutEndLine(); abort = true;  }   
231                                 }
232                         }
233                         
234                         string temp = validParameter.validFile(parameters, "processors", false);                if (temp == "not found") { temp = "1"; }
235                         convert(temp, processors);
236                         
237                         includeAbunds = validParameter.validFile(parameters, "include", false);         if (includeAbunds == "not found") { includeAbunds = "greater"; }
238                         if ((includeAbunds != "greater") && (includeAbunds != "greaterequal") && (includeAbunds != "all")) { includeAbunds = "greater"; m->mothurOut("Invalid include setting. options are greater, greaterequal or all. using greater."); m->mothurOutEndLine(); }
239                         
240                         temp = validParameter.validFile(parameters, "ksize", false);                    if (temp == "not found") { temp = "7"; }
241                         convert(temp, ksize);
242                                                 
243                         temp = validParameter.validFile(parameters, "window", false);                   if (temp == "not found") { temp = "50"; }                       
244                         convert(temp, window);
245                         
246                         temp = validParameter.validFile(parameters, "match", false);                    if (temp == "not found") { temp = "5"; }
247                         convert(temp, match);
248                         
249                         temp = validParameter.validFile(parameters, "mismatch", false);                 if (temp == "not found") { temp = "-4"; }
250                         convert(temp, mismatch);
251                         
252                         temp = validParameter.validFile(parameters, "divergence", false);               if (temp == "not found") { temp = "1.007"; }
253                         convert(temp, divR);
254                         
255                         temp = validParameter.validFile(parameters, "minsim", false);                   if (temp == "not found") { temp = "90"; }
256                         convert(temp, minSimilarity);
257                         
258                         temp = validParameter.validFile(parameters, "mincov", false);                   if (temp == "not found") { temp = "70"; }
259                         convert(temp, minCoverage);
260                         
261                         temp = validParameter.validFile(parameters, "minbs", false);                    if (temp == "not found") { temp = "90"; }
262                         convert(temp, minBS);
263                         
264                         temp = validParameter.validFile(parameters, "minsnp", false);                   if (temp == "not found") { temp = "100"; }
265                         convert(temp, minSNP);
266
267                         temp = validParameter.validFile(parameters, "parents", false);                  if (temp == "not found") { temp = "3"; }
268                         convert(temp, parents); 
269                         
270                         temp = validParameter.validFile(parameters, "realign", false);                  if (temp == "not found") { temp = "f"; }
271                         realign = m->isTrue(temp); 
272                         
273                         temp = validParameter.validFile(parameters, "trim", false);                             if (temp == "not found") { temp = "f"; }
274                         trim = m->isTrue(temp); 
275                         
276                         search = validParameter.validFile(parameters, "search", false);                 if (search == "not found") { search = "distance"; }
277                         
278                         temp = validParameter.validFile(parameters, "iters", false);                    if (temp == "not found") { temp = "100"; }              
279                         convert(temp, iters); 
280                          
281                         temp = validParameter.validFile(parameters, "increment", false);                if (temp == "not found") { temp = "5"; }
282                         convert(temp, increment);
283                         
284                         temp = validParameter.validFile(parameters, "numwanted", false);                if (temp == "not found") { temp = "15"; }               
285                         convert(temp, numwanted);
286
287                         if ((search != "distance") && (search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true;  }
288                 }
289         }
290         catch(exception& e) {
291                 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
292                 exit(1);
293         }
294 }
295 //**********************************************************************************************************************
296
297 void ChimeraSlayerCommand::help(){
298         try {
299         
300                 m->mothurOut("The chimera.slayer command reads a fastafile and templatefile and outputs potentially chimeric sequences.\n");
301                 m->mothurOut("This command was modeled after the chimeraSlayer written by the Broad Institute.\n");
302                 m->mothurOut("The chimera.slayer command parameters are fasta, name, template, processors, trim, ksize, window, match, mismatch, divergence. minsim, mincov, minbs, minsnp, parents, search, iters, increment and numwanted.\n"); //realign,
303                 m->mothurOut("The fasta parameter allows you to enter the fasta file containing your potentially chimeric sequences, and is required. \n");
304                 m->mothurOut("The name parameter allows you to provide a name file, if you are using template=self. \n");
305                 m->mothurOut("You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n");
306                 m->mothurOut("The template parameter allows you to enter a template 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");
307                 m->mothurOut("The processors parameter allows you to specify how many processors you would like to use.  The default is 1. \n");
308                 #ifdef USE_MPI
309                 m->mothurOut("When using MPI, the processors parameter is set to the number of MPI processes running. \n");
310                 #endif
311                 m->mothurOut("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");
312                 m->mothurOut("The window parameter allows you to specify the window size for searching for chimeras, default=50. \n");
313                 m->mothurOut("The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default=5.\n");
314                 m->mothurOut("The numwanted parameter allows you to specify how many sequences you would each query sequence compared with, default=15.\n");
315                 m->mothurOut("The ksize parameter allows you to input kmersize, default is 7, used if search is kmer. \n");
316                 m->mothurOut("The match parameter allows you to reward matched bases in blast search, default is 5. \n");
317                 m->mothurOut("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");
318                 m->mothurOut("The mismatch parameter allows you to penalize mismatched bases in blast search, default is -4. \n");
319                 m->mothurOut("The divergence parameter allows you to set a cutoff for chimera determination, default is 1.007. \n");
320                 m->mothurOut("The iters parameter allows you to specify the number of bootstrap iters to do with the chimeraslayer method, default=100.\n");
321                 m->mothurOut("The minsim parameter allows you to specify a minimum similarity with the parent fragments, default=90. \n");
322                 m->mothurOut("The mincov parameter allows you to specify minimum coverage by closest matches found in template. Default is 70, meaning 70%. \n");
323                 m->mothurOut("The minbs parameter allows you to specify minimum bootstrap support for calling a sequence chimeric. Default is 90, meaning 90%. \n");
324                 m->mothurOut("The minsnp parameter allows you to specify percent of SNPs to sample on each side of breakpoint for computing bootstrap support (default: 100) \n");
325                 m->mothurOut("The search parameter allows you to specify search method for finding the closest parent. Choices are distance, blast, and kmer, default distance. \n");
326                 m->mothurOut("The realign parameter allows you to realign the query to the potential parents. Choices are true or false, default false.  \n");
327                 m->mothurOut("The chimera.slayer command should be in the following format: \n");
328                 m->mothurOut("chimera.slayer(fasta=yourFastaFile, template=yourTemplate, search=yourSearch) \n");
329                 m->mothurOut("Example: chimera.slayer(fasta=AD.align, template=core_set_aligned.imputed.fasta, search=kmer) \n");
330                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n\n");     
331         }
332         catch(exception& e) {
333                 m->errorOut(e, "ChimeraSlayerCommand", "help");
334                 exit(1);
335         }
336 }
337
338 //***************************************************************************************************************
339
340 ChimeraSlayerCommand::~ChimeraSlayerCommand(){  /*      do nothing      */      }
341
342 //***************************************************************************************************************
343
344 int ChimeraSlayerCommand::execute(){
345         try{
346                 
347                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
348                 
349                 for (int s = 0; s < fastaFileNames.size(); s++) {
350                                 
351                         m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
352                 
353                         int start = time(NULL); 
354                         
355                         if (templatefile != "self") { //you want to run slayer with a refernce template
356                                 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);     
357                         }else {
358                                 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
359                                         chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, nameFileNames[s], search, includeAbunds, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);    
360                                 }else {
361                                         
362                                         m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
363                                         
364                                         //use unique.seqs to create new name and fastafile
365                                         string inputString = "fasta=" + fastaFileNames[s];
366                                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
367                                         m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
368                                                                  
369                                         Command* uniqueCommand = new DeconvoluteCommand(inputString);
370                                         uniqueCommand->execute();
371                                         
372                                         map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
373                                         
374                                         delete uniqueCommand;
375                                         
376                                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
377                                         
378                                         string nameFile = filenames["name"][0];
379                                         fastaFileNames[s] = filenames["fasta"][0];
380                         
381                                         chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, nameFile, search, includeAbunds, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);    
382                                 }
383                         }
384                                 
385                         if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]);  }//if user entered a file with a path then preserve it                               
386                         string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimera";
387                         string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "slayer.accnos";
388                         string trimFastaFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "slayer.fasta";
389                         
390                         if (m->control_pressed) { delete chimera; for (int j = 0; j < outputNames.size(); j++) {        remove(outputNames[j].c_str()); }  return 0;    }
391                         
392                         if (chimera->getUnaligned()) { 
393                                 m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); 
394                                 delete chimera;
395                                 return 0; 
396                         }
397                         templateSeqsLength = chimera->getLength();
398                         
399                 #ifdef USE_MPI  
400                         int pid, numSeqsPerProcessor; 
401                                 int tag = 2001;
402                                 vector<unsigned long int> MPIPos;
403                                 
404                                 MPI_Status status; 
405                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
406                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
407
408                                 MPI_File inMPI;
409                                 MPI_File outMPI;
410                                 MPI_File outMPIAccnos;
411                                 MPI_File outMPIFasta;
412                                 
413                                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
414                                 int inMode=MPI_MODE_RDONLY; 
415                                 
416                                 char outFilename[1024];
417                                 strcpy(outFilename, outputFileName.c_str());
418                                 
419                                 char outAccnosFilename[1024];
420                                 strcpy(outAccnosFilename, accnosFileName.c_str());
421                         
422                                 char outFastaFilename[1024];
423                                 strcpy(outFastaFilename, trimFastaFileName.c_str());
424                                 
425                                 char inFileName[1024];
426                                 strcpy(inFileName, fastaFileNames[s].c_str());
427
428                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
429                                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
430                                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
431                                 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
432
433                         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++) {   remove(outputNames[j].c_str()); }   delete chimera; return 0;  }
434                         
435                                 if (pid == 0) { //you are the root process 
436                                         m->mothurOutEndLine();
437                                         m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
438                                         m->mothurOutEndLine();
439                 
440                                         string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
441                                         
442                                         //print header
443                                         int length = outTemp.length();
444                                         char* buf2 = new char[length];
445                                         memcpy(buf2, outTemp.c_str(), length);
446
447                                         MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
448                                         delete buf2;
449
450                                         MPIPos = m->setFilePosFasta(fastaFileNames[s], numSeqs); //fills MPIPos, returns numSeqs
451                                         
452                                         //send file positions to all processes
453                                         for(int i = 1; i < processors; i++) { 
454                                                 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
455                                                 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
456                                         }
457                                         
458                                         //figure out how many sequences you have to align
459                                         numSeqsPerProcessor = numSeqs / processors;
460                                         int startIndex =  pid * numSeqsPerProcessor;
461                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
462                                 
463                                         //do your part
464                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
465                                         
466                                         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++) {   remove(outputNames[j].c_str()); }  remove(outputFileName.c_str());  remove(accnosFileName.c_str());  delete chimera; return 0;  }
467
468                                 }else{ //you are a child process
469                                         MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
470                                         MPIPos.resize(numSeqs+1);
471                                         MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
472                                         
473                                         //figure out how many sequences you have to align
474                                         numSeqsPerProcessor = numSeqs / processors;
475                                         int startIndex =  pid * numSeqsPerProcessor;
476                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
477                                         
478                                         //do your part
479                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
480                                         
481                                         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++) {   remove(outputNames[j].c_str()); }  delete chimera; return 0;  }
482                                 }
483                                 
484                                 //close files 
485                                 MPI_File_close(&inMPI);
486                                 MPI_File_close(&outMPI);
487                                 MPI_File_close(&outMPIAccnos); 
488                                 if (trim) { MPI_File_close(&outMPIFasta); }
489                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
490                                 
491                 #else
492                         ofstream outHeader;
493                         string tempHeader = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimeras.tempHeader";
494                         m->openOutputFile(tempHeader, outHeader);
495                         
496                         chimera->printHeader(outHeader);
497                         outHeader.close();
498                         
499                         vector<unsigned long int> positions = m->divideFile(fastaFileNames[s], processors);
500                                 
501                         for (int i = 0; i < (positions.size()-1); i++) {
502                                 lines.push_back(new linePair(positions[i], positions[(i+1)]));
503                         }       
504
505                         //break up file
506                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
507                                 if(processors == 1){
508                                         numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
509                                         
510                                         if (m->control_pressed) { outputTypes.clear(); if (trim) { remove(trimFastaFileName.c_str()); } remove(outputFileName.c_str()); remove(tempHeader.c_str()); remove(accnosFileName.c_str()); for (int j = 0; j < outputNames.size(); j++) {      remove(outputNames[j].c_str()); } for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear(); delete chimera; return 0; }
511                                         
512                                 }else{
513                                         processIDS.resize(0);
514                                         
515                                         numSeqs = createProcesses(outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName); 
516                                 
517                                         rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
518                                         rename((accnosFileName + toString(processIDS[0]) + ".temp").c_str(), accnosFileName.c_str());
519                                         if (trim) {  rename((trimFastaFileName + toString(processIDS[0]) + ".temp").c_str(), trimFastaFileName.c_str()); }
520                                                 
521                                         //append output files
522                                         for(int i=1;i<processors;i++){
523                                                 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
524                                                 remove((outputFileName + toString(processIDS[i]) + ".temp").c_str());
525                                         }
526                                         
527                                         //append output files
528                                         for(int i=1;i<processors;i++){
529                                                 m->appendFiles((accnosFileName + toString(processIDS[i]) + ".temp"), accnosFileName);
530                                                 remove((accnosFileName + toString(processIDS[i]) + ".temp").c_str());
531                                         }
532                                         
533                                         if (trim) {
534                                                 for(int i=1;i<processors;i++){
535                                                         m->appendFiles((trimFastaFileName + toString(processIDS[i]) + ".temp"), trimFastaFileName);
536                                                         remove((trimFastaFileName + toString(processIDS[i]) + ".temp").c_str());
537                                                 }
538                                         }
539                                         
540                                         if (m->control_pressed) { outputTypes.clear(); if (trim) { remove(trimFastaFileName.c_str()); } remove(outputFileName.c_str()); remove(accnosFileName.c_str()); for (int j = 0; j < outputNames.size(); j++) {  remove(outputNames[j].c_str()); } for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear(); delete chimera; return 0; }
541                                 }
542
543                         #else
544                                 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
545                                 
546                                 if (m->control_pressed) { outputTypes.clear(); if (trim) { remove(trimFastaFileName.c_str()); } remove(outputFileName.c_str()); remove(tempHeader.c_str()); remove(accnosFileName.c_str()); for (int j = 0; j < outputNames.size(); j++) {      remove(outputNames[j].c_str()); } for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear(); delete chimera; return 0; }
547                                 
548                         #endif
549                         
550                         m->appendFiles(outputFileName, tempHeader);
551                 
552                         remove(outputFileName.c_str());
553                         rename(tempHeader.c_str(), outputFileName.c_str());
554                         
555                 #endif
556                         delete chimera;
557                         
558                         
559                         for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
560                         
561                         outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
562                         outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
563                         if (trim) {  outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }
564                         
565                         m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
566                 }
567                 
568                 m->mothurOutEndLine();
569                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
570                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
571                 m->mothurOutEndLine();
572
573                 return 0;
574                 
575         }
576         catch(exception& e) {
577                 m->errorOut(e, "ChimeraSlayerCommand", "execute");
578                 exit(1);
579         }
580 }
581 //**********************************************************************************************************************
582
583 int ChimeraSlayerCommand::driver(linePair* filePos, string outputFName, string filename, string accnos, string fasta){
584         try {
585                 ofstream out;
586                 m->openOutputFile(outputFName, out);
587                 
588                 ofstream out2;
589                 m->openOutputFile(accnos, out2);
590                 
591                 ofstream out3;
592                 if (trim) {  m->openOutputFile(fasta, out3); }
593                 
594                 ifstream inFASTA;
595                 m->openInputFile(filename, inFASTA);
596
597                 inFASTA.seekg(filePos->start);
598
599                 bool done = false;
600                 int count = 0;
601         
602                 while (!done) {
603                 
604                         if (m->control_pressed) {       out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1;       }
605                 
606                         Sequence* candidateSeq = new Sequence(inFASTA);  m->gobble(inFASTA);
607                                 
608                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
609                                 
610                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
611                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
612                                 }else{
613                                         //find chimeras
614                                         chimera->getChimeras(candidateSeq);
615                                         
616                                         if (m->control_pressed) {       delete candidateSeq; return 1;  }
617                 
618                                         //print results
619                                         Sequence* trimmed = chimera->print(out, out2);
620                                         
621                                         if (trim) { trimmed->printSequence(out3); delete trimmed; }
622                                 }
623                         count++;
624                         }
625                         delete candidateSeq;
626                         
627                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
628                                 unsigned long int pos = inFASTA.tellg();
629                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
630                         #else
631                                 if (inFASTA.eof()) { break; }
632                         #endif
633                         
634                         //report progress
635                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
636                 }
637                 //report progress
638                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
639                 
640                 out.close();
641                 out2.close();
642                 if (trim) { out3.close(); }
643                 inFASTA.close();
644                                 
645                 return count;
646         }
647         catch(exception& e) {
648                 m->errorOut(e, "ChimeraSlayerCommand", "driver");
649                 exit(1);
650         }
651 }
652 //**********************************************************************************************************************
653 #ifdef USE_MPI
654 int ChimeraSlayerCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, MPI_File& outFastaMPI, vector<unsigned long int>& MPIPos){
655         try {                           
656                 MPI_Status status; 
657                 int pid;
658                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
659                 
660                 for(int i=0;i<num;i++){
661                         
662                         if (m->control_pressed) {       return 1;       }
663                         
664                         //read next sequence
665                         int length = MPIPos[start+i+1] - MPIPos[start+i];
666
667                         char* buf4 = new char[length];
668                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
669         
670                         string tempBuf = buf4;
671                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
672                         istringstream iss (tempBuf,istringstream::in);
673
674                         delete buf4;
675
676                         Sequence* candidateSeq = new Sequence(iss);  m->gobble(iss);
677                 
678                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
679                                 
680                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
681                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
682                                 }else{
683                 
684                                         //find chimeras
685                                         chimera->getChimeras(candidateSeq);
686                         
687                                         if (m->control_pressed) {       delete candidateSeq; return 1;  }
688                 
689                                         //print results
690                                         Sequence* trimmed = chimera->print(outMPI, outAccMPI);
691                                         
692                                         if (trim) {  
693                                                 string outputString = ">" + trimmed->getName() + "\n" + trimmed->getAligned() + "\n";
694                                                 delete trimmed;
695                                                 
696                                                 //write to accnos file
697                                                 int length = outputString.length();
698                                                 char* buf2 = new char[length];
699                                                 memcpy(buf2, outputString.c_str(), length);
700                                                 
701                                                 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
702                                                 delete buf2;
703                                         }
704                                                 
705                                 }
706                         }
707                         delete candidateSeq;
708                         
709                         //report progress
710                         if((i+1) % 100 == 0){  cout << "Processing sequence: " << (i+1) << endl;        m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n");          }
711                 }
712                 //report progress
713                 if(num % 100 != 0){             cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n");  }
714                 
715                                 
716                 return 0;
717         }
718         catch(exception& e) {
719                 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
720                 exit(1);
721         }
722 }
723 #endif
724
725 /**************************************************************************************************/
726
727 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta) {
728         try {
729 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
730                 int process = 0;
731                 int num = 0;
732                 
733                 //loop through and create all the processes you want
734                 while (process != processors) {
735                         int pid = fork();
736                         
737                         if (pid > 0) {
738                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
739                                 process++;
740                         }else if (pid == 0){
741                                 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp");
742                                 
743                                 //pass numSeqs to parent
744                                 ofstream out;
745                                 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
746                                 m->openOutputFile(tempFile, out);
747                                 out << num << endl;
748                                 out.close();
749                                 
750                                 exit(0);
751                         }else { 
752                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
753                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
754                                 exit(0);
755                         }
756                 }
757                 
758                 //force parent to wait until all the processes are done
759                 for (int i=0;i<processors;i++) { 
760                         int temp = processIDS[i];
761                         wait(&temp);
762                 }
763                 
764                 for (int i = 0; i < processIDS.size(); i++) {
765                         ifstream in;
766                         string tempFile =  outputFileName + toString(processIDS[i]) + ".num.temp";
767                         m->openInputFile(tempFile, in);
768                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
769                         in.close(); remove(tempFile.c_str());
770                 }
771                 
772                 return num;
773 #endif          
774         }
775         catch(exception& e) {
776                 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
777                 exit(1);
778         }
779 }
780
781 /**************************************************************************************************/
782
783