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(){
135 m->mothurOut("The filter.seqs command reads a file containing sequences and creates a .filter and .filter.fasta file.\n");
136 m->mothurOut("The filter.seqs command parameters are fasta, trump, soft, hard and vertical. \n");
137 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");
138 m->mothurOut("For example: fasta=abrecovery.fasta-amazon.fasta \n");
139 m->mothurOut("The trump parameter .... The default is ...\n");
140 m->mothurOut("The soft parameter .... The default is ....\n");
141 m->mothurOut("The hard parameter .... The default is ....\n");
142 m->mothurOut("The vertical parameter .... The default is T.\n");
143 m->mothurOut("The filter.seqs command should be in the following format: \n");
144 m->mothurOut("filter.seqs(fasta=yourFastaFile, trump=yourTrump, soft=yourSoft, hard=yourHard, vertical=yourVertical) \n");
145 m->mothurOut("Example filter.seqs(fasta=abrecovery.fasta, trump=..., soft=..., hard=..., vertical=T).\n");
146 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n\n");
149 catch(exception& e) {
150 m->errorOut(e, "FilterSeqsCommand", "help");
155 /**************************************************************************************/
157 int FilterSeqsCommand::execute() {
160 if (abort == true) { return 0; }
161 vector<string> outputNames;
164 openInputFile(fastafileNames[0], inFASTA);
166 Sequence testSeq(inFASTA);
167 alignmentLength = testSeq.getAlignLength();
170 ////////////create filter/////////////////
172 filter = createFilter();
176 string filterFile = outputDir + filterFileName + ".filter";
177 openOutputFile(filterFile, outFilter);
178 outFilter << filter << endl;
180 outputNames.push_back(filterFile);
183 ////////////run filter/////////////////
186 for (int i = 0; i < fastafileNames.size(); i++) {
188 openInputFile(fastafileNames[i], in);
189 string filteredFasta = outputDir + getRootName(getSimpleName(fastafileNames[i])) + "filter.fasta";
191 openOutputFile(filteredFasta, outFASTA);
192 outputNames.push_back(filteredFasta);
196 if (m->control_pressed) { in.close(); outFASTA.close(); for(int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
199 if (seq.getName() != "") {
200 string align = seq.getAligned();
201 string filterSeq = "";
203 for(int j=0;j<alignmentLength;j++){
204 if(filter[j] == '1'){
205 filterSeq += align[j];
209 outFASTA << '>' << seq.getName() << endl << filterSeq << endl;
218 int filteredLength = 0;
219 for(int i=0;i<alignmentLength;i++){
220 if(filter[i] == '1'){ filteredLength++; }
223 if (m->control_pressed) { for(int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
226 m->mothurOutEndLine();
227 m->mothurOut("Length of filtered alignment: " + toString(filteredLength)); m->mothurOutEndLine();
228 m->mothurOut("Number of columns removed: " + toString((alignmentLength-filteredLength))); m->mothurOutEndLine();
229 m->mothurOut("Length of the original alignment: " + toString(alignmentLength)); m->mothurOutEndLine();
230 m->mothurOut("Number of sequences used to construct filter: " + toString(numSeqs)); m->mothurOutEndLine();
233 m->mothurOutEndLine();
234 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
235 for(int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
236 m->mothurOutEndLine();
241 catch(exception& e) {
242 m->errorOut(e, "FilterSeqsCommand", "execute");
246 /**************************************************************************************/
247 string FilterSeqsCommand::createFilter() {
249 string filterString = "";
253 if (soft != 0) { F.setSoft(soft); }
254 if (trump != '*') { F.setTrump(trump); }
256 F.setLength(alignmentLength);
258 if(soft != 0 || isTrue(vertical)){
262 if(hard.compare("") != 0) { F.doHard(hard); }
263 else { F.setFilter(string(alignmentLength, '1')); }
267 if(trump != '*' || isTrue(vertical) || soft != 0){
268 for (int s = 0; s < fastafileNames.size(); s++) {
270 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
274 int Atag = 1; int Ttag = 2; int Ctag = 3; int Gtag = 4; int Gaptag = 5;
279 rc = MPI_Comm_size(MPI_COMM_WORLD, &processors);
280 rc = MPI_Comm_rank(MPI_COMM_WORLD, &pid);
283 char* tempFileName = new char(fastafileNames[s].length());
284 tempFileName = &(fastafileNames[s][0]);
286 MPI_File_open(MPI_COMM_WORLD, tempFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &in); //comm, filename, mode, info, filepointer
288 if (pid == 0) { //you are the root process
289 setLines(fastafileNames[s]);
291 for (int j = 0; j < lines.size(); j++) { //each process
292 if (j != 0) { //don't send to yourself
293 MPI_Send(&lines[j]->start, 1, MPI_INT, j, tag, MPI_COMM_WORLD); //start position in file
294 MPI_Send(&lines[j]->numSeqs, 1, MPI_INT, j, tag, MPI_COMM_WORLD); //how many sequences we are sending
295 MPI_Send(&bufferSizes[j], 1, MPI_INT, j, tag, MPI_COMM_WORLD); //how bytes for the read
298 //cout << "done sending" << endl;
299 //cout << "parent = " << pid << " lines = " << lines[pid]->start << '\t' << lines[pid]->numSeqs << " size = " << lines.size() << endl;
301 cout << "parent = " << pid << " address of Filter " << &F << " address of FilterString " << &filterString << " address of numSeqs = " << &numSeqs << " address of soft = " << &soft << endl;
303 char* buf = new char(bufferSizes[0]);
304 //cout << pid << '\t' << bufferSizes[0] << " line 1 start pos = " << lines[1]->start << " buffer size 0 " << bufferSizes[0] << " buffer size 1 " << bufferSizes[1] << endl;
305 MPI_File_read_at(in, 0, buf, bufferSizes[0], MPI_CHAR, &status);
307 cout << pid << " done reading " << &buf << endl;
308 string tempBuf = buf;
310 //cout << pid << '\t' << (tempBuf.substr(0, 10)) << endl;
313 istringstream iss (tempBuf,istringstream::in);
314 string name, seqstring;
319 if (m->control_pressed) { return filterString; }
320 cout << "here" << endl;
322 cout << "here1" << endl;
324 cout << seq.getName() << endl;
325 if (seq.getName() != "") {
326 seqs.push_back(seq.getAligned());
331 for(int i=0;i<seqs.size();i++){
333 if (m->control_pressed) { return filterString; }
335 Sequence seq("", seqs[i]);
337 if(trump != '*'){ F.doTrump(seq); }
338 if(isTrue(vertical) || soft != 0){ F.getFreqs(seq); }
342 if((i+1) % 100 == 0){ m->mothurOut(toString(i+1)); m->mothurOutEndLine(); }
346 if((seqs.size()) % 100 != 0){ m->mothurOut(toString(seqs.size())); m->mothurOutEndLine(); }
349 //MPICreateFilter(F, seqs);
351 vector<int> temp; temp.resize(alignmentLength);
353 //get the frequencies from the child processes
354 for(int i = 0; i < ((processors-1)*5); i++) {
355 cout << "i = " << i << endl;
356 int ierr = MPI_Recv(&temp, alignmentLength, MPI_INT, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, &status);
358 int receiveTag = temp[temp.size()-1]; //child process added a int to the end to indicate what letter count this is for
360 int sender = status.MPI_SOURCE;
362 if (receiveTag == Atag) { //you are recieveing the A frequencies
363 for (int k = 0; k < alignmentLength; k++) { F.a[k] += temp[k]; }
364 }else if (receiveTag == Ttag) { //you are recieveing the T frequencies
365 for (int k = 0; k < alignmentLength; k++) { F.t[k] += temp[k]; }
366 }else if (receiveTag == Ctag) { //you are recieveing the C frequencies
367 for (int k = 0; k < alignmentLength; k++) { F.c[k] += temp[k]; }
368 }else if (receiveTag == Gtag) { //you are recieveing the G frequencies
369 for (int k = 0; k < alignmentLength; k++) { F.g[k] += temp[k]; }
370 }else if (receiveTag == Gaptag) { //you are recieveing the gap frequencies
371 for (int k = 0; k < alignmentLength; k++) { F.gap[k] += temp[k]; }
374 m->mothurOut("receive tag = " + toString(receiveTag) + " " + toString(sender) + " is complete."); m->mothurOutEndLine();
378 }else { //i am the child process
379 int startPos, numLines, bufferSize;
380 cout << "child = " << pid << " address of Filter " << &F << " address of FilterString " << &filterString << " address of numSeqs = " << &numSeqs << " address of soft = " << &soft<< endl;
381 ierr = MPI_Recv(&startPos, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
382 ierr = MPI_Recv(&numLines, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
383 ierr = MPI_Recv(&bufferSize, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
384 //cout << "child = " << pid << " done recv messages startpos = " << startPos << " numLines = " << numLines << " buffersize = " << bufferSize << endl;
388 char* buf2 = new char(bufferSize);
389 MPI_File_read_at( in, startPos, buf2, bufferSize, MPI_CHAR, &status);
390 cout << pid << " done reading " << &buf2 << endl;
392 string tempBuf = buf2;
394 // cout << pid << '\t' << (tempBuf.substr(0, 10)) << endl;
395 istringstream iss (tempBuf,istringstream::in);
397 string name, seqstring;
402 if (m->control_pressed) { return filterString; }
403 cout << "here" << endl;
405 cout << "here1" << endl;
407 cout << seq.getName() << endl;
409 if (seq.getName() != "") {
410 seqs.push_back(seq.getAligned());
414 for(int i=0;i<seqs.size();i++){
416 if (m->control_pressed) { return filterString; }
418 Sequence seq("", seqs[i]);
420 if(trump != '*'){ F.doTrump(seq); }
421 if(isTrue(vertical) || soft != 0){ F.getFreqs(seq); }
425 if((i+1) % 100 == 0){ m->mothurOut(toString(i+1)); m->mothurOutEndLine(); }
429 if((seqs.size()) % 100 != 0){ m->mothurOut(toString(seqs.size())); m->mothurOutEndLine(); }
431 //MPICreateFilter(F, seqs);
433 //send my fequency counts
435 int ierr = MPI_Send( &F.a[0], alignmentLength, MPI_INT, 0, tag, MPI_COMM_WORLD);
437 ierr = MPI_Send( &F.t[0], alignmentLength, MPI_INT, 0, tag, MPI_COMM_WORLD);
439 ierr = MPI_Send( &F.c[0], alignmentLength, MPI_INT, 0, tag, MPI_COMM_WORLD);
441 ierr = MPI_Send( &F.g[0], alignmentLength, MPI_INT, 0, tag, MPI_COMM_WORLD);
442 F.gap.push_back(Gaptag);
443 ierr = MPI_Send( &F.gap[0], alignmentLength, MPI_INT, 0, tag, MPI_COMM_WORLD);
445 cout << "child " << pid << " done sending counts" << endl;
448 MPI_Barrier(MPI_COMM_WORLD);
451 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
454 openInputFile(fastafileNames[s], inFASTA);
455 int numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
458 numSeqs += numFastaSeqs;
460 lines.push_back(new linePair(0, numFastaSeqs));
462 driverCreateFilter(F, fastafileNames[s], lines[0]);
465 setLines(fastafileNames[s]);
466 createProcessesCreateFilter(F, fastafileNames[s]);
470 openInputFile(fastafileNames[s], inFASTA);
471 int numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
474 numSeqs += numFastaSeqs;
476 lines.push_back(new linePair(0, numFastaSeqs));
478 driverCreateFilter(F, lines[0], fastafileNames[s]);
487 //merge all frequency data and create filter string
489 //MPI_Comm_rank(MPI_COMM_WORLD, &pid);
491 //if (pid == 0) { //only one process should output to screen
494 cout << "made it here" << endl;
495 F.setNumSeqs(numSeqs);
497 if(isTrue(vertical) == 1) { F.doVertical(); }
498 if(soft != 0) { F.doSoft(); }
499 //cout << "Filter String = " << F.getFilter() << endl;
500 filterString = F.getFilter();
504 catch(exception& e) {
505 m->errorOut(e, "FilterSeqsCommand", "createFilter");
509 /**************************************************************************************/
510 int FilterSeqsCommand::driverCreateFilter(Filters& F, string filename, linePair* line) {
514 openInputFile(filename, in);
516 in.seekg(line->start);
518 for(int i=0;i<line->numSeqs;i++){
520 if (m->control_pressed) { in.close(); return 1; }
523 if (seq.getName() != "") {
524 if(trump != '*'){ F.doTrump(seq); }
525 if(isTrue(vertical) || soft != 0){ F.getFreqs(seq); }
530 if((i+1) % 100 == 0){ m->mothurOut(toString(i+1)); m->mothurOutEndLine(); }
534 if((line->numSeqs) % 100 != 0){ m->mothurOut(toString(line->numSeqs)); m->mothurOutEndLine(); }
540 catch(exception& e) {
541 m->errorOut(e, "FilterSeqsCommand", "driverCreateFilter");
545 /**************************************************************************************/
546 int FilterSeqsCommand::MPICreateFilter(Filters& F, vector<string>& seqStrings) {
549 for(int i=0;i<seqStrings.size();i++){
551 if (m->control_pressed) { return 1; }
553 Sequence seq("", seqStrings[0]);
555 if(trump != '*'){ F.doTrump(seq); }
556 if(isTrue(vertical) || soft != 0){ F.getFreqs(seq); }
560 if((i+1) % 100 == 0){ m->mothurOut(toString(i+1)); m->mothurOutEndLine(); }
564 if((seqStrings.size()) % 100 != 0){ m->mothurOut(toString(seqStrings.size())); m->mothurOutEndLine(); }
568 catch(exception& e) {
569 m->errorOut(e, "FilterSeqsCommand", "MPICreateFilter");
574 /**************************************************************************************************/
576 int FilterSeqsCommand::createProcessesCreateFilter(Filters& F, string filename) {
578 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
581 vector<int> processIDS;
583 //loop through and create all the processes you want
584 while (process != processors) {
588 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
591 driverCreateFilter(F, filename, lines[process]);
593 }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
596 //force parent to wait until all the processes are done
597 for (int i=0;i<processors;i++) {
598 int temp = processIDS[i];
605 catch(exception& e) {
606 m->errorOut(e, "FilterSeqsCommand", "createProcessesCreateFilter");
610 /**************************************************************************************************/
612 int FilterSeqsCommand::setLines(string filename) {
614 vector<int> positions;
619 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
622 openInputFile(filename, inFASTA);
626 while(!inFASTA.eof()){
627 input = getline(inFASTA);
629 if (input.length() != 0) {
630 numbuf += input.length();
631 if(input[0] == '>'){ long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1); buf[(pos - input.length() - 1)] = numbuf; }
637 int numFastaSeqs = positions.size();
639 numSeqs += numFastaSeqs;
641 int numSeqsPerProcessor = numFastaSeqs / processors;
643 for (int i = 0; i < processors; i++) {
645 long int startPos = positions[ i * numSeqsPerProcessor ];
646 if(i == processors - 1){
647 numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;
648 bufferSizes.push_back(numbuf-buf[startPos]);
650 int myEnd = positions[ (i+1) * numSeqsPerProcessor ];
651 bufferSizes.push_back(buf[myEnd]-buf[startPos]);
653 lines.push_back(new linePair(startPos, numSeqsPerProcessor));
658 catch(exception& e) {
659 m->errorOut(e, "FilterSeqsCommand", "setLines");
663 /**************************************************************************************************/
664 int FilterSeqsCommand::parseBuffer(string file, vector<string>& seqs) {
667 istringstream iss (file,istringstream::in);
668 string name, seqstring;
670 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
671 Sequence* seq34 = new Sequence();
672 cout << "address of new sequence " << pid << '\t' << seq34 << endl;
673 cout << "address of seqStrings " << pid << '\t' << &seqs << endl;
677 if (m->control_pressed) { return 0; }
678 cout << "here" << endl;
679 Sequence* seq = new Sequence(iss);
680 cout << "here1" << endl;
682 cout << seq->getName() << endl;
683 if (seq->getName() != "") {
684 seqs.push_back(seq->getAligned());
691 catch(exception& e) {
692 m->errorOut(e, "FilterSeqsCommand", "parseBuffer");
696 /**************************************************************************************/