]> git.donarmstrong.com Git - mothur.git/blob - chimeracheckcommand.cpp
changed how we break up the files on parallelized commands to avoid scanning file.
[mothur.git] / chimeracheckcommand.cpp
1 /*
2  *  chimeracheckcommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 3/31/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "chimeracheckcommand.h"
11
12 //***************************************************************************************************************
13
14 ChimeraCheckCommand::ChimeraCheckCommand(string option)  {
15         try {
16                 abort = false;
17                 
18                 //allow user to run help
19                 if(option == "help") { help(); abort = true; }
20                 
21                 else {
22                         //valid paramters for this command
23                         string Array[] =  {"fasta","processors","increment","template","ksize","svg", "name","outputdir","inputdir" };
24                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
25                         
26                         OptionParser parser(option);
27                         map<string,string> parameters = parser.getParameters();
28                         
29                         ValidParameters validParameter("chimera.check");
30                         map<string,string>::iterator it;
31                         
32                         //check to make sure all parameters are valid for command
33                         for (it = parameters.begin(); it != parameters.end(); it++) { 
34                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
35                         }
36                         
37                         //if the user changes the input directory command factory will send this info to us in the output parameter 
38                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
39                         if (inputDir == "not found"){   inputDir = "";          }
40                         else {
41                                 it = parameters.find("template");
42                                 //user has given a template file
43                                 if(it != parameters.end()){ 
44                                         string path = hasPath(it->second);
45                                         //if the user has not given a path then, add inputdir. else leave path alone.
46                                         if (path == "") {       parameters["template"] = inputDir + it->second;         }
47                                 }
48                         }
49                         
50                         //check for required parameters
51                         fastafile = validParameter.validFile(parameters, "fasta", false);
52                         if (fastafile == "not found") { fastafile = ""; m->mothurOut("fasta is a required parameter for the chimera.check command."); m->mothurOutEndLine(); abort = true;  }
53                         else { 
54                                 splitAtDash(fastafile, fastaFileNames);
55                                 
56                                 //go through files and make sure they are good, if not, then disregard them
57                                 for (int i = 0; i < fastaFileNames.size(); i++) {
58                                         if (inputDir != "") {
59                                                 string path = hasPath(fastaFileNames[i]);
60                                                 //if the user has not given a path then, add inputdir. else leave path alone.
61                                                 if (path == "") {       fastaFileNames[i] = inputDir + fastaFileNames[i];               }
62                                         }
63         
64                                         int ableToOpen;
65                                         ifstream in;
66                                         
67                                         ableToOpen = openInputFile(fastaFileNames[i], in, "noerror");
68                                 
69                                         //if you can't open it, try default location
70                                         if (ableToOpen == 1) {
71                                                 if (m->getDefaultPath() != "") { //default path is set
72                                                         string tryPath = m->getDefaultPath() + getSimpleName(fastaFileNames[i]);
73                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
74                                                         ableToOpen = openInputFile(tryPath, in, "noerror");
75                                                         fastaFileNames[i] = tryPath;
76                                                 }
77                                         }
78                                         in.close();
79                                         
80                                         if (ableToOpen == 1) { 
81                                                 m->mothurOut("Unable to open " + fastaFileNames[i] +". It will be disregarded."); m->mothurOutEndLine(); 
82                                                 //erase from file list
83                                                 fastaFileNames.erase(fastaFileNames.begin()+i);
84                                                 i--;
85                                         }
86                                 }
87                                 
88                                 //make sure there is at least one valid file left
89                                 if (fastaFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
90                         }
91                         
92                         //if the user changes the output directory command factory will send this info to us in the output parameter 
93                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
94
95                         templatefile = validParameter.validFile(parameters, "template", true);
96                         if (templatefile == "not open") { abort = true; }
97                         else if (templatefile == "not found") { templatefile = "";  m->mothurOut("template is a required parameter for the chimera.check command."); m->mothurOutEndLine(); abort = true;  }    
98                         
99                         namefile = validParameter.validFile(parameters, "name", false);
100                         if (namefile == "not found") { namefile = ""; }
101                         else { 
102                                 splitAtDash(namefile, nameFileNames);
103                                 
104                                 //go through files and make sure they are good, if not, then disregard them
105                                 for (int i = 0; i < nameFileNames.size(); i++) {
106                                         if (inputDir != "") {
107                                                 string path = hasPath(nameFileNames[i]);
108                                                 //if the user has not given a path then, add inputdir. else leave path alone.
109                                                 if (path == "") {       nameFileNames[i] = inputDir + nameFileNames[i];         }
110                                         }
111         
112                                         int ableToOpen;
113                                         ifstream in;
114                                         
115                                         ableToOpen = openInputFile(nameFileNames[i], in, "noerror");
116                                 
117                                         //if you can't open it, try default location
118                                         if (ableToOpen == 1) {
119                                                 if (m->getDefaultPath() != "") { //default path is set
120                                                         string tryPath = m->getDefaultPath() + getSimpleName(nameFileNames[i]);
121                                                         m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
122                                                         ableToOpen = openInputFile(tryPath, in, "noerror");
123                                                         nameFileNames[i] = tryPath;
124                                                 }
125                                         }
126                                         in.close();
127                                         
128                                         if (ableToOpen == 1) { 
129                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
130                                                 //erase from file list
131                                                 nameFileNames.erase(nameFileNames.begin()+i);
132                                                 i--;
133                                         }
134                                         
135                                 }
136                                 
137                                 //make sure there is at least one valid file left
138                                 if (nameFileNames.size() != 0) {
139                                         if (nameFileNames.size() != fastaFileNames.size()) { 
140                                                  m->mothurOut("Different number of valid name files and fasta files, aborting command."); m->mothurOutEndLine(); 
141                                                  abort = true;
142                                         }
143                                 }
144                         }
145
146                         string temp = validParameter.validFile(parameters, "processors", false);                if (temp == "not found") { temp = "1"; }
147                         convert(temp, processors);
148                         
149                         temp = validParameter.validFile(parameters, "ksize", false);                    if (temp == "not found") { temp = "7"; }
150                         convert(temp, ksize);
151                         
152                         temp = validParameter.validFile(parameters, "svg", false);                              if (temp == "not found") { temp = "F"; }
153                         svg = isTrue(temp);
154                         if (nameFileNames.size() != 0) { svg = true; }
155                         
156                         temp = validParameter.validFile(parameters, "increment", false);                if (temp == "not found") { temp = "10"; }
157                         convert(temp, increment);                       
158                 }
159         }
160         catch(exception& e) {
161                 m->errorOut(e, "ChimeraCheckCommand", "ChimeraCheckCommand");
162                 exit(1);
163         }
164 }
165 //**********************************************************************************************************************
166
167 void ChimeraCheckCommand::help(){
168         try {
169         
170                 m->mothurOut("The chimera.check command reads a fastafile and templatefile and outputs potentially chimeric sequences.\n");
171                 m->mothurOut("This command was created using the algorythms described in CHIMERA_CHECK version 2.7 written by Niels Larsen. \n");
172                 m->mothurOut("The chimera.check command parameters are fasta, template, processors, ksize, increment, svg and name.\n");
173                 m->mothurOut("The fasta parameter allows you to enter the fasta file containing your potentially chimeric sequences, and is required. \n");
174                 m->mothurOut("You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amzon.fasta \n");
175                 m->mothurOut("The template parameter allows you to enter a template file containing known non-chimeric sequences, and is required. \n");
176                 m->mothurOut("The processors parameter allows you to specify how many processors you would like to use.  The default is 1. \n");
177                 #ifdef USE_MPI
178                 m->mothurOut("When using MPI, the processors parameter is set to the number of MPI processes running. \n");
179                 #endif
180                 m->mothurOut("The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default is 10.\n");
181                 m->mothurOut("The ksize parameter allows you to input kmersize, default is 7. \n");
182                 m->mothurOut("The svg parameter allows you to specify whether or not you would like a svg file outputted for each query sequence, default is False.\n");
183                 m->mothurOut("The name parameter allows you to enter a file containing names of sequences you would like .svg files for.\n");
184                 m->mothurOut("You may enter multiple name files by separating their names with dashes. ie. fasta=abrecovery.svg.names-amzon.svg.names \n");
185                 m->mothurOut("The chimera.check command should be in the following format: \n");
186                 m->mothurOut("chimera.check(fasta=yourFastaFile, template=yourTemplateFile, processors=yourProcessors, ksize=yourKmerSize) \n");
187                 m->mothurOut("Example: chimera.check(fasta=AD.fasta, template=core_set_aligned,imputed.fasta, processors=4, ksize=8) \n");
188                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n\n");     
189         }
190         catch(exception& e) {
191                 m->errorOut(e, "ChimeraCheckCommand", "help");
192                 exit(1);
193         }
194 }
195
196 //***************************************************************************************************************
197
198 ChimeraCheckCommand::~ChimeraCheckCommand(){    /*      do nothing      */      }
199
200 //***************************************************************************************************************
201
202 int ChimeraCheckCommand::execute(){
203         try{
204                 
205                 if (abort == true) { return 0; }
206                 
207                 for (int i = 0; i < fastaFileNames.size(); i++) {
208                                 
209                         m->mothurOut("Checking sequences from " + fastaFileNames[i] + " ..." ); m->mothurOutEndLine();
210                         
211                         int start = time(NULL); 
212                         
213                         string thisNameFile = "";
214                         if (nameFileNames.size() != 0) { thisNameFile = nameFileNames[i]; }
215                         
216                         chimera = new ChimeraCheckRDP(fastaFileNames[i], templatefile, thisNameFile, svg, increment, ksize, outputDir);                 
217
218                         if (m->control_pressed) { delete chimera;       return 0;       }
219                         
220                         string outputFileName = outputDir + getRootName(getSimpleName(fastaFileNames[i]))  + "chimeracheck.chimeras";
221                         outputNames.push_back(outputFileName);
222                         
223                 #ifdef USE_MPI
224                 
225                                 int pid, end, numSeqsPerProcessor; 
226                                 int tag = 2001;
227                                 vector<unsigned long int> MPIPos;
228                                 
229                                 MPI_Status status; 
230                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
231                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
232
233                                 MPI_File inMPI;
234                                 MPI_File outMPI;
235                                                         
236                                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
237                                 int inMode=MPI_MODE_RDONLY; 
238                                                         
239                                 char outFilename[1024];
240                                 strcpy(outFilename, outputFileName.c_str());
241                         
242                                 char inFileName[1024];
243                                 strcpy(inFileName, fastaFileNames[i].c_str());
244
245                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
246                                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
247                                 
248                                 if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI);  for (int j = 0; j < outputNames.size(); j++) {    remove(outputNames[j].c_str()); } delete chimera; return 0;  }
249                                 
250                                 if (pid == 0) { //you are the root process 
251                                         MPIPos = setFilePosFasta(fastaFileNames[i], numSeqs); //fills MPIPos, returns numSeqs
252                                         
253                                         //send file positions to all processes
254                                         for(int j = 1; j < processors; j++) { 
255                                                 MPI_Send(&numSeqs, 1, MPI_INT, j, tag, MPI_COMM_WORLD);
256                                                 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, j, tag, MPI_COMM_WORLD);
257                                         }       
258                                         
259                                         //figure out how many sequences you have to align
260                                         numSeqsPerProcessor = numSeqs / processors;
261                                         int startIndex =  pid * numSeqsPerProcessor;
262                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
263                                         
264                                 
265                                         //align your part
266                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, MPIPos);
267                                         
268                                         if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI);  for (int j = 0; j < outputNames.size(); j++) {    remove(outputNames[j].c_str()); }   delete chimera; return 0;  }
269                                         
270                                         //wait on chidren
271                                         for(int j = 1; j < processors; j++) { 
272                                                 char buf[4];
273                                                 MPI_Recv(buf, 4, MPI_CHAR, j, tag, MPI_COMM_WORLD, &status); 
274                                         }
275                                 }else{ //you are a child process
276                                         MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
277                                         MPIPos.resize(numSeqs+1);
278                                         MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
279                                         
280                                         //figure out how many sequences you have to align
281                                         numSeqsPerProcessor = numSeqs / processors;
282                                         int startIndex =  pid * numSeqsPerProcessor;
283                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
284                                         
285                                         //align your part
286                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, MPIPos);
287                                         
288                                         if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI);   for (int j = 0; j < outputNames.size(); j++) {   remove(outputNames[j].c_str()); }  delete chimera; return 0;  }
289                                         
290                                         //tell parent you are done.
291                                         char buf[4];
292                                         strcpy(buf, "done"); 
293                                         MPI_Send(buf, 4, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
294                                 }
295                                 
296                                 //close files 
297                                 MPI_File_close(&inMPI);
298                                 MPI_File_close(&outMPI);
299                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
300                 #else
301                         
302                         vector<unsigned long int> positions = divideFile(fastaFileNames[i], processors);
303                                 
304                         for (int s = 0; s < (positions.size()-1); s++) {
305                                 lines.push_back(new linePair(positions[s], positions[(s+1)]));
306                         }       
307                         
308                         //break up file
309                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
310                                 if(processors == 1){
311                                         numSeqs = driver(lines[0], outputFileName, fastaFileNames[i]);
312                                         
313                                         if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) {        remove(outputNames[j].c_str()); } for (int j = 0; j < lines.size(); j++) {  delete lines[j];  }  lines.clear(); delete chimera; return 0; }
314                                                                         
315                                 }else{
316                                         processIDS.resize(0);
317                                         
318                                         numSeqs = createProcesses(outputFileName, fastaFileNames[i]); 
319                                 
320                                         rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
321                                                 
322                                         //append output files
323                                         for(int j=1;j<processors;j++){
324                                                 appendFiles((outputFileName + toString(processIDS[j]) + ".temp"), outputFileName);
325                                                 remove((outputFileName + toString(processIDS[j]) + ".temp").c_str());
326                                         }
327                                         
328                                         if (m->control_pressed) { 
329                                                 for (int j = 0; j < outputNames.size(); j++) {  remove(outputNames[j].c_str()); } 
330                                                 for (int j = 0; j < lines.size(); j++) {  delete lines[j];  }  lines.clear();
331                                                 delete chimera;
332                                                 return 0;
333                                         }
334                                 }
335
336                         #else
337                                 numSeqs = driver(lines[0], outputFileName, fastaFileNames[i]);
338                                 
339                                 if (m->control_pressed) { for (int j = 0; j < lines.size(); j++) {  delete lines[j];  }  lines.clear(); for (int j = 0; j < outputNames.size(); j++) {  remove(outputNames[j].c_str()); } delete chimera; return 0; }
340                         #endif
341                 #endif          
342                         delete chimera;
343                         for (int j = 0; j < lines.size(); j++) {  delete lines[j];  }  lines.clear();
344                         
345                         m->mothurOutEndLine(); m->mothurOut("This method does not determine if a sequence is chimeric, but allows you to make that determination based on the IS values."); m->mothurOutEndLine(); 
346                         m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
347
348                 }
349                 
350                 m->mothurOutEndLine();
351                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
352                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
353                 m->mothurOutEndLine();
354         
355                 return 0;
356                 
357         }
358         catch(exception& e) {
359                 m->errorOut(e, "ChimeraCheckCommand", "execute");
360                 exit(1);
361         }
362 }
363 //**********************************************************************************************************************
364
365 int ChimeraCheckCommand::driver(linePair* filePos, string outputFName, string filename){
366         try {
367                 ofstream out;
368                 openOutputFile(outputFName, out);
369                 
370                 ofstream out2;
371                 
372                 ifstream inFASTA;
373                 openInputFile(filename, inFASTA);
374
375                 inFASTA.seekg(filePos->start);
376
377                 bool done = false;
378                 int count = 0;
379         
380                 while (!done) {
381
382                         if (m->control_pressed) {       return 1;       }
383                 
384                         Sequence* candidateSeq = new Sequence(inFASTA);  gobble(inFASTA);
385                                 
386                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
387                                 //find chimeras
388                                 chimera->getChimeras(candidateSeq);
389                                 
390                                 if (m->control_pressed) {       delete candidateSeq; return 1;  }
391         
392                                 //print results
393                                 chimera->print(out, out2);
394                         }
395                         delete candidateSeq;
396                         
397                         unsigned long int pos = inFASTA.tellg();
398                         if ((pos == -1) || (pos >= filePos->end)) { break; }
399                         
400                         //report progress
401                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
402                 }
403                 //report progress
404                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
405                 
406                 out.close();
407                 inFASTA.close();
408                                 
409                 return count;
410         }
411         catch(exception& e) {
412                 m->errorOut(e, "ChimeraCheckCommand", "driver");
413                 exit(1);
414         }
415 }
416 //**********************************************************************************************************************
417 #ifdef USE_MPI
418 int ChimeraCheckCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, vector<unsigned long int>& MPIPos){
419         try {
420                 MPI_File outAccMPI;
421                 MPI_Status status; 
422                 int pid;
423                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
424                 
425                 for(int i=0;i<num;i++){
426                         
427                         if (m->control_pressed) { return 0; }
428                         
429                         //read next sequence
430                         int length = MPIPos[start+i+1] - MPIPos[start+i];
431         
432                         char* buf4 = new char[length];
433                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
434                         
435                         string tempBuf = buf4;
436                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
437                         istringstream iss (tempBuf,istringstream::in);
438                         delete buf4;
439
440                         Sequence* candidateSeq = new Sequence(iss);  gobble(iss);
441                                 
442                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
443                                 //find chimeras
444                                 chimera->getChimeras(candidateSeq);
445                                         
446                                 //print results
447                                 chimera->print(outMPI, outAccMPI);
448                         }
449                         delete candidateSeq;
450                         
451                         //report progress
452                         if((i+1) % 100 == 0){  cout << "Processing sequence: " << (i+1) << endl;        m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n");          }
453                 }
454                 //report progress
455                 if(num % 100 != 0){             cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n");  }
456                 
457                 return 0;
458         }
459         catch(exception& e) {
460                 m->errorOut(e, "ChimeraCheckCommand", "driverMPI");
461                 exit(1);
462         }
463 }
464 #endif
465
466 /**************************************************************************************************/
467
468 int ChimeraCheckCommand::createProcesses(string outputFileName, string filename) {
469         try {
470 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
471                 int process = 0;
472                 int num = 0;
473                 
474                 //loop through and create all the processes you want
475                 while (process != processors) {
476                         int pid = fork();
477                         
478                         if (pid > 0) {
479                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
480                                 process++;
481                         }else if (pid == 0){
482                                 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename);
483                                 
484                                 //pass numSeqs to parent
485                                 ofstream out;
486                                 string tempFile = toString(getpid()) + ".temp";
487                                 openOutputFile(tempFile, out);
488                                 out << num << endl;
489                                 out.close();
490                                 
491                                 exit(0);
492                         }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
493                 }
494                 
495                 //force parent to wait until all the processes are done
496                 for (int i=0;i<processors;i++) { 
497                         int temp = processIDS[i];
498                         wait(&temp);
499                 }
500                 
501                 for (int i = 0; i < processIDS.size(); i++) {
502                         ifstream in;
503                         string tempFile =  toString(processIDS[i]) + ".temp";
504                         openInputFile(tempFile, in);
505                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
506                         in.close(); remove(tempFile.c_str());
507                 }
508                 
509                 return num;
510 #endif          
511         }
512         catch(exception& e) {
513                 m->errorOut(e, "ChimeraCheckCommand", "createProcesses");
514                 exit(1);
515         }
516 }
517 /**************************************************************************************************/
518
519