]> git.donarmstrong.com Git - mothur.git/blob - chimeracheckcommand.cpp
added parse.fastaq command, added permute option to venn command, fixed bug with...
[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 = m->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                                 m->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 = m->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 = m->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() + m->getSimpleName(fastaFileNames[i]);
73                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
74                                                         ableToOpen = m->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                                 m->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 = m->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 = m->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() + m->getSimpleName(nameFileNames[i]);
121                                                         m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
122                                                         ableToOpen = m->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 = m->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                         if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[i]);  }//if user entered a file with a path then preserve it
221                         string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[i]))  + "chimeracheck.chimeras";
222                         outputNames.push_back(outputFileName);
223                         
224                 #ifdef USE_MPI
225                 
226                                 int pid, end, numSeqsPerProcessor; 
227                                 int tag = 2001;
228                                 vector<unsigned long int> MPIPos;
229                                 
230                                 MPI_Status status; 
231                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
232                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
233
234                                 MPI_File inMPI;
235                                 MPI_File outMPI;
236                                                         
237                                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
238                                 int inMode=MPI_MODE_RDONLY; 
239                                                         
240                                 char outFilename[1024];
241                                 strcpy(outFilename, outputFileName.c_str());
242                         
243                                 char inFileName[1024];
244                                 strcpy(inFileName, fastaFileNames[i].c_str());
245
246                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
247                                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
248                                 
249                                 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;  }
250                                 
251                                 if (pid == 0) { //you are the root process 
252                                         MPIPos = m->setFilePosFasta(fastaFileNames[i], numSeqs); //fills MPIPos, returns numSeqs
253                                         
254                                         //send file positions to all processes
255                                         for(int j = 1; j < processors; j++) { 
256                                                 MPI_Send(&numSeqs, 1, MPI_INT, j, tag, MPI_COMM_WORLD);
257                                                 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, j, tag, MPI_COMM_WORLD);
258                                         }       
259                                         
260                                         //figure out how many sequences you have to align
261                                         numSeqsPerProcessor = numSeqs / processors;
262                                         int startIndex =  pid * numSeqsPerProcessor;
263                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
264                                         
265                                 
266                                         //align your part
267                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, MPIPos);
268                                         
269                                         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;  }
270                                         
271                                         //wait on chidren
272                                         for(int j = 1; j < processors; j++) { 
273                                                 char buf[4];
274                                                 MPI_Recv(buf, 4, MPI_CHAR, j, tag, MPI_COMM_WORLD, &status); 
275                                         }
276                                 }else{ //you are a child process
277                                         MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
278                                         MPIPos.resize(numSeqs+1);
279                                         MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
280                                         
281                                         //figure out how many sequences you have to align
282                                         numSeqsPerProcessor = numSeqs / processors;
283                                         int startIndex =  pid * numSeqsPerProcessor;
284                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
285                                         
286                                         //align your part
287                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, MPIPos);
288                                         
289                                         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;  }
290                                         
291                                         //tell parent you are done.
292                                         char buf[4];
293                                         strcpy(buf, "done"); 
294                                         MPI_Send(buf, 4, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
295                                 }
296                                 
297                                 //close files 
298                                 MPI_File_close(&inMPI);
299                                 MPI_File_close(&outMPI);
300                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
301                 #else
302                         
303                         vector<unsigned long int> positions = m->divideFile(fastaFileNames[i], processors);
304                                 
305                         for (int s = 0; s < (positions.size()-1); s++) {
306                                 lines.push_back(new linePair(positions[s], positions[(s+1)]));
307                         }       
308                         
309                         //break up file
310                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
311                                 if(processors == 1){
312                                         numSeqs = driver(lines[0], outputFileName, fastaFileNames[i]);
313                                         
314                                         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; }
315                                                                         
316                                 }else{
317                                         processIDS.resize(0);
318                                         
319                                         numSeqs = createProcesses(outputFileName, fastaFileNames[i]); 
320                                 
321                                         rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
322                                                 
323                                         //append output files
324                                         for(int j=1;j<processors;j++){
325                                                 m->appendFiles((outputFileName + toString(processIDS[j]) + ".temp"), outputFileName);
326                                                 remove((outputFileName + toString(processIDS[j]) + ".temp").c_str());
327                                         }
328                                         
329                                         if (m->control_pressed) { 
330                                                 for (int j = 0; j < outputNames.size(); j++) {  remove(outputNames[j].c_str()); } 
331                                                 for (int j = 0; j < lines.size(); j++) {  delete lines[j];  }  lines.clear();
332                                                 delete chimera;
333                                                 return 0;
334                                         }
335                                 }
336
337                         #else
338                                 numSeqs = driver(lines[0], outputFileName, fastaFileNames[i]);
339                                 
340                                 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; }
341                         #endif
342                 #endif          
343                         delete chimera;
344                         for (int j = 0; j < lines.size(); j++) {  delete lines[j];  }  lines.clear();
345                         
346                         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(); 
347                         m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
348
349                 }
350                 
351                 m->mothurOutEndLine();
352                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
353                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
354                 m->mothurOutEndLine();
355         
356                 return 0;
357                 
358         }
359         catch(exception& e) {
360                 m->errorOut(e, "ChimeraCheckCommand", "execute");
361                 exit(1);
362         }
363 }
364 //**********************************************************************************************************************
365
366 int ChimeraCheckCommand::driver(linePair* filePos, string outputFName, string filename){
367         try {
368                 ofstream out;
369                 m->openOutputFile(outputFName, out);
370                 
371                 ofstream out2;
372                 
373                 ifstream inFASTA;
374                 m->openInputFile(filename, inFASTA);
375
376                 inFASTA.seekg(filePos->start);
377
378                 bool done = false;
379                 int count = 0;
380         
381                 while (!done) {
382
383                         if (m->control_pressed) {       return 1;       }
384                 
385                         Sequence* candidateSeq = new Sequence(inFASTA);  m->gobble(inFASTA);
386                                 
387                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
388                                 //find chimeras
389                                 chimera->getChimeras(candidateSeq);
390                                 
391                                 if (m->control_pressed) {       delete candidateSeq; return 1;  }
392         
393                                 //print results
394                                 chimera->print(out, out2);
395                         }
396                         delete candidateSeq;
397                         
398                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
399                                 unsigned long int pos = inFASTA.tellg();
400                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
401                         #else
402                                 if (inFASTA.eof()) { break; }
403                         #endif
404                         
405                         //report progress
406                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
407                 }
408                 //report progress
409                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
410                 
411                 out.close();
412                 inFASTA.close();
413                                 
414                 return count;
415         }
416         catch(exception& e) {
417                 m->errorOut(e, "ChimeraCheckCommand", "driver");
418                 exit(1);
419         }
420 }
421 //**********************************************************************************************************************
422 #ifdef USE_MPI
423 int ChimeraCheckCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, vector<unsigned long int>& MPIPos){
424         try {
425                 MPI_File outAccMPI;
426                 MPI_Status status; 
427                 int pid;
428                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
429                 
430                 for(int i=0;i<num;i++){
431                         
432                         if (m->control_pressed) { return 0; }
433                         
434                         //read next sequence
435                         int length = MPIPos[start+i+1] - MPIPos[start+i];
436         
437                         char* buf4 = new char[length];
438                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
439                         
440                         string tempBuf = buf4;
441                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
442                         istringstream iss (tempBuf,istringstream::in);
443                         delete buf4;
444
445                         Sequence* candidateSeq = new Sequence(iss);  m->gobble(iss);
446                                 
447                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
448                                 //find chimeras
449                                 chimera->getChimeras(candidateSeq);
450                                         
451                                 //print results
452                                 chimera->print(outMPI, outAccMPI);
453                         }
454                         delete candidateSeq;
455                         
456                         //report progress
457                         if((i+1) % 100 == 0){  cout << "Processing sequence: " << (i+1) << endl;        m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n");          }
458                 }
459                 //report progress
460                 if(num % 100 != 0){             cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n");  }
461                 
462                 return 0;
463         }
464         catch(exception& e) {
465                 m->errorOut(e, "ChimeraCheckCommand", "driverMPI");
466                 exit(1);
467         }
468 }
469 #endif
470
471 /**************************************************************************************************/
472
473 int ChimeraCheckCommand::createProcesses(string outputFileName, string filename) {
474         try {
475 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
476                 int process = 0;
477                 int num = 0;
478                 
479                 //loop through and create all the processes you want
480                 while (process != processors) {
481                         int pid = fork();
482                         
483                         if (pid > 0) {
484                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
485                                 process++;
486                         }else if (pid == 0){
487                                 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename);
488                                 
489                                 //pass numSeqs to parent
490                                 ofstream out;
491                                 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
492                                 m->openOutputFile(tempFile, out);
493                                 out << num << endl;
494                                 out.close();
495                                 
496                                 exit(0);
497                         }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
498                 }
499                 
500                 //force parent to wait until all the processes are done
501                 for (int i=0;i<processors;i++) { 
502                         int temp = processIDS[i];
503                         wait(&temp);
504                 }
505                 
506                 for (int i = 0; i < processIDS.size(); i++) {
507                         ifstream in;
508                         string tempFile =  outputFileName + toString(processIDS[i]) + ".num.temp";
509                         m->openInputFile(tempFile, in);
510                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
511                         in.close(); remove(tempFile.c_str());
512                 }
513                 
514                 return num;
515 #endif          
516         }
517         catch(exception& e) {
518                 m->errorOut(e, "ChimeraCheckCommand", "createProcesses");
519                 exit(1);
520         }
521 }
522 /**************************************************************************************************/
523
524