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