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