]> git.donarmstrong.com Git - mothur.git/blob - chimeraslayercommand.cpp
removed parse.sff command and made its functionality part of sffinfo command. fixed...
[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", "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         }
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", "include","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                         includeAbunds = validParameter.validFile(parameters, "include", false);         if (includeAbunds == "not found") { includeAbunds = "greater"; }
235                         if ((includeAbunds != "greater") && (includeAbunds != "greaterequal") && (includeAbunds != "all")) { includeAbunds = "greater"; m->mothurOut("Invalid include setting. options are greater, greaterequal or all. using greater."); m->mothurOutEndLine(); }
236                         
237                         temp = validParameter.validFile(parameters, "ksize", false);                    if (temp == "not found") { temp = "7"; }
238                         convert(temp, ksize);
239                                                 
240                         temp = validParameter.validFile(parameters, "window", false);                   if (temp == "not found") { temp = "50"; }                       
241                         convert(temp, window);
242                         
243                         temp = validParameter.validFile(parameters, "match", false);                    if (temp == "not found") { temp = "5"; }
244                         convert(temp, match);
245                         
246                         temp = validParameter.validFile(parameters, "mismatch", false);                 if (temp == "not found") { temp = "-4"; }
247                         convert(temp, mismatch);
248                         
249                         temp = validParameter.validFile(parameters, "divergence", false);               if (temp == "not found") { temp = "1.007"; }
250                         convert(temp, divR);
251                         
252                         temp = validParameter.validFile(parameters, "minsim", false);                   if (temp == "not found") { temp = "90"; }
253                         convert(temp, minSimilarity);
254                         
255                         temp = validParameter.validFile(parameters, "mincov", false);                   if (temp == "not found") { temp = "70"; }
256                         convert(temp, minCoverage);
257                         
258                         temp = validParameter.validFile(parameters, "minbs", false);                    if (temp == "not found") { temp = "90"; }
259                         convert(temp, minBS);
260                         
261                         temp = validParameter.validFile(parameters, "minsnp", false);                   if (temp == "not found") { temp = "100"; }
262                         convert(temp, minSNP);
263
264                         temp = validParameter.validFile(parameters, "parents", false);                  if (temp == "not found") { temp = "3"; }
265                         convert(temp, parents); 
266                         
267                         temp = validParameter.validFile(parameters, "realign", false);                  if (temp == "not found") { temp = "f"; }
268                         realign = m->isTrue(temp); 
269                         
270                         search = validParameter.validFile(parameters, "search", false);                 if (search == "not found") { search = "distance"; }
271                         
272                         temp = validParameter.validFile(parameters, "iters", false);                    if (temp == "not found") { temp = "100"; }              
273                         convert(temp, iters); 
274                          
275                         temp = validParameter.validFile(parameters, "increment", false);                if (temp == "not found") { temp = "5"; }
276                         convert(temp, increment);
277                         
278                         temp = validParameter.validFile(parameters, "numwanted", false);                if (temp == "not found") { temp = "15"; }               
279                         convert(temp, numwanted);
280
281                         if ((search != "distance") && (search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true;  }
282                 }
283         }
284         catch(exception& e) {
285                 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
286                 exit(1);
287         }
288 }
289 //**********************************************************************************************************************
290
291 void ChimeraSlayerCommand::help(){
292         try {
293         
294                 m->mothurOut("The chimera.slayer command reads a fastafile and templatefile and outputs potentially chimeric sequences.\n");
295                 m->mothurOut("This command was modeled after the chimeraSlayer written by the Broad Institute.\n");
296                 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,
297                 m->mothurOut("The fasta parameter allows you to enter the fasta file containing your potentially chimeric sequences, and is required. \n");
298                 m->mothurOut("The name parameter allows you to provide a name file, if you are using template=self. \n");
299                 m->mothurOut("You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n");
300                 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");
301                 m->mothurOut("The processors parameter allows you to specify how many processors you would like to use.  The default is 1. \n");
302                 #ifdef USE_MPI
303                 m->mothurOut("When using MPI, the processors parameter is set to the number of MPI processes running. \n");
304                 #endif
305                 m->mothurOut("The window parameter allows you to specify the window size for searching for chimeras, default=50. \n");
306                 m->mothurOut("The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default=5.\n");
307                 m->mothurOut("The numwanted parameter allows you to specify how many sequences you would each query sequence compared with, default=15.\n");
308                 m->mothurOut("The ksize parameter allows you to input kmersize, default is 7, used if search is kmer. \n");
309                 m->mothurOut("The match parameter allows you to reward matched bases in blast search, default is 5. \n");
310                 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");
311                 m->mothurOut("The mismatch parameter allows you to penalize mismatched bases in blast search, default is -4. \n");
312                 m->mothurOut("The divergence parameter allows you to set a cutoff for chimera determination, default is 1.007. \n");
313                 m->mothurOut("The iters parameter allows you to specify the number of bootstrap iters to do with the chimeraslayer method, default=100.\n");
314                 m->mothurOut("The minsim parameter allows you to specify a minimum similarity with the parent fragments, default=90. \n");
315                 m->mothurOut("The mincov parameter allows you to specify minimum coverage by closest matches found in template. Default is 70, meaning 70%. \n");
316                 m->mothurOut("The minbs parameter allows you to specify minimum bootstrap support for calling a sequence chimeric. Default is 90, meaning 90%. \n");
317                 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");
318                 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");
319                 m->mothurOut("The realign parameter allows you to realign the query to the potential parents. Choices are true or false, default false.  \n");
320                 m->mothurOut("The chimera.slayer command should be in the following format: \n");
321                 m->mothurOut("chimera.slayer(fasta=yourFastaFile, template=yourTemplate, search=yourSearch) \n");
322                 m->mothurOut("Example: chimera.slayer(fasta=AD.align, template=core_set_aligned.imputed.fasta, search=kmer) \n");
323                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n\n");     
324         }
325         catch(exception& e) {
326                 m->errorOut(e, "ChimeraSlayerCommand", "help");
327                 exit(1);
328         }
329 }
330
331 //***************************************************************************************************************
332
333 ChimeraSlayerCommand::~ChimeraSlayerCommand(){  /*      do nothing      */      }
334
335 //***************************************************************************************************************
336
337 int ChimeraSlayerCommand::execute(){
338         try{
339                 
340                 if (abort == true) { return 0; }
341                 
342                 for (int s = 0; s < fastaFileNames.size(); s++) {
343                                 
344                         m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
345                 
346                         int start = time(NULL); 
347                         
348                         if (templatefile != "self") { //you want to run slayer with a refernce template
349                                 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);   
350                         }else {
351                                 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
352                                         chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, nameFileNames[s], search, includeAbunds, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);  
353                                 }else {
354                                         
355                                         m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
356                                         
357                                         //use unique.seqs to create new name and fastafile
358                                         string inputString = "fasta=" + fastaFileNames[s];
359                                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
360                                         m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
361                                                                  
362                                         Command* uniqueCommand = new DeconvoluteCommand(inputString);
363                                         uniqueCommand->execute();
364                                         
365                                         map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
366                                         
367                                         delete uniqueCommand;
368                                         
369                                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
370                                         
371                                         string nameFile = filenames["name"][0];
372                                         fastaFileNames[s] = filenames["fasta"][0];
373                         
374                                         chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, nameFile, search, includeAbunds, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);  
375                                 }
376                         }
377                                 
378                         if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]);  }//if user entered a file with a path then preserve it                               
379                         string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimeras";
380                         string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "slayer.accnos";
381                         
382                         if (m->control_pressed) { delete chimera; for (int j = 0; j < outputNames.size(); j++) {        remove(outputNames[j].c_str()); }  return 0;    }
383                         
384                         if (chimera->getUnaligned()) { 
385                                 m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); 
386                                 delete chimera;
387                                 return 0; 
388                         }
389                         templateSeqsLength = chimera->getLength();
390                         
391                 #ifdef USE_MPI  
392                         int pid, end, numSeqsPerProcessor; 
393                                 int tag = 2001;
394                                 vector<unsigned long int> MPIPos;
395                                 
396                                 MPI_Status status; 
397                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
398                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
399
400                                 MPI_File inMPI;
401                                 MPI_File outMPI;
402                                 MPI_File outMPIAccnos;
403                                 
404                                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
405                                 int inMode=MPI_MODE_RDONLY; 
406                                 
407                                 char outFilename[1024];
408                                 strcpy(outFilename, outputFileName.c_str());
409                                 
410                                 char outAccnosFilename[1024];
411                                 strcpy(outAccnosFilename, accnosFileName.c_str());
412                                 
413                                 char inFileName[1024];
414                                 strcpy(inFileName, fastaFileNames[s].c_str());
415
416                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
417                                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
418                                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
419
420                                 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;  }
421                         
422                                 if (pid == 0) { //you are the root process 
423                                         m->mothurOutEndLine();
424                                         m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
425                                         m->mothurOutEndLine();
426                 
427                                         string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
428                                         
429                                         //print header
430                                         int length = outTemp.length();
431                                         char* buf2 = new char[length];
432                                         memcpy(buf2, outTemp.c_str(), length);
433
434                                         MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
435                                         delete buf2;
436
437                                         MPIPos = m->setFilePosFasta(fastaFileNames[s], numSeqs); //fills MPIPos, returns numSeqs
438                                         
439                                         //send file positions to all processes
440                                         for(int i = 1; i < processors; i++) { 
441                                                 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
442                                                 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
443                                         }
444                                         
445                                         //figure out how many sequences you have to align
446                                         numSeqsPerProcessor = numSeqs / processors;
447                                         int startIndex =  pid * numSeqsPerProcessor;
448                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
449                                 
450                                         //do your part
451                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, MPIPos);
452                                         
453                                         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;  }
454
455                                 }else{ //you are a child process
456                                         MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
457                                         MPIPos.resize(numSeqs+1);
458                                         MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
459                                         
460                                         //figure out how many sequences you have to align
461                                         numSeqsPerProcessor = numSeqs / processors;
462                                         int startIndex =  pid * numSeqsPerProcessor;
463                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
464                                         
465                                         //do your part
466                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, MPIPos);
467                                         
468                                         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;  }
469                                 }
470                                 
471                                 //close files 
472                                 MPI_File_close(&inMPI);
473                                 MPI_File_close(&outMPI);
474                                 MPI_File_close(&outMPIAccnos);
475                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
476                                 
477                 #else
478                         ofstream outHeader;
479                         string tempHeader = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimeras.tempHeader";
480                         m->openOutputFile(tempHeader, outHeader);
481                         
482                         chimera->printHeader(outHeader);
483                         outHeader.close();
484                         
485                         vector<unsigned long int> positions = m->divideFile(fastaFileNames[s], processors);
486                                 
487                         for (int i = 0; i < (positions.size()-1); i++) {
488                                 lines.push_back(new linePair(positions[i], positions[(i+1)]));
489                         }       
490
491                         //break up file
492                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
493                                 if(processors == 1){
494                                         numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName);
495                                         
496                                         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; }
497                                         
498                                 }else{
499                                         processIDS.resize(0);
500                                         
501                                         numSeqs = createProcesses(outputFileName, fastaFileNames[s], accnosFileName); 
502                                 
503                                         rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
504                                         rename((accnosFileName + toString(processIDS[0]) + ".temp").c_str(), accnosFileName.c_str());
505                                                 
506                                         //append output files
507                                         for(int i=1;i<processors;i++){
508                                                 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
509                                                 remove((outputFileName + toString(processIDS[i]) + ".temp").c_str());
510                                         }
511                                         
512                                         //append output files
513                                         for(int i=1;i<processors;i++){
514                                                 m->appendFiles((accnosFileName + toString(processIDS[i]) + ".temp"), accnosFileName);
515                                                 remove((accnosFileName + toString(processIDS[i]) + ".temp").c_str());
516                                         }
517                                         
518                                         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; }
519                                 }
520
521                         #else
522                                 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName);
523                                 
524                                 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; }
525                                 
526                         #endif
527                         
528                         m->appendFiles(outputFileName, tempHeader);
529                 
530                         remove(outputFileName.c_str());
531                         rename(tempHeader.c_str(), outputFileName.c_str());
532                         
533                 #endif
534                         delete chimera;
535                         
536                         
537                         for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
538                         
539                         outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
540                         outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
541                         
542                         m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
543                 }
544                 
545                 m->mothurOutEndLine();
546                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
547                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
548                 m->mothurOutEndLine();
549
550                 return 0;
551                 
552         }
553         catch(exception& e) {
554                 m->errorOut(e, "ChimeraSlayerCommand", "execute");
555                 exit(1);
556         }
557 }
558 //**********************************************************************************************************************
559
560 int ChimeraSlayerCommand::driver(linePair* filePos, string outputFName, string filename, string accnos){
561         try {
562                 ofstream out;
563                 m->openOutputFile(outputFName, out);
564                 
565                 ofstream out2;
566                 m->openOutputFile(accnos, out2);
567                 
568                 ifstream inFASTA;
569                 m->openInputFile(filename, inFASTA);
570
571                 inFASTA.seekg(filePos->start);
572
573                 bool done = false;
574                 int count = 0;
575         
576                 while (!done) {
577                 
578                         if (m->control_pressed) {       return 1;       }
579                 
580                         Sequence* candidateSeq = new Sequence(inFASTA);  m->gobble(inFASTA);
581                                 
582                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
583                                 
584                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
585                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
586                                 }else{
587                                         //find chimeras
588                                         chimera->getChimeras(candidateSeq);
589                                         
590                                         if (m->control_pressed) {       delete candidateSeq; return 1;  }
591                 
592                                         //print results
593                                         chimera->print(out, out2);
594                                 }
595                         count++;
596                         }
597                         delete candidateSeq;
598                         
599                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
600                                 unsigned long int pos = inFASTA.tellg();
601                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
602                         #else
603                                 if (inFASTA.eof()) { break; }
604                         #endif
605                         
606                         //report progress
607                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
608                 }
609                 //report progress
610                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
611                 
612                 out.close();
613                 out2.close();
614                 inFASTA.close();
615                                 
616                 return count;
617         }
618         catch(exception& e) {
619                 m->errorOut(e, "ChimeraSlayerCommand", "driver");
620                 exit(1);
621         }
622 }
623 //**********************************************************************************************************************
624 #ifdef USE_MPI
625 int ChimeraSlayerCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, vector<unsigned long int>& MPIPos){
626         try {                           
627                 MPI_Status status; 
628                 int pid;
629                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
630                 
631                 for(int i=0;i<num;i++){
632                         
633                         if (m->control_pressed) {       return 1;       }
634                         
635                         //read next sequence
636                         int length = MPIPos[start+i+1] - MPIPos[start+i];
637
638                         char* buf4 = new char[length];
639                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
640         
641                         string tempBuf = buf4;
642                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
643                         istringstream iss (tempBuf,istringstream::in);
644
645                         delete buf4;
646
647                         Sequence* candidateSeq = new Sequence(iss);  m->gobble(iss);
648                 
649                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
650                                 
651                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
652                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
653                                 }else{
654                 
655                                         //find chimeras
656                                         chimera->getChimeras(candidateSeq);
657                         
658                                         if (m->control_pressed) {       delete candidateSeq; return 1;  }
659                 //cout << "about to print" << endl;
660                                         //print results
661                                         bool isChimeric = chimera->print(outMPI, outAccMPI);
662                                 }
663                         }
664                         delete candidateSeq;
665                         
666                         //report progress
667                         if((i+1) % 100 == 0){  cout << "Processing sequence: " << (i+1) << endl;        m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n");          }
668                 }
669                 //report progress
670                 if(num % 100 != 0){             cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n");  }
671                 
672                                 
673                 return 0;
674         }
675         catch(exception& e) {
676                 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
677                 exit(1);
678         }
679 }
680 #endif
681
682 /**************************************************************************************************/
683
684 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos) {
685         try {
686 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
687                 int process = 0;
688                 int num = 0;
689                 
690                 //loop through and create all the processes you want
691                 while (process != processors) {
692                         int pid = fork();
693                         
694                         if (pid > 0) {
695                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
696                                 process++;
697                         }else if (pid == 0){
698                                 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp");
699                                 
700                                 //pass numSeqs to parent
701                                 ofstream out;
702                                 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
703                                 m->openOutputFile(tempFile, out);
704                                 out << num << endl;
705                                 out.close();
706                                 
707                                 exit(0);
708                         }else { 
709                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
710                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
711                                 exit(0);
712                         }
713                 }
714                 
715                 //force parent to wait until all the processes are done
716                 for (int i=0;i<processors;i++) { 
717                         int temp = processIDS[i];
718                         wait(&temp);
719                 }
720                 
721                 for (int i = 0; i < processIDS.size(); i++) {
722                         ifstream in;
723                         string tempFile =  outputFileName + toString(processIDS[i]) + ".num.temp";
724                         m->openInputFile(tempFile, in);
725                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
726                         in.close(); remove(tempFile.c_str());
727                 }
728                 
729                 return num;
730 #endif          
731         }
732         catch(exception& e) {
733                 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
734                 exit(1);
735         }
736 }
737
738 /**************************************************************************************************/
739
740