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