]> git.donarmstrong.com Git - mothur.git/blob - chimeraccodecommand.cpp
added pipeline commands which involved change to command factory and command class...
[mothur.git] / chimeraccodecommand.cpp
1 /*
2  *  chimeraccodecommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 3/30/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "chimeraccodecommand.h"
11 #include "ccode.h"
12
13 //**********************************************************************************************************************
14 vector<string> ChimeraCcodeCommand::getValidParameters(){       
15         try {
16                 string AlignArray[] =  {"fasta", "filter", "processors", "window", "template", "mask", "numwanted", "outputdir","inputdir" };
17                 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
18                 return myArray;
19         }
20         catch(exception& e) {
21                 m->errorOut(e, "ChimeraCcodeCommand", "getValidParameters");
22                 exit(1);
23         }
24 }
25 //**********************************************************************************************************************
26 ChimeraCcodeCommand::ChimeraCcodeCommand(){     
27         try {
28                 vector<string> tempOutNames;
29                 outputTypes["chimera"] = tempOutNames;
30                 outputTypes["mapinfo"] = tempOutNames;
31                 outputTypes["accnos"] = tempOutNames;
32         }
33         catch(exception& e) {
34                 m->errorOut(e, "ChimeraCcodeCommand", "ChimeraCcodeCommand");
35                 exit(1);
36         }
37 }
38 //**********************************************************************************************************************
39 vector<string> ChimeraCcodeCommand::getRequiredParameters(){    
40         try {
41                 string AlignArray[] =  {"template","fasta"};
42                 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
43                 return myArray;
44         }
45         catch(exception& e) {
46                 m->errorOut(e, "ChimeraCcodeCommand", "getRequiredParameters");
47                 exit(1);
48         }
49 }
50 //**********************************************************************************************************************
51 vector<string> ChimeraCcodeCommand::getRequiredFiles(){ 
52         try {
53                 vector<string> myArray;
54                 return myArray;
55         }
56         catch(exception& e) {
57                 m->errorOut(e, "ChimeraCcodeCommand", "getRequiredFiles");
58                 exit(1);
59         }
60 }
61 //***************************************************************************************************************
62 ChimeraCcodeCommand::ChimeraCcodeCommand(string option)  {
63         try {
64                 abort = false;
65                 
66                 //allow user to run help
67                 if(option == "help") { help(); abort = true; }
68                 
69                 else {
70                         //valid paramters for this command
71                         string Array[] =  {"fasta", "filter", "processors", "window", "template", "mask", "numwanted", "outputdir","inputdir" };
72                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
73                         
74                         OptionParser parser(option);
75                         map<string,string> parameters = parser.getParameters();
76                         
77                         ValidParameters validParameter("chimera.ccode");
78                         map<string,string>::iterator it;
79                         
80                         //check to make sure all parameters are valid for command
81                         for (it = parameters.begin(); it != parameters.end(); it++) { 
82                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
83                         }
84                         
85                         vector<string> tempOutNames;
86                         outputTypes["chimera"] = tempOutNames;
87                         outputTypes["mapinfo"] = tempOutNames;
88                         outputTypes["accnos"] = tempOutNames;
89                         
90                         //if the user changes the input directory command factory will send this info to us in the output parameter 
91                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
92                         if (inputDir == "not found"){   inputDir = "";          }
93                         else {
94                                 string path;
95                                 it = parameters.find("template");
96                                 //user has given a template file
97                                 if(it != parameters.end()){ 
98                                         path = m->hasPath(it->second);
99                                         //if the user has not given a path then, add inputdir. else leave path alone.
100                                         if (path == "") {       parameters["template"] = inputDir + it->second;         }
101                                 }
102                         }
103
104                         //check for required parameters
105                         fastafile = validParameter.validFile(parameters, "fasta", false);
106                         if (fastafile == "not found") { fastafile = ""; m->mothurOut("fasta is a required parameter for the chimera.ccode command."); m->mothurOutEndLine(); abort = true;  }
107                         else { 
108                                 m->splitAtDash(fastafile, fastaFileNames);
109                                 
110                                 //go through files and make sure they are good, if not, then disregard them
111                                 for (int i = 0; i < fastaFileNames.size(); i++) {
112                                         if (inputDir != "") {
113                                                 string path = m->hasPath(fastaFileNames[i]);
114                                                 //if the user has not given a path then, add inputdir. else leave path alone.
115                                                 if (path == "") {       fastaFileNames[i] = inputDir + fastaFileNames[i];               }
116                                         }
117         
118                                         int ableToOpen;
119                                         ifstream in;
120                                         
121                                         ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
122                                 
123                                         //if you can't open it, try default location
124                                         if (ableToOpen == 1) {
125                                                 if (m->getDefaultPath() != "") { //default path is set
126                                                         string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
127                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
128                                                         ableToOpen = m->openInputFile(tryPath, in, "noerror");
129                                                         fastaFileNames[i] = tryPath;
130                                                 }
131                                         }
132                                         
133                                         //if you can't open it, try default location
134                                         if (ableToOpen == 1) {
135                                                 if (m->getOutputDir() != "") { //default path is set
136                                                         string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
137                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
138                                                         ableToOpen = m->openInputFile(tryPath, in, "noerror");
139                                                         fastaFileNames[i] = tryPath;
140                                                 }
141                                         }
142                                         
143                                         in.close();
144                                         
145                                         if (ableToOpen == 1) { 
146                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
147                                                 //erase from file list
148                                                 fastaFileNames.erase(fastaFileNames.begin()+i);
149                                                 i--;
150                                         }
151                                 }
152                                 
153                                 //make sure there is at least one valid file left
154                                 if (fastaFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
155                         }
156                         
157                         //if the user changes the output directory command factory will send this info to us in the output parameter 
158                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
159
160                         templatefile = validParameter.validFile(parameters, "template", true);
161                         if (templatefile == "not open") { abort = true; }
162                         else if (templatefile == "not found") { templatefile = ""; m->mothurOut("template is a required parameter for the chimera.ccode command."); m->mothurOutEndLine(); abort = true;  }             
163                         
164                         maskfile = validParameter.validFile(parameters, "mask", false);
165                         if (maskfile == "not found") { maskfile = "";  }        
166                         else if (maskfile != "default")  { 
167                                 if (inputDir != "") {
168                                         string path = m->hasPath(maskfile);
169                                         //if the user has not given a path then, add inputdir. else leave path alone.
170                                         if (path == "") {       maskfile = inputDir + maskfile;         }
171                                 }
172
173                                 ifstream in;
174                                 int     ableToOpen = m->openInputFile(maskfile, in);
175                                 if (ableToOpen == 1) { abort = true; }
176                                 in.close();
177                         }
178                         
179                         string temp;
180                         temp = validParameter.validFile(parameters, "filter", false);                   if (temp == "not found") { temp = "F"; }
181                         filter = m->isTrue(temp);
182                         
183                         temp = validParameter.validFile(parameters, "processors", false);               if (temp == "not found") { temp = "1"; }
184                         convert(temp, processors);
185                         
186                         temp = validParameter.validFile(parameters, "window", false);                   if (temp == "not found") { temp = "0"; }
187                         convert(temp, window);
188                         
189                         temp = validParameter.validFile(parameters, "numwanted", false);                if (temp == "not found") { temp = "20"; }
190                         convert(temp, numwanted);
191
192                 }
193         }
194         catch(exception& e) {
195                 m->errorOut(e, "ChimeraCcodeCommand", "ChimeraCcodeCommand");
196                 exit(1);
197         }
198 }
199 //**********************************************************************************************************************
200
201 void ChimeraCcodeCommand::help(){
202         try {
203         
204                 m->mothurOut("The chimera.ccode command reads a fastafile and templatefile and outputs potentially chimeric sequences.\n");
205                 m->mothurOut("This command was created using the algorythms described in the 'Evaluating putative chimeric sequences from PCR-amplified products' paper by Juan M. Gonzalez, Johannes Zimmerman and Cesareo Saiz-Jimenez.\n");
206                 m->mothurOut("The chimera.ccode command parameters are fasta, template, filter, mask, processors, window and numwanted.\n");
207                 m->mothurOut("The fasta parameter allows you to enter the fasta file containing your potentially chimeric sequences, and is required. \n");
208                 m->mothurOut("You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amzon.fasta \n");
209                 m->mothurOut("The template parameter allows you to enter a template file containing known non-chimeric sequences, and is required. \n");
210                 m->mothurOut("The filter parameter allows you to specify if you would like to apply a vertical and 50% soft filter. \n");
211                 m->mothurOut("The processors parameter allows you to specify how many processors you would like to use.  The default is 1. \n");
212                 #ifdef USE_MPI
213                 m->mothurOut("When using MPI, the processors parameter is set to the number of MPI processes running. \n");
214                 #endif
215                 m->mothurOut("The mask parameter allows you to specify a file containing one sequence you wish to use as a mask for the your sequences. \n");
216                 m->mothurOut("The window parameter allows you to specify the window size for searching for chimeras. \n");
217                 m->mothurOut("The numwanted parameter allows you to specify how many sequences you would each query sequence compared with.\n");
218                 m->mothurOut("The chimera.ccode command should be in the following format: \n");
219                 m->mothurOut("chimera.ccode(fasta=yourFastaFile, template=yourTemplate) \n");
220                 m->mothurOut("Example: chimera.ccode(fasta=AD.align, template=core_set_aligned.imputed.fasta) \n");
221                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n\n");     
222         }
223         catch(exception& e) {
224                 m->errorOut(e, "ChimeraCcodeCommand", "help");
225                 exit(1);
226         }
227 }
228
229 //***************************************************************************************************************
230
231 ChimeraCcodeCommand::~ChimeraCcodeCommand(){    /*      do nothing      */      }
232
233 //***************************************************************************************************************
234
235 int ChimeraCcodeCommand::execute(){
236         try{
237                 
238                 if (abort == true) { return 0; }
239                 
240                 for (int s = 0; s < fastaFileNames.size(); s++) {
241                                 
242                         m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
243                 
244                         int start = time(NULL); 
245                         
246                         //set user options
247                         if (maskfile == "default") { m->mothurOut("I am using the default 236627 EU009184.1 Shigella dysenteriae str. FBD013."); m->mothurOutEndLine();  }
248
249                         chimera = new Ccode(fastaFileNames[s], templatefile, filter, maskfile, window, numwanted, outputDir);   
250                         
251                         //is your template aligned?
252                         if (chimera->getUnaligned()) { m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); delete chimera; return 0; }
253                         templateSeqsLength = chimera->getLength();
254                         
255                         if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]);  }//if user entered a file with a path then preserve it
256                         string outputFileName, accnosFileName;
257                         if (maskfile != "") {
258                                 outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + maskfile + ".ccode.chimeras";
259                                 accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + maskfile + ".ccode.accnos";
260                         }else {
261                                 outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "ccode.chimeras";
262                                 accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "ccode.accnos";
263                         }
264
265                         string mapInfo = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "mapinfo";
266                         
267                         if (m->control_pressed) { delete chimera;  for (int j = 0; j < outputNames.size(); j++) {       remove(outputNames[j].c_str()); } outputTypes.clear(); return 0;        }
268                         
269                 #ifdef USE_MPI
270                 
271                                 int pid, end, numSeqsPerProcessor; 
272                                 int tag = 2001;
273                                 vector<unsigned long int> MPIPos;
274                                                                 
275                                 MPI_Status status; 
276                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
277                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
278
279                                 MPI_File inMPI;
280                                 MPI_File outMPI;
281                                 MPI_File outMPIAccnos;
282                                 
283                                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
284                                 int inMode=MPI_MODE_RDONLY; 
285                                 
286                                 char outFilename[1024];
287                                 strcpy(outFilename, outputFileName.c_str());
288                                 
289                                 char outAccnosFilename[1024];
290                                 strcpy(outAccnosFilename, accnosFileName.c_str());
291                                 
292                                 char inFileName[1024];
293                                 strcpy(inFileName, fastaFileNames[s].c_str());
294
295                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
296                                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
297                                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
298
299                                 if (m->control_pressed) {  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()); } outputTypes.clear();  delete chimera; return 0;  }
300                         
301                                 if (pid == 0) { //you are the root process 
302                                         string outTemp = "For full window mapping info refer to " + mapInfo + "\n\n";
303                                         
304                                         //print header
305                                         int length = outTemp.length();
306                                         char* buf2 = new char[length];
307                                         memcpy(buf2, outTemp.c_str(), length);
308
309                                         MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
310                                         delete buf2;
311
312                                         MPIPos = m->setFilePosFasta(fastaFileNames[s], numSeqs); //fills MPIPos, returns numSeqs
313                                         
314                                         //send file positions to all processes
315                                         for(int i = 1; i < processors; i++) { 
316                                                 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
317                                                 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
318                                         }
319                                         
320                                         //figure out how many sequences you have to align
321                                         numSeqsPerProcessor = numSeqs / processors;
322                                         int startIndex =  pid * numSeqsPerProcessor;
323                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
324                                         
325                                 
326                                         //align your part
327                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, MPIPos);
328                                         
329                                         if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI);   MPI_File_close(&outMPIAccnos);  remove(outputFileName.c_str());  remove(accnosFileName.c_str());  for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } outputTypes.clear();  delete chimera; return 0;  }
330
331                                 }else{ //you are a child process
332                                         MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
333                                         MPIPos.resize(numSeqs+1);
334                                         MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
335                                         
336                                         //figure out how many sequences you have to align
337                                         numSeqsPerProcessor = numSeqs / processors;
338                                         int startIndex =  pid * numSeqsPerProcessor;
339                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
340                                         
341                                         
342                                         //align your part
343                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, MPIPos);
344                                         
345                                         if (m->control_pressed) {  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()); }  outputTypes.clear(); delete chimera; return 0;  }
346                                 }
347                                 
348                                 //close files 
349                                 MPI_File_close(&inMPI);
350                                 MPI_File_close(&outMPI);
351                                 MPI_File_close(&outMPIAccnos);
352                                 
353                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
354                                         
355                 #else
356                         ofstream outHeader;
357                         string tempHeader = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + maskfile + "ccode.chimeras.tempHeader";
358                         m->openOutputFile(tempHeader, outHeader);
359                         
360                         outHeader << "For full window mapping info refer to " << mapInfo << endl << endl;
361
362                         outHeader.close();
363                         
364                         vector<unsigned long int> positions = m->divideFile(fastaFileNames[s], processors);
365                                 
366                         for (int i = 0; i < (positions.size()-1); i++) {
367                                 lines.push_back(new linePair(positions[i], positions[(i+1)]));
368                         }       
369                         
370                         //break up file
371                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
372                                 if(processors == 1){
373                                                                                 
374                                         numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName);
375                                         
376                                         if (m->control_pressed) { 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];  } outputTypes.clear();  lines.clear(); delete chimera; return 0; }
377                                         
378                                 }else{
379                                         processIDS.resize(0);
380                                         
381                                         numSeqs = createProcesses(outputFileName, fastaFileNames[s], accnosFileName); 
382                                 
383                                         rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
384                                         rename((accnosFileName + toString(processIDS[0]) + ".temp").c_str(), accnosFileName.c_str());
385                                                 
386                                         //append output files
387                                         for(int i=1;i<processors;i++){
388                                                 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
389                                                 remove((outputFileName + toString(processIDS[i]) + ".temp").c_str());
390                                         }
391                                         
392                                         //append output files
393                                         for(int i=1;i<processors;i++){
394                                                 m->appendFiles((accnosFileName + toString(processIDS[i]) + ".temp"), accnosFileName);
395                                                 remove((accnosFileName + toString(processIDS[i]) + ".temp").c_str());
396                                         }
397                                         
398                                         if (m->control_pressed) { 
399                                                 remove(outputFileName.c_str()); 
400                                                 remove(accnosFileName.c_str());
401                                                 for (int j = 0; j < outputNames.size(); j++) {  remove(outputNames[j].c_str()); } outputTypes.clear();
402                                                 for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
403                                                 delete chimera;
404                                                 return 0;
405                                         }
406
407                                 }
408
409                         #else
410                                 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName);
411                                 
412                                 if (m->control_pressed) { 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];  } outputTypes.clear();  lines.clear(); delete chimera; return 0; }
413                                 
414                         #endif
415         
416                         m->appendFiles(outputFileName, tempHeader);
417                 
418                         remove(outputFileName.c_str());
419                         rename(tempHeader.c_str(), outputFileName.c_str());
420                 #endif
421                 
422                         delete chimera;
423                         
424                         outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
425                         outputNames.push_back(mapInfo); outputTypes["mapinfo"].push_back(mapInfo);
426                         outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
427                          
428                         for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
429                         
430                         m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
431                 }
432                 
433                 m->mothurOutEndLine();
434                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
435                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
436                 m->mothurOutEndLine();
437                 
438                 return 0;
439                 
440         }
441         catch(exception& e) {
442                 m->errorOut(e, "ChimeraCcodeCommand", "execute");
443                 exit(1);
444         }
445 }
446 //**********************************************************************************************************************
447
448 int ChimeraCcodeCommand::driver(linePair* filePos, string outputFName, string filename, string accnos){
449         try {
450                 ofstream out;
451                 m->openOutputFile(outputFName, out);
452                 
453                 ofstream out2;
454                 m->openOutputFile(accnos, out2);
455                 
456                 ifstream inFASTA;
457                 m->openInputFile(filename, inFASTA);
458
459                 inFASTA.seekg(filePos->start);
460
461                 bool done = false;
462                 int count = 0;
463         
464                 while (!done) {
465                 
466                         if (m->control_pressed) {       return 1;       }
467                 
468                         Sequence* candidateSeq = new Sequence(inFASTA);  m->gobble(inFASTA);
469                                 
470                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
471                                 
472                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
473                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
474                                 }else{
475                                         //find chimeras
476                                         chimera->getChimeras(candidateSeq);
477                                         
478                                         if (m->control_pressed) {       delete candidateSeq; return 1;  }
479                 
480                                         //print results
481                                         chimera->print(out, out2);
482                                 }
483                                 count++;
484                         }
485                         delete candidateSeq;
486                         
487                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
488                                 unsigned long int pos = inFASTA.tellg();
489                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
490                         #else
491                                 if (inFASTA.eof()) { break; }
492                         #endif
493                         
494                         //report progress
495                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
496                 }
497                 //report progress
498                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
499                 
500                 out.close();
501                 out2.close();
502                 inFASTA.close();
503                                 
504                 return count;
505         }
506         catch(exception& e) {
507                 m->errorOut(e, "ChimeraCcodeCommand", "driver");
508                 exit(1);
509         }
510 }
511 //**********************************************************************************************************************
512 #ifdef USE_MPI
513 int ChimeraCcodeCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, vector<unsigned long int>& MPIPos){
514         try {
515                                 
516                 MPI_Status status; 
517                 int pid;
518                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
519                 
520                 for(int i=0;i<num;i++){
521                 
522                         if (m->control_pressed) { return 0; }
523                         
524                         //read next sequence
525                         int length = MPIPos[start+i+1] - MPIPos[start+i];
526         
527                         char* buf4 = new char[length];
528                                 
529                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
530                         
531                         string tempBuf = buf4;
532                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
533                         istringstream iss (tempBuf,istringstream::in);
534                         delete buf4;
535
536                         Sequence* candidateSeq = new Sequence(iss);  m->gobble(iss);
537                                 
538                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
539                                 
540                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
541                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
542                                 }else{
543                                         //find chimeras
544                                         chimera->getChimeras(candidateSeq);
545                                         
546                                         if (m->control_pressed) {       delete candidateSeq; return 1;  }
547                 
548                                         //print results
549                                         bool isChimeric = chimera->print(outMPI, outAccMPI);
550                                 }
551                         }
552                         delete candidateSeq;
553                         
554                         //report progress
555                         if((i+1) % 100 == 0){  cout << "Processing sequence: " << (i+1) << endl;        m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n");          }
556                 }
557                 //report progress
558                 if(num % 100 != 0){             cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n");  }
559                 
560                                 
561                 return 0;
562         }
563         catch(exception& e) {
564                 m->errorOut(e, "ChimeraCcodeCommand", "driverMPI");
565                 exit(1);
566         }
567 }
568 #endif
569
570 /**************************************************************************************************/
571
572 int ChimeraCcodeCommand::createProcesses(string outputFileName, string filename, string accnos) {
573         try {
574 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
575                 int process = 0;
576                 int num = 0;
577                 
578                 //loop through and create all the processes you want
579                 while (process != processors) {
580                         int pid = fork();
581                         
582                         if (pid > 0) {
583                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
584                                 process++;
585                         }else if (pid == 0){
586                                 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp");
587                                 
588                                 //pass numSeqs to parent
589                                 ofstream out;
590                                 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
591                                 m->openOutputFile(tempFile, out);
592                                 out << num << endl;
593                                 out.close();
594
595                                 exit(0);
596                         }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
597                 }
598                 
599                 //force parent to wait until all the processes are done
600                 for (int i=0;i<processors;i++) { 
601                         int temp = processIDS[i];
602                         wait(&temp);
603                 }
604                 
605                 for (int i = 0; i < processIDS.size(); i++) {
606                         ifstream in;
607                         string tempFile =  outputFileName + toString(processIDS[i]) + ".num.temp";
608                         m->openInputFile(tempFile, in);
609                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
610                         in.close(); remove(tempFile.c_str());
611                 }
612                 
613                 return num;
614 #endif          
615         }
616         catch(exception& e) {
617                 m->errorOut(e, "ChimeraCcodeCommand", "createProcesses");
618                 exit(1);
619         }
620 }
621 //**********************************************************************************************************************
622