2 * filterseqscommand.cpp
5 * Created by Thomas Ryabin on 5/4/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
10 #include "filterseqscommand.h"
11 #include "sequence.hpp"
13 /**************************************************************************************/
15 FilterSeqsCommand::FilterSeqsCommand(string option) {
20 //allow user to run help
21 if(option == "help") { help(); abort = true; }
24 //valid paramters for this command
25 string Array[] = {"fasta", "trump", "soft", "hard", "vertical", "outputdir","inputdir", "processors"};
26 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
28 OptionParser parser(option);
29 map<string,string> parameters = parser.getParameters();
31 ValidParameters validParameter;
32 map<string,string>::iterator it;
34 //check to make sure all parameters are valid for command
35 for (it = parameters.begin(); it != parameters.end(); it++) {
36 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
39 //if the user changes the input directory command factory will send this info to us in the output parameter
40 string inputDir = validParameter.validFile(parameters, "inputdir", false);
41 if (inputDir == "not found"){ inputDir = ""; }
44 it = parameters.find("fasta");
45 //user has given a template file
46 if(it != parameters.end()){
47 path = hasPath(it->second);
48 //if the user has not given a path then, add inputdir. else leave path alone.
49 if (path == "") { parameters["fasta"] = inputDir + it->second; }
52 it = parameters.find("hard");
53 //user has given a template file
54 if(it != parameters.end()){
55 path = hasPath(it->second);
56 //if the user has not given a path then, add inputdir. else leave path alone.
57 if (path == "") { parameters["hard"] = inputDir + it->second; }
61 //check for required parameters
62 fasta = validParameter.validFile(parameters, "fasta", false);
63 if (fasta == "not found") { m->mothurOut("fasta is a required parameter for the filter.seqs command."); m->mothurOutEndLine(); abort = true; }
65 splitAtDash(fasta, fastafileNames);
67 //go through files and make sure they are good, if not, then disregard them
68 for (int i = 0; i < fastafileNames.size(); i++) {
70 string path = hasPath(fastafileNames[i]);
71 //if the user has not given a path then, add inputdir. else leave path alone.
72 if (path == "") { fastafileNames[i] = inputDir + fastafileNames[i]; }
77 ableToOpen = openInputFile(fastafileNames[i], in);
78 if (ableToOpen == 1) {
79 m->mothurOut(fastafileNames[i] + " will be disregarded."); m->mothurOutEndLine();
80 //erase from file list
81 fastafileNames.erase(fastafileNames.begin()+i);
84 string simpleName = getSimpleName(fastafileNames[i]);
85 filterFileName += simpleName.substr(0, simpleName.find_first_of('.'));
90 //make sure there is at least one valid file left
91 if (fastafileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
95 //if the user changes the output directory command factory will send this info to us in the output parameter
96 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
98 outputDir += hasPath(fastafileNames[0]); //if user entered a file with a path then preserve it
101 //check for optional parameter and set defaults
102 // ...at some point should added some additional type checking...
105 temp = validParameter.validFile(parameters, "trump", false); if (temp == "not found") { temp = "*"; }
108 temp = validParameter.validFile(parameters, "soft", false); if (temp == "not found") { soft = 0; }
109 else { soft = (float)atoi(temp.c_str()) / 100.0; }
111 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = "1"; }
112 convert(temp, processors);
114 hard = validParameter.validFile(parameters, "hard", true); if (hard == "not found") { hard = ""; }
115 else if (hard == "not open") { abort = true; }
117 vertical = validParameter.validFile(parameters, "vertical", false); if (vertical == "not found") { vertical = "T"; }
124 catch(exception& e) {
125 m->errorOut(e, "FilterSeqsCommand", "FilterSeqsCommand");
130 //**********************************************************************************************************************
132 void FilterSeqsCommand::help(){
136 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
141 m->mothurOut("The filter.seqs command reads a file containing sequences and creates a .filter and .filter.fasta file.\n");
142 m->mothurOut("The filter.seqs command parameters are fasta, trump, soft, hard and vertical. \n");
143 m->mothurOut("The fasta parameter is required. You may enter several fasta files to build the filter from and filter, by separating their names with -'s.\n");
144 m->mothurOut("For example: fasta=abrecovery.fasta-amazon.fasta \n");
145 m->mothurOut("The trump parameter .... The default is ...\n");
146 m->mothurOut("The soft parameter .... The default is ....\n");
147 m->mothurOut("The hard parameter .... The default is ....\n");
148 m->mothurOut("The vertical parameter .... The default is T.\n");
149 m->mothurOut("The filter.seqs command should be in the following format: \n");
150 m->mothurOut("filter.seqs(fasta=yourFastaFile, trump=yourTrump, soft=yourSoft, hard=yourHard, vertical=yourVertical) \n");
151 m->mothurOut("Example filter.seqs(fasta=abrecovery.fasta, trump=..., soft=..., hard=..., vertical=T).\n");
152 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n\n");
159 catch(exception& e) {
160 m->errorOut(e, "FilterSeqsCommand", "help");
165 /**************************************************************************************/
167 int FilterSeqsCommand::execute() {
170 if (abort == true) { return 0; }
171 vector<string> outputNames;
174 openInputFile(fastafileNames[0], inFASTA);
176 Sequence testSeq(inFASTA);
177 alignmentLength = testSeq.getAlignLength();
180 ////////////create filter/////////////////
182 filter = createFilter();
186 string filterFile = outputDir + filterFileName + ".filter";
187 openOutputFile(filterFile, outFilter);
188 outFilter << filter << endl;
190 outputNames.push_back(filterFile);
193 ////////////run filter/////////////////
196 for (int i = 0; i < fastafileNames.size(); i++) {
198 openInputFile(fastafileNames[i], in);
199 string filteredFasta = outputDir + getRootName(getSimpleName(fastafileNames[i])) + "filter.fasta";
201 openOutputFile(filteredFasta, outFASTA);
202 outputNames.push_back(filteredFasta);
206 if (m->control_pressed) { in.close(); outFASTA.close(); for(int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
209 if (seq.getName() != "") {
210 string align = seq.getAligned();
211 string filterSeq = "";
213 for(int j=0;j<alignmentLength;j++){
214 if(filter[j] == '1'){
215 filterSeq += align[j];
219 outFASTA << '>' << seq.getName() << endl << filterSeq << endl;
228 int filteredLength = 0;
229 for(int i=0;i<alignmentLength;i++){
230 if(filter[i] == '1'){ filteredLength++; }
233 if (m->control_pressed) { for(int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
237 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
242 m->mothurOutEndLine();
243 m->mothurOut("Length of filtered alignment: " + toString(filteredLength)); m->mothurOutEndLine();
244 m->mothurOut("Number of columns removed: " + toString((alignmentLength-filteredLength))); m->mothurOutEndLine();
245 m->mothurOut("Length of the original alignment: " + toString(alignmentLength)); m->mothurOutEndLine();
246 m->mothurOut("Number of sequences used to construct filter: " + toString(numSeqs)); m->mothurOutEndLine();
249 m->mothurOutEndLine();
250 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
251 for(int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
252 m->mothurOutEndLine();
261 catch(exception& e) {
262 m->errorOut(e, "FilterSeqsCommand", "execute");
266 /**************************************************************************************/
267 string FilterSeqsCommand::createFilter() {
269 string filterString = "";
273 if (soft != 0) { F.setSoft(soft); }
274 if (trump != '*') { F.setTrump(trump); }
276 F.setLength(alignmentLength);
278 if(soft != 0 || isTrue(vertical)){
282 if(hard.compare("") != 0) { F.doHard(hard); }
283 else { F.setFilter(string(alignmentLength, '1')); }
287 if(trump != '*' || isTrue(vertical) || soft != 0){
288 for (int s = 0; s < fastafileNames.size(); s++) {
290 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
295 int Atag = 1; int Ttag = 2; int Ctag = 3; int Gtag = 4; int Gaptag = 5;
299 rc = MPI_Comm_size(MPI_COMM_WORLD, &processors);
300 rc = MPI_Comm_rank(MPI_COMM_WORLD, &pid);
303 char* tempFileName = &(fastafileNames[s][0]);
304 MPI_File_open(MPI_COMM_WORLD, tempFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &in); //comm, filename, mode, info, filepointer
306 if (pid == 0) { //you are the root process
307 setLines(fastafileNames[s]);
309 for (int j = 0; j < lines.size(); j++) { //each process
310 if (j != 0) { //don't send to yourself
311 MPI_Send(&lines[j]->start, 1, MPI_INT, j, 2001, MPI_COMM_WORLD); //start position in file
312 MPI_Send(&lines[j]->numSeqs, 1, MPI_INT, j, 2001, MPI_COMM_WORLD); //how many sequences we are sending
313 MPI_Send(&bufferSizes[j], 1, MPI_INT, j, 2001, MPI_COMM_WORLD); //how bytes for the read
316 cout << "done sending" << endl;
317 cout << "parent = " << pid << " lines = " << lines[pid]->start << '\t' << lines[pid]->numSeqs << " size = " << lines.size() << endl;
319 buf = new char(bufferSizes[0]);
320 cout << pid << '\t' << bufferSizes[0] << " line 1 start pos = " << lines[1]->start << " buffer size 0 " << bufferSizes[0] << " buffer size 1 " << bufferSizes[1] << endl;
321 MPI_File_read_at(in, 0, buf, bufferSizes[0], MPI_CHAR, &status);
323 cout << pid << " done reading " << endl;
324 string tempBuf = buf;
325 cout << pid << '\t' << (tempBuf.substr(0, 10)) << endl;
327 MPICreateFilter(F, tempBuf);
329 vector<int> temp; temp.resize(numSeqs);
331 //get the frequencies from the child processes
332 for(int i = 0; i < ((processors-1)*5); i++) {
333 cout << "i = " << i << endl;
334 int ierr = MPI_Recv(&temp, numSeqs, MPI_INT, MPI_ANY_SOURCE, 2001, MPI_COMM_WORLD, &status);
336 int receiveTag = temp[temp.size()-1]; //child process added a int to the end to indicate what letter count this is for
338 int sender = status.MPI_SOURCE;
340 if (receiveTag == Atag) { //you are recieveing the A frequencies
341 for (int k = 0; k < alignmentLength; k++) { F.a[k] += temp[k]; }
342 }else if (receiveTag == Ttag) { //you are recieveing the T frequencies
343 for (int k = 0; k < alignmentLength; k++) { F.t[k] += temp[k]; }
344 }else if (receiveTag == Ctag) { //you are recieveing the C frequencies
345 for (int k = 0; k < alignmentLength; k++) { F.c[k] += temp[k]; }
346 }else if (receiveTag == Gtag) { //you are recieveing the G frequencies
347 for (int k = 0; k < alignmentLength; k++) { F.g[k] += temp[k]; }
348 }else if (receiveTag == Gaptag) { //you are recieveing the gap frequencies
349 for (int k = 0; k < alignmentLength; k++) { F.gap[k] += temp[k]; }
352 m->mothurOut("receive tag = " + toString(receiveTag) + " " + toString(sender) + " is complete."); m->mothurOutEndLine();
356 }else { //i am the child process
357 int startPos, numLines, bufferSize;
358 cout << "child = " << pid << endl;
359 ierr = MPI_Recv(&startPos, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
360 ierr = MPI_Recv(&numLines, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
361 ierr = MPI_Recv(&bufferSize, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
362 cout << "child = " << pid << " done recv messages startpos = " << startPos << " numLines = " << numLines << " buffersize = " << bufferSize << endl;
366 char* buf2 = new char(bufferSize);
367 MPI_File_read_at( in, startPos, buf2, bufferSize, MPI_CHAR, &status);
368 cout << pid << " done reading " << endl;
370 string tempBuf = buf2;
371 cout << pid << '\t' << (tempBuf.substr(0, 10)) << endl;
372 MPICreateFilter(F, tempBuf);
374 //send my fequency counts
376 int ierr = MPI_Send( &F.a[0], alignmentLength, MPI_INT, 0, 2001, MPI_COMM_WORLD);
378 ierr = MPI_Send( &F.t[0], alignmentLength, MPI_INT, 0, 2001, MPI_COMM_WORLD);
380 ierr = MPI_Send( &F.c[0], alignmentLength, MPI_INT, 0, 2001, MPI_COMM_WORLD);
382 ierr = MPI_Send( &F.g[0], alignmentLength, MPI_INT, 0, 2001, MPI_COMM_WORLD);
383 F.gap.push_back(Gaptag);
384 ierr = MPI_Send( &F.gap[0], alignmentLength, MPI_INT, 0, 2001, MPI_COMM_WORLD);
386 cout << "child " << pid << " done sending counts" << endl;
389 MPI_Barrier(MPI_COMM_WORLD);
392 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
395 openInputFile(fastafileNames[s], inFASTA);
396 int numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
399 numSeqs += numFastaSeqs;
401 lines.push_back(new linePair(0, numFastaSeqs));
403 driverCreateFilter(F, fastafileNames[s], lines[0]);
406 setLines(fastafileNames[s]);
407 createProcessesCreateFilter(F, fastafileNames[s]);
411 openInputFile(fastafileNames[s], inFASTA);
412 int numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
415 numSeqs += numFastaSeqs;
417 lines.push_back(new linePair(0, numFastaSeqs));
419 driverCreateFilter(F, lines[0], fastafileNames[s]);
428 //merge all frequency data and create filter string
430 //MPI_Comm_rank(MPI_COMM_WORLD, &pid);
432 //if (pid == 0) { //only one process should output to screen
435 cout << "made it here" << endl;
436 F.setNumSeqs(numSeqs);
438 if(isTrue(vertical) == 1) { F.doVertical(); }
439 if(soft != 0) { F.doSoft(); }
440 //cout << "Filter String = " << F.getFilter() << endl;
441 filterString = F.getFilter();
445 catch(exception& e) {
446 m->errorOut(e, "FilterSeqsCommand", "createFilter");
450 /**************************************************************************************/
451 int FilterSeqsCommand::driverCreateFilter(Filters& F, string filename, linePair* line) {
455 openInputFile(filename, in);
457 in.seekg(line->start);
459 for(int i=0;i<line->numSeqs;i++){
461 if (m->control_pressed) { in.close(); return 1; }
464 if (seq.getName() != "") {
465 if(trump != '*'){ F.doTrump(seq); }
466 if(isTrue(vertical) || soft != 0){ F.getFreqs(seq); }
471 if((i+1) % 100 == 0){ m->mothurOut(toString(i+1)); m->mothurOutEndLine(); }
475 if((line->numSeqs) % 100 != 0){ m->mothurOut(toString(line->numSeqs)); m->mothurOutEndLine(); }
481 catch(exception& e) {
482 m->errorOut(e, "FilterSeqsCommand", "driverCreateFilter");
486 /**************************************************************************************/
487 int FilterSeqsCommand::MPICreateFilter(Filters& F, string temp) {
490 vector<string> seqStrings;
491 parseBuffer(temp, seqStrings);
493 for(int i=0;i<seqStrings.size();i++){
495 if (m->control_pressed) { return 1; }
497 Sequence seq("", seqStrings[0]);
499 if(trump != '*'){ F.doTrump(seq); }
500 if(isTrue(vertical) || soft != 0){ F.getFreqs(seq); }
504 if((i+1) % 100 == 0){ m->mothurOut(toString(i+1)); m->mothurOutEndLine(); }
508 if((seqStrings.size()) % 100 != 0){ m->mothurOut(toString(seqStrings.size())); m->mothurOutEndLine(); }
512 catch(exception& e) {
513 m->errorOut(e, "FilterSeqsCommand", "MPICreateFilter");
518 /**************************************************************************************************/
520 int FilterSeqsCommand::createProcessesCreateFilter(Filters& F, string filename) {
522 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
525 vector<int> processIDS;
527 //loop through and create all the processes you want
528 while (process != processors) {
532 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
535 driverCreateFilter(F, filename, lines[process]);
537 }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
540 //force parent to wait until all the processes are done
541 for (int i=0;i<processors;i++) {
542 int temp = processIDS[i];
549 catch(exception& e) {
550 m->errorOut(e, "FilterSeqsCommand", "createProcessesCreateFilter");
554 /**************************************************************************************************/
556 int FilterSeqsCommand::setLines(string filename) {
558 vector<int> positions;
563 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
566 openInputFile(filename, inFASTA);
570 while(!inFASTA.eof()){
571 input = getline(inFASTA);
573 if (input.length() != 0) {
574 numbuf += input.length();
575 if(input[0] == '>'){ long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1); buf[(pos - input.length() - 1)] = numbuf; }
581 int numFastaSeqs = positions.size();
583 numSeqs += numFastaSeqs;
585 int numSeqsPerProcessor = numFastaSeqs / processors;
587 for (int i = 0; i < processors; i++) {
589 long int startPos = positions[ i * numSeqsPerProcessor ];
590 if(i == processors - 1){
591 numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;
592 bufferSizes.push_back(numbuf-buf[startPos]);
594 int myEnd = positions[ (i+1) * numSeqsPerProcessor ];
595 bufferSizes.push_back(buf[myEnd]-buf[startPos]);
597 lines.push_back(new linePair(startPos, numSeqsPerProcessor));
602 catch(exception& e) {
603 m->errorOut(e, "FilterSeqsCommand", "setLines");
607 /**************************************************************************************************/
608 int FilterSeqsCommand::parseBuffer(string file, vector<string>& seqs) {
611 istringstream iss (file,istringstream::in);
612 string name, seqstring;
616 if (m->control_pressed) { return 0; }
617 cout << "here" << endl;
619 cout << "here1" << endl;
621 cout << seq.getName() << endl;
622 if (seq.getName() != "") {
623 seqs.push_back(seq.getAligned());
629 catch(exception& e) {
630 m->errorOut(e, "FilterSeqsCommand", "parseBuffer");
634 /**************************************************************************************/