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(){
33 abort = true; calledHelp = true;
34 vector<string> tempOutNames;
35 outputTypes["phylip"] = tempOutNames;
36 outputTypes["column"] = tempOutNames;
39 m->errorOut(e, "DistanceCommand", "DistanceCommand");
43 //**********************************************************************************************************************
44 vector<string> DistanceCommand::getRequiredParameters(){
46 string Array[] = {"fasta"};
47 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
51 m->errorOut(e, "DistanceCommand", "getRequiredParameters");
55 //**********************************************************************************************************************
56 vector<string> DistanceCommand::getRequiredFiles(){
58 vector<string> myArray;
62 m->errorOut(e, "DistanceCommand", "getRequiredFiles");
66 //**********************************************************************************************************************
67 DistanceCommand::DistanceCommand(string option) {
69 abort = false; calledHelp = false;
72 //allow user to run help
73 if(option == "help") { help(); abort = true; calledHelp = true; }
76 //valid paramters for this command
77 string Array[] = {"fasta","oldfasta","column", "output", "calc", "countends", "cutoff", "processors", "outputdir","inputdir","compress"};
79 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
81 OptionParser parser(option);
82 map<string, string> parameters = parser.getParameters();
84 ValidParameters validParameter("dist.seqs");
85 map<string, string>::iterator it2;
87 //check to make sure all parameters are valid for command
88 for (it2 = parameters.begin(); it2 != parameters.end(); it2++) {
89 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) { abort = true; }
92 //initialize outputTypes
93 vector<string> tempOutNames;
94 outputTypes["phylip"] = tempOutNames;
95 outputTypes["column"] = tempOutNames;
97 //if the user changes the input directory command factory will send this info to us in the output parameter
98 string inputDir = validParameter.validFile(parameters, "inputdir", false);
99 if (inputDir == "not found"){ inputDir = ""; }
102 it2 = parameters.find("fasta");
103 //user has given a template file
104 if(it2 != parameters.end()){
105 path = m->hasPath(it2->second);
106 //if the user has not given a path then, add inputdir. else leave path alone.
107 if (path == "") { parameters["fasta"] = inputDir + it2->second; }
110 it2 = parameters.find("oldfasta");
111 //user has given a template file
112 if(it2 != parameters.end()){
113 path = m->hasPath(it2->second);
114 //if the user has not given a path then, add inputdir. else leave path alone.
115 if (path == "") { parameters["oldfasta"] = inputDir + it2->second; }
118 it2 = parameters.find("column");
119 //user has given a template file
120 if(it2 != parameters.end()){
121 path = m->hasPath(it2->second);
122 //if the user has not given a path then, add inputdir. else leave path alone.
123 if (path == "") { parameters["column"] = inputDir + it2->second; }
127 //check for required parameters
128 fastafile = validParameter.validFile(parameters, "fasta", true);
129 if (fastafile == "not found") { m->mothurOut("fasta is a required parameter for the dist.seqs command."); m->mothurOutEndLine(); abort = true; }
130 else if (fastafile == "not open") { abort = true; }
133 m->openInputFile(fastafile, inFASTA);
134 alignDB = SequenceDB(inFASTA);
138 oldfastafile = validParameter.validFile(parameters, "oldfasta", true);
139 if (oldfastafile == "not found") { oldfastafile = ""; }
140 else if (oldfastafile == "not open") { abort = true; }
142 column = validParameter.validFile(parameters, "column", true);
143 if (column == "not found") { column = ""; }
144 else if (column == "not open") { abort = true; }
146 //if the user changes the output directory command factory will send this info to us in the output parameter
147 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
149 outputDir += m->hasPath(fastafile); //if user entered a file with a path then preserve it
152 //check for optional parameter and set defaults
153 // ...at some point should added some additional type checking...
154 calc = validParameter.validFile(parameters, "calc", false);
155 if (calc == "not found") { calc = "onegap"; }
157 if (calc == "default") { calc = "onegap"; }
159 m->splitAtDash(calc, Estimators);
162 temp = validParameter.validFile(parameters, "countends", false); if(temp == "not found"){ temp = "T"; }
163 convert(temp, countends);
165 temp = validParameter.validFile(parameters, "cutoff", false); if(temp == "not found"){ temp = "1.0"; }
166 convert(temp, cutoff);
168 temp = validParameter.validFile(parameters, "processors", false); if(temp == "not found"){ temp = "1"; }
169 convert(temp, processors);
171 temp = validParameter.validFile(parameters, "compress", false); if(temp == "not found"){ temp = "F"; }
172 convert(temp, compress);
174 output = validParameter.validFile(parameters, "output", false); if(output == "not found"){ output = "column"; }
176 if (((column != "") && (oldfastafile == "")) || ((column == "") && (oldfastafile != ""))) { m->mothurOut("If you provide column or oldfasta, you must provide both."); m->mothurOutEndLine(); abort=true; }
178 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; }
180 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"; }
182 ValidCalculators validCalculator;
184 if (m->isTrue(countends) == true) {
185 for (int i=0; i<Estimators.size(); i++) {
186 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
187 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
188 else if (Estimators[i] == "eachgap") { distCalculator = new eachGapDist(); }
189 else if (Estimators[i] == "onegap") { distCalculator = new oneGapDist(); }
193 for (int i=0; i<Estimators.size(); i++) {
194 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
195 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
196 else if (Estimators[i] == "eachgap"){ distCalculator = new eachGapIgnoreTermGapDist(); }
197 else if (Estimators[i] == "onegap") { distCalculator = new oneGapIgnoreTermGapDist(); }
205 catch(exception& e) {
206 m->errorOut(e, "DistanceCommand", "DistanceCommand");
211 //**********************************************************************************************************************
213 DistanceCommand::~DistanceCommand(){}
215 //**********************************************************************************************************************
217 void DistanceCommand::help(){
219 m->mothurOut("The dist.seqs command reads a file containing sequences and creates a distance file.\n");
220 m->mothurOut("The dist.seqs command parameters are fasta, oldfasta, column, calc, countends, output, compress, cutoff and processors. \n");
221 m->mothurOut("The fasta parameter is required.\n");
222 m->mothurOut("The oldfasta and column parameters allow you to append the distances calculated to the column file.\n");
223 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");
224 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");
225 m->mothurOut("The cutoff parameter allows you to specify maximum distance to keep. The default is 1.0.\n");
226 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");
227 m->mothurOut("The processors parameter allows you to specify number of processors to use. The default is 1.\n");
228 m->mothurOut("The compress parameter allows you to indicate that you want the resulting distance file compressed. The default is false.\n");
229 m->mothurOut("The dist.seqs command should be in the following format: \n");
230 m->mothurOut("dist.seqs(fasta=yourFastaFile, calc=yourCalc, countends=yourEnds, cutoff= yourCutOff, processors=yourProcessors) \n");
231 m->mothurOut("Example dist.seqs(fasta=amazon.fasta, calc=eachgap, countends=F, cutoff= 2.0, processors=3).\n");
232 m->mothurOut("Note: No spaces between parameter labels (i.e. calc), '=' and parameters (i.e.yourCalc).\n\n");
234 catch(exception& e) {
235 m->errorOut(e, "DistanceCommand", "help");
239 //**********************************************************************************************************************
241 int DistanceCommand::execute(){
244 if (abort == true) { if (calledHelp) { return 0; } return 2; }
246 int startTime = time(NULL);
248 //save number of new sequence
249 numNewFasta = alignDB.getNumSeqs();
251 //sanity check the oldfasta and column file as well as add oldfasta sequences to alignDB
252 if ((oldfastafile != "") && (column != "")) { if (!(sanityCheck())) { return 0; } }
254 if (m->control_pressed) { return 0; }
256 int numSeqs = alignDB.getNumSeqs();
261 if (output == "lt") { //does the user want lower triangle phylip formatted file
262 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "phylip.dist";
263 remove(outputFile.c_str()); outputTypes["phylip"].push_back(outputFile);
265 //output numSeqs to phylip formatted dist file
266 }else if (output == "column") { //user wants column format
267 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "dist";
268 outputTypes["column"].push_back(outputFile);
270 //so we don't accidentally overwrite
271 if (outputFile == column) {
272 string tempcolumn = column + ".old";
273 rename(column.c_str(), tempcolumn.c_str());
276 remove(outputFile.c_str());
277 }else { //assume square
278 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "square.dist";
279 remove(outputFile.c_str());
280 outputTypes["phylip"].push_back(outputFile);
290 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running
291 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
293 //each process gets where it should start and stop in the file
294 if (output != "square") {
295 start = int (sqrt(float(pid)/float(processors)) * numSeqs);
296 end = int (sqrt(float(pid+1)/float(processors)) * numSeqs);
298 start = int ((float(pid)/float(processors)) * numSeqs);
299 end = int ((float(pid+1)/float(processors)) * numSeqs);
302 if (output == "column") {
304 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
306 //char* filename = new char[outputFile.length()];
307 //memcpy(filename, outputFile.c_str(), outputFile.length());
310 strcpy(filename, outputFile.c_str());
312 MPI_File_open(MPI_COMM_WORLD, filename, amode, MPI_INFO_NULL, &outMPI);
315 if (pid == 0) { //you are the root process
320 driverMPI(start, end, outMPI, cutoff);
322 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
325 for(int i = 1; i < processors; i++) {
326 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
329 MPI_Recv(buf, 5, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status);
331 }else { //you are a child process
333 driverMPI(start, end, outMPI, cutoff);
335 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
339 //tell parent you are done.
340 MPI_Send(buf, 5, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
343 MPI_File_close(&outMPI);
345 }else { //lower triangle format
346 if (pid == 0) { //you are the root process
350 unsigned long int mySize;
352 if (output != "square"){ driverMPI(start, end, outputFile, mySize); }
353 else { driverMPI(start, end, outputFile, mySize, output); }
355 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; return 0; }
357 int amode=MPI_MODE_APPEND|MPI_MODE_WRONLY|MPI_MODE_CREATE; //
361 //char* filename = new char[outputFile.length()];
362 //memcpy(filename, outputFile.c_str(), outputFile.length());
365 strcpy(filename, outputFile.c_str());
367 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
371 for(int b = 1; b < processors; b++) {
372 unsigned long int fileSize;
374 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
376 MPI_Recv(&fileSize, 1, MPI_LONG, b, tag, MPI_COMM_WORLD, &status);
378 string outTemp = outputFile + toString(b) + ".temp";
380 char* buf = new char[outTemp.length()];
381 memcpy(buf, outTemp.c_str(), outTemp.length());
383 MPI_File_open(MPI_COMM_SELF, buf, MPI_MODE_DELETE_ON_CLOSE|MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);
387 while (count < fileSize) {
389 MPI_File_read(inMPI, buf2, 1, MPI_CHAR, &status);
390 MPI_File_write(outMPI, buf2, 1, MPI_CHAR, &status);
394 MPI_File_close(&inMPI); //deleted on close
397 MPI_File_close(&outMPI);
398 }else { //you are a child process
400 unsigned long int size;
401 if (output != "square"){ driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size); }
402 else { driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size, output); }
404 if (m->control_pressed) { delete distCalculator; return 0; }
406 //tell parent you are done.
407 MPI_Send(&size, 1, MPI_LONG, 0, tag, MPI_COMM_WORLD);
410 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
413 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
414 //if you don't need to fork anything
416 if (output != "square") { driver(0, numSeqs, outputFile, cutoff); }
417 else { driver(0, numSeqs, outputFile, "square"); }
418 }else{ //you have multiple processors
420 unsigned long int numDists = 0;
422 if (output == "square") {
423 numDists = numSeqs * numSeqs;
425 for(int i=0;i<numSeqs;i++){
426 for(int j=0;j<i;j++){
428 if (numDists > processors) { break; }
433 if (numDists < processors) { processors = numDists; }
435 for (int i = 0; i < processors; i++) {
436 distlinePair tempLine;
437 lines.push_back(tempLine);
438 if (output != "square") {
439 lines[i].start = int (sqrt(float(i)/float(processors)) * numSeqs);
440 lines[i].end = int (sqrt(float(i+1)/float(processors)) * numSeqs);
442 lines[i].start = int ((float(i)/float(processors)) * numSeqs);
443 lines[i].end = int ((float(i+1)/float(processors)) * numSeqs);
448 createProcesses(outputFile);
452 if (output != "square") { driver(0, numSeqs, outputFile, cutoff); }
453 else { driver(0, numSeqs, outputFile, "square"); }
457 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; remove(outputFile.c_str()); return 0; }
460 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
462 if (pid == 0) { //only one process should output to screen
465 //if (output == "square") { convertMatrix(outputFile); }
468 fileHandle.open(outputFile.c_str());
470 m->gobble(fileHandle);
471 if (fileHandle.eof()) { m->mothurOut(outputFile + " is blank. This can result if there are no distances below your cutoff."); m->mothurOutEndLine(); }
474 //append the old column file to the new one
475 if ((oldfastafile != "") && (column != "")) {
476 //we had to rename the column file so we didnt overwrite above, but we want to keep old name
477 if (outputFile == column) {
478 string tempcolumn = column + ".old";
479 m->appendFiles(tempcolumn, outputFile);
480 remove(tempcolumn.c_str());
482 m->appendFiles(outputFile, column);
483 remove(outputFile.c_str());
487 if (outputDir != "") {
488 string newOutputName = outputDir + m->getSimpleName(outputFile);
489 rename(outputFile.c_str(), newOutputName.c_str());
490 remove(outputFile.c_str());
491 outputFile = newOutputName;
500 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; remove(outputFile.c_str()); return 0; }
502 delete distCalculator;
504 //set phylip file as new current phylipfile
506 itTypes = outputTypes.find("phylip");
507 if (itTypes != outputTypes.end()) {
508 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setPhylipFile(current); }
511 //set column file as new current columnfile
512 itTypes = outputTypes.find("column");
513 if (itTypes != outputTypes.end()) {
514 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setColumnFile(current); }
517 m->mothurOutEndLine();
518 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
519 m->mothurOut(outputFile); m->mothurOutEndLine();
520 m->mothurOutEndLine();
521 m->mothurOut("It took " + toString(time(NULL) - startTime) + " to calculate the distances for " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
524 if (m->isTrue(compress)) {
525 m->mothurOut("Compressing..."); m->mothurOutEndLine();
526 m->mothurOut("(Replacing " + outputFile + " with " + outputFile + ".gz)"); m->mothurOutEndLine();
527 system(("gzip -v " + outputFile).c_str());
528 outputNames.push_back(outputFile + ".gz");
529 }else { outputNames.push_back(outputFile); }
534 catch(exception& e) {
535 m->errorOut(e, "DistanceCommand", "execute");
539 /**************************************************************************************************/
540 void DistanceCommand::createProcesses(string filename) {
542 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
546 //loop through and create all the processes you want
547 while (process != processors) {
551 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
554 if (output != "square") { driver(lines[process].start, lines[process].end, filename + toString(getpid()) + ".temp", cutoff); }
555 else { driver(lines[process].start, lines[process].end, filename + toString(getpid()) + ".temp", "square"); }
558 m->mothurOut("[ERROR]: unable to spawn the necessary processes. Error code: " + toString(pid)); m->mothurOutEndLine();
560 for (int i=0;i<processIDS.size();i++) { int temp = processIDS[i]; kill (temp, SIGINT); }
565 //parent does its part
566 if (output != "square") { driver(lines[0].start, lines[0].end, filename, cutoff); }
567 else { driver(lines[0].start, lines[0].end, filename, "square"); }
570 //force parent to wait until all the processes are done
571 for (int i=0;i<processIDS.size();i++) {
572 int temp = processIDS[i];
576 //append and remove temp files
577 for (int i=0;i<processIDS.size();i++) {
578 m->appendFiles((filename + toString(processIDS[i]) + ".temp"), filename);
579 remove((filename + toString(processIDS[i]) + ".temp").c_str());
583 catch(exception& e) {
584 m->errorOut(e, "DistanceCommand", "createProcesses");
589 /**************************************************************************************************/
590 /////// need to fix to work with calcs and sequencedb
591 int DistanceCommand::driver(int startLine, int endLine, string dFileName, float cutoff){
594 int startTime = time(NULL);
597 ofstream outFile(dFileName.c_str(), ios::trunc);
598 outFile.setf(ios::fixed, ios::showpoint);
599 outFile << setprecision(4);
601 if((output == "lt") && startLine == 0){ outFile << alignDB.getNumSeqs() << endl; }
603 for(int i=startLine;i<endLine;i++){
605 string name = alignDB.get(i).getName();
606 if (name.length() < 10) { //pad with spaces to make compatible
607 while (name.length() < 10) { name += " "; }
609 outFile << name << '\t';
611 for(int j=0;j<i;j++){
613 if (m->control_pressed) { outFile.close(); return 0; }
615 //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
616 //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
617 if ((i >= numNewFasta) && (j >= numNewFasta)) { break; }
619 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
620 double dist = distCalculator->getDist();
623 if (output == "column") { outFile << alignDB.get(i).getName() << ' ' << alignDB.get(j).getName() << ' ' << dist << endl; }
625 if (output == "lt") { outFile << dist << '\t'; }
628 if (output == "lt") { outFile << endl; }
631 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
635 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
641 catch(exception& e) {
642 m->errorOut(e, "DistanceCommand", "driver");
646 /**************************************************************************************************/
647 /////// need to fix to work with calcs and sequencedb
648 int DistanceCommand::driver(int startLine, int endLine, string dFileName, string square){
651 int startTime = time(NULL);
654 ofstream outFile(dFileName.c_str(), ios::trunc);
655 outFile.setf(ios::fixed, ios::showpoint);
656 outFile << setprecision(4);
658 if(startLine == 0){ outFile << alignDB.getNumSeqs() << endl; }
660 for(int i=startLine;i<endLine;i++){
662 string name = alignDB.get(i).getName();
663 //pad with spaces to make compatible
664 if (name.length() < 10) { while (name.length() < 10) { name += " "; } }
666 outFile << name << '\t';
668 for(int j=0;j<alignDB.getNumSeqs();j++){
670 if (m->control_pressed) { outFile.close(); return 0; }
672 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
673 double dist = distCalculator->getDist();
675 outFile << dist << '\t';
681 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
685 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
691 catch(exception& e) {
692 m->errorOut(e, "DistanceCommand", "driver");
697 /**************************************************************************************************/
698 /////// need to fix to work with calcs and sequencedb
699 int DistanceCommand::driverMPI(int startLine, int endLine, MPI_File& outMPI, float cutoff){
702 int startTime = time(NULL);
704 string outputString = "";
706 for(int i=startLine;i<endLine;i++){
708 for(int j=0;j<i;j++){
710 if (m->control_pressed) { return 0; }
712 //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
713 //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
714 if ((i >= numNewFasta) && (j >= numNewFasta)) { break; }
716 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
717 double dist = distCalculator->getDist();
720 outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n');
725 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
726 cout << i << '\t' << (time(NULL) - startTime) << endl;
730 //send results to parent
731 int length = outputString.length();
733 char* buf = new char[length];
734 memcpy(buf, outputString.c_str(), length);
736 MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status);
742 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
743 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
746 catch(exception& e) {
747 m->errorOut(e, "DistanceCommand", "driverMPI");
751 /**************************************************************************************************/
752 /////// need to fix to work with calcs and sequencedb
753 int DistanceCommand::driverMPI(int startLine, int endLine, string file, unsigned long int& size){
758 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
760 //char* filename = new char[file.length()];
761 //memcpy(filename, file.c_str(), file.length());
764 strcpy(filename, file.c_str());
766 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
769 int startTime = time(NULL);
771 string outputString = "";
774 if(startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n"; }
776 for(int i=startLine;i<endLine;i++){
778 string name = alignDB.get(i).getName();
779 if (name.length() < 10) { //pad with spaces to make compatible
780 while (name.length() < 10) { name += " "; }
782 outputString += name + "\t";
784 for(int j=0;j<i;j++){
786 if (m->control_pressed) { return 0; }
788 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
789 double dist = distCalculator->getDist();
791 outputString += toString(dist) + "\t";
794 outputString += "\n";
798 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
799 cout << i << '\t' << (time(NULL) - startTime) << endl;
803 //send results to parent
804 int length = outputString.length();
805 char* buf = new char[length];
806 memcpy(buf, outputString.c_str(), length);
808 MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
809 size += outputString.length();
814 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
815 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
816 MPI_File_close(&outMPI);
820 catch(exception& e) {
821 m->errorOut(e, "DistanceCommand", "driverMPI");
825 /**************************************************************************************************/
826 /////// need to fix to work with calcs and sequencedb
827 int DistanceCommand::driverMPI(int startLine, int endLine, string file, unsigned long int& size, string square){
832 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
834 //char* filename = new char[file.length()];
835 //memcpy(filename, file.c_str(), file.length());
838 strcpy(filename, file.c_str());
840 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
843 int startTime = time(NULL);
845 string outputString = "";
848 if(startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n"; }
850 for(int i=startLine;i<endLine;i++){
852 string name = alignDB.get(i).getName();
853 if (name.length() < 10) { //pad with spaces to make compatible
854 while (name.length() < 10) { name += " "; }
856 outputString += name + "\t";
858 for(int j=0;j<alignDB.getNumSeqs();j++){
860 if (m->control_pressed) { return 0; }
862 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
863 double dist = distCalculator->getDist();
865 outputString += toString(dist) + "\t";
868 outputString += "\n";
872 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
873 cout << i << '\t' << (time(NULL) - startTime) << endl;
877 //send results to parent
878 int length = outputString.length();
879 char* buf = new char[length];
880 memcpy(buf, outputString.c_str(), length);
882 MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
883 size += outputString.length();
888 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
889 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
890 MPI_File_close(&outMPI);
894 catch(exception& e) {
895 m->errorOut(e, "DistanceCommand", "driverMPI");
900 /**************************************************************************************************
901 int DistanceCommand::convertMatrix(string outputFile) {
904 //sort file by first column so the distances for each row are together
905 string outfile = m->getRootName(outputFile) + "sorted.dist.temp";
908 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
909 string command = "sort -n " + outputFile + " -o " + outfile;
910 system(command.c_str());
911 #else //sort using windows sort
912 string command = "sort " + outputFile + " /O " + outfile;
913 system(command.c_str());
917 //output to new file distance for each row and save positions in file where new row begins
919 m->openInputFile(outfile, in);
922 m->openOutputFile(outputFile, out);
924 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
926 out << alignDB.getNumSeqs() << endl;
928 //get first currentRow
929 string first, currentRow, second;
931 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key
932 map<string, float>::iterator it;
937 rowDists[first] = 0.00; //distance to yourself is 0.0
940 //m->openInputFile(outfile, in);
943 if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
945 in >> first >> second >> dist; m->gobble(in);
947 if (first != currentRow) {
949 out << currentRow << '\t'; //print name
952 for (it = rowDists.begin(); it != rowDists.end(); it++) {
953 out << it->second << '\t';
960 rowDists[first] = 0.00;
961 rowDists[second] = dist;
963 rowDists[second] = dist;
967 out << currentRow << '\t'; //print name
970 for (it = rowDists.begin(); it != rowDists.end(); it++) {
971 out << it->second << '\t';
978 remove(outfile.c_str());
983 catch(exception& e) {
984 m->errorOut(e, "DistanceCommand", "convertMatrix");
988 /**************************************************************************************************
989 int DistanceCommand::convertToLowerTriangle(string outputFile) {
992 //sort file by first column so the distances for each row are together
993 string outfile = m->getRootName(outputFile) + "sorted.dist.temp";
996 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
997 string command = "sort -n " + outputFile + " -o " + outfile;
998 system(command.c_str());
999 #else //sort using windows sort
1000 string command = "sort " + outputFile + " /O " + outfile;
1001 system(command.c_str());
1005 //output to new file distance for each row and save positions in file where new row begins
1007 m->openInputFile(outfile, in);
1010 m->openOutputFile(outputFile, out);
1012 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1014 out << alignDB.getNumSeqs() << endl;
1016 //get first currentRow
1017 string first, currentRow, second;
1021 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key
1022 map<string, float>::iterator it;
1027 rowDists[first] = 0.00; //distance to yourself is 0.0
1030 //m->openInputFile(outfile, in);
1033 if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
1035 in >> first >> second >> dist; m->gobble(in);
1037 if (first != currentRow) {
1038 //print out last row
1039 out << currentRow << '\t'; //print name
1042 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1043 if (j >= i) { break; }
1044 out << it->second << '\t';
1052 rowDists[first] = 0.00;
1053 rowDists[second] = dist;
1057 rowDists[second] = dist;
1060 //print out last row
1061 out << currentRow << '\t'; //print name
1064 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1065 out << it->second << '\t';
1072 remove(outfile.c_str());
1077 catch(exception& e) {
1078 m->errorOut(e, "DistanceCommand", "convertToLowerTriangle");
1082 /**************************************************************************************************/
1083 //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,
1084 //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.
1085 //also check to make sure the 2 files have the same alignment length.
1086 bool DistanceCommand::sanityCheck() {
1090 //make sure the 2 fasta files have the same alignment length
1092 m->openInputFile(fastafile, in);
1093 int fastaAlignLength = 0;
1095 Sequence tempIn(in);
1096 fastaAlignLength = tempIn.getAligned().length();
1101 m->openInputFile(oldfastafile, in2);
1102 int oldfastaAlignLength = 0;
1104 Sequence tempIn2(in2);
1105 oldfastaAlignLength = tempIn2.getAligned().length();
1109 if (fastaAlignLength != oldfastaAlignLength) { m->mothurOut("fasta files do not have the same alignment length."); m->mothurOutEndLine(); return false; }
1111 //read fasta file and save names as well as adding them to the alignDB
1112 set<string> namesOldFasta;
1115 m->openInputFile(oldfastafile, inFasta);
1117 while (!inFasta.eof()) {
1118 if (m->control_pressed) { inFasta.close(); return good; }
1120 Sequence temp(inFasta);
1122 if (temp.getName() != "") {
1123 namesOldFasta.insert(temp.getName()); //save name
1124 alignDB.push_back(temp); //add to DB
1132 //read through the column file checking names and removing distances above the cutoff
1134 m->openInputFile(column, inDist);
1137 string outputFile = column + ".temp";
1138 m->openOutputFile(outputFile, outDist);
1140 string name1, name2;
1142 while (!inDist.eof()) {
1143 if (m->control_pressed) { inDist.close(); outDist.close(); remove(outputFile.c_str()); return good; }
1145 inDist >> name1 >> name2 >> dist; m->gobble(inDist);
1147 //both names are in fasta file and distance is below cutoff
1148 if ((namesOldFasta.count(name1) == 0) || (namesOldFasta.count(name2) == 0)) { good = false; break; }
1150 if (dist <= cutoff) {
1151 outDist << name1 << '\t' << name2 << '\t' << dist << endl;
1160 remove(column.c_str());
1161 rename(outputFile.c_str(), column.c_str());
1163 remove(outputFile.c_str()); //temp file is bad because file mismatch above
1169 catch(exception& e) {
1170 m->errorOut(e, "DistanceCommand", "sanityCheck");
1174 /**************************************************************************************************/