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
299 char buf[bufferSizes[0]];
300 MPI_File_read_at(in, 0, buf, bufferSizes[0], MPI_CHAR, &status);
302 MPICreateFilter(F, buf);
304 vector<int> temp; temp.resize(alignmentLength+1);
306 //get the frequencies from the child processes
307 for(int i = 0; i < ((processors-1)*5); i++) {
308 cout << "i = " << i << endl;
309 //vector<int> trial; trial.resize(10);
310 //cout << "trials size = " << trial.size() << endl;
311 //int ierr = MPI_Recv(&trial[0], 10, MPI_INT, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, &status);
312 int ierr = MPI_Recv(&temp[0], (alignmentLength+1), MPI_INT, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, &status);
313 cout << "recieved something" << endl;
314 //for (int g = 0; g < trial.size(); g++) { cout << trial[g] << '\t'; } cout << endl;
315 int receiveTag = temp[temp.size()-1]; //child process added a int to the end to indicate what letter count this is for
316 cout << "reciveve tag = " << receiveTag << endl;
317 for (int k = 0; k < alignmentLength; k++) { cout << k << '\t' << temp[k] << endl; }
318 cout << "done " << endl << endl;
320 int sender = status.MPI_SOURCE;
322 if (receiveTag == Atag) { //you are recieveing the A frequencies
323 for (int k = 0; k < alignmentLength; k++) { F.a[k] += temp[k]; }
324 }else if (receiveTag == Ttag) { //you are recieveing the T frequencies
325 for (int k = 0; k < alignmentLength; k++) { F.t[k] += temp[k]; }
326 }else if (receiveTag == Ctag) { //you are recieveing the C frequencies
327 for (int k = 0; k < alignmentLength; k++) { F.c[k] += temp[k]; }
328 }else if (receiveTag == Gtag) { //you are recieveing the G frequencies
329 for (int k = 0; k < alignmentLength; k++) { F.g[k] += temp[k]; }
330 }else if (receiveTag == Gaptag) { //you are recieveing the gap frequencies
331 for (int k = 0; k < alignmentLength; k++) { F.gap[k] += temp[k]; }
334 m->mothurOut("receive tag = " + toString(receiveTag) + " " + toString(sender) + " is complete."); m->mothurOutEndLine();
338 }else { //i am the child process
339 int startPos, numLines, bufferSize;
340 ierr = MPI_Recv(&startPos, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
341 ierr = MPI_Recv(&numLines, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
342 ierr = MPI_Recv(&bufferSize, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
345 char buf2[bufferSize];
346 MPI_File_read_at( in, startPos, buf2, bufferSize, MPI_CHAR, &status);
348 MPICreateFilter(F, buf2);
350 //send my fequency counts
352 int ierr = MPI_Send(&(F.a[0]), (alignmentLength+1), MPI_INT, 0, tag, MPI_COMM_WORLD);
354 ierr = MPI_Send (&(F.t[0]), (alignmentLength+1), MPI_INT, 0, tag, MPI_COMM_WORLD);
356 ierr = MPI_Send(&(F.c[0]), (alignmentLength+1), MPI_INT, 0, tag, MPI_COMM_WORLD);
358 ierr = MPI_Send(&(F.g[0]), (alignmentLength+1), MPI_INT, 0, tag, MPI_COMM_WORLD);
359 F.gap.push_back(Gaptag);
360 ierr = MPI_Send(&(F.gap[0]), (alignmentLength+1), MPI_INT, 0, tag, MPI_COMM_WORLD);
363 MPI_Barrier(MPI_COMM_WORLD);
366 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
369 openInputFile(fastafileNames[s], inFASTA);
370 int numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
373 numSeqs += numFastaSeqs;
375 lines.push_back(new linePair(0, numFastaSeqs));
377 driverCreateFilter(F, fastafileNames[s], lines[0]);
380 setLines(fastafileNames[s]);
381 createProcessesCreateFilter(F, fastafileNames[s]);
385 openInputFile(fastafileNames[s], inFASTA);
386 int numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
389 numSeqs += numFastaSeqs;
391 lines.push_back(new linePair(0, numFastaSeqs));
393 driverCreateFilter(F, lines[0], fastafileNames[s]);
401 cout << "made it here, numSeqs = " << numSeqs << endl;
402 F.setNumSeqs(numSeqs);
404 if(isTrue(vertical) == 1) { F.doVertical(); }
405 if(soft != 0) { F.doSoft(); }
406 //cout << "Filter String = " << F.getFilter() << endl;
407 filterString = F.getFilter();
411 catch(exception& e) {
412 m->errorOut(e, "FilterSeqsCommand", "createFilter");
416 /**************************************************************************************/
417 int FilterSeqsCommand::driverCreateFilter(Filters& F, string filename, linePair* line) {
421 openInputFile(filename, in);
423 in.seekg(line->start);
425 for(int i=0;i<line->numSeqs;i++){
427 if (m->control_pressed) { in.close(); return 1; }
430 if (seq.getName() != "") {
431 if(trump != '*'){ F.doTrump(seq); }
432 if(isTrue(vertical) || soft != 0){ F.getFreqs(seq); }
437 if((i+1) % 100 == 0){ m->mothurOut(toString(i+1)); m->mothurOutEndLine(); }
441 if((line->numSeqs) % 100 != 0){ m->mothurOut(toString(line->numSeqs)); m->mothurOutEndLine(); }
447 catch(exception& e) {
448 m->errorOut(e, "FilterSeqsCommand", "driverCreateFilter");
452 /**************************************************************************************/
453 int FilterSeqsCommand::MPICreateFilter(Filters& F, string input) {
456 vector<string> seqStrings;
457 parseBuffer(input, seqStrings);
459 for(int i=0;i<seqStrings.size();i++){
461 if (m->control_pressed) { return 1; }
463 Sequence seq("", seqStrings[i]);
465 if(trump != '*'){ F.doTrump(seq); }
466 if(isTrue(vertical) || soft != 0){ F.getFreqs(seq); }
470 if((i+1) % 100 == 0){ m->mothurOut(toString(i+1)); m->mothurOutEndLine(); }
474 if((seqStrings.size()) % 100 != 0){ m->mothurOut(toString(seqStrings.size())); m->mothurOutEndLine(); }
478 catch(exception& e) {
479 m->errorOut(e, "FilterSeqsCommand", "MPICreateFilter");
484 /**************************************************************************************************/
486 int FilterSeqsCommand::createProcessesCreateFilter(Filters& F, string filename) {
488 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
491 vector<int> processIDS;
493 //loop through and create all the processes you want
494 while (process != processors) {
498 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
501 driverCreateFilter(F, filename, lines[process]);
503 }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
506 //force parent to wait until all the processes are done
507 for (int i=0;i<processors;i++) {
508 int temp = processIDS[i];
515 catch(exception& e) {
516 m->errorOut(e, "FilterSeqsCommand", "createProcessesCreateFilter");
520 /**************************************************************************************************/
522 int FilterSeqsCommand::setLines(string filename) {
524 vector<int> positions;
529 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
532 openInputFile(filename, inFASTA);
536 while(!inFASTA.eof()){
537 input = getline(inFASTA);
539 if (input.length() != 0) {
540 numbuf += input.length();
541 if(input[0] == '>'){ long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1); buf[(pos - input.length() - 1)] = numbuf; }
547 int numFastaSeqs = positions.size();
549 numSeqs += numFastaSeqs;
551 int numSeqsPerProcessor = numFastaSeqs / processors;
553 for (int i = 0; i < processors; i++) {
555 long int startPos = positions[ i * numSeqsPerProcessor ];
556 if(i == processors - 1){
557 numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;
558 bufferSizes.push_back(numbuf-buf[startPos]);
560 int myEnd = positions[ (i+1) * numSeqsPerProcessor ];
561 bufferSizes.push_back(buf[myEnd]-buf[startPos]);
563 lines.push_back(new linePair(startPos, numSeqsPerProcessor));
568 catch(exception& e) {
569 m->errorOut(e, "FilterSeqsCommand", "setLines");
573 /**************************************************************************************************/
574 int FilterSeqsCommand::parseBuffer(string file, vector<string>& seqs) {
577 istringstream iss (file,istringstream::in);
578 string name, seqstring;
582 if (m->control_pressed) { return 0; }
584 Sequence seq(iss); gobble(iss);
586 if (seq.getName() != "") {
587 seqs.push_back(seq.getAligned());
593 catch(exception& e) {
594 m->errorOut(e, "FilterSeqsCommand", "parseBuffer");
598 /**************************************************************************************/