5 * Created by Sarah Westcott on 5/7/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
10 #include "distancecommand.h"
11 #include "ignoregaps.h"
12 #include "eachgapdist.h"
13 #include "eachgapignore.h"
14 #include "onegapdist.h"
15 #include "onegapignore.h"
17 //**********************************************************************************************************************
19 DistanceCommand::DistanceCommand(string option) {
24 //allow user to run help
25 if(option == "help") { help(); abort = true; }
28 //valid paramters for this command
29 string Array[] = {"fasta", "output", "calc", "countends", "cutoff", "processors", "outputdir","inputdir"};
30 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
32 OptionParser parser(option);
33 map<string, string> parameters = parser.getParameters();
35 ValidParameters validParameter;
36 map<string, string>::iterator it2;
38 //check to make sure all parameters are valid for command
39 for (it2 = parameters.begin(); it2 != parameters.end(); it2++) {
40 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) { abort = true; }
43 //if the user changes the input directory command factory will send this info to us in the output parameter
44 string inputDir = validParameter.validFile(parameters, "inputdir", false);
45 if (inputDir == "not found"){ inputDir = ""; }
48 it2 = parameters.find("fasta");
49 //user has given a template file
50 if(it2 != parameters.end()){
51 path = hasPath(it2->second);
52 //if the user has not given a path then, add inputdir. else leave path alone.
53 if (path == "") { parameters["fasta"] = inputDir + it2->second; }
57 //check for required parameters
58 fastafile = validParameter.validFile(parameters, "fasta", true);
59 if (fastafile == "not found") { m->mothurOut("fasta is a required parameter for the dist.seqs command."); m->mothurOutEndLine(); abort = true; }
60 else if (fastafile == "not open") { abort = true; }
63 openInputFile(fastafile, inFASTA);
64 alignDB = SequenceDB(inFASTA);
68 //if the user changes the output directory command factory will send this info to us in the output parameter
69 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
71 outputDir += hasPath(fastafile); //if user entered a file with a path then preserve it
74 //check for optional parameter and set defaults
75 // ...at some point should added some additional type checking...
76 calc = validParameter.validFile(parameters, "calc", false);
77 if (calc == "not found") { calc = "onegap"; }
79 if (calc == "default") { calc = "onegap"; }
81 splitAtDash(calc, Estimators);
84 temp = validParameter.validFile(parameters, "countends", false); if(temp == "not found"){ temp = "T"; }
85 convert(temp, countends);
87 temp = validParameter.validFile(parameters, "cutoff", false); if(temp == "not found"){ temp = "1.0"; }
88 convert(temp, cutoff);
90 temp = validParameter.validFile(parameters, "processors", false); if(temp == "not found"){ temp = "1"; }
91 convert(temp, processors);
93 output = validParameter.validFile(parameters, "output", false); if(output == "not found"){ output = "column"; }
95 if ((output != "column") && (output != "lt") && (output != "square")) { m->mothurOut(output + " is not a valid output form. Options are column, lt and square. I will use column."); m->mothurOutEndLine(); output = "column"; }
97 ValidCalculators validCalculator;
99 if (isTrue(countends) == true) {
100 for (int i=0; i<Estimators.size(); i++) {
101 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
102 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
103 else if (Estimators[i] == "eachgap") { distCalculator = new eachGapDist(); }
104 else if (Estimators[i] == "onegap") { distCalculator = new oneGapDist(); }
108 for (int i=0; i<Estimators.size(); i++) {
109 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
110 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
111 else if (Estimators[i] == "eachgap"){ distCalculator = new eachGapIgnoreTermGapDist(); }
112 else if (Estimators[i] == "onegap") { distCalculator = new oneGapIgnoreTermGapDist(); }
120 catch(exception& e) {
121 m->errorOut(e, "DistanceCommand", "DistanceCommand");
126 //**********************************************************************************************************************
128 DistanceCommand::~DistanceCommand(){
130 for(int i=0;i<lines.size();i++){
136 //**********************************************************************************************************************
138 void DistanceCommand::help(){
140 m->mothurOut("The dist.seqs command reads a file containing sequences and creates a distance file.\n");
141 m->mothurOut("The dist.seqs command parameters are fasta, calc, countends, output, cutoff and processors. \n");
142 m->mothurOut("The fasta parameter is required.\n");
143 m->mothurOut("The calc parameter allows you to specify the method of calculating the distances. Your options are: nogaps, onegap or eachgap. The default is onegap.\n");
144 m->mothurOut("The countends parameter allows you to specify whether to include terminal gaps in distance. Your options are: T or F. The default is T.\n");
145 m->mothurOut("The cutoff parameter allows you to specify maximum distance to keep. The default is 1.0.\n");
146 m->mothurOut("The output parameter allows you to specify format of your distance matrix. Options are column, lt, and square. The default is column.\n");
147 m->mothurOut("The processors parameter allows you to specify number of processors to use. The default is 1.\n");
148 m->mothurOut("The dist.seqs command should be in the following format: \n");
149 m->mothurOut("dist.seqs(fasta=yourFastaFile, calc=yourCalc, countends=yourEnds, cutoff= yourCutOff, processors=yourProcessors) \n");
150 m->mothurOut("Example dist.seqs(fasta=amazon.fasta, calc=eachgap, countends=F, cutoff= 2.0, processors=3).\n");
151 m->mothurOut("Note: No spaces between parameter labels (i.e. calc), '=' and parameters (i.e.yourCalc).\n\n");
153 catch(exception& e) {
154 m->errorOut(e, "DistanceCommand", "help");
158 //**********************************************************************************************************************
160 int DistanceCommand::execute(){
163 if (abort == true) { return 0; }
165 int startTime = time(NULL);
167 int numSeqs = alignDB.getNumSeqs();
172 if (output == "lt") { //does the user want lower triangle phylip formatted file
173 outputFile = outputDir + getRootName(getSimpleName(fastafile)) + "phylip.dist";
174 remove(outputFile.c_str());
176 //output numSeqs to phylip formatted dist file
177 }else if (output == "column") { //user wants column format
178 outputFile = outputDir + getRootName(getSimpleName(fastafile)) + "dist";
179 remove(outputFile.c_str());
180 }else { //assume square
181 outputFile = outputDir + getRootName(getSimpleName(fastafile)) + "square.dist";
182 remove(outputFile.c_str());
192 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running
193 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
195 //each process gets where it should start and stop in the file
196 start = int (sqrt(float(pid)/float(processors)) * numSeqs);
197 end = int (sqrt(float(pid+1)/float(processors)) * numSeqs);
199 if (output != "lt") {
201 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
203 //char* filename = new char[outputFile.length()];
204 //memcpy(filename, outputFile.c_str(), outputFile.length());
207 strcpy(filename, outputFile.c_str());
209 MPI_File_open(MPI_COMM_WORLD, filename, amode, MPI_INFO_NULL, &outMPI);
212 if (pid == 0) { //you are the root process
216 driverMPI(start, end, outMPI, cutoff);
218 if (m->control_pressed) { MPI_File_close(&outMPI); delete distCalculator; return 0; }
221 for(int i = 1; i < processors; i++) {
222 if (m->control_pressed) { MPI_File_close(&outMPI); delete distCalculator; return 0; }
225 MPI_Recv(buf, 4, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status);
227 }else { //you are a child process
229 driverMPI(start, end, outMPI, cutoff);
231 if (m->control_pressed) { MPI_File_close(&outMPI); delete distCalculator; return 0; }
235 //tell parent you are done.
236 MPI_Send(buf, 4, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
239 MPI_File_close(&outMPI);
241 }else { //lower triangle format
242 if (pid == 0) { //you are the root process
247 driverMPI(start, end, outputFile, mySize);
249 if (m->control_pressed) { delete distCalculator; return 0; }
251 int amode=MPI_MODE_APPEND|MPI_MODE_WRONLY|MPI_MODE_CREATE; //
255 //char* filename = new char[outputFile.length()];
256 //memcpy(filename, outputFile.c_str(), outputFile.length());
259 strcpy(filename, outputFile.c_str());
261 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
265 for(int b = 1; b < processors; b++) {
268 if (m->control_pressed) { MPI_File_close(&outMPI); delete distCalculator; return 0; }
270 MPI_Recv(&fileSize, 1, MPI_LONG, b, tag, MPI_COMM_WORLD, &status);
272 string outTemp = outputFile + toString(b) + ".temp";
274 char* buf = new char[outTemp.length()];
275 memcpy(buf, outTemp.c_str(), outTemp.length());
277 MPI_File_open(MPI_COMM_SELF, buf, MPI_MODE_DELETE_ON_CLOSE|MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);
281 while (count < fileSize) {
283 MPI_File_read(inMPI, buf2, 1, MPI_CHAR, &status);
284 MPI_File_write(outMPI, buf2, 1, MPI_CHAR, &status);
288 MPI_File_close(&inMPI); //deleted on close
291 MPI_File_close(&outMPI);
292 }else { //you are a child process
295 driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size);
297 if (m->control_pressed) { delete distCalculator; return 0; }
299 //tell parent you are done.
300 MPI_Send(&size, 1, MPI_LONG, 0, tag, MPI_COMM_WORLD);
305 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
306 //if you don't need to fork anything
308 driver(0, numSeqs, outputFile, cutoff);
309 }else{ //you have multiple processors
311 for (int i = 0; i < processors; i++) {
312 lines.push_back(new linePair());
313 lines[i]->start = int (sqrt(float(i)/float(processors)) * numSeqs);
314 lines[i]->end = int (sqrt(float(i+1)/float(processors)) * numSeqs);
317 createProcesses(outputFile);
319 map<int, int>::iterator it = processIDS.begin();
320 rename((outputFile + toString(it->second) + ".temp").c_str(), outputFile.c_str());
323 //append and remove temp files
324 for (; it != processIDS.end(); it++) {
325 appendFiles((outputFile + toString(it->second) + ".temp"), outputFile);
326 remove((outputFile + toString(it->second) + ".temp").c_str());
331 driver(0, numSeqs, outputFile, cutoff);
335 if (m->control_pressed) { delete distCalculator; remove(outputFile.c_str()); return 0; }
338 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
340 if (pid == 0) { //only one process should output to screen
343 if (output == "square") { convertMatrix(outputFile); }
346 fileHandle.open(outputFile.c_str());
349 if (fileHandle.eof()) { m->mothurOut(outputFile + " is blank. This can result if there are no distances below your cutoff."); m->mothurOutEndLine(); }
357 if (m->control_pressed) { delete distCalculator; remove(outputFile.c_str()); return 0; }
359 delete distCalculator;
361 m->mothurOutEndLine();
362 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
363 m->mothurOut(outputFile); m->mothurOutEndLine();
364 m->mothurOutEndLine();
365 m->mothurOut("It took " + toString(time(NULL) - startTime) + " to calculate the distances for " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
369 catch(exception& e) {
370 m->errorOut(e, "DistanceCommand", "execute");
374 /**************************************************************************************************/
375 void DistanceCommand::createProcesses(string filename) {
377 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
381 //loop through and create all the processes you want
382 while (process != processors) {
386 processIDS[lines[process]->end] = pid; //create map from line number to pid so you can append files in correct order later
389 driver(lines[process]->start, lines[process]->end, filename + toString(getpid()) + ".temp", cutoff);
391 }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
394 //force parent to wait until all the processes are done
395 for (map<int, int>::iterator it = processIDS.begin(); it != processIDS.end(); it++) {
396 int temp = it->second;
401 catch(exception& e) {
402 m->errorOut(e, "DistanceCommand", "createProcesses");
407 /**************************************************************************************************/
408 /////// need to fix to work with calcs and sequencedb
409 int DistanceCommand::driver(int startLine, int endLine, string dFileName, float cutoff){
412 int startTime = time(NULL);
415 ofstream outFile(dFileName.c_str(), ios::trunc);
416 outFile.setf(ios::fixed, ios::showpoint);
417 outFile << setprecision(4);
419 if((output == "lt") && startLine == 0){ outFile << alignDB.getNumSeqs() << endl; }
421 for(int i=startLine;i<endLine;i++){
423 string name = alignDB.get(i).getName();
424 if (name.length() < 10) { //pad with spaces to make compatible
425 while (name.length() < 10) { name += " "; }
427 outFile << name << '\t';
429 for(int j=0;j<i;j++){
431 if (m->control_pressed) { outFile.close(); return 0; }
433 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
434 double dist = distCalculator->getDist();
437 if (output == "column") { outFile << alignDB.get(i).getName() << ' ' << alignDB.get(j).getName() << ' ' << dist << endl; }
439 if (output == "lt") { outFile << dist << '\t'; }
441 if (output == "square") { //make a square column you can convert to square phylip
442 outFile << alignDB.get(i).getName() << '\t' << alignDB.get(j).getName() << '\t' << dist << endl;
443 outFile << alignDB.get(j).getName() << '\t' << alignDB.get(i).getName() << '\t' << dist << endl;
448 if (output == "lt") { outFile << endl; }
451 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
455 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
461 catch(exception& e) {
462 m->errorOut(e, "DistanceCommand", "driver");
467 /**************************************************************************************************/
468 /////// need to fix to work with calcs and sequencedb
469 int DistanceCommand::driverMPI(int startLine, int endLine, MPI_File& outMPI, float cutoff){
472 int startTime = time(NULL);
474 string outputString = "";
476 for(int i=startLine;i<endLine;i++){
478 for(int j=0;j<i;j++){
480 if (m->control_pressed) { return 0; }
482 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
483 double dist = distCalculator->getDist();
486 if (output == "column") { outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n'); }
489 if (output == "square") { //make a square column you can convert to square phylip
490 outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n');
491 outputString += (alignDB.get(j).getName() + ' ' + alignDB.get(i).getName() + ' ' + toString(dist) + '\n');
496 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
497 cout << i << '\t' << (time(NULL) - startTime) << endl;
501 //send results to parent
502 int length = outputString.length();
504 char* buf = new char[length];
505 memcpy(buf, outputString.c_str(), length);
507 MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status);
513 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
514 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
517 catch(exception& e) {
518 m->errorOut(e, "DistanceCommand", "driverMPI");
522 /**************************************************************************************************/
523 /////// need to fix to work with calcs and sequencedb
524 int DistanceCommand::driverMPI(int startLine, int endLine, string file, long& size){
529 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
531 //char* filename = new char[file.length()];
532 //memcpy(filename, file.c_str(), file.length());
535 strcpy(filename, file.c_str());
537 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
540 int startTime = time(NULL);
542 string outputString = "";
545 if((output == "lt") && startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n"; }
547 for(int i=startLine;i<endLine;i++){
549 string name = alignDB.get(i).getName();
550 if (name.length() < 10) { //pad with spaces to make compatible
551 while (name.length() < 10) { name += " "; }
553 outputString += name + "\t";
555 for(int j=0;j<i;j++){
557 if (m->control_pressed) { return 0; }
559 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
560 double dist = distCalculator->getDist();
562 if (output == "lt") { outputString += toString(dist) + "\t"; }
565 if (output == "lt") { outputString += "\n"; }
569 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
570 cout << i << '\t' << (time(NULL) - startTime) << endl;
574 //send results to parent
575 int length = outputString.length();
576 char* buf = new char[length];
577 memcpy(buf, outputString.c_str(), length);
579 MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
580 size += outputString.length();
585 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
586 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
587 MPI_File_close(&outMPI);
591 catch(exception& e) {
592 m->errorOut(e, "DistanceCommand", "driverMPI");
597 /**************************************************************************************************/
598 int DistanceCommand::convertMatrix(string outputFile) {
601 //sort file by first column so the distances for each row are together
602 string outfile = getRootName(outputFile) + "sorted.dist.temp";
605 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
606 string command = "sort -n " + outputFile + " -o " + outfile;
607 system(command.c_str());
608 #else //sort using windows sort
609 string command = "sort " + outputFile + " /O " + outfile;
610 system(command.c_str());
614 //output to new file distance for each row and save positions in file where new row begins
616 openInputFile(outfile, in);
619 openOutputFile(outputFile, out);
621 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
623 out << alignDB.getNumSeqs() << endl;
625 //get first currentRow
626 string first, currentRow, second;
628 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key
629 map<string, float>::iterator it;
634 rowDists[first] = 0.00; //distance to yourself is 0.0
637 //openInputFile(outfile, in);
640 if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
642 in >> first >> second >> dist; gobble(in);
644 if (first != currentRow) {
646 out << currentRow << '\t'; //print name
649 for (it = rowDists.begin(); it != rowDists.end(); it++) {
650 out << it->second << '\t';
657 rowDists[first] = 0.00;
658 rowDists[second] = dist;
660 rowDists[second] = dist;
664 out << currentRow << '\t'; //print name
667 for (it = rowDists.begin(); it != rowDists.end(); it++) {
668 out << it->second << '\t';
675 remove(outfile.c_str());
680 catch(exception& e) {
681 m->errorOut(e, "DistanceCommand", "convertMatrix");
685 /**************************************************************************************************/
686 int DistanceCommand::convertToLowerTriangle(string outputFile) {
689 //sort file by first column so the distances for each row are together
690 string outfile = getRootName(outputFile) + "sorted.dist.temp";
693 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
694 string command = "sort -n " + outputFile + " -o " + outfile;
695 system(command.c_str());
696 #else //sort using windows sort
697 string command = "sort " + outputFile + " /O " + outfile;
698 system(command.c_str());
702 //output to new file distance for each row and save positions in file where new row begins
704 openInputFile(outfile, in);
707 openOutputFile(outputFile, out);
709 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
711 out << alignDB.getNumSeqs() << endl;
713 //get first currentRow
714 string first, currentRow, second;
718 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key
719 map<string, float>::iterator it;
724 rowDists[first] = 0.00; //distance to yourself is 0.0
727 //openInputFile(outfile, in);
730 if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
732 in >> first >> second >> dist; gobble(in);
734 if (first != currentRow) {
736 out << currentRow << '\t'; //print name
739 for (it = rowDists.begin(); it != rowDists.end(); it++) {
740 if (j >= i) { break; }
741 out << it->second << '\t';
749 rowDists[first] = 0.00;
750 rowDists[second] = dist;
754 rowDists[second] = dist;
758 out << currentRow << '\t'; //print name
761 for (it = rowDists.begin(); it != rowDists.end(); it++) {
762 out << it->second << '\t';
769 remove(outfile.c_str());
774 catch(exception& e) {
775 m->errorOut(e, "DistanceCommand", "convertToLowerTriangle");
779 /**************************************************************************************************
780 void DistanceCommand::appendFiles(string temp, string filename) {
785 //open output file in append mode
786 openOutputFileAppend(filename, output);
787 openInputFile(temp, input);
789 while(char c = input.get()){
790 if(input.eof()) { break; }
791 else { output << c; }
797 catch(exception& e) {
798 m->errorOut(e, "DistanceCommand", "appendFiles");
802 /**************************************************************************************************/