5 * Created by Sarah Westcott on 5/7/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
10 #include "distancecommand.h"
12 //**********************************************************************************************************************
13 vector<string> DistanceCommand::setParameters(){
15 CommandParameter pcolumn("column", "InputTypes", "", "", "none", "none", "OldFastaColumn","column",false,false); parameters.push_back(pcolumn);
16 CommandParameter poldfasta("oldfasta", "InputTypes", "", "", "none", "none", "OldFastaColumn","",false,false); parameters.push_back(poldfasta);
17 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none","phylip-column",false,true, true); parameters.push_back(pfasta);
18 CommandParameter poutput("output", "Multiple", "column-lt-square-phylip", "column", "", "", "","phylip-column",false,false, true); parameters.push_back(poutput);
19 CommandParameter pcalc("calc", "Multiple", "nogaps-eachgap-onegap", "onegap", "", "", "","",false,false); parameters.push_back(pcalc);
20 CommandParameter pcountends("countends", "Boolean", "", "T", "", "", "","",false,false); parameters.push_back(pcountends);
21 CommandParameter pcompress("compress", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(pcompress);
22 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "","",false,false, true); parameters.push_back(pprocessors);
23 CommandParameter pcutoff("cutoff", "Number", "", "1.0", "", "", "","",false,false, true); parameters.push_back(pcutoff);
24 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
25 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
27 vector<string> myArray;
28 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
32 m->errorOut(e, "DistanceCommand", "setParameters");
36 //**********************************************************************************************************************
37 string DistanceCommand::getHelpString(){
39 string helpString = "";
40 helpString += "The dist.seqs command reads a file containing sequences and creates a distance file.\n";
41 helpString += "The dist.seqs command parameters are fasta, oldfasta, column, calc, countends, output, compress, cutoff and processors. \n";
42 helpString += "The fasta parameter is required, unless you have a valid current fasta file.\n";
43 helpString += "The oldfasta and column parameters allow you to append the distances calculated to the column file.\n";
44 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";
45 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";
46 helpString += "The cutoff parameter allows you to specify maximum distance to keep. The default is 1.0.\n";
47 helpString += "The output parameter allows you to specify format of your distance matrix. Options are column, lt, and square. The default is column.\n";
48 helpString += "The processors parameter allows you to specify number of processors to use. The default is 1.\n";
49 helpString += "The compress parameter allows you to indicate that you want the resulting distance file compressed. The default is false.\n";
50 helpString += "The dist.seqs command should be in the following format: \n";
51 helpString += "dist.seqs(fasta=yourFastaFile, calc=yourCalc, countends=yourEnds, cutoff= yourCutOff, processors=yourProcessors) \n";
52 helpString += "Example dist.seqs(fasta=amazon.fasta, calc=eachgap, countends=F, cutoff= 2.0, processors=3).\n";
53 helpString += "Note: No spaces between parameter labels (i.e. calc), '=' and parameters (i.e.yourCalc).\n";
57 m->errorOut(e, "DistanceCommand", "getHelpString");
61 //**********************************************************************************************************************
62 string DistanceCommand::getOutputPattern(string type) {
66 if (type == "phylip") { pattern = "[filename],[outputtag],dist"; }
67 else if (type == "column") { pattern = "[filename],dist"; }
68 else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true; }
73 m->errorOut(e, "DistanceCommand", "getOutputPattern");
77 //**********************************************************************************************************************
78 DistanceCommand::DistanceCommand(){
80 abort = true; calledHelp = true;
82 vector<string> tempOutNames;
83 outputTypes["phylip"] = tempOutNames;
84 outputTypes["column"] = tempOutNames;
87 m->errorOut(e, "DistanceCommand", "DistanceCommand");
91 //**********************************************************************************************************************
92 DistanceCommand::DistanceCommand(string option) {
94 abort = false; calledHelp = false;
97 //allow user to run help
98 if(option == "help") { help(); abort = true; calledHelp = true; }
99 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
102 vector<string> myArray = setParameters();
104 OptionParser parser(option);
105 map<string, string> parameters = parser.getParameters();
107 ValidParameters validParameter("dist.seqs");
108 map<string, string>::iterator it2;
110 //check to make sure all parameters are valid for command
111 for (it2 = parameters.begin(); it2 != parameters.end(); it2++) {
112 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) { abort = true; }
115 //initialize outputTypes
116 vector<string> tempOutNames;
117 outputTypes["phylip"] = tempOutNames;
118 outputTypes["column"] = tempOutNames;
120 //if the user changes the input directory command factory will send this info to us in the output parameter
121 string inputDir = validParameter.validFile(parameters, "inputdir", false);
122 if (inputDir == "not found"){ inputDir = ""; }
125 it2 = parameters.find("fasta");
126 //user has given a template file
127 if(it2 != parameters.end()){
128 path = m->hasPath(it2->second);
129 //if the user has not given a path then, add inputdir. else leave path alone.
130 if (path == "") { parameters["fasta"] = inputDir + it2->second; }
133 it2 = parameters.find("oldfasta");
134 //user has given a template file
135 if(it2 != parameters.end()){
136 path = m->hasPath(it2->second);
137 //if the user has not given a path then, add inputdir. else leave path alone.
138 if (path == "") { parameters["oldfasta"] = inputDir + it2->second; }
141 it2 = parameters.find("column");
142 //user has given a template file
143 if(it2 != parameters.end()){
144 path = m->hasPath(it2->second);
145 //if the user has not given a path then, add inputdir. else leave path alone.
146 if (path == "") { parameters["column"] = inputDir + it2->second; }
150 //check for required parameters
151 fastafile = validParameter.validFile(parameters, "fasta", true);
152 if (fastafile == "not found") {
153 fastafile = m->getFastaFile();
154 if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine();
156 m->openInputFile(fastafile, inFASTA);
157 alignDB = SequenceDB(inFASTA);
159 }else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
160 }else if (fastafile == "not open") { abort = true; }
163 m->openInputFile(fastafile, inFASTA);
164 alignDB = SequenceDB(inFASTA);
166 m->setFastaFile(fastafile);
169 oldfastafile = validParameter.validFile(parameters, "oldfasta", true);
170 if (oldfastafile == "not found") { oldfastafile = ""; }
171 else if (oldfastafile == "not open") { abort = true; }
173 column = validParameter.validFile(parameters, "column", true);
174 if (column == "not found") { column = ""; }
175 else if (column == "not open") { abort = true; }
176 else { m->setColumnFile(column); }
178 //if the user changes the output directory command factory will send this info to us in the output parameter
179 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
181 outputDir += m->hasPath(fastafile); //if user entered a file with a path then preserve it
184 //check for optional parameter and set defaults
185 // ...at some point should added some additional type checking...
186 calc = validParameter.validFile(parameters, "calc", false);
187 if (calc == "not found") { calc = "onegap"; }
189 if (calc == "default") { calc = "onegap"; }
191 m->splitAtDash(calc, Estimators);
194 temp = validParameter.validFile(parameters, "countends", false); if(temp == "not found"){ temp = "T"; }
195 convert(temp, countends);
197 temp = validParameter.validFile(parameters, "cutoff", false); if(temp == "not found"){ temp = "1.0"; }
198 m->mothurConvert(temp, cutoff);
200 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
201 m->setProcessors(temp);
202 m->mothurConvert(temp, processors);
204 temp = validParameter.validFile(parameters, "compress", false); if(temp == "not found"){ temp = "F"; }
205 convert(temp, compress);
207 output = validParameter.validFile(parameters, "output", false); if(output == "not found"){ output = "column"; }
208 if (output == "phylip") { output = "lt"; }
210 if (((column != "") && (oldfastafile == "")) || ((column == "") && (oldfastafile != ""))) { m->mothurOut("If you provide column or oldfasta, you must provide both."); m->mothurOutEndLine(); abort=true; }
212 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; }
214 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"; }
219 catch(exception& e) {
220 m->errorOut(e, "DistanceCommand", "DistanceCommand");
224 //**********************************************************************************************************************
226 int DistanceCommand::execute(){
229 if (abort == true) { if (calledHelp) { return 0; } return 2; }
231 int startTime = time(NULL);
233 //save number of new sequence
234 numNewFasta = alignDB.getNumSeqs();
236 //sanity check the oldfasta and column file as well as add oldfasta sequences to alignDB
237 if ((oldfastafile != "") && (column != "")) { if (!(sanityCheck())) { return 0; } }
239 if (m->control_pressed) { return 0; }
241 int numSeqs = alignDB.getNumSeqs();
244 if (!alignDB.sameLength()) { m->mothurOut("[ERROR]: your sequences are not the same length, aborting."); m->mothurOutEndLine(); return 0; }
248 map<string, string> variables;
249 variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(fastafile));
250 if (output == "lt") { //does the user want lower triangle phylip formatted file
251 variables["[outputtag]"] = "phylip";
252 outputFile = getOutputFileName("phylip", variables);
253 m->mothurRemove(outputFile); outputTypes["phylip"].push_back(outputFile);
255 //output numSeqs to phylip formatted dist file
256 }else if (output == "column") { //user wants column format
257 outputFile = getOutputFileName("column", variables);
258 outputTypes["column"].push_back(outputFile);
260 //so we don't accidentally overwrite
261 if (outputFile == column) {
262 string tempcolumn = column + ".old";
263 rename(column.c_str(), tempcolumn.c_str());
266 m->mothurRemove(outputFile);
267 }else { //assume square
268 variables["[outputtag]"] = "square";
269 outputFile = getOutputFileName("phylip", variables);
270 m->mothurRemove(outputFile);
271 outputTypes["phylip"].push_back(outputFile);
281 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running
282 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
284 //each process gets where it should start and stop in the file
285 if (output != "square") {
286 start = int (sqrt(float(pid)/float(processors)) * numSeqs);
287 end = int (sqrt(float(pid+1)/float(processors)) * numSeqs);
289 start = int ((float(pid)/float(processors)) * numSeqs);
290 end = int ((float(pid+1)/float(processors)) * numSeqs);
293 if (output == "column") {
295 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
297 //char* filename = new char[outputFile.length()];
298 //memcpy(filename, outputFile.c_str(), outputFile.length());
301 strcpy(filename, outputFile.c_str());
303 MPI_File_open(MPI_COMM_WORLD, filename, amode, MPI_INFO_NULL, &outMPI);
306 if (pid == 0) { //you are the root process
311 driverMPI(start, end, outMPI, cutoff);
313 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); return 0; }
316 for(int i = 1; i < processors; i++) {
317 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); return 0; }
320 MPI_Recv(buf, 5, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status);
322 }else { //you are a child process
324 driverMPI(start, end, outMPI, cutoff);
326 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); return 0; }
330 //tell parent you are done.
331 MPI_Send(buf, 5, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
334 MPI_File_close(&outMPI);
336 }else { //lower triangle format
337 if (pid == 0) { //you are the root process
341 unsigned long long mySize;
343 if (output != "square"){ driverMPI(start, end, outputFile, mySize); }
344 else { driverMPI(start, end, outputFile, mySize, output); }
346 if (m->control_pressed) { outputTypes.clear(); return 0; }
348 int amode=MPI_MODE_APPEND|MPI_MODE_WRONLY|MPI_MODE_CREATE; //
352 //char* filename = new char[outputFile.length()];
353 //memcpy(filename, outputFile.c_str(), outputFile.length());
356 strcpy(filename, outputFile.c_str());
358 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
362 for(int b = 1; b < processors; b++) {
363 unsigned long long fileSize;
365 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); return 0; }
367 MPI_Recv(&fileSize, 1, MPI_LONG, b, tag, MPI_COMM_WORLD, &status);
369 string outTemp = outputFile + toString(b) + ".temp";
371 char* buf = new char[outTemp.length()];
372 memcpy(buf, outTemp.c_str(), outTemp.length());
374 MPI_File_open(MPI_COMM_SELF, buf, MPI_MODE_DELETE_ON_CLOSE|MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);
378 while (count < fileSize) {
380 MPI_File_read(inMPI, buf2, 1, MPI_CHAR, &status);
381 MPI_File_write(outMPI, buf2, 1, MPI_CHAR, &status);
385 MPI_File_close(&inMPI); //deleted on close
388 MPI_File_close(&outMPI);
389 }else { //you are a child process
391 unsigned long long size;
392 if (output != "square"){ driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size); }
393 else { driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size, output); }
395 if (m->control_pressed) { return 0; }
397 //tell parent you are done.
398 MPI_Send(&size, 1, MPI_LONG, 0, tag, MPI_COMM_WORLD);
401 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
404 //#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
405 //if you don't need to fork anything
407 if (output != "square") { driver(0, numSeqs, outputFile, cutoff); }
408 else { driver(0, numSeqs, outputFile, "square"); }
409 }else{ //you have multiple processors
411 unsigned long long numDists = 0;
413 if (output == "square") {
414 numDists = numSeqs * numSeqs;
416 for(int i=0;i<numSeqs;i++){
417 for(int j=0;j<i;j++){
419 if (numDists > processors) { break; }
424 if (numDists < processors) { processors = numDists; }
426 for (int i = 0; i < processors; i++) {
427 distlinePair tempLine;
428 lines.push_back(tempLine);
429 if (output != "square") {
430 lines[i].start = int (sqrt(float(i)/float(processors)) * numSeqs);
431 lines[i].end = int (sqrt(float(i+1)/float(processors)) * numSeqs);
433 lines[i].start = int ((float(i)/float(processors)) * numSeqs);
434 lines[i].end = int ((float(i+1)/float(processors)) * numSeqs);
439 createProcesses(outputFile);
443 //if (output != "square") { driver(0, numSeqs, outputFile, cutoff); }
444 //else { driver(0, numSeqs, outputFile, "square"); }
448 if (m->control_pressed) { outputTypes.clear(); m->mothurRemove(outputFile); return 0; }
451 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
453 if (pid == 0) { //only one process should output to screen
456 //if (output == "square") { convertMatrix(outputFile); }
459 fileHandle.open(outputFile.c_str());
461 m->gobble(fileHandle);
462 if (fileHandle.eof()) { m->mothurOut(outputFile + " is blank. This can result if there are no distances below your cutoff."); m->mothurOutEndLine(); }
465 //append the old column file to the new one
466 if ((oldfastafile != "") && (column != "")) {
467 //we had to rename the column file so we didnt overwrite above, but we want to keep old name
468 if (outputFile == column) {
469 string tempcolumn = column + ".old";
470 m->appendFiles(tempcolumn, outputFile);
471 m->mothurRemove(tempcolumn);
473 m->appendFiles(outputFile, column);
474 m->mothurRemove(outputFile);
478 if (outputDir != "") {
479 string newOutputName = outputDir + m->getSimpleName(outputFile);
480 rename(outputFile.c_str(), newOutputName.c_str());
481 m->mothurRemove(outputFile);
482 outputFile = newOutputName;
491 if (m->control_pressed) { outputTypes.clear(); m->mothurRemove(outputFile); return 0; }
493 //set phylip file as new current phylipfile
495 itTypes = outputTypes.find("phylip");
496 if (itTypes != outputTypes.end()) {
497 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setPhylipFile(current); }
500 //set column file as new current columnfile
501 itTypes = outputTypes.find("column");
502 if (itTypes != outputTypes.end()) {
503 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setColumnFile(current); }
506 m->mothurOutEndLine();
507 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
508 m->mothurOut(outputFile); m->mothurOutEndLine();
509 m->mothurOutEndLine();
510 m->mothurOut("It took " + toString(time(NULL) - startTime) + " to calculate the distances for " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
513 if (m->isTrue(compress)) {
514 m->mothurOut("Compressing..."); m->mothurOutEndLine();
515 m->mothurOut("(Replacing " + outputFile + " with " + outputFile + ".gz)"); m->mothurOutEndLine();
516 system(("gzip -v " + outputFile).c_str());
517 outputNames.push_back(outputFile + ".gz");
518 }else { outputNames.push_back(outputFile); }
523 catch(exception& e) {
524 m->errorOut(e, "DistanceCommand", "execute");
528 /**************************************************************************************************/
529 void DistanceCommand::createProcesses(string filename) {
531 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
535 //loop through and create all the processes you want
536 while (process != processors) {
540 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
543 if (output != "square") { driver(lines[process].start, lines[process].end, filename + toString(getpid()) + ".temp", cutoff); }
544 else { driver(lines[process].start, lines[process].end, filename + toString(getpid()) + ".temp", "square"); }
547 m->mothurOut("[ERROR]: unable to spawn the necessary processes. Error code: " + toString(pid)); m->mothurOutEndLine();
549 for (int i=0;i<processIDS.size();i++) { int temp = processIDS[i]; kill (temp, SIGINT); }
554 //parent does its part
555 if (output != "square") { driver(lines[0].start, lines[0].end, filename, cutoff); }
556 else { driver(lines[0].start, lines[0].end, filename, "square"); }
559 //force parent to wait until all the processes are done
560 for (int i=0;i<processIDS.size();i++) {
561 int temp = processIDS[i];
565 //////////////////////////////////////////////////////////////////////////////////////////////////////
566 //Windows version shared memory, so be careful when passing variables through the distanceData struct.
567 //Above fork() will clone, so memory is separate, but that's not the case with windows,
568 //that's why the distance calculator was moved inside of the driver to make separate copies.
569 //////////////////////////////////////////////////////////////////////////////////////////////////////
571 vector<distanceData*> pDataArray; //[processors-1];
572 DWORD dwThreadIdArray[processors-1];
573 HANDLE hThreadArray[processors-1];
575 //Create processor-1 worker threads.
576 for( int i=0; i<processors-1; i++ ){
578 // Allocate memory for thread data.
579 distanceData* tempDist = new distanceData(lines[i+1].start, lines[i+1].end, (filename + toString(i) + ".temp"), cutoff, alignDB, Estimators, m, output, numNewFasta, countends);
580 pDataArray.push_back(tempDist);
581 processIDS.push_back(i);
583 //MyDistThreadFunction is in header. It must be global or static to work with the threads.
584 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
585 hThreadArray[i] = CreateThread(NULL, 0, MyDistThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);
589 if (output != "square") { driver(lines[0].start, lines[0].end, filename, cutoff); }
590 else { driver(lines[0].start, lines[0].end, filename, "square"); }
592 //Wait until all threads have terminated.
593 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
595 //Close all thread handles and free memory allocations.
596 for(int i=0; i < pDataArray.size(); i++){
597 CloseHandle(hThreadArray[i]);
598 delete pDataArray[i];
602 //append and remove temp files
603 for (int i=0;i<processIDS.size();i++) {
604 m->appendFiles((filename + toString(processIDS[i]) + ".temp"), filename);
605 m->mothurRemove((filename + toString(processIDS[i]) + ".temp"));
609 catch(exception& e) {
610 m->errorOut(e, "DistanceCommand", "createProcesses");
614 /**************************************************************************************************/
615 /////// need to fix to work with calcs and sequencedb
616 int DistanceCommand::driver(int startLine, int endLine, string dFileName, float cutoff){
618 ValidCalculators validCalculator;
619 Dist* distCalculator;
620 if (m->isTrue(countends) == true) {
621 for (int i=0; i<Estimators.size(); i++) {
622 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
623 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
624 else if (Estimators[i] == "eachgap") { distCalculator = new eachGapDist(); }
625 else if (Estimators[i] == "onegap") { distCalculator = new oneGapDist(); }
629 for (int i=0; i<Estimators.size(); i++) {
630 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
631 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
632 else if (Estimators[i] == "eachgap"){ distCalculator = new eachGapIgnoreTermGapDist(); }
633 else if (Estimators[i] == "onegap") { distCalculator = new oneGapIgnoreTermGapDist(); }
638 int startTime = time(NULL);
641 ofstream outFile(dFileName.c_str(), ios::trunc);
642 outFile.setf(ios::fixed, ios::showpoint);
643 outFile << setprecision(4);
645 if((output == "lt") && startLine == 0){ outFile << alignDB.getNumSeqs() << endl; }
647 for(int i=startLine;i<endLine;i++){
649 string name = alignDB.get(i).getName();
650 if (name.length() < 10) { //pad with spaces to make compatible
651 while (name.length() < 10) { name += " "; }
653 outFile << name << '\t';
655 for(int j=0;j<i;j++){
657 if (m->control_pressed) { delete distCalculator; outFile.close(); return 0; }
659 //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
660 //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
661 if ((i >= numNewFasta) && (j >= numNewFasta)) { break; }
663 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
664 double dist = distCalculator->getDist();
667 if (output == "column") { outFile << alignDB.get(i).getName() << ' ' << alignDB.get(j).getName() << ' ' << dist << endl; }
669 if (output == "lt") { outFile << dist << '\t'; }
672 if (output == "lt") { outFile << endl; }
675 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
679 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
682 delete distCalculator;
686 catch(exception& e) {
687 m->errorOut(e, "DistanceCommand", "driver");
691 /**************************************************************************************************/
692 /////// need to fix to work with calcs and sequencedb
693 int DistanceCommand::driver(int startLine, int endLine, string dFileName, string square){
695 ValidCalculators validCalculator;
696 Dist* distCalculator;
697 if (m->isTrue(countends) == true) {
698 for (int i=0; i<Estimators.size(); i++) {
699 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
700 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
701 else if (Estimators[i] == "eachgap") { distCalculator = new eachGapDist(); }
702 else if (Estimators[i] == "onegap") { distCalculator = new oneGapDist(); }
706 for (int i=0; i<Estimators.size(); i++) {
707 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
708 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
709 else if (Estimators[i] == "eachgap"){ distCalculator = new eachGapIgnoreTermGapDist(); }
710 else if (Estimators[i] == "onegap") { distCalculator = new oneGapIgnoreTermGapDist(); }
715 int startTime = time(NULL);
718 ofstream outFile(dFileName.c_str(), ios::trunc);
719 outFile.setf(ios::fixed, ios::showpoint);
720 outFile << setprecision(4);
722 if(startLine == 0){ outFile << alignDB.getNumSeqs() << endl; }
724 for(int i=startLine;i<endLine;i++){
726 string name = alignDB.get(i).getName();
727 //pad with spaces to make compatible
728 if (name.length() < 10) { while (name.length() < 10) { name += " "; } }
730 outFile << name << '\t';
732 for(int j=0;j<alignDB.getNumSeqs();j++){
734 if (m->control_pressed) { delete distCalculator; outFile.close(); return 0; }
736 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
737 double dist = distCalculator->getDist();
739 outFile << dist << '\t';
745 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
749 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
752 delete distCalculator;
756 catch(exception& e) {
757 m->errorOut(e, "DistanceCommand", "driver");
762 /**************************************************************************************************/
763 /////// need to fix to work with calcs and sequencedb
764 int DistanceCommand::driverMPI(int startLine, int endLine, MPI_File& outMPI, float cutoff){
767 ValidCalculators validCalculator;
768 Dist* distCalculator;
769 if (m->isTrue(countends) == true) {
770 for (int i=0; i<Estimators.size(); i++) {
771 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
772 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
773 else if (Estimators[i] == "eachgap") { distCalculator = new eachGapDist(); }
774 else if (Estimators[i] == "onegap") { distCalculator = new oneGapDist(); }
778 for (int i=0; i<Estimators.size(); i++) {
779 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
780 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
781 else if (Estimators[i] == "eachgap"){ distCalculator = new eachGapIgnoreTermGapDist(); }
782 else if (Estimators[i] == "onegap") { distCalculator = new oneGapIgnoreTermGapDist(); }
789 int startTime = time(NULL);
791 string outputString = "";
793 for(int i=startLine;i<endLine;i++){
795 for(int j=0;j<i;j++){
797 if (m->control_pressed) { delete distCalculator; return 0; }
799 //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
800 //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
801 if ((i >= numNewFasta) && (j >= numNewFasta)) { break; }
803 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
804 double dist = distCalculator->getDist();
807 outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n');
812 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
813 cout << i << '\t' << (time(NULL) - startTime) << endl;
817 //send results to parent
818 int length = outputString.length();
820 char* buf = new char[length];
821 memcpy(buf, outputString.c_str(), length);
823 MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status);
829 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
830 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
831 delete distCalculator;
834 catch(exception& e) {
835 m->errorOut(e, "DistanceCommand", "driverMPI");
839 /**************************************************************************************************/
840 /////// need to fix to work with calcs and sequencedb
841 int DistanceCommand::driverMPI(int startLine, int endLine, string file, unsigned long long& size){
843 ValidCalculators validCalculator;
844 Dist* distCalculator;
845 if (m->isTrue(countends) == true) {
846 for (int i=0; i<Estimators.size(); i++) {
847 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
848 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
849 else if (Estimators[i] == "eachgap") { distCalculator = new eachGapDist(); }
850 else if (Estimators[i] == "onegap") { distCalculator = new oneGapDist(); }
854 for (int i=0; i<Estimators.size(); i++) {
855 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
856 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
857 else if (Estimators[i] == "eachgap"){ distCalculator = new eachGapIgnoreTermGapDist(); }
858 else if (Estimators[i] == "onegap") { distCalculator = new oneGapIgnoreTermGapDist(); }
867 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
869 //char* filename = new char[file.length()];
870 //memcpy(filename, file.c_str(), file.length());
873 strcpy(filename, file.c_str());
875 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
878 int startTime = time(NULL);
880 string outputString = "";
883 if(startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n"; }
885 for(int i=startLine;i<endLine;i++){
887 string name = alignDB.get(i).getName();
888 if (name.length() < 10) { //pad with spaces to make compatible
889 while (name.length() < 10) { name += " "; }
891 outputString += name + "\t";
893 for(int j=0;j<i;j++){
895 if (m->control_pressed) { delete distCalculator; return 0; }
897 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
898 double dist = distCalculator->getDist();
900 outputString += toString(dist) + "\t";
903 outputString += "\n";
907 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
908 cout << i << '\t' << (time(NULL) - startTime) << endl;
912 //send results to parent
913 int length = outputString.length();
914 char* buf = new char[length];
915 memcpy(buf, outputString.c_str(), length);
917 MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
918 size += outputString.length();
923 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
924 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
925 MPI_File_close(&outMPI);
926 delete distCalculator;
930 catch(exception& e) {
931 m->errorOut(e, "DistanceCommand", "driverMPI");
935 /**************************************************************************************************/
936 /////// need to fix to work with calcs and sequencedb
937 int DistanceCommand::driverMPI(int startLine, int endLine, string file, unsigned long long& size, string square){
939 ValidCalculators validCalculator;
940 Dist* distCalculator;
941 if (m->isTrue(countends) == true) {
942 for (int i=0; i<Estimators.size(); i++) {
943 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
944 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
945 else if (Estimators[i] == "eachgap") { distCalculator = new eachGapDist(); }
946 else if (Estimators[i] == "onegap") { distCalculator = new oneGapDist(); }
950 for (int i=0; i<Estimators.size(); i++) {
951 if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) {
952 if (Estimators[i] == "nogaps") { distCalculator = new ignoreGaps(); }
953 else if (Estimators[i] == "eachgap"){ distCalculator = new eachGapIgnoreTermGapDist(); }
954 else if (Estimators[i] == "onegap") { distCalculator = new oneGapIgnoreTermGapDist(); }
962 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
964 //char* filename = new char[file.length()];
965 //memcpy(filename, file.c_str(), file.length());
968 strcpy(filename, file.c_str());
970 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
973 int startTime = time(NULL);
975 string outputString = "";
978 if(startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n"; }
980 for(int i=startLine;i<endLine;i++){
982 string name = alignDB.get(i).getName();
983 if (name.length() < 10) { //pad with spaces to make compatible
984 while (name.length() < 10) { name += " "; }
986 outputString += name + "\t";
988 for(int j=0;j<alignDB.getNumSeqs();j++){
990 if (m->control_pressed) { delete distCalculator; return 0; }
992 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
993 double dist = distCalculator->getDist();
995 outputString += toString(dist) + "\t";
998 outputString += "\n";
1002 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
1003 cout << i << '\t' << (time(NULL) - startTime) << endl;
1007 //send results to parent
1008 int length = outputString.length();
1009 char* buf = new char[length];
1010 memcpy(buf, outputString.c_str(), length);
1012 MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
1013 size += outputString.length();
1018 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
1019 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
1020 MPI_File_close(&outMPI);
1021 delete distCalculator;
1024 catch(exception& e) {
1025 m->errorOut(e, "DistanceCommand", "driverMPI");
1030 /**************************************************************************************************
1031 int DistanceCommand::convertMatrix(string outputFile) {
1034 //sort file by first column so the distances for each row are together
1035 string outfile = m->getRootName(outputFile) + "sorted.dist.temp";
1038 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1039 string command = "sort -n " + outputFile + " -o " + outfile;
1040 system(command.c_str());
1041 #else //sort using windows sort
1042 string command = "sort " + outputFile + " /O " + outfile;
1043 system(command.c_str());
1047 //output to new file distance for each row and save positions in file where new row begins
1049 m->openInputFile(outfile, in);
1052 m->openOutputFile(outputFile, out);
1054 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1056 out << alignDB.getNumSeqs() << endl;
1058 //get first currentRow
1059 string first, currentRow, second;
1061 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key
1062 map<string, float>::iterator it;
1067 rowDists[first] = 0.00; //distance to yourself is 0.0
1070 //m->openInputFile(outfile, in);
1073 if (m->control_pressed) { in.close(); m->mothurRemove(outfile); out.close(); return 0; }
1075 in >> first >> second >> dist; m->gobble(in);
1077 if (first != currentRow) {
1078 //print out last row
1079 out << currentRow << '\t'; //print name
1082 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1083 out << it->second << '\t';
1090 rowDists[first] = 0.00;
1091 rowDists[second] = dist;
1093 rowDists[second] = dist;
1096 //print out last row
1097 out << currentRow << '\t'; //print name
1100 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1101 out << it->second << '\t';
1108 m->mothurRemove(outfile);
1113 catch(exception& e) {
1114 m->errorOut(e, "DistanceCommand", "convertMatrix");
1118 **************************************************************************************************
1119 int DistanceCommand::convertToLowerTriangle(string outputFile) {
1122 //sort file by first column so the distances for each row are together
1123 string outfile = m->getRootName(outputFile) + "sorted.dist.temp";
1126 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1127 string command = "sort -n " + outputFile + " -o " + outfile;
1128 system(command.c_str());
1129 #else //sort using windows sort
1130 string command = "sort " + outputFile + " /O " + outfile;
1131 system(command.c_str());
1135 //output to new file distance for each row and save positions in file where new row begins
1137 m->openInputFile(outfile, in);
1140 m->openOutputFile(outputFile, out);
1142 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1144 out << alignDB.getNumSeqs() << endl;
1146 //get first currentRow
1147 string first, currentRow, second;
1151 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key
1152 map<string, float>::iterator it;
1157 rowDists[first] = 0.00; //distance to yourself is 0.0
1160 //m->openInputFile(outfile, in);
1163 if (m->control_pressed) { in.close(); m->mothurRemove(outfile); out.close(); return 0; }
1165 in >> first >> second >> dist; m->gobble(in);
1167 if (first != currentRow) {
1168 //print out last row
1169 out << currentRow << '\t'; //print name
1172 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1173 if (j >= i) { break; }
1174 out << it->second << '\t';
1182 rowDists[first] = 0.00;
1183 rowDists[second] = dist;
1187 rowDists[second] = dist;
1190 //print out last row
1191 out << currentRow << '\t'; //print name
1194 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1195 out << it->second << '\t';
1202 m->mothurRemove(outfile);
1207 catch(exception& e) {
1208 m->errorOut(e, "DistanceCommand", "convertToLowerTriangle");
1212 **************************************************************************************************/
1213 //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,
1214 //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.
1215 //also check to make sure the 2 files have the same alignment length.
1216 bool DistanceCommand::sanityCheck() {
1220 //make sure the 2 fasta files have the same alignment length
1222 m->openInputFile(fastafile, in);
1223 int fastaAlignLength = 0;
1225 Sequence tempIn(in);
1226 fastaAlignLength = tempIn.getAligned().length();
1231 m->openInputFile(oldfastafile, in2);
1232 int oldfastaAlignLength = 0;
1234 Sequence tempIn2(in2);
1235 oldfastaAlignLength = tempIn2.getAligned().length();
1239 if (fastaAlignLength != oldfastaAlignLength) { m->mothurOut("fasta files do not have the same alignment length."); m->mothurOutEndLine(); return false; }
1241 //read fasta file and save names as well as adding them to the alignDB
1242 set<string> namesOldFasta;
1245 m->openInputFile(oldfastafile, inFasta);
1247 while (!inFasta.eof()) {
1248 if (m->control_pressed) { inFasta.close(); return good; }
1250 Sequence temp(inFasta);
1252 if (temp.getName() != "") {
1253 namesOldFasta.insert(temp.getName()); //save name
1254 alignDB.push_back(temp); //add to DB
1262 //read through the column file checking names and removing distances above the cutoff
1264 m->openInputFile(column, inDist);
1267 string outputFile = column + ".temp";
1268 m->openOutputFile(outputFile, outDist);
1270 string name1, name2;
1272 while (!inDist.eof()) {
1273 if (m->control_pressed) { inDist.close(); outDist.close(); m->mothurRemove(outputFile); return good; }
1275 inDist >> name1 >> name2 >> dist; m->gobble(inDist);
1277 //both names are in fasta file and distance is below cutoff
1278 if ((namesOldFasta.count(name1) == 0) || (namesOldFasta.count(name2) == 0)) { good = false; break; }
1280 if (dist <= cutoff) {
1281 outDist << name1 << '\t' << name2 << '\t' << dist << endl;
1290 m->mothurRemove(column);
1291 rename(outputFile.c_str(), column.c_str());
1293 m->mothurRemove(outputFile); //temp file is bad because file mismatch above
1299 catch(exception& e) {
1300 m->errorOut(e, "DistanceCommand", "sanityCheck");
1304 /**************************************************************************************************/