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);
157 oldfastafile = validParameter.validFile(parameters, "oldfasta", true);
158 if (oldfastafile == "not found") { oldfastafile = ""; }
159 else if (oldfastafile == "not open") { abort = true; }
161 column = validParameter.validFile(parameters, "column", true);
162 if (column == "not found") { column = ""; }
163 else if (column == "not open") { abort = true; }
165 //if the user changes the output directory command factory will send this info to us in the output parameter
166 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
168 outputDir += m->hasPath(fastafile); //if user entered a file with a path then preserve it
171 //check for optional parameter and set defaults
172 // ...at some point should added some additional type checking...
173 calc = validParameter.validFile(parameters, "calc", false);
174 if (calc == "not found") { calc = "onegap"; }
176 if (calc == "default") { calc = "onegap"; }
178 m->splitAtDash(calc, Estimators);
181 temp = validParameter.validFile(parameters, "countends", false); if(temp == "not found"){ temp = "T"; }
182 convert(temp, countends);
184 temp = validParameter.validFile(parameters, "cutoff", false); if(temp == "not found"){ temp = "1.0"; }
185 convert(temp, cutoff);
187 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
188 m->setProcessors(temp);
189 convert(temp, processors);
191 temp = validParameter.validFile(parameters, "compress", false); if(temp == "not found"){ temp = "F"; }
192 convert(temp, compress);
194 output = validParameter.validFile(parameters, "output", false); if(output == "not found"){ output = "column"; }
196 if (((column != "") && (oldfastafile == "")) || ((column == "") && (oldfastafile != ""))) { m->mothurOut("If you provide column or oldfasta, you must provide both."); m->mothurOutEndLine(); abort=true; }
198 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; }
200 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"; }
202 ValidCalculators validCalculator;
204 if (m->isTrue(countends) == true) {
205 for (int i=0; i<Estimators.size(); i++) {
206 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
207 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
208 else if (Estimators[i] == "eachgap") { distCalculator = new eachGapDist(); }
209 else if (Estimators[i] == "onegap") { distCalculator = new oneGapDist(); }
213 for (int i=0; i<Estimators.size(); i++) {
214 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
215 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
216 else if (Estimators[i] == "eachgap"){ distCalculator = new eachGapIgnoreTermGapDist(); }
217 else if (Estimators[i] == "onegap") { distCalculator = new oneGapIgnoreTermGapDist(); }
225 catch(exception& e) {
226 m->errorOut(e, "DistanceCommand", "DistanceCommand");
230 //**********************************************************************************************************************
232 int DistanceCommand::execute(){
235 if (abort == true) { if (calledHelp) { return 0; } return 2; }
237 int startTime = time(NULL);
239 //save number of new sequence
240 numNewFasta = alignDB.getNumSeqs();
242 //sanity check the oldfasta and column file as well as add oldfasta sequences to alignDB
243 if ((oldfastafile != "") && (column != "")) { if (!(sanityCheck())) { return 0; } }
245 if (m->control_pressed) { return 0; }
247 int numSeqs = alignDB.getNumSeqs();
250 if (!alignDB.sameLength()) { m->mothurOut("[ERROR]: your sequences are not the same length, aborting."); m->mothurOutEndLine(); return 0; }
254 if (output == "lt") { //does the user want lower triangle phylip formatted file
255 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "phylip.dist";
256 remove(outputFile.c_str()); outputTypes["phylip"].push_back(outputFile);
258 //output numSeqs to phylip formatted dist file
259 }else if (output == "column") { //user wants column format
260 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "dist";
261 outputTypes["column"].push_back(outputFile);
263 //so we don't accidentally overwrite
264 if (outputFile == column) {
265 string tempcolumn = column + ".old";
266 rename(column.c_str(), tempcolumn.c_str());
269 remove(outputFile.c_str());
270 }else { //assume square
271 outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "square.dist";
272 remove(outputFile.c_str());
273 outputTypes["phylip"].push_back(outputFile);
283 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running
284 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
286 //each process gets where it should start and stop in the file
287 if (output != "square") {
288 start = int (sqrt(float(pid)/float(processors)) * numSeqs);
289 end = int (sqrt(float(pid+1)/float(processors)) * numSeqs);
291 start = int ((float(pid)/float(processors)) * numSeqs);
292 end = int ((float(pid+1)/float(processors)) * numSeqs);
295 if (output == "column") {
297 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
299 //char* filename = new char[outputFile.length()];
300 //memcpy(filename, outputFile.c_str(), outputFile.length());
303 strcpy(filename, outputFile.c_str());
305 MPI_File_open(MPI_COMM_WORLD, filename, amode, MPI_INFO_NULL, &outMPI);
308 if (pid == 0) { //you are the root process
313 driverMPI(start, end, outMPI, cutoff);
315 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
318 for(int i = 1; i < processors; i++) {
319 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
322 MPI_Recv(buf, 5, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status);
324 }else { //you are a child process
326 driverMPI(start, end, outMPI, cutoff);
328 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
332 //tell parent you are done.
333 MPI_Send(buf, 5, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
336 MPI_File_close(&outMPI);
338 }else { //lower triangle format
339 if (pid == 0) { //you are the root process
343 unsigned long int mySize;
345 if (output != "square"){ driverMPI(start, end, outputFile, mySize); }
346 else { driverMPI(start, end, outputFile, mySize, output); }
348 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; return 0; }
350 int amode=MPI_MODE_APPEND|MPI_MODE_WRONLY|MPI_MODE_CREATE; //
354 //char* filename = new char[outputFile.length()];
355 //memcpy(filename, outputFile.c_str(), outputFile.length());
358 strcpy(filename, outputFile.c_str());
360 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
364 for(int b = 1; b < processors; b++) {
365 unsigned long int fileSize;
367 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator; return 0; }
369 MPI_Recv(&fileSize, 1, MPI_LONG, b, tag, MPI_COMM_WORLD, &status);
371 string outTemp = outputFile + toString(b) + ".temp";
373 char* buf = new char[outTemp.length()];
374 memcpy(buf, outTemp.c_str(), outTemp.length());
376 MPI_File_open(MPI_COMM_SELF, buf, MPI_MODE_DELETE_ON_CLOSE|MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);
380 while (count < fileSize) {
382 MPI_File_read(inMPI, buf2, 1, MPI_CHAR, &status);
383 MPI_File_write(outMPI, buf2, 1, MPI_CHAR, &status);
387 MPI_File_close(&inMPI); //deleted on close
390 MPI_File_close(&outMPI);
391 }else { //you are a child process
393 unsigned long int size;
394 if (output != "square"){ driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size); }
395 else { driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size, output); }
397 if (m->control_pressed) { delete distCalculator; return 0; }
399 //tell parent you are done.
400 MPI_Send(&size, 1, MPI_LONG, 0, tag, MPI_COMM_WORLD);
403 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
406 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
407 //if you don't need to fork anything
409 if (output != "square") { driver(0, numSeqs, outputFile, cutoff); }
410 else { driver(0, numSeqs, outputFile, "square"); }
411 }else{ //you have multiple processors
413 unsigned long int numDists = 0;
415 if (output == "square") {
416 numDists = numSeqs * numSeqs;
418 for(int i=0;i<numSeqs;i++){
419 for(int j=0;j<i;j++){
421 if (numDists > processors) { break; }
426 if (numDists < processors) { processors = numDists; }
428 for (int i = 0; i < processors; i++) {
429 distlinePair tempLine;
430 lines.push_back(tempLine);
431 if (output != "square") {
432 lines[i].start = int (sqrt(float(i)/float(processors)) * numSeqs);
433 lines[i].end = int (sqrt(float(i+1)/float(processors)) * numSeqs);
435 lines[i].start = int ((float(i)/float(processors)) * numSeqs);
436 lines[i].end = int ((float(i+1)/float(processors)) * numSeqs);
441 createProcesses(outputFile);
445 if (output != "square") { driver(0, numSeqs, outputFile, cutoff); }
446 else { driver(0, numSeqs, outputFile, "square"); }
450 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; remove(outputFile.c_str()); return 0; }
453 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
455 if (pid == 0) { //only one process should output to screen
458 //if (output == "square") { convertMatrix(outputFile); }
461 fileHandle.open(outputFile.c_str());
463 m->gobble(fileHandle);
464 if (fileHandle.eof()) { m->mothurOut(outputFile + " is blank. This can result if there are no distances below your cutoff."); m->mothurOutEndLine(); }
467 //append the old column file to the new one
468 if ((oldfastafile != "") && (column != "")) {
469 //we had to rename the column file so we didnt overwrite above, but we want to keep old name
470 if (outputFile == column) {
471 string tempcolumn = column + ".old";
472 m->appendFiles(tempcolumn, outputFile);
473 remove(tempcolumn.c_str());
475 m->appendFiles(outputFile, column);
476 remove(outputFile.c_str());
480 if (outputDir != "") {
481 string newOutputName = outputDir + m->getSimpleName(outputFile);
482 rename(outputFile.c_str(), newOutputName.c_str());
483 remove(outputFile.c_str());
484 outputFile = newOutputName;
493 if (m->control_pressed) { outputTypes.clear(); delete distCalculator; remove(outputFile.c_str()); return 0; }
495 delete distCalculator;
497 //set phylip file as new current phylipfile
499 itTypes = outputTypes.find("phylip");
500 if (itTypes != outputTypes.end()) {
501 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setPhylipFile(current); }
504 //set column file as new current columnfile
505 itTypes = outputTypes.find("column");
506 if (itTypes != outputTypes.end()) {
507 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setColumnFile(current); }
510 m->mothurOutEndLine();
511 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
512 m->mothurOut(outputFile); m->mothurOutEndLine();
513 m->mothurOutEndLine();
514 m->mothurOut("It took " + toString(time(NULL) - startTime) + " to calculate the distances for " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
517 if (m->isTrue(compress)) {
518 m->mothurOut("Compressing..."); m->mothurOutEndLine();
519 m->mothurOut("(Replacing " + outputFile + " with " + outputFile + ".gz)"); m->mothurOutEndLine();
520 system(("gzip -v " + outputFile).c_str());
521 outputNames.push_back(outputFile + ".gz");
522 }else { outputNames.push_back(outputFile); }
527 catch(exception& e) {
528 m->errorOut(e, "DistanceCommand", "execute");
532 /**************************************************************************************************/
533 void DistanceCommand::createProcesses(string filename) {
535 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
539 //loop through and create all the processes you want
540 while (process != processors) {
544 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
547 if (output != "square") { driver(lines[process].start, lines[process].end, filename + toString(getpid()) + ".temp", cutoff); }
548 else { driver(lines[process].start, lines[process].end, filename + toString(getpid()) + ".temp", "square"); }
551 m->mothurOut("[ERROR]: unable to spawn the necessary processes. Error code: " + toString(pid)); m->mothurOutEndLine();
553 for (int i=0;i<processIDS.size();i++) { int temp = processIDS[i]; kill (temp, SIGINT); }
558 //parent does its part
559 if (output != "square") { driver(lines[0].start, lines[0].end, filename, cutoff); }
560 else { driver(lines[0].start, lines[0].end, filename, "square"); }
563 //force parent to wait until all the processes are done
564 for (int i=0;i<processIDS.size();i++) {
565 int temp = processIDS[i];
569 //append and remove temp files
570 for (int i=0;i<processIDS.size();i++) {
571 m->appendFiles((filename + toString(processIDS[i]) + ".temp"), filename);
572 remove((filename + toString(processIDS[i]) + ".temp").c_str());
576 catch(exception& e) {
577 m->errorOut(e, "DistanceCommand", "createProcesses");
582 /**************************************************************************************************/
583 /////// need to fix to work with calcs and sequencedb
584 int DistanceCommand::driver(int startLine, int endLine, string dFileName, float cutoff){
587 int startTime = time(NULL);
590 ofstream outFile(dFileName.c_str(), ios::trunc);
591 outFile.setf(ios::fixed, ios::showpoint);
592 outFile << setprecision(4);
594 if((output == "lt") && startLine == 0){ outFile << alignDB.getNumSeqs() << endl; }
596 for(int i=startLine;i<endLine;i++){
598 string name = alignDB.get(i).getName();
599 if (name.length() < 10) { //pad with spaces to make compatible
600 while (name.length() < 10) { name += " "; }
602 outFile << name << '\t';
604 for(int j=0;j<i;j++){
606 if (m->control_pressed) { outFile.close(); return 0; }
608 //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
609 //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
610 if ((i >= numNewFasta) && (j >= numNewFasta)) { break; }
612 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
613 double dist = distCalculator->getDist();
616 if (output == "column") { outFile << alignDB.get(i).getName() << ' ' << alignDB.get(j).getName() << ' ' << dist << endl; }
618 if (output == "lt") { outFile << dist << '\t'; }
621 if (output == "lt") { outFile << endl; }
624 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
628 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
634 catch(exception& e) {
635 m->errorOut(e, "DistanceCommand", "driver");
639 /**************************************************************************************************/
640 /////// need to fix to work with calcs and sequencedb
641 int DistanceCommand::driver(int startLine, int endLine, string dFileName, string square){
644 int startTime = time(NULL);
647 ofstream outFile(dFileName.c_str(), ios::trunc);
648 outFile.setf(ios::fixed, ios::showpoint);
649 outFile << setprecision(4);
651 if(startLine == 0){ outFile << alignDB.getNumSeqs() << endl; }
653 for(int i=startLine;i<endLine;i++){
655 string name = alignDB.get(i).getName();
656 //pad with spaces to make compatible
657 if (name.length() < 10) { while (name.length() < 10) { name += " "; } }
659 outFile << name << '\t';
661 for(int j=0;j<alignDB.getNumSeqs();j++){
663 if (m->control_pressed) { outFile.close(); return 0; }
665 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
666 double dist = distCalculator->getDist();
668 outFile << dist << '\t';
674 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
678 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
684 catch(exception& e) {
685 m->errorOut(e, "DistanceCommand", "driver");
690 /**************************************************************************************************/
691 /////// need to fix to work with calcs and sequencedb
692 int DistanceCommand::driverMPI(int startLine, int endLine, MPI_File& outMPI, float cutoff){
695 int startTime = time(NULL);
697 string outputString = "";
699 for(int i=startLine;i<endLine;i++){
701 for(int j=0;j<i;j++){
703 if (m->control_pressed) { return 0; }
705 //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
706 //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
707 if ((i >= numNewFasta) && (j >= numNewFasta)) { break; }
709 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
710 double dist = distCalculator->getDist();
713 outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n');
718 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
719 cout << i << '\t' << (time(NULL) - startTime) << endl;
723 //send results to parent
724 int length = outputString.length();
726 char* buf = new char[length];
727 memcpy(buf, outputString.c_str(), length);
729 MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status);
735 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
736 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
739 catch(exception& e) {
740 m->errorOut(e, "DistanceCommand", "driverMPI");
744 /**************************************************************************************************/
745 /////// need to fix to work with calcs and sequencedb
746 int DistanceCommand::driverMPI(int startLine, int endLine, string file, unsigned long int& size){
751 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
753 //char* filename = new char[file.length()];
754 //memcpy(filename, file.c_str(), file.length());
757 strcpy(filename, file.c_str());
759 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
762 int startTime = time(NULL);
764 string outputString = "";
767 if(startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n"; }
769 for(int i=startLine;i<endLine;i++){
771 string name = alignDB.get(i).getName();
772 if (name.length() < 10) { //pad with spaces to make compatible
773 while (name.length() < 10) { name += " "; }
775 outputString += name + "\t";
777 for(int j=0;j<i;j++){
779 if (m->control_pressed) { return 0; }
781 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
782 double dist = distCalculator->getDist();
784 outputString += toString(dist) + "\t";
787 outputString += "\n";
791 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
792 cout << i << '\t' << (time(NULL) - startTime) << endl;
796 //send results to parent
797 int length = outputString.length();
798 char* buf = new char[length];
799 memcpy(buf, outputString.c_str(), length);
801 MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
802 size += outputString.length();
807 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
808 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
809 MPI_File_close(&outMPI);
813 catch(exception& e) {
814 m->errorOut(e, "DistanceCommand", "driverMPI");
818 /**************************************************************************************************/
819 /////// need to fix to work with calcs and sequencedb
820 int DistanceCommand::driverMPI(int startLine, int endLine, string file, unsigned long int& size, string square){
825 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
827 //char* filename = new char[file.length()];
828 //memcpy(filename, file.c_str(), file.length());
831 strcpy(filename, file.c_str());
833 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
836 int startTime = time(NULL);
838 string outputString = "";
841 if(startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n"; }
843 for(int i=startLine;i<endLine;i++){
845 string name = alignDB.get(i).getName();
846 if (name.length() < 10) { //pad with spaces to make compatible
847 while (name.length() < 10) { name += " "; }
849 outputString += name + "\t";
851 for(int j=0;j<alignDB.getNumSeqs();j++){
853 if (m->control_pressed) { return 0; }
855 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
856 double dist = distCalculator->getDist();
858 outputString += toString(dist) + "\t";
861 outputString += "\n";
865 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
866 cout << i << '\t' << (time(NULL) - startTime) << endl;
870 //send results to parent
871 int length = outputString.length();
872 char* buf = new char[length];
873 memcpy(buf, outputString.c_str(), length);
875 MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
876 size += outputString.length();
881 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
882 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
883 MPI_File_close(&outMPI);
887 catch(exception& e) {
888 m->errorOut(e, "DistanceCommand", "driverMPI");
893 /**************************************************************************************************
894 int DistanceCommand::convertMatrix(string outputFile) {
897 //sort file by first column so the distances for each row are together
898 string outfile = m->getRootName(outputFile) + "sorted.dist.temp";
901 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
902 string command = "sort -n " + outputFile + " -o " + outfile;
903 system(command.c_str());
904 #else //sort using windows sort
905 string command = "sort " + outputFile + " /O " + outfile;
906 system(command.c_str());
910 //output to new file distance for each row and save positions in file where new row begins
912 m->openInputFile(outfile, in);
915 m->openOutputFile(outputFile, out);
917 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
919 out << alignDB.getNumSeqs() << endl;
921 //get first currentRow
922 string first, currentRow, second;
924 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key
925 map<string, float>::iterator it;
930 rowDists[first] = 0.00; //distance to yourself is 0.0
933 //m->openInputFile(outfile, in);
936 if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
938 in >> first >> second >> dist; m->gobble(in);
940 if (first != currentRow) {
942 out << currentRow << '\t'; //print name
945 for (it = rowDists.begin(); it != rowDists.end(); it++) {
946 out << it->second << '\t';
953 rowDists[first] = 0.00;
954 rowDists[second] = dist;
956 rowDists[second] = dist;
960 out << currentRow << '\t'; //print name
963 for (it = rowDists.begin(); it != rowDists.end(); it++) {
964 out << it->second << '\t';
971 remove(outfile.c_str());
976 catch(exception& e) {
977 m->errorOut(e, "DistanceCommand", "convertMatrix");
981 /**************************************************************************************************
982 int DistanceCommand::convertToLowerTriangle(string outputFile) {
985 //sort file by first column so the distances for each row are together
986 string outfile = m->getRootName(outputFile) + "sorted.dist.temp";
989 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
990 string command = "sort -n " + outputFile + " -o " + outfile;
991 system(command.c_str());
992 #else //sort using windows sort
993 string command = "sort " + outputFile + " /O " + outfile;
994 system(command.c_str());
998 //output to new file distance for each row and save positions in file where new row begins
1000 m->openInputFile(outfile, in);
1003 m->openOutputFile(outputFile, out);
1005 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1007 out << alignDB.getNumSeqs() << endl;
1009 //get first currentRow
1010 string first, currentRow, second;
1014 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key
1015 map<string, float>::iterator it;
1020 rowDists[first] = 0.00; //distance to yourself is 0.0
1023 //m->openInputFile(outfile, in);
1026 if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
1028 in >> first >> second >> dist; m->gobble(in);
1030 if (first != currentRow) {
1031 //print out last row
1032 out << currentRow << '\t'; //print name
1035 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1036 if (j >= i) { break; }
1037 out << it->second << '\t';
1045 rowDists[first] = 0.00;
1046 rowDists[second] = dist;
1050 rowDists[second] = dist;
1053 //print out last row
1054 out << currentRow << '\t'; //print name
1057 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1058 out << it->second << '\t';
1065 remove(outfile.c_str());
1070 catch(exception& e) {
1071 m->errorOut(e, "DistanceCommand", "convertToLowerTriangle");
1075 /**************************************************************************************************/
1076 //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,
1077 //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.
1078 //also check to make sure the 2 files have the same alignment length.
1079 bool DistanceCommand::sanityCheck() {
1083 //make sure the 2 fasta files have the same alignment length
1085 m->openInputFile(fastafile, in);
1086 int fastaAlignLength = 0;
1088 Sequence tempIn(in);
1089 fastaAlignLength = tempIn.getAligned().length();
1094 m->openInputFile(oldfastafile, in2);
1095 int oldfastaAlignLength = 0;
1097 Sequence tempIn2(in2);
1098 oldfastaAlignLength = tempIn2.getAligned().length();
1102 if (fastaAlignLength != oldfastaAlignLength) { m->mothurOut("fasta files do not have the same alignment length."); m->mothurOutEndLine(); return false; }
1104 //read fasta file and save names as well as adding them to the alignDB
1105 set<string> namesOldFasta;
1108 m->openInputFile(oldfastafile, inFasta);
1110 while (!inFasta.eof()) {
1111 if (m->control_pressed) { inFasta.close(); return good; }
1113 Sequence temp(inFasta);
1115 if (temp.getName() != "") {
1116 namesOldFasta.insert(temp.getName()); //save name
1117 alignDB.push_back(temp); //add to DB
1125 //read through the column file checking names and removing distances above the cutoff
1127 m->openInputFile(column, inDist);
1130 string outputFile = column + ".temp";
1131 m->openOutputFile(outputFile, outDist);
1133 string name1, name2;
1135 while (!inDist.eof()) {
1136 if (m->control_pressed) { inDist.close(); outDist.close(); remove(outputFile.c_str()); return good; }
1138 inDist >> name1 >> name2 >> dist; m->gobble(inDist);
1140 //both names are in fasta file and distance is below cutoff
1141 if ((namesOldFasta.count(name1) == 0) || (namesOldFasta.count(name2) == 0)) { good = false; break; }
1143 if (dist <= cutoff) {
1144 outDist << name1 << '\t' << name2 << '\t' << dist << endl;
1153 remove(column.c_str());
1154 rename(outputFile.c_str(), column.c_str());
1156 remove(outputFile.c_str()); //temp file is bad because file mismatch above
1162 catch(exception& e) {
1163 m->errorOut(e, "DistanceCommand", "sanityCheck");
1167 /**************************************************************************************************/