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