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::setParameters(){
20 CommandParameter pcolumn("column", "InputTypes", "", "", "none", "none", "OldFastaColumn",false,false); parameters.push_back(pcolumn);
21 CommandParameter poldfasta("oldfasta", "InputTypes", "", "", "none", "none", "OldFastaColumn",false,false); parameters.push_back(poldfasta);
22 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
23 CommandParameter poutput("output", "Multiple", "column-lt-square", "column", "", "", "",false,false); parameters.push_back(poutput);
24 CommandParameter pcalc("calc", "Multiple", "nogaps-eachgap-onegap", "onegap", "", "", "",false,false); parameters.push_back(pcalc);
25 CommandParameter pcountends("countends", "Boolean", "", "T", "", "", "",false,false); parameters.push_back(pcountends);
26 CommandParameter pcompress("compress", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(pcompress);
27 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
28 CommandParameter pcutoff("cutoff", "Number", "", "1.0", "", "", "",false,false); parameters.push_back(pcutoff);
29 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
30 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
32 vector<string> myArray;
33 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
37 m->errorOut(e, "DistanceCommand", "setParameters");
41 //**********************************************************************************************************************
42 string DistanceCommand::getHelpString(){
44 string helpString = "";
45 helpString += "The dist.seqs command reads a file containing sequences and creates a distance file.\n";
46 helpString += "The dist.seqs command parameters are fasta, oldfasta, column, calc, countends, output, compress, cutoff and processors. \n";
47 helpString += "The fasta parameter is required, unless you have a valid current fasta file.\n";
48 helpString += "The oldfasta and column parameters allow you to append the distances calculated to the column file.\n";
49 helpString += "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";
50 helpString += "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";
51 helpString += "The cutoff parameter allows you to specify maximum distance to keep. The default is 1.0.\n";
52 helpString += "The output parameter allows you to specify format of your distance matrix. Options are column, lt, and square. The default is column.\n";
53 helpString += "The processors parameter allows you to specify number of processors to use. The default is 1.\n";
54 helpString += "The compress parameter allows you to indicate that you want the resulting distance file compressed. The default is false.\n";
55 helpString += "The dist.seqs command should be in the following format: \n";
56 helpString += "dist.seqs(fasta=yourFastaFile, calc=yourCalc, countends=yourEnds, cutoff= yourCutOff, processors=yourProcessors) \n";
57 helpString += "Example dist.seqs(fasta=amazon.fasta, calc=eachgap, countends=F, cutoff= 2.0, processors=3).\n";
58 helpString += "Note: No spaces between parameter labels (i.e. calc), '=' and parameters (i.e.yourCalc).\n";
62 m->errorOut(e, "DistanceCommand", "getHelpString");
66 //**********************************************************************************************************************
67 DistanceCommand::DistanceCommand(){
69 abort = true; calledHelp = true;
71 vector<string> tempOutNames;
72 outputTypes["phylip"] = tempOutNames;
73 outputTypes["column"] = tempOutNames;
76 m->errorOut(e, "DistanceCommand", "DistanceCommand");
80 //**********************************************************************************************************************
81 DistanceCommand::DistanceCommand(string option) {
83 abort = false; calledHelp = false;
86 //allow user to run help
87 if(option == "help") { help(); abort = true; calledHelp = true; }
88 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
91 vector<string> myArray = setParameters();
93 OptionParser parser(option);
94 map<string, string> parameters = parser.getParameters();
96 ValidParameters validParameter("dist.seqs");
97 map<string, string>::iterator it2;
99 //check to make sure all parameters are valid for command
100 for (it2 = parameters.begin(); it2 != parameters.end(); it2++) {
101 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) { abort = true; }
104 //initialize outputTypes
105 vector<string> tempOutNames;
106 outputTypes["phylip"] = tempOutNames;
107 outputTypes["column"] = tempOutNames;
109 //if the user changes the input directory command factory will send this info to us in the output parameter
110 string inputDir = validParameter.validFile(parameters, "inputdir", false);
111 if (inputDir == "not found"){ inputDir = ""; }
114 it2 = parameters.find("fasta");
115 //user has given a template file
116 if(it2 != parameters.end()){
117 path = m->hasPath(it2->second);
118 //if the user has not given a path then, add inputdir. else leave path alone.
119 if (path == "") { parameters["fasta"] = inputDir + it2->second; }
122 it2 = parameters.find("oldfasta");
123 //user has given a template file
124 if(it2 != parameters.end()){
125 path = m->hasPath(it2->second);
126 //if the user has not given a path then, add inputdir. else leave path alone.
127 if (path == "") { parameters["oldfasta"] = inputDir + it2->second; }
130 it2 = parameters.find("column");
131 //user has given a template file
132 if(it2 != parameters.end()){
133 path = m->hasPath(it2->second);
134 //if the user has not given a path then, add inputdir. else leave path alone.
135 if (path == "") { parameters["column"] = inputDir + it2->second; }
139 //check for required parameters
140 fastafile = validParameter.validFile(parameters, "fasta", true);
141 if (fastafile == "not found") {
142 fastafile = m->getFastaFile();
143 if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine();
145 m->openInputFile(fastafile, inFASTA);
146 alignDB = SequenceDB(inFASTA);
148 }else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
149 }else if (fastafile == "not open") { abort = true; }
152 m->openInputFile(fastafile, inFASTA);
153 alignDB = SequenceDB(inFASTA);
155 m->setFastaFile(fastafile);
158 oldfastafile = validParameter.validFile(parameters, "oldfasta", true);
159 if (oldfastafile == "not found") { oldfastafile = ""; }
160 else if (oldfastafile == "not open") { abort = true; }
162 column = validParameter.validFile(parameters, "column", true);
163 if (column == "not found") { column = ""; }
164 else if (column == "not open") { abort = true; }
165 else { m->setColumnFile(column); }
167 //if the user changes the output directory command factory will send this info to us in the output parameter
168 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
170 outputDir += m->hasPath(fastafile); //if user entered a file with a path then preserve it
173 //check for optional parameter and set defaults
174 // ...at some point should added some additional type checking...
175 calc = validParameter.validFile(parameters, "calc", false);
176 if (calc == "not found") { calc = "onegap"; }
178 if (calc == "default") { calc = "onegap"; }
180 m->splitAtDash(calc, Estimators);
183 temp = validParameter.validFile(parameters, "countends", false); if(temp == "not found"){ temp = "T"; }
184 convert(temp, countends);
186 temp = validParameter.validFile(parameters, "cutoff", false); if(temp == "not found"){ temp = "1.0"; }
187 convert(temp, cutoff);
189 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
190 m->setProcessors(temp);
191 convert(temp, processors);
193 temp = validParameter.validFile(parameters, "compress", false); if(temp == "not found"){ temp = "F"; }
194 convert(temp, compress);
196 output = validParameter.validFile(parameters, "output", false); if(output == "not found"){ output = "column"; }
198 if (((column != "") && (oldfastafile == "")) || ((column == "") && (oldfastafile != ""))) { m->mothurOut("If you provide column or oldfasta, you must provide both."); m->mothurOutEndLine(); abort=true; }
200 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; }
202 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"; }
204 ValidCalculators validCalculator;
206 if (m->isTrue(countends) == true) {
207 for (int i=0; i<Estimators.size(); i++) {
208 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
209 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
210 else if (Estimators[i] == "eachgap") { distCalculator = new eachGapDist(); }
211 else if (Estimators[i] == "onegap") { distCalculator = new oneGapDist(); }
215 for (int i=0; i<Estimators.size(); i++) {
216 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
217 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
218 else if (Estimators[i] == "eachgap"){ distCalculator = new eachGapIgnoreTermGapDist(); }
219 else if (Estimators[i] == "onegap") { distCalculator = new oneGapIgnoreTermGapDist(); }
227 catch(exception& e) {
228 m->errorOut(e, "DistanceCommand", "DistanceCommand");
232 //**********************************************************************************************************************
234 int DistanceCommand::execute(){
237 if (abort == true) { if (calledHelp) { return 0; } return 2; }
239 int startTime = time(NULL);
241 //save number of new sequence
242 numNewFasta = alignDB.getNumSeqs();
244 //sanity check the oldfasta and column file as well as add oldfasta sequences to alignDB
245 if ((oldfastafile != "") && (column != "")) { if (!(sanityCheck())) { return 0; } }
247 if (m->control_pressed) { return 0; }
249 int numSeqs = alignDB.getNumSeqs();
252 if (!alignDB.sameLength()) { m->mothurOut("[ERROR]: your sequences are not the same length, aborting."); m->mothurOutEndLine(); return 0; }
256 if (output == "lt") { //does the user want lower triangle phylip formatted file
257 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "phylip.dist";
258 remove(outputFile.c_str()); outputTypes["phylip"].push_back(outputFile);
260 //output numSeqs to phylip formatted dist file
261 }else if (output == "column") { //user wants column format
262 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "dist";
263 outputTypes["column"].push_back(outputFile);
265 //so we don't accidentally overwrite
266 if (outputFile == column) {
267 string tempcolumn = column + ".old";
268 rename(column.c_str(), tempcolumn.c_str());
271 remove(outputFile.c_str());
272 }else { //assume square
273 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "square.dist";
274 remove(outputFile.c_str());
275 outputTypes["phylip"].push_back(outputFile);
285 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running
286 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
288 //each process gets where it should start and stop in the file
289 if (output != "square") {
290 start = int (sqrt(float(pid)/float(processors)) * numSeqs);
291 end = int (sqrt(float(pid+1)/float(processors)) * numSeqs);
293 start = int ((float(pid)/float(processors)) * numSeqs);
294 end = int ((float(pid+1)/float(processors)) * numSeqs);
297 if (output == "column") {
299 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
301 //char* filename = new char[outputFile.length()];
302 //memcpy(filename, outputFile.c_str(), outputFile.length());
305 strcpy(filename, outputFile.c_str());
307 MPI_File_open(MPI_COMM_WORLD, filename, amode, MPI_INFO_NULL, &outMPI);
310 if (pid == 0) { //you are the root process
315 driverMPI(start, end, outMPI, cutoff);
317 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
320 for(int i = 1; i < processors; i++) {
321 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
324 MPI_Recv(buf, 5, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status);
326 }else { //you are a child process
328 driverMPI(start, end, outMPI, cutoff);
330 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
334 //tell parent you are done.
335 MPI_Send(buf, 5, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
338 MPI_File_close(&outMPI);
340 }else { //lower triangle format
341 if (pid == 0) { //you are the root process
345 unsigned long int mySize;
347 if (output != "square"){ driverMPI(start, end, outputFile, mySize); }
348 else { driverMPI(start, end, outputFile, mySize, output); }
350 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; return 0; }
352 int amode=MPI_MODE_APPEND|MPI_MODE_WRONLY|MPI_MODE_CREATE; //
356 //char* filename = new char[outputFile.length()];
357 //memcpy(filename, outputFile.c_str(), outputFile.length());
360 strcpy(filename, outputFile.c_str());
362 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
366 for(int b = 1; b < processors; b++) {
367 unsigned long int fileSize;
369 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
371 MPI_Recv(&fileSize, 1, MPI_LONG, b, tag, MPI_COMM_WORLD, &status);
373 string outTemp = outputFile + toString(b) + ".temp";
375 char* buf = new char[outTemp.length()];
376 memcpy(buf, outTemp.c_str(), outTemp.length());
378 MPI_File_open(MPI_COMM_SELF, buf, MPI_MODE_DELETE_ON_CLOSE|MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);
382 while (count < fileSize) {
384 MPI_File_read(inMPI, buf2, 1, MPI_CHAR, &status);
385 MPI_File_write(outMPI, buf2, 1, MPI_CHAR, &status);
389 MPI_File_close(&inMPI); //deleted on close
392 MPI_File_close(&outMPI);
393 }else { //you are a child process
395 unsigned long int size;
396 if (output != "square"){ driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size); }
397 else { driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size, output); }
399 if (m->control_pressed) { delete distCalculator; return 0; }
401 //tell parent you are done.
402 MPI_Send(&size, 1, MPI_LONG, 0, tag, MPI_COMM_WORLD);
405 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
408 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
409 //if you don't need to fork anything
411 if (output != "square") { driver(0, numSeqs, outputFile, cutoff); }
412 else { driver(0, numSeqs, outputFile, "square"); }
413 }else{ //you have multiple processors
415 unsigned long int numDists = 0;
417 if (output == "square") {
418 numDists = numSeqs * numSeqs;
420 for(int i=0;i<numSeqs;i++){
421 for(int j=0;j<i;j++){
423 if (numDists > processors) { break; }
428 if (numDists < processors) { processors = numDists; }
430 for (int i = 0; i < processors; i++) {
431 distlinePair tempLine;
432 lines.push_back(tempLine);
433 if (output != "square") {
434 lines[i].start = int (sqrt(float(i)/float(processors)) * numSeqs);
435 lines[i].end = int (sqrt(float(i+1)/float(processors)) * numSeqs);
437 lines[i].start = int ((float(i)/float(processors)) * numSeqs);
438 lines[i].end = int ((float(i+1)/float(processors)) * numSeqs);
443 createProcesses(outputFile);
447 if (output != "square") { driver(0, numSeqs, outputFile, cutoff); }
448 else { driver(0, numSeqs, outputFile, "square"); }
452 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; remove(outputFile.c_str()); return 0; }
455 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
457 if (pid == 0) { //only one process should output to screen
460 //if (output == "square") { convertMatrix(outputFile); }
463 fileHandle.open(outputFile.c_str());
465 m->gobble(fileHandle);
466 if (fileHandle.eof()) { m->mothurOut(outputFile + " is blank. This can result if there are no distances below your cutoff."); m->mothurOutEndLine(); }
469 //append the old column file to the new one
470 if ((oldfastafile != "") && (column != "")) {
471 //we had to rename the column file so we didnt overwrite above, but we want to keep old name
472 if (outputFile == column) {
473 string tempcolumn = column + ".old";
474 m->appendFiles(tempcolumn, outputFile);
475 remove(tempcolumn.c_str());
477 m->appendFiles(outputFile, column);
478 remove(outputFile.c_str());
482 if (outputDir != "") {
483 string newOutputName = outputDir + m->getSimpleName(outputFile);
484 rename(outputFile.c_str(), newOutputName.c_str());
485 remove(outputFile.c_str());
486 outputFile = newOutputName;
495 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; remove(outputFile.c_str()); return 0; }
497 delete distCalculator;
499 //set phylip file as new current phylipfile
501 itTypes = outputTypes.find("phylip");
502 if (itTypes != outputTypes.end()) {
503 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setPhylipFile(current); }
506 //set column file as new current columnfile
507 itTypes = outputTypes.find("column");
508 if (itTypes != outputTypes.end()) {
509 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setColumnFile(current); }
512 m->mothurOutEndLine();
513 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
514 m->mothurOut(outputFile); m->mothurOutEndLine();
515 m->mothurOutEndLine();
516 m->mothurOut("It took " + toString(time(NULL) - startTime) + " to calculate the distances for " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
519 if (m->isTrue(compress)) {
520 m->mothurOut("Compressing..."); m->mothurOutEndLine();
521 m->mothurOut("(Replacing " + outputFile + " with " + outputFile + ".gz)"); m->mothurOutEndLine();
522 system(("gzip -v " + outputFile).c_str());
523 outputNames.push_back(outputFile + ".gz");
524 }else { outputNames.push_back(outputFile); }
529 catch(exception& e) {
530 m->errorOut(e, "DistanceCommand", "execute");
534 /**************************************************************************************************/
535 void DistanceCommand::createProcesses(string filename) {
537 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
541 //loop through and create all the processes you want
542 while (process != processors) {
546 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
549 if (output != "square") { driver(lines[process].start, lines[process].end, filename + toString(getpid()) + ".temp", cutoff); }
550 else { driver(lines[process].start, lines[process].end, filename + toString(getpid()) + ".temp", "square"); }
553 m->mothurOut("[ERROR]: unable to spawn the necessary processes. Error code: " + toString(pid)); m->mothurOutEndLine();
555 for (int i=0;i<processIDS.size();i++) { int temp = processIDS[i]; kill (temp, SIGINT); }
560 //parent does its part
561 if (output != "square") { driver(lines[0].start, lines[0].end, filename, cutoff); }
562 else { driver(lines[0].start, lines[0].end, filename, "square"); }
565 //force parent to wait until all the processes are done
566 for (int i=0;i<processIDS.size();i++) {
567 int temp = processIDS[i];
571 //append and remove temp files
572 for (int i=0;i<processIDS.size();i++) {
573 m->appendFiles((filename + toString(processIDS[i]) + ".temp"), filename);
574 remove((filename + toString(processIDS[i]) + ".temp").c_str());
578 catch(exception& e) {
579 m->errorOut(e, "DistanceCommand", "createProcesses");
584 /**************************************************************************************************/
585 /////// need to fix to work with calcs and sequencedb
586 int DistanceCommand::driver(int startLine, int endLine, string dFileName, float cutoff){
589 int startTime = time(NULL);
592 ofstream outFile(dFileName.c_str(), ios::trunc);
593 outFile.setf(ios::fixed, ios::showpoint);
594 outFile << setprecision(4);
596 if((output == "lt") && startLine == 0){ outFile << alignDB.getNumSeqs() << endl; }
598 for(int i=startLine;i<endLine;i++){
600 string name = alignDB.get(i).getName();
601 if (name.length() < 10) { //pad with spaces to make compatible
602 while (name.length() < 10) { name += " "; }
604 outFile << name << '\t';
606 for(int j=0;j<i;j++){
608 if (m->control_pressed) { outFile.close(); return 0; }
610 //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
611 //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
612 if ((i >= numNewFasta) && (j >= numNewFasta)) { break; }
614 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
615 double dist = distCalculator->getDist();
618 if (output == "column") { outFile << alignDB.get(i).getName() << ' ' << alignDB.get(j).getName() << ' ' << dist << endl; }
620 if (output == "lt") { outFile << dist << '\t'; }
623 if (output == "lt") { outFile << endl; }
626 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
630 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
636 catch(exception& e) {
637 m->errorOut(e, "DistanceCommand", "driver");
641 /**************************************************************************************************/
642 /////// need to fix to work with calcs and sequencedb
643 int DistanceCommand::driver(int startLine, int endLine, string dFileName, string square){
646 int startTime = time(NULL);
649 ofstream outFile(dFileName.c_str(), ios::trunc);
650 outFile.setf(ios::fixed, ios::showpoint);
651 outFile << setprecision(4);
653 if(startLine == 0){ outFile << alignDB.getNumSeqs() << endl; }
655 for(int i=startLine;i<endLine;i++){
657 string name = alignDB.get(i).getName();
658 //pad with spaces to make compatible
659 if (name.length() < 10) { while (name.length() < 10) { name += " "; } }
661 outFile << name << '\t';
663 for(int j=0;j<alignDB.getNumSeqs();j++){
665 if (m->control_pressed) { outFile.close(); return 0; }
667 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
668 double dist = distCalculator->getDist();
670 outFile << dist << '\t';
676 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
680 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
686 catch(exception& e) {
687 m->errorOut(e, "DistanceCommand", "driver");
692 /**************************************************************************************************/
693 /////// need to fix to work with calcs and sequencedb
694 int DistanceCommand::driverMPI(int startLine, int endLine, MPI_File& outMPI, float cutoff){
697 int startTime = time(NULL);
699 string outputString = "";
701 for(int i=startLine;i<endLine;i++){
703 for(int j=0;j<i;j++){
705 if (m->control_pressed) { return 0; }
707 //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
708 //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
709 if ((i >= numNewFasta) && (j >= numNewFasta)) { break; }
711 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
712 double dist = distCalculator->getDist();
715 outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n');
720 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
721 cout << i << '\t' << (time(NULL) - startTime) << endl;
725 //send results to parent
726 int length = outputString.length();
728 char* buf = new char[length];
729 memcpy(buf, outputString.c_str(), length);
731 MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status);
737 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
738 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
741 catch(exception& e) {
742 m->errorOut(e, "DistanceCommand", "driverMPI");
746 /**************************************************************************************************/
747 /////// need to fix to work with calcs and sequencedb
748 int DistanceCommand::driverMPI(int startLine, int endLine, string file, unsigned long int& size){
753 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
755 //char* filename = new char[file.length()];
756 //memcpy(filename, file.c_str(), file.length());
759 strcpy(filename, file.c_str());
761 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
764 int startTime = time(NULL);
766 string outputString = "";
769 if(startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n"; }
771 for(int i=startLine;i<endLine;i++){
773 string name = alignDB.get(i).getName();
774 if (name.length() < 10) { //pad with spaces to make compatible
775 while (name.length() < 10) { name += " "; }
777 outputString += name + "\t";
779 for(int j=0;j<i;j++){
781 if (m->control_pressed) { return 0; }
783 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
784 double dist = distCalculator->getDist();
786 outputString += toString(dist) + "\t";
789 outputString += "\n";
793 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
794 cout << i << '\t' << (time(NULL) - startTime) << endl;
798 //send results to parent
799 int length = outputString.length();
800 char* buf = new char[length];
801 memcpy(buf, outputString.c_str(), length);
803 MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
804 size += outputString.length();
809 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
810 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
811 MPI_File_close(&outMPI);
815 catch(exception& e) {
816 m->errorOut(e, "DistanceCommand", "driverMPI");
820 /**************************************************************************************************/
821 /////// need to fix to work with calcs and sequencedb
822 int DistanceCommand::driverMPI(int startLine, int endLine, string file, unsigned long int& size, string square){
827 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
829 //char* filename = new char[file.length()];
830 //memcpy(filename, file.c_str(), file.length());
833 strcpy(filename, file.c_str());
835 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
838 int startTime = time(NULL);
840 string outputString = "";
843 if(startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n"; }
845 for(int i=startLine;i<endLine;i++){
847 string name = alignDB.get(i).getName();
848 if (name.length() < 10) { //pad with spaces to make compatible
849 while (name.length() < 10) { name += " "; }
851 outputString += name + "\t";
853 for(int j=0;j<alignDB.getNumSeqs();j++){
855 if (m->control_pressed) { return 0; }
857 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
858 double dist = distCalculator->getDist();
860 outputString += toString(dist) + "\t";
863 outputString += "\n";
867 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
868 cout << i << '\t' << (time(NULL) - startTime) << endl;
872 //send results to parent
873 int length = outputString.length();
874 char* buf = new char[length];
875 memcpy(buf, outputString.c_str(), length);
877 MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
878 size += outputString.length();
883 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
884 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
885 MPI_File_close(&outMPI);
889 catch(exception& e) {
890 m->errorOut(e, "DistanceCommand", "driverMPI");
895 /**************************************************************************************************
896 int DistanceCommand::convertMatrix(string outputFile) {
899 //sort file by first column so the distances for each row are together
900 string outfile = m->getRootName(outputFile) + "sorted.dist.temp";
903 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
904 string command = "sort -n " + outputFile + " -o " + outfile;
905 system(command.c_str());
906 #else //sort using windows sort
907 string command = "sort " + outputFile + " /O " + outfile;
908 system(command.c_str());
912 //output to new file distance for each row and save positions in file where new row begins
914 m->openInputFile(outfile, in);
917 m->openOutputFile(outputFile, out);
919 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
921 out << alignDB.getNumSeqs() << endl;
923 //get first currentRow
924 string first, currentRow, second;
926 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key
927 map<string, float>::iterator it;
932 rowDists[first] = 0.00; //distance to yourself is 0.0
935 //m->openInputFile(outfile, in);
938 if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
940 in >> first >> second >> dist; m->gobble(in);
942 if (first != currentRow) {
944 out << currentRow << '\t'; //print name
947 for (it = rowDists.begin(); it != rowDists.end(); it++) {
948 out << it->second << '\t';
955 rowDists[first] = 0.00;
956 rowDists[second] = dist;
958 rowDists[second] = dist;
962 out << currentRow << '\t'; //print name
965 for (it = rowDists.begin(); it != rowDists.end(); it++) {
966 out << it->second << '\t';
973 remove(outfile.c_str());
978 catch(exception& e) {
979 m->errorOut(e, "DistanceCommand", "convertMatrix");
983 /**************************************************************************************************
984 int DistanceCommand::convertToLowerTriangle(string outputFile) {
987 //sort file by first column so the distances for each row are together
988 string outfile = m->getRootName(outputFile) + "sorted.dist.temp";
991 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
992 string command = "sort -n " + outputFile + " -o " + outfile;
993 system(command.c_str());
994 #else //sort using windows sort
995 string command = "sort " + outputFile + " /O " + outfile;
996 system(command.c_str());
1000 //output to new file distance for each row and save positions in file where new row begins
1002 m->openInputFile(outfile, in);
1005 m->openOutputFile(outputFile, out);
1007 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1009 out << alignDB.getNumSeqs() << endl;
1011 //get first currentRow
1012 string first, currentRow, second;
1016 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key
1017 map<string, float>::iterator it;
1022 rowDists[first] = 0.00; //distance to yourself is 0.0
1025 //m->openInputFile(outfile, in);
1028 if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
1030 in >> first >> second >> dist; m->gobble(in);
1032 if (first != currentRow) {
1033 //print out last row
1034 out << currentRow << '\t'; //print name
1037 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1038 if (j >= i) { break; }
1039 out << it->second << '\t';
1047 rowDists[first] = 0.00;
1048 rowDists[second] = dist;
1052 rowDists[second] = dist;
1055 //print out last row
1056 out << currentRow << '\t'; //print name
1059 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1060 out << it->second << '\t';
1067 remove(outfile.c_str());
1072 catch(exception& e) {
1073 m->errorOut(e, "DistanceCommand", "convertToLowerTriangle");
1077 /**************************************************************************************************/
1078 //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,
1079 //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.
1080 //also check to make sure the 2 files have the same alignment length.
1081 bool DistanceCommand::sanityCheck() {
1085 //make sure the 2 fasta files have the same alignment length
1087 m->openInputFile(fastafile, in);
1088 int fastaAlignLength = 0;
1090 Sequence tempIn(in);
1091 fastaAlignLength = tempIn.getAligned().length();
1096 m->openInputFile(oldfastafile, in2);
1097 int oldfastaAlignLength = 0;
1099 Sequence tempIn2(in2);
1100 oldfastaAlignLength = tempIn2.getAligned().length();
1104 if (fastaAlignLength != oldfastaAlignLength) { m->mothurOut("fasta files do not have the same alignment length."); m->mothurOutEndLine(); return false; }
1106 //read fasta file and save names as well as adding them to the alignDB
1107 set<string> namesOldFasta;
1110 m->openInputFile(oldfastafile, inFasta);
1112 while (!inFasta.eof()) {
1113 if (m->control_pressed) { inFasta.close(); return good; }
1115 Sequence temp(inFasta);
1117 if (temp.getName() != "") {
1118 namesOldFasta.insert(temp.getName()); //save name
1119 alignDB.push_back(temp); //add to DB
1127 //read through the column file checking names and removing distances above the cutoff
1129 m->openInputFile(column, inDist);
1132 string outputFile = column + ".temp";
1133 m->openOutputFile(outputFile, outDist);
1135 string name1, name2;
1137 while (!inDist.eof()) {
1138 if (m->control_pressed) { inDist.close(); outDist.close(); remove(outputFile.c_str()); return good; }
1140 inDist >> name1 >> name2 >> dist; m->gobble(inDist);
1142 //both names are in fasta file and distance is below cutoff
1143 if ((namesOldFasta.count(name1) == 0) || (namesOldFasta.count(name2) == 0)) { good = false; break; }
1145 if (dist <= cutoff) {
1146 outDist << name1 << '\t' << name2 << '\t' << dist << endl;
1155 remove(column.c_str());
1156 rename(outputFile.c_str(), column.c_str());
1158 remove(outputFile.c_str()); //temp file is bad because file mismatch above
1164 catch(exception& e) {
1165 m->errorOut(e, "DistanceCommand", "sanityCheck");
1169 /**************************************************************************************************/