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 //**********************************************************************************************************************
18 vector<string> DistanceCommand::getValidParameters(){
20 string Array[] = {"fasta","oldfasta","column", "output", "calc", "countends", "cutoff", "processors", "outputdir","inputdir","compress"};
21 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
25 m->errorOut(e, "DistanceCommand", "getValidParameters");
29 //**********************************************************************************************************************
30 DistanceCommand::DistanceCommand(){
33 //initialize outputTypes
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, "ChopSeqsCommand", "getRequiredParameters");
55 //**********************************************************************************************************************
56 vector<string> DistanceCommand::getRequiredFiles(){
58 vector<string> myArray;
62 m->errorOut(e, "DistanceCommand", "getRequiredFiles");
66 //**********************************************************************************************************************
67 DistanceCommand::DistanceCommand(string option) {
72 //allow user to run help
73 if(option == "help") { help(); abort = 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 for(int i=0;i<lines.size();i++){
221 //**********************************************************************************************************************
223 void DistanceCommand::help(){
225 m->mothurOut("The dist.seqs command reads a file containing sequences and creates a distance file.\n");
226 m->mothurOut("The dist.seqs command parameters are fasta, oldfasta, column, calc, countends, output, compress, cutoff and processors. \n");
227 m->mothurOut("The fasta parameter is required.\n");
228 m->mothurOut("The oldfasta and column parameters allow you to append the distances calculated to the column file.\n");
229 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");
230 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");
231 m->mothurOut("The cutoff parameter allows you to specify maximum distance to keep. The default is 1.0.\n");
232 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");
233 m->mothurOut("The processors parameter allows you to specify number of processors to use. The default is 1.\n");
234 m->mothurOut("The compress parameter allows you to indicate that you want the resulting distance file compressed. The default is false.\n");
235 m->mothurOut("The dist.seqs command should be in the following format: \n");
236 m->mothurOut("dist.seqs(fasta=yourFastaFile, calc=yourCalc, countends=yourEnds, cutoff= yourCutOff, processors=yourProcessors) \n");
237 m->mothurOut("Example dist.seqs(fasta=amazon.fasta, calc=eachgap, countends=F, cutoff= 2.0, processors=3).\n");
238 m->mothurOut("Note: No spaces between parameter labels (i.e. calc), '=' and parameters (i.e.yourCalc).\n\n");
240 catch(exception& e) {
241 m->errorOut(e, "DistanceCommand", "help");
245 //**********************************************************************************************************************
247 int DistanceCommand::execute(){
250 if (abort == true) { return 0; }
252 int startTime = time(NULL);
254 //save number of new sequence
255 numNewFasta = alignDB.getNumSeqs();
257 //sanity check the oldfasta and column file as well as add oldfasta sequences to alignDB
258 if ((oldfastafile != "") && (column != "")) { if (!(sanityCheck())) { return 0; } }
260 if (m->control_pressed) { return 0; }
262 int numSeqs = alignDB.getNumSeqs();
267 if (output == "lt") { //does the user want lower triangle phylip formatted file
268 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "phylip.dist";
269 remove(outputFile.c_str()); outputTypes["phylip"].push_back(outputFile);
271 //output numSeqs to phylip formatted dist file
272 }else if (output == "column") { //user wants column format
273 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "dist";
274 outputTypes["column"].push_back(outputFile);
276 //so we don't accidentally overwrite
277 if (outputFile == column) {
278 string tempcolumn = column + ".old";
279 rename(column.c_str(), tempcolumn.c_str());
282 remove(outputFile.c_str());
283 }else { //assume square
284 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "square.dist";
285 remove(outputFile.c_str());
286 outputTypes["phylip"].push_back(outputFile);
296 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running
297 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
299 //each process gets where it should start and stop in the file
300 if (output != "square") {
301 start = int (sqrt(float(pid)/float(processors)) * numSeqs);
302 end = int (sqrt(float(pid+1)/float(processors)) * numSeqs);
304 start = int ((float(pid)/float(processors)) * numSeqs);
305 end = int ((float(pid+1)/float(processors)) * numSeqs);
308 if (output == "column") {
310 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
312 //char* filename = new char[outputFile.length()];
313 //memcpy(filename, outputFile.c_str(), outputFile.length());
316 strcpy(filename, outputFile.c_str());
318 MPI_File_open(MPI_COMM_WORLD, filename, amode, MPI_INFO_NULL, &outMPI);
321 if (pid == 0) { //you are the root process
326 driverMPI(start, end, outMPI, cutoff);
328 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
331 for(int i = 1; i < processors; i++) {
332 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
335 MPI_Recv(buf, 5, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status);
337 }else { //you are a child process
339 driverMPI(start, end, outMPI, cutoff);
341 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
345 //tell parent you are done.
346 MPI_Send(buf, 5, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
349 MPI_File_close(&outMPI);
351 }else { //lower triangle format
352 if (pid == 0) { //you are the root process
356 unsigned long int mySize;
358 if (output != "square"){ driverMPI(start, end, outputFile, mySize); }
359 else { driverMPI(start, end, outputFile, mySize, output); }
361 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; return 0; }
363 int amode=MPI_MODE_APPEND|MPI_MODE_WRONLY|MPI_MODE_CREATE; //
367 //char* filename = new char[outputFile.length()];
368 //memcpy(filename, outputFile.c_str(), outputFile.length());
371 strcpy(filename, outputFile.c_str());
373 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
377 for(int b = 1; b < processors; b++) {
378 unsigned long int fileSize;
380 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
382 MPI_Recv(&fileSize, 1, MPI_LONG, b, tag, MPI_COMM_WORLD, &status);
384 string outTemp = outputFile + toString(b) + ".temp";
386 char* buf = new char[outTemp.length()];
387 memcpy(buf, outTemp.c_str(), outTemp.length());
389 MPI_File_open(MPI_COMM_SELF, buf, MPI_MODE_DELETE_ON_CLOSE|MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);
393 while (count < fileSize) {
395 MPI_File_read(inMPI, buf2, 1, MPI_CHAR, &status);
396 MPI_File_write(outMPI, buf2, 1, MPI_CHAR, &status);
400 MPI_File_close(&inMPI); //deleted on close
403 MPI_File_close(&outMPI);
404 }else { //you are a child process
406 unsigned long int size;
407 if (output != "square"){ driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size); }
408 else { driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size, output); }
410 if (m->control_pressed) { delete distCalculator; return 0; }
412 //tell parent you are done.
413 MPI_Send(&size, 1, MPI_LONG, 0, tag, MPI_COMM_WORLD);
416 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
419 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
420 //if you don't need to fork anything
422 if (output != "square") { driver(0, numSeqs, outputFile, cutoff); }
423 else { driver(0, numSeqs, outputFile, "square"); }
424 }else{ //you have multiple processors
426 unsigned long int numDists = 0;
428 if (output == "square") {
429 numDists = numSeqs * numSeqs;
431 for(int i=0;i<numSeqs;i++){
432 for(int j=0;j<i;j++){
434 if (numDists > processors) { break; }
439 if (numDists < processors) { processors = numDists; }
441 for (int i = 0; i < processors; i++) {
442 lines.push_back(new linePair());
443 if (output != "square") {
444 lines[i]->start = int (sqrt(float(i)/float(processors)) * numSeqs);
445 lines[i]->end = int (sqrt(float(i+1)/float(processors)) * numSeqs);
447 lines[i]->start = int ((float(i)/float(processors)) * numSeqs);
448 lines[i]->end = int ((float(i+1)/float(processors)) * numSeqs);
450 //cout << i << '\t' << lines[i]->start << '\t' << lines[i]->end << endl;
453 createProcesses(outputFile);
457 if (output != "square") { driver(0, numSeqs, outputFile, cutoff); }
458 else { driver(0, numSeqs, outputFile, "square"); }
462 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; remove(outputFile.c_str()); return 0; }
465 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
467 if (pid == 0) { //only one process should output to screen
470 //if (output == "square") { convertMatrix(outputFile); }
473 fileHandle.open(outputFile.c_str());
475 m->gobble(fileHandle);
476 if (fileHandle.eof()) { m->mothurOut(outputFile + " is blank. This can result if there are no distances below your cutoff."); m->mothurOutEndLine(); }
479 //append the old column file to the new one
480 if ((oldfastafile != "") && (column != "")) {
481 //we had to rename the column file so we didnt overwrite above, but we want to keep old name
482 if (outputFile == column) {
483 string tempcolumn = column + ".old";
484 m->appendFiles(tempcolumn, outputFile);
485 remove(tempcolumn.c_str());
487 m->appendFiles(outputFile, column);
488 remove(outputFile.c_str());
492 if (outputDir != "") {
493 string newOutputName = outputDir + m->getSimpleName(outputFile);
494 rename(outputFile.c_str(), newOutputName.c_str());
495 remove(outputFile.c_str());
496 outputFile = newOutputName;
505 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; remove(outputFile.c_str()); return 0; }
507 delete distCalculator;
509 m->mothurOutEndLine();
510 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
511 m->mothurOut(outputFile); m->mothurOutEndLine();
512 m->mothurOutEndLine();
513 m->mothurOut("It took " + toString(time(NULL) - startTime) + " to calculate the distances for " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
516 if (m->isTrue(compress)) {
517 m->mothurOut("Compressing..."); m->mothurOutEndLine();
518 m->mothurOut("(Replacing " + outputFile + " with " + outputFile + ".gz)"); m->mothurOutEndLine();
519 system(("gzip -v " + outputFile).c_str());
520 outputNames.push_back(outputFile + ".gz");
521 }else { outputNames.push_back(outputFile); }
526 catch(exception& e) {
527 m->errorOut(e, "DistanceCommand", "execute");
531 /**************************************************************************************************/
532 void DistanceCommand::createProcesses(string filename) {
534 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
538 //loop through and create all the processes you want
539 while (process != processors) {
543 processIDS[lines[process]->end] = pid; //create map from line number to pid so you can append files in correct order later
546 if (output != "square") { driver(lines[process]->start, lines[process]->end, filename + toString(getpid()) + ".temp", cutoff); }
547 else { driver(lines[process]->start, lines[process]->end, filename + toString(getpid()) + ".temp", "square"); }
550 m->mothurOut("[ERROR]: unable to spawn the necessary processes. Error code: " + toString(pid)); m->mothurOutEndLine();
551 for (map<int, int>::iterator it = processIDS.begin(); it != processIDS.end(); it++) { int temp = it->second; kill (temp, SIGINT); }
556 //parent does its part
557 if (output != "square") { driver(lines[0]->start, lines[0]->end, filename, cutoff); }
558 else { driver(lines[0]->start, lines[0]->end, filename, "square"); }
561 //force parent to wait until all the processes are done
562 for (map<int, int>::iterator it = processIDS.begin(); it != processIDS.end(); it++) {
563 int temp = it->second;
567 //append and remove temp files
568 for (map<int, int>::iterator it = processIDS.begin(); it != processIDS.end(); it++) {
569 m->appendFiles((filename + toString(it->second) + ".temp"), filename);
570 remove((filename + toString(it->second) + ".temp").c_str());
574 catch(exception& e) {
575 m->errorOut(e, "DistanceCommand", "createProcesses");
580 /**************************************************************************************************/
581 /////// need to fix to work with calcs and sequencedb
582 int DistanceCommand::driver(int startLine, int endLine, string dFileName, float cutoff){
585 int startTime = time(NULL);
588 ofstream outFile(dFileName.c_str(), ios::trunc);
589 outFile.setf(ios::fixed, ios::showpoint);
590 outFile << setprecision(4);
592 if((output == "lt") && startLine == 0){ outFile << alignDB.getNumSeqs() << endl; }
594 for(int i=startLine;i<endLine;i++){
596 string name = alignDB.get(i).getName();
597 if (name.length() < 10) { //pad with spaces to make compatible
598 while (name.length() < 10) { name += " "; }
600 outFile << name << '\t';
602 for(int j=0;j<i;j++){
604 if (m->control_pressed) { outFile.close(); return 0; }
606 //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
607 //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
608 if ((i >= numNewFasta) && (j >= numNewFasta)) { break; }
610 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
611 double dist = distCalculator->getDist();
614 if (output == "column") { outFile << alignDB.get(i).getName() << ' ' << alignDB.get(j).getName() << ' ' << dist << endl; }
616 if (output == "lt") { outFile << dist << '\t'; }
619 if (output == "lt") { outFile << endl; }
622 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
626 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
632 catch(exception& e) {
633 m->errorOut(e, "DistanceCommand", "driver");
637 /**************************************************************************************************/
638 /////// need to fix to work with calcs and sequencedb
639 int DistanceCommand::driver(int startLine, int endLine, string dFileName, string square){
642 int startTime = time(NULL);
645 ofstream outFile(dFileName.c_str(), ios::trunc);
646 outFile.setf(ios::fixed, ios::showpoint);
647 outFile << setprecision(4);
649 if(startLine == 0){ outFile << alignDB.getNumSeqs() << endl; }
651 for(int i=startLine;i<endLine;i++){
653 string name = alignDB.get(i).getName();
654 //pad with spaces to make compatible
655 if (name.length() < 10) { while (name.length() < 10) { name += " "; } }
657 outFile << name << '\t';
659 for(int j=0;j<alignDB.getNumSeqs();j++){
661 if (m->control_pressed) { outFile.close(); return 0; }
663 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
664 double dist = distCalculator->getDist();
666 outFile << dist << '\t';
672 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
676 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
682 catch(exception& e) {
683 m->errorOut(e, "DistanceCommand", "driver");
688 /**************************************************************************************************/
689 /////// need to fix to work with calcs and sequencedb
690 int DistanceCommand::driverMPI(int startLine, int endLine, MPI_File& outMPI, float cutoff){
693 int startTime = time(NULL);
695 string outputString = "";
697 for(int i=startLine;i<endLine;i++){
699 for(int j=0;j<i;j++){
701 if (m->control_pressed) { return 0; }
703 //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
704 //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
705 if ((i >= numNewFasta) && (j >= numNewFasta)) { break; }
707 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
708 double dist = distCalculator->getDist();
711 outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n');
716 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
717 cout << i << '\t' << (time(NULL) - startTime) << endl;
721 //send results to parent
722 int length = outputString.length();
724 char* buf = new char[length];
725 memcpy(buf, outputString.c_str(), length);
727 MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status);
733 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
734 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
737 catch(exception& e) {
738 m->errorOut(e, "DistanceCommand", "driverMPI");
742 /**************************************************************************************************/
743 /////// need to fix to work with calcs and sequencedb
744 int DistanceCommand::driverMPI(int startLine, int endLine, string file, unsigned long int& size){
749 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
751 //char* filename = new char[file.length()];
752 //memcpy(filename, file.c_str(), file.length());
755 strcpy(filename, file.c_str());
757 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
760 int startTime = time(NULL);
762 string outputString = "";
765 if(startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n"; }
767 for(int i=startLine;i<endLine;i++){
769 string name = alignDB.get(i).getName();
770 if (name.length() < 10) { //pad with spaces to make compatible
771 while (name.length() < 10) { name += " "; }
773 outputString += name + "\t";
775 for(int j=0;j<i;j++){
777 if (m->control_pressed) { return 0; }
779 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
780 double dist = distCalculator->getDist();
782 outputString += toString(dist) + "\t";
785 outputString += "\n";
789 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
790 cout << i << '\t' << (time(NULL) - startTime) << endl;
794 //send results to parent
795 int length = outputString.length();
796 char* buf = new char[length];
797 memcpy(buf, outputString.c_str(), length);
799 MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
800 size += outputString.length();
805 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
806 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
807 MPI_File_close(&outMPI);
811 catch(exception& e) {
812 m->errorOut(e, "DistanceCommand", "driverMPI");
816 /**************************************************************************************************/
817 /////// need to fix to work with calcs and sequencedb
818 int DistanceCommand::driverMPI(int startLine, int endLine, string file, unsigned long int& size, string square){
823 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
825 //char* filename = new char[file.length()];
826 //memcpy(filename, file.c_str(), file.length());
829 strcpy(filename, file.c_str());
831 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
834 int startTime = time(NULL);
836 string outputString = "";
839 if(startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n"; }
841 for(int i=startLine;i<endLine;i++){
843 string name = alignDB.get(i).getName();
844 if (name.length() < 10) { //pad with spaces to make compatible
845 while (name.length() < 10) { name += " "; }
847 outputString += name + "\t";
849 for(int j=0;j<alignDB.getNumSeqs();j++){
851 if (m->control_pressed) { return 0; }
853 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
854 double dist = distCalculator->getDist();
856 outputString += toString(dist) + "\t";
859 outputString += "\n";
863 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
864 cout << i << '\t' << (time(NULL) - startTime) << endl;
868 //send results to parent
869 int length = outputString.length();
870 char* buf = new char[length];
871 memcpy(buf, outputString.c_str(), length);
873 MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
874 size += outputString.length();
879 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
880 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
881 MPI_File_close(&outMPI);
885 catch(exception& e) {
886 m->errorOut(e, "DistanceCommand", "driverMPI");
891 /**************************************************************************************************
892 int DistanceCommand::convertMatrix(string outputFile) {
895 //sort file by first column so the distances for each row are together
896 string outfile = m->getRootName(outputFile) + "sorted.dist.temp";
899 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
900 string command = "sort -n " + outputFile + " -o " + outfile;
901 system(command.c_str());
902 #else //sort using windows sort
903 string command = "sort " + outputFile + " /O " + outfile;
904 system(command.c_str());
908 //output to new file distance for each row and save positions in file where new row begins
910 m->openInputFile(outfile, in);
913 m->openOutputFile(outputFile, out);
915 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
917 out << alignDB.getNumSeqs() << endl;
919 //get first currentRow
920 string first, currentRow, second;
922 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key
923 map<string, float>::iterator it;
928 rowDists[first] = 0.00; //distance to yourself is 0.0
931 //m->openInputFile(outfile, in);
934 if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
936 in >> first >> second >> dist; m->gobble(in);
938 if (first != currentRow) {
940 out << currentRow << '\t'; //print name
943 for (it = rowDists.begin(); it != rowDists.end(); it++) {
944 out << it->second << '\t';
951 rowDists[first] = 0.00;
952 rowDists[second] = dist;
954 rowDists[second] = dist;
958 out << currentRow << '\t'; //print name
961 for (it = rowDists.begin(); it != rowDists.end(); it++) {
962 out << it->second << '\t';
969 remove(outfile.c_str());
974 catch(exception& e) {
975 m->errorOut(e, "DistanceCommand", "convertMatrix");
979 /**************************************************************************************************
980 int DistanceCommand::convertToLowerTriangle(string outputFile) {
983 //sort file by first column so the distances for each row are together
984 string outfile = m->getRootName(outputFile) + "sorted.dist.temp";
987 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
988 string command = "sort -n " + outputFile + " -o " + outfile;
989 system(command.c_str());
990 #else //sort using windows sort
991 string command = "sort " + outputFile + " /O " + outfile;
992 system(command.c_str());
996 //output to new file distance for each row and save positions in file where new row begins
998 m->openInputFile(outfile, in);
1001 m->openOutputFile(outputFile, out);
1003 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1005 out << alignDB.getNumSeqs() << endl;
1007 //get first currentRow
1008 string first, currentRow, second;
1012 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key
1013 map<string, float>::iterator it;
1018 rowDists[first] = 0.00; //distance to yourself is 0.0
1021 //m->openInputFile(outfile, in);
1024 if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
1026 in >> first >> second >> dist; m->gobble(in);
1028 if (first != currentRow) {
1029 //print out last row
1030 out << currentRow << '\t'; //print name
1033 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1034 if (j >= i) { break; }
1035 out << it->second << '\t';
1043 rowDists[first] = 0.00;
1044 rowDists[second] = dist;
1048 rowDists[second] = dist;
1051 //print out last row
1052 out << currentRow << '\t'; //print name
1055 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1056 out << it->second << '\t';
1063 remove(outfile.c_str());
1068 catch(exception& e) {
1069 m->errorOut(e, "DistanceCommand", "convertToLowerTriangle");
1073 /**************************************************************************************************/
1074 //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,
1075 //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.
1076 //also check to make sure the 2 files have the same alignment length.
1077 bool DistanceCommand::sanityCheck() {
1081 //make sure the 2 fasta files have the same alignment length
1083 m->openInputFile(fastafile, in);
1084 int fastaAlignLength = 0;
1086 Sequence tempIn(in);
1087 fastaAlignLength = tempIn.getAligned().length();
1092 m->openInputFile(oldfastafile, in2);
1093 int oldfastaAlignLength = 0;
1095 Sequence tempIn2(in2);
1096 oldfastaAlignLength = tempIn2.getAligned().length();
1100 if (fastaAlignLength != oldfastaAlignLength) { m->mothurOut("fasta files do not have the same alignment length."); m->mothurOutEndLine(); return false; }
1102 //read fasta file and save names as well as adding them to the alignDB
1103 set<string> namesOldFasta;
1106 m->openInputFile(oldfastafile, inFasta);
1108 while (!inFasta.eof()) {
1109 if (m->control_pressed) { inFasta.close(); return good; }
1111 Sequence temp(inFasta);
1113 if (temp.getName() != "") {
1114 namesOldFasta.insert(temp.getName()); //save name
1115 alignDB.push_back(temp); //add to DB
1123 //read through the column file checking names and removing distances above the cutoff
1125 m->openInputFile(column, inDist);
1128 string outputFile = column + ".temp";
1129 m->openOutputFile(outputFile, outDist);
1131 string name1, name2;
1133 while (!inDist.eof()) {
1134 if (m->control_pressed) { inDist.close(); outDist.close(); remove(outputFile.c_str()); return good; }
1136 inDist >> name1 >> name2 >> dist; m->gobble(inDist);
1138 //both names are in fasta file and distance is below cutoff
1139 if ((namesOldFasta.count(name1) == 0) || (namesOldFasta.count(name2) == 0)) { good = false; break; }
1141 if (dist <= cutoff) {
1142 outDist << name1 << '\t' << name2 << '\t' << dist << endl;
1151 remove(column.c_str());
1152 rename(outputFile.c_str(), column.c_str());
1154 remove(outputFile.c_str()); //temp file is bad because file mismatch above
1158 catch(exception& e) {
1159 m->errorOut(e, "DistanceCommand", "m->appendFiles");
1163 /**************************************************************************************************/