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"
18 //**********************************************************************************************************************
19 vector<string> DistanceCommand::getValidParameters(){
21 string Array[] = {"fasta","oldfasta","column", "output", "calc", "countends", "cutoff", "processors", "outputdir","inputdir","compress"};
22 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
26 m->errorOut(e, "DistanceCommand", "getValidParameters");
30 //**********************************************************************************************************************
31 DistanceCommand::DistanceCommand(){
34 //initialize outputTypes
35 vector<string> tempOutNames;
36 outputTypes["phylip"] = tempOutNames;
37 outputTypes["column"] = tempOutNames;
40 m->errorOut(e, "DistanceCommand", "DistanceCommand");
44 //**********************************************************************************************************************
45 vector<string> DistanceCommand::getRequiredParameters(){
47 string Array[] = {"fasta"};
48 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
52 m->errorOut(e, "DistanceCommand", "getRequiredParameters");
56 //**********************************************************************************************************************
57 vector<string> DistanceCommand::getRequiredFiles(){
59 vector<string> myArray;
63 m->errorOut(e, "DistanceCommand", "getRequiredFiles");
67 //**********************************************************************************************************************
68 DistanceCommand::DistanceCommand(string option) {
73 //allow user to run help
74 if(option == "help") { help(); abort = true; }
77 //valid paramters for this command
78 string Array[] = {"fasta","oldfasta","column", "output", "calc", "countends", "cutoff", "processors", "outputdir","inputdir","compress"};
80 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
82 OptionParser parser(option);
83 map<string, string> parameters = parser.getParameters();
85 ValidParameters validParameter("dist.seqs");
86 map<string, string>::iterator it2;
88 //check to make sure all parameters are valid for command
89 for (it2 = parameters.begin(); it2 != parameters.end(); it2++) {
90 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) { abort = true; }
93 //initialize outputTypes
94 vector<string> tempOutNames;
95 outputTypes["phylip"] = tempOutNames;
96 outputTypes["column"] = tempOutNames;
98 //if the user changes the input directory command factory will send this info to us in the output parameter
99 string inputDir = validParameter.validFile(parameters, "inputdir", false);
100 if (inputDir == "not found"){ inputDir = ""; }
103 it2 = parameters.find("fasta");
104 //user has given a template file
105 if(it2 != parameters.end()){
106 path = m->hasPath(it2->second);
107 //if the user has not given a path then, add inputdir. else leave path alone.
108 if (path == "") { parameters["fasta"] = inputDir + it2->second; }
111 it2 = parameters.find("oldfasta");
112 //user has given a template file
113 if(it2 != parameters.end()){
114 path = m->hasPath(it2->second);
115 //if the user has not given a path then, add inputdir. else leave path alone.
116 if (path == "") { parameters["oldfasta"] = inputDir + it2->second; }
119 it2 = parameters.find("column");
120 //user has given a template file
121 if(it2 != parameters.end()){
122 path = m->hasPath(it2->second);
123 //if the user has not given a path then, add inputdir. else leave path alone.
124 if (path == "") { parameters["column"] = inputDir + it2->second; }
128 //check for required parameters
129 fastafile = validParameter.validFile(parameters, "fasta", true);
130 if (fastafile == "not found") { m->mothurOut("fasta is a required parameter for the dist.seqs command."); m->mothurOutEndLine(); abort = true; }
131 else if (fastafile == "not open") { abort = true; }
134 m->openInputFile(fastafile, inFASTA);
135 alignDB = SequenceDB(inFASTA);
139 oldfastafile = validParameter.validFile(parameters, "oldfasta", true);
140 if (oldfastafile == "not found") { oldfastafile = ""; }
141 else if (oldfastafile == "not open") { abort = true; }
143 column = validParameter.validFile(parameters, "column", true);
144 if (column == "not found") { column = ""; }
145 else if (column == "not open") { abort = true; }
147 //if the user changes the output directory command factory will send this info to us in the output parameter
148 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
150 outputDir += m->hasPath(fastafile); //if user entered a file with a path then preserve it
153 //check for optional parameter and set defaults
154 // ...at some point should added some additional type checking...
155 calc = validParameter.validFile(parameters, "calc", false);
156 if (calc == "not found") { calc = "onegap"; }
158 if (calc == "default") { calc = "onegap"; }
160 m->splitAtDash(calc, Estimators);
163 temp = validParameter.validFile(parameters, "countends", false); if(temp == "not found"){ temp = "T"; }
164 convert(temp, countends);
166 temp = validParameter.validFile(parameters, "cutoff", false); if(temp == "not found"){ temp = "1.0"; }
167 convert(temp, cutoff);
169 temp = validParameter.validFile(parameters, "processors", false); if(temp == "not found"){ temp = "1"; }
170 convert(temp, processors);
172 temp = validParameter.validFile(parameters, "compress", false); if(temp == "not found"){ temp = "F"; }
173 convert(temp, compress);
175 output = validParameter.validFile(parameters, "output", false); if(output == "not found"){ output = "column"; }
177 if (((column != "") && (oldfastafile == "")) || ((column == "") && (oldfastafile != ""))) { m->mothurOut("If you provide column or oldfasta, you must provide both."); m->mothurOutEndLine(); abort=true; }
179 if ((column != "") && (oldfastafile != "") && (output != "column")) { m->mothurOut("You have provided column and oldfasta, indicating you want to append distances to your column file. Your output must be in column format to do so."); m->mothurOutEndLine(); abort=true; }
181 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"; }
183 ValidCalculators validCalculator;
185 if (m->isTrue(countends) == true) {
186 for (int i=0; i<Estimators.size(); i++) {
187 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
188 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
189 else if (Estimators[i] == "eachgap") { distCalculator = new eachGapDist(); }
190 else if (Estimators[i] == "onegap") { distCalculator = new oneGapDist(); }
194 for (int i=0; i<Estimators.size(); i++) {
195 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
196 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
197 else if (Estimators[i] == "eachgap"){ distCalculator = new eachGapIgnoreTermGapDist(); }
198 else if (Estimators[i] == "onegap") { distCalculator = new oneGapIgnoreTermGapDist(); }
206 catch(exception& e) {
207 m->errorOut(e, "DistanceCommand", "DistanceCommand");
212 //**********************************************************************************************************************
214 DistanceCommand::~DistanceCommand(){}
216 //**********************************************************************************************************************
218 void DistanceCommand::help(){
220 m->mothurOut("The dist.seqs command reads a file containing sequences and creates a distance file.\n");
221 m->mothurOut("The dist.seqs command parameters are fasta, oldfasta, column, calc, countends, output, compress, cutoff and processors. \n");
222 m->mothurOut("The fasta parameter is required.\n");
223 m->mothurOut("The oldfasta and column parameters allow you to append the distances calculated to the column file.\n");
224 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");
225 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");
226 m->mothurOut("The cutoff parameter allows you to specify maximum distance to keep. The default is 1.0.\n");
227 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");
228 m->mothurOut("The processors parameter allows you to specify number of processors to use. The default is 1.\n");
229 m->mothurOut("The compress parameter allows you to indicate that you want the resulting distance file compressed. The default is false.\n");
230 m->mothurOut("The dist.seqs command should be in the following format: \n");
231 m->mothurOut("dist.seqs(fasta=yourFastaFile, calc=yourCalc, countends=yourEnds, cutoff= yourCutOff, processors=yourProcessors) \n");
232 m->mothurOut("Example dist.seqs(fasta=amazon.fasta, calc=eachgap, countends=F, cutoff= 2.0, processors=3).\n");
233 m->mothurOut("Note: No spaces between parameter labels (i.e. calc), '=' and parameters (i.e.yourCalc).\n\n");
235 catch(exception& e) {
236 m->errorOut(e, "DistanceCommand", "help");
240 //**********************************************************************************************************************
242 int DistanceCommand::execute(){
245 if (abort == true) { return 0; }
247 int startTime = time(NULL);
249 //save number of new sequence
250 numNewFasta = alignDB.getNumSeqs();
252 //sanity check the oldfasta and column file as well as add oldfasta sequences to alignDB
253 if ((oldfastafile != "") && (column != "")) { if (!(sanityCheck())) { return 0; } }
255 if (m->control_pressed) { return 0; }
257 int numSeqs = alignDB.getNumSeqs();
262 if (output == "lt") { //does the user want lower triangle phylip formatted file
263 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "phylip.dist";
264 remove(outputFile.c_str()); outputTypes["phylip"].push_back(outputFile);
266 //output numSeqs to phylip formatted dist file
267 }else if (output == "column") { //user wants column format
268 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "dist";
269 outputTypes["column"].push_back(outputFile);
271 //so we don't accidentally overwrite
272 if (outputFile == column) {
273 string tempcolumn = column + ".old";
274 rename(column.c_str(), tempcolumn.c_str());
277 remove(outputFile.c_str());
278 }else { //assume square
279 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "square.dist";
280 remove(outputFile.c_str());
281 outputTypes["phylip"].push_back(outputFile);
291 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running
292 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
294 //each process gets where it should start and stop in the file
295 if (output != "square") {
296 start = int (sqrt(float(pid)/float(processors)) * numSeqs);
297 end = int (sqrt(float(pid+1)/float(processors)) * numSeqs);
299 start = int ((float(pid)/float(processors)) * numSeqs);
300 end = int ((float(pid+1)/float(processors)) * numSeqs);
303 if (output == "column") {
305 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
307 //char* filename = new char[outputFile.length()];
308 //memcpy(filename, outputFile.c_str(), outputFile.length());
311 strcpy(filename, outputFile.c_str());
313 MPI_File_open(MPI_COMM_WORLD, filename, amode, MPI_INFO_NULL, &outMPI);
316 if (pid == 0) { //you are the root process
321 driverMPI(start, end, outMPI, cutoff);
323 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
326 for(int i = 1; i < processors; i++) {
327 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
330 MPI_Recv(buf, 5, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status);
332 }else { //you are a child process
334 driverMPI(start, end, outMPI, cutoff);
336 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
340 //tell parent you are done.
341 MPI_Send(buf, 5, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
344 MPI_File_close(&outMPI);
346 }else { //lower triangle format
347 if (pid == 0) { //you are the root process
351 unsigned long int mySize;
353 if (output != "square"){ driverMPI(start, end, outputFile, mySize); }
354 else { driverMPI(start, end, outputFile, mySize, output); }
356 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; return 0; }
358 int amode=MPI_MODE_APPEND|MPI_MODE_WRONLY|MPI_MODE_CREATE; //
362 //char* filename = new char[outputFile.length()];
363 //memcpy(filename, outputFile.c_str(), outputFile.length());
366 strcpy(filename, outputFile.c_str());
368 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
372 for(int b = 1; b < processors; b++) {
373 unsigned long int fileSize;
375 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
377 MPI_Recv(&fileSize, 1, MPI_LONG, b, tag, MPI_COMM_WORLD, &status);
379 string outTemp = outputFile + toString(b) + ".temp";
381 char* buf = new char[outTemp.length()];
382 memcpy(buf, outTemp.c_str(), outTemp.length());
384 MPI_File_open(MPI_COMM_SELF, buf, MPI_MODE_DELETE_ON_CLOSE|MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);
388 while (count < fileSize) {
390 MPI_File_read(inMPI, buf2, 1, MPI_CHAR, &status);
391 MPI_File_write(outMPI, buf2, 1, MPI_CHAR, &status);
395 MPI_File_close(&inMPI); //deleted on close
398 MPI_File_close(&outMPI);
399 }else { //you are a child process
401 unsigned long int size;
402 if (output != "square"){ driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size); }
403 else { driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size, output); }
405 if (m->control_pressed) { delete distCalculator; return 0; }
407 //tell parent you are done.
408 MPI_Send(&size, 1, MPI_LONG, 0, tag, MPI_COMM_WORLD);
411 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
414 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
415 //if you don't need to fork anything
417 if (output != "square") { driver(0, numSeqs, outputFile, cutoff); }
418 else { driver(0, numSeqs, outputFile, "square"); }
419 }else{ //you have multiple processors
421 unsigned long int numDists = 0;
423 if (output == "square") {
424 numDists = numSeqs * numSeqs;
426 for(int i=0;i<numSeqs;i++){
427 for(int j=0;j<i;j++){
429 if (numDists > processors) { break; }
434 if (numDists < processors) { processors = numDists; }
436 for (int i = 0; i < processors; i++) {
437 distlinePair tempLine;
438 lines.push_back(tempLine);
439 if (output != "square") {
440 lines[i].start = int (sqrt(float(i)/float(processors)) * numSeqs);
441 lines[i].end = int (sqrt(float(i+1)/float(processors)) * numSeqs);
443 lines[i].start = int ((float(i)/float(processors)) * numSeqs);
444 lines[i].end = int ((float(i+1)/float(processors)) * numSeqs);
449 createProcesses(outputFile);
453 if (output != "square") { driver(0, numSeqs, outputFile, cutoff); }
454 else { driver(0, numSeqs, outputFile, "square"); }
458 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; remove(outputFile.c_str()); return 0; }
461 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
463 if (pid == 0) { //only one process should output to screen
466 //if (output == "square") { convertMatrix(outputFile); }
469 fileHandle.open(outputFile.c_str());
471 m->gobble(fileHandle);
472 if (fileHandle.eof()) { m->mothurOut(outputFile + " is blank. This can result if there are no distances below your cutoff."); m->mothurOutEndLine(); }
475 //append the old column file to the new one
476 if ((oldfastafile != "") && (column != "")) {
477 //we had to rename the column file so we didnt overwrite above, but we want to keep old name
478 if (outputFile == column) {
479 string tempcolumn = column + ".old";
480 m->appendFiles(tempcolumn, outputFile);
481 remove(tempcolumn.c_str());
483 m->appendFiles(outputFile, column);
484 remove(outputFile.c_str());
488 if (outputDir != "") {
489 string newOutputName = outputDir + m->getSimpleName(outputFile);
490 rename(outputFile.c_str(), newOutputName.c_str());
491 remove(outputFile.c_str());
492 outputFile = newOutputName;
501 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; remove(outputFile.c_str()); return 0; }
503 delete distCalculator;
505 m->mothurOutEndLine();
506 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
507 m->mothurOut(outputFile); m->mothurOutEndLine();
508 m->mothurOutEndLine();
509 m->mothurOut("It took " + toString(time(NULL) - startTime) + " to calculate the distances for " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
512 if (m->isTrue(compress)) {
513 m->mothurOut("Compressing..."); m->mothurOutEndLine();
514 m->mothurOut("(Replacing " + outputFile + " with " + outputFile + ".gz)"); m->mothurOutEndLine();
515 system(("gzip -v " + outputFile).c_str());
516 outputNames.push_back(outputFile + ".gz");
517 }else { outputNames.push_back(outputFile); }
522 catch(exception& e) {
523 m->errorOut(e, "DistanceCommand", "execute");
527 /**************************************************************************************************/
528 void DistanceCommand::createProcesses(string filename) {
530 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
534 //loop through and create all the processes you want
535 while (process != processors) {
539 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
542 if (output != "square") { driver(lines[process].start, lines[process].end, filename + toString(getpid()) + ".temp", cutoff); }
543 else { driver(lines[process].start, lines[process].end, filename + toString(getpid()) + ".temp", "square"); }
546 m->mothurOut("[ERROR]: unable to spawn the necessary processes. Error code: " + toString(pid)); m->mothurOutEndLine();
548 for (int i=0;i<processIDS.size();i++) { int temp = processIDS[i]; kill (temp, SIGINT); }
553 //parent does its part
554 if (output != "square") { driver(lines[0].start, lines[0].end, filename, cutoff); }
555 else { driver(lines[0].start, lines[0].end, filename, "square"); }
558 //force parent to wait until all the processes are done
559 for (int i=0;i<processIDS.size();i++) {
560 int temp = processIDS[i];
564 //append and remove temp files
565 for (int i=0;i<processIDS.size();i++) {
566 m->appendFiles((filename + toString(processIDS[i]) + ".temp"), filename);
567 remove((filename + toString(processIDS[i]) + ".temp").c_str());
571 catch(exception& e) {
572 m->errorOut(e, "DistanceCommand", "createProcesses");
577 /**************************************************************************************************/
578 /////// need to fix to work with calcs and sequencedb
579 int DistanceCommand::driver(int startLine, int endLine, string dFileName, float cutoff){
582 int startTime = time(NULL);
585 ofstream outFile(dFileName.c_str(), ios::trunc);
586 outFile.setf(ios::fixed, ios::showpoint);
587 outFile << setprecision(4);
589 if((output == "lt") && startLine == 0){ outFile << alignDB.getNumSeqs() << endl; }
591 for(int i=startLine;i<endLine;i++){
593 string name = alignDB.get(i).getName();
594 if (name.length() < 10) { //pad with spaces to make compatible
595 while (name.length() < 10) { name += " "; }
597 outFile << name << '\t';
599 for(int j=0;j<i;j++){
601 if (m->control_pressed) { outFile.close(); return 0; }
603 //if there was a column file given and we are appending, we don't want to calculate the distances that are already in the column file
604 //the alignDB contains the new sequences and then the old, so if i an oldsequence and j is an old sequence then break out of this loop
605 if ((i >= numNewFasta) && (j >= numNewFasta)) { break; }
607 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
608 double dist = distCalculator->getDist();
611 if (output == "column") { outFile << alignDB.get(i).getName() << ' ' << alignDB.get(j).getName() << ' ' << dist << endl; }
613 if (output == "lt") { outFile << dist << '\t'; }
616 if (output == "lt") { outFile << endl; }
619 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
623 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
629 catch(exception& e) {
630 m->errorOut(e, "DistanceCommand", "driver");
634 /**************************************************************************************************/
635 /////// need to fix to work with calcs and sequencedb
636 int DistanceCommand::driver(int startLine, int endLine, string dFileName, string square){
639 int startTime = time(NULL);
642 ofstream outFile(dFileName.c_str(), ios::trunc);
643 outFile.setf(ios::fixed, ios::showpoint);
644 outFile << setprecision(4);
646 if(startLine == 0){ outFile << alignDB.getNumSeqs() << endl; }
648 for(int i=startLine;i<endLine;i++){
650 string name = alignDB.get(i).getName();
651 //pad with spaces to make compatible
652 if (name.length() < 10) { while (name.length() < 10) { name += " "; } }
654 outFile << name << '\t';
656 for(int j=0;j<alignDB.getNumSeqs();j++){
658 if (m->control_pressed) { outFile.close(); return 0; }
660 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
661 double dist = distCalculator->getDist();
663 outFile << dist << '\t';
669 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
673 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
679 catch(exception& e) {
680 m->errorOut(e, "DistanceCommand", "driver");
685 /**************************************************************************************************/
686 /////// need to fix to work with calcs and sequencedb
687 int DistanceCommand::driverMPI(int startLine, int endLine, MPI_File& outMPI, float cutoff){
690 int startTime = time(NULL);
692 string outputString = "";
694 for(int i=startLine;i<endLine;i++){
696 for(int j=0;j<i;j++){
698 if (m->control_pressed) { return 0; }
700 //if there was a column file given and we are appending, we don't want to calculate the distances that are already in the column file
701 //the alignDB contains the new sequences and then the old, so if i an oldsequence and j is an old sequence then break out of this loop
702 if ((i >= numNewFasta) && (j >= numNewFasta)) { break; }
704 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
705 double dist = distCalculator->getDist();
708 outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n');
713 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
714 cout << i << '\t' << (time(NULL) - startTime) << endl;
718 //send results to parent
719 int length = outputString.length();
721 char* buf = new char[length];
722 memcpy(buf, outputString.c_str(), length);
724 MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status);
730 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
731 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
734 catch(exception& e) {
735 m->errorOut(e, "DistanceCommand", "driverMPI");
739 /**************************************************************************************************/
740 /////// need to fix to work with calcs and sequencedb
741 int DistanceCommand::driverMPI(int startLine, int endLine, string file, unsigned long int& size){
746 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
748 //char* filename = new char[file.length()];
749 //memcpy(filename, file.c_str(), file.length());
752 strcpy(filename, file.c_str());
754 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
757 int startTime = time(NULL);
759 string outputString = "";
762 if(startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n"; }
764 for(int i=startLine;i<endLine;i++){
766 string name = alignDB.get(i).getName();
767 if (name.length() < 10) { //pad with spaces to make compatible
768 while (name.length() < 10) { name += " "; }
770 outputString += name + "\t";
772 for(int j=0;j<i;j++){
774 if (m->control_pressed) { return 0; }
776 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
777 double dist = distCalculator->getDist();
779 outputString += toString(dist) + "\t";
782 outputString += "\n";
786 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
787 cout << i << '\t' << (time(NULL) - startTime) << endl;
791 //send results to parent
792 int length = outputString.length();
793 char* buf = new char[length];
794 memcpy(buf, outputString.c_str(), length);
796 MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
797 size += outputString.length();
802 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
803 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
804 MPI_File_close(&outMPI);
808 catch(exception& e) {
809 m->errorOut(e, "DistanceCommand", "driverMPI");
813 /**************************************************************************************************/
814 /////// need to fix to work with calcs and sequencedb
815 int DistanceCommand::driverMPI(int startLine, int endLine, string file, unsigned long int& size, string square){
820 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
822 //char* filename = new char[file.length()];
823 //memcpy(filename, file.c_str(), file.length());
826 strcpy(filename, file.c_str());
828 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
831 int startTime = time(NULL);
833 string outputString = "";
836 if(startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n"; }
838 for(int i=startLine;i<endLine;i++){
840 string name = alignDB.get(i).getName();
841 if (name.length() < 10) { //pad with spaces to make compatible
842 while (name.length() < 10) { name += " "; }
844 outputString += name + "\t";
846 for(int j=0;j<alignDB.getNumSeqs();j++){
848 if (m->control_pressed) { return 0; }
850 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
851 double dist = distCalculator->getDist();
853 outputString += toString(dist) + "\t";
856 outputString += "\n";
860 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
861 cout << i << '\t' << (time(NULL) - startTime) << endl;
865 //send results to parent
866 int length = outputString.length();
867 char* buf = new char[length];
868 memcpy(buf, outputString.c_str(), length);
870 MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
871 size += outputString.length();
876 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
877 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
878 MPI_File_close(&outMPI);
882 catch(exception& e) {
883 m->errorOut(e, "DistanceCommand", "driverMPI");
888 /**************************************************************************************************
889 int DistanceCommand::convertMatrix(string outputFile) {
892 //sort file by first column so the distances for each row are together
893 string outfile = m->getRootName(outputFile) + "sorted.dist.temp";
896 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
897 string command = "sort -n " + outputFile + " -o " + outfile;
898 system(command.c_str());
899 #else //sort using windows sort
900 string command = "sort " + outputFile + " /O " + outfile;
901 system(command.c_str());
905 //output to new file distance for each row and save positions in file where new row begins
907 m->openInputFile(outfile, in);
910 m->openOutputFile(outputFile, out);
912 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
914 out << alignDB.getNumSeqs() << endl;
916 //get first currentRow
917 string first, currentRow, second;
919 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key
920 map<string, float>::iterator it;
925 rowDists[first] = 0.00; //distance to yourself is 0.0
928 //m->openInputFile(outfile, in);
931 if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
933 in >> first >> second >> dist; m->gobble(in);
935 if (first != currentRow) {
937 out << currentRow << '\t'; //print name
940 for (it = rowDists.begin(); it != rowDists.end(); it++) {
941 out << it->second << '\t';
948 rowDists[first] = 0.00;
949 rowDists[second] = dist;
951 rowDists[second] = dist;
955 out << currentRow << '\t'; //print name
958 for (it = rowDists.begin(); it != rowDists.end(); it++) {
959 out << it->second << '\t';
966 remove(outfile.c_str());
971 catch(exception& e) {
972 m->errorOut(e, "DistanceCommand", "convertMatrix");
976 /**************************************************************************************************
977 int DistanceCommand::convertToLowerTriangle(string outputFile) {
980 //sort file by first column so the distances for each row are together
981 string outfile = m->getRootName(outputFile) + "sorted.dist.temp";
984 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
985 string command = "sort -n " + outputFile + " -o " + outfile;
986 system(command.c_str());
987 #else //sort using windows sort
988 string command = "sort " + outputFile + " /O " + outfile;
989 system(command.c_str());
993 //output to new file distance for each row and save positions in file where new row begins
995 m->openInputFile(outfile, in);
998 m->openOutputFile(outputFile, out);
1000 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1002 out << alignDB.getNumSeqs() << endl;
1004 //get first currentRow
1005 string first, currentRow, second;
1009 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key
1010 map<string, float>::iterator it;
1015 rowDists[first] = 0.00; //distance to yourself is 0.0
1018 //m->openInputFile(outfile, in);
1021 if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
1023 in >> first >> second >> dist; m->gobble(in);
1025 if (first != currentRow) {
1026 //print out last row
1027 out << currentRow << '\t'; //print name
1030 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1031 if (j >= i) { break; }
1032 out << it->second << '\t';
1040 rowDists[first] = 0.00;
1041 rowDists[second] = dist;
1045 rowDists[second] = dist;
1048 //print out last row
1049 out << currentRow << '\t'; //print name
1052 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1053 out << it->second << '\t';
1060 remove(outfile.c_str());
1065 catch(exception& e) {
1066 m->errorOut(e, "DistanceCommand", "convertToLowerTriangle");
1070 /**************************************************************************************************/
1071 //its okay if the column file does not contain all the names in the fasta file, since some distance may have been above a cutoff,
1072 //but no sequences can be in the column file that are not in oldfasta. also, if a distance is above the cutoff given then remove it.
1073 //also check to make sure the 2 files have the same alignment length.
1074 bool DistanceCommand::sanityCheck() {
1078 //make sure the 2 fasta files have the same alignment length
1080 m->openInputFile(fastafile, in);
1081 int fastaAlignLength = 0;
1083 Sequence tempIn(in);
1084 fastaAlignLength = tempIn.getAligned().length();
1089 m->openInputFile(oldfastafile, in2);
1090 int oldfastaAlignLength = 0;
1092 Sequence tempIn2(in2);
1093 oldfastaAlignLength = tempIn2.getAligned().length();
1097 if (fastaAlignLength != oldfastaAlignLength) { m->mothurOut("fasta files do not have the same alignment length."); m->mothurOutEndLine(); return false; }
1099 //read fasta file and save names as well as adding them to the alignDB
1100 set<string> namesOldFasta;
1103 m->openInputFile(oldfastafile, inFasta);
1105 while (!inFasta.eof()) {
1106 if (m->control_pressed) { inFasta.close(); return good; }
1108 Sequence temp(inFasta);
1110 if (temp.getName() != "") {
1111 namesOldFasta.insert(temp.getName()); //save name
1112 alignDB.push_back(temp); //add to DB
1120 //read through the column file checking names and removing distances above the cutoff
1122 m->openInputFile(column, inDist);
1125 string outputFile = column + ".temp";
1126 m->openOutputFile(outputFile, outDist);
1128 string name1, name2;
1130 while (!inDist.eof()) {
1131 if (m->control_pressed) { inDist.close(); outDist.close(); remove(outputFile.c_str()); return good; }
1133 inDist >> name1 >> name2 >> dist; m->gobble(inDist);
1135 //both names are in fasta file and distance is below cutoff
1136 if ((namesOldFasta.count(name1) == 0) || (namesOldFasta.count(name2) == 0)) { good = false; break; }
1138 if (dist <= cutoff) {
1139 outDist << name1 << '\t' << name2 << '\t' << dist << endl;
1148 remove(column.c_str());
1149 rename(outputFile.c_str(), column.c_str());
1151 remove(outputFile.c_str()); //temp file is bad because file mismatch above
1155 catch(exception& e) {
1156 m->errorOut(e, "DistanceCommand", "sanityCheck");
1160 /**************************************************************************************************/