]> git.donarmstrong.com Git - mothur.git/blob - distancecommand.cpp
fixes while testing
[mothur.git] / distancecommand.cpp
1 /*
2  *  distancecommand.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 5/7/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
10 #include "distancecommand.h"
11 #include "ignoregaps.h"
12 #include "eachgapdist.h"
13 #include "eachgapignore.h"
14 #include "onegapdist.h"
15 #include "onegapignore.h"
16
17 //**********************************************************************************************************************
18 vector<string> DistanceCommand::getValidParameters(){   
19         try {
20                 string Array[] =  {"fasta","oldfasta","column", "output", "calc", "countends", "cutoff", "processors", "outputdir","inputdir","compress"};
21                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
22                 return myArray;
23         }
24         catch(exception& e) {
25                 m->errorOut(e, "DistanceCommand", "getValidParameters");
26                 exit(1);
27         }
28 }
29 //**********************************************************************************************************************
30 DistanceCommand::DistanceCommand(){     
31         try {
32                 abort = true;
33                 //initialize outputTypes
34                 vector<string> tempOutNames;
35                 outputTypes["phylip"] = tempOutNames;
36                 outputTypes["column"] = tempOutNames;
37         }
38         catch(exception& e) {
39                 m->errorOut(e, "DistanceCommand", "DistanceCommand");
40                 exit(1);
41         }
42 }
43 //**********************************************************************************************************************
44 vector<string> DistanceCommand::getRequiredParameters(){        
45         try {
46                 string Array[] =  {"fasta"};
47                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
48                 return myArray;
49         }
50         catch(exception& e) {
51                 m->errorOut(e, "ChopSeqsCommand", "getRequiredParameters");
52                 exit(1);
53         }
54 }
55 //**********************************************************************************************************************
56 vector<string> DistanceCommand::getRequiredFiles(){     
57         try {
58                 vector<string> myArray;
59                 return myArray;
60         }
61         catch(exception& e) {
62                 m->errorOut(e, "DistanceCommand", "getRequiredFiles");
63                 exit(1);
64         }
65 }
66 //**********************************************************************************************************************
67 DistanceCommand::DistanceCommand(string option) {
68         try {
69                 abort = false;
70                 Estimators.clear();
71                                 
72                 //allow user to run help
73                 if(option == "help") { help(); abort = true; }
74                 
75                 else {
76                         //valid paramters for this command
77                         string Array[] =  {"fasta","oldfasta","column", "output", "calc", "countends", "cutoff", "processors", "outputdir","inputdir","compress"};
78
79                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
80                         
81                         OptionParser parser(option);
82                         map<string, string> parameters = parser.getParameters();
83                         
84                         ValidParameters validParameter("dist.seqs");
85                         map<string, string>::iterator it2;
86                 
87                         //check to make sure all parameters are valid for command
88                         for (it2 = parameters.begin(); it2 != parameters.end(); it2++) { 
89                                 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) {  abort = true;  }
90                         }
91                         
92                         //initialize outputTypes
93                         vector<string> tempOutNames;
94                         outputTypes["phylip"] = tempOutNames;
95                         outputTypes["column"] = tempOutNames;
96                 
97                         //if the user changes the input directory command factory will send this info to us in the output parameter 
98                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
99                         if (inputDir == "not found"){   inputDir = "";          }
100                         else {
101                                 string path;
102                                 it2 = parameters.find("fasta");
103                                 //user has given a template file
104                                 if(it2 != parameters.end()){ 
105                                         path = m->hasPath(it2->second);
106                                         //if the user has not given a path then, add inputdir. else leave path alone.
107                                         if (path == "") {       parameters["fasta"] = inputDir + it2->second;           }
108                                 }
109                                 
110                                 it2 = parameters.find("oldfasta");
111                                 //user has given a template file
112                                 if(it2 != parameters.end()){ 
113                                         path = m->hasPath(it2->second);
114                                         //if the user has not given a path then, add inputdir. else leave path alone.
115                                         if (path == "") {       parameters["oldfasta"] = inputDir + it2->second;                }
116                                 }
117                                 
118                                 it2 = parameters.find("column");
119                                 //user has given a template file
120                                 if(it2 != parameters.end()){ 
121                                         path = m->hasPath(it2->second);
122                                         //if the user has not given a path then, add inputdir. else leave path alone.
123                                         if (path == "") {       parameters["column"] = inputDir + it2->second;          }
124                                 }
125                         }
126
127                         //check for required parameters
128                         fastafile = validParameter.validFile(parameters, "fasta", true);
129                         if (fastafile == "not found") { m->mothurOut("fasta is a required parameter for the dist.seqs command."); m->mothurOutEndLine(); abort = true; }
130                         else if (fastafile == "not open") { abort = true; }     
131                         else{
132                                 ifstream inFASTA;
133                                 m->openInputFile(fastafile, inFASTA);
134                                 alignDB = SequenceDB(inFASTA); 
135                                 inFASTA.close();
136                         }
137                         
138                         oldfastafile = validParameter.validFile(parameters, "oldfasta", true);
139                         if (oldfastafile == "not found") { oldfastafile = ""; }
140                         else if (oldfastafile == "not open") { abort = true; }  
141                         
142                         column = validParameter.validFile(parameters, "column", true);
143                         if (column == "not found") { column = ""; }
144                         else if (column == "not open") { abort = true; }        
145                         
146                         //if the user changes the output directory command factory will send this info to us in the output parameter 
147                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
148                                 outputDir = ""; 
149                                 outputDir += m->hasPath(fastafile); //if user entered a file with a path then preserve it       
150                         }
151
152                         //check for optional parameter and set defaults
153                         // ...at some point should added some additional type checking...
154                         calc = validParameter.validFile(parameters, "calc", false);                     
155                         if (calc == "not found") { calc = "onegap";  }
156                         else { 
157                                  if (calc == "default")  {  calc = "onegap";  }
158                         }
159                         m->splitAtDash(calc, Estimators);
160
161                         string temp;
162                         temp = validParameter.validFile(parameters, "countends", false);        if(temp == "not found"){        temp = "T";     }
163                         convert(temp, countends); 
164                         
165                         temp = validParameter.validFile(parameters, "cutoff", false);           if(temp == "not found"){        temp = "1.0"; }
166                         convert(temp, cutoff); 
167                         
168                         temp = validParameter.validFile(parameters, "processors", false);       if(temp == "not found"){        temp = "1"; }
169                         convert(temp, processors); 
170                         
171                         temp = validParameter.validFile(parameters, "compress", false);         if(temp == "not found"){  temp = "F"; }
172                         convert(temp, compress);
173
174                         output = validParameter.validFile(parameters, "output", false);         if(output == "not found"){      output = "column"; }
175                         
176                         if (((column != "") && (oldfastafile == "")) || ((column == "") && (oldfastafile != ""))) { m->mothurOut("If you provide column or oldfasta, you must provide both."); m->mothurOutEndLine(); abort=true; }
177                         
178                         if ((column != "") && (oldfastafile != "") && (output != "column")) { m->mothurOut("You have provided column and oldfasta, indicating you want to append distances to your column file. Your output must be in column format to do so."); m->mothurOutEndLine(); abort=true; }
179                         
180                         if ((output != "column") && (output != "lt") && (output != "square")) { m->mothurOut(output + " is not a valid output form. Options are column, lt and square. I will use column."); m->mothurOutEndLine(); output = "column"; }
181                         
182                         ValidCalculators validCalculator;
183                         
184                         if (m->isTrue(countends) == true) {
185                                 for (int i=0; i<Estimators.size(); i++) {
186                                         if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) { 
187                                                 if (Estimators[i] == "nogaps")                  {       distCalculator = new ignoreGaps();      }
188                                                 else if (Estimators[i] == "eachgap")    {       distCalculator = new eachGapDist();     }
189                                                 else if (Estimators[i] == "onegap")             {       distCalculator = new oneGapDist();      }
190                                         }
191                                 }
192                         }else {
193                                 for (int i=0; i<Estimators.size(); i++) {
194                                         if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) { 
195                                                 if (Estimators[i] == "nogaps")          {       distCalculator = new ignoreGaps();                                      }
196                                                 else if (Estimators[i] == "eachgap"){   distCalculator = new eachGapIgnoreTermGapDist();        }
197                                                 else if (Estimators[i] == "onegap")     {       distCalculator = new oneGapIgnoreTermGapDist();         }
198                                         }
199                                 }
200                         }
201
202                 }
203                                 
204         }
205         catch(exception& e) {
206                 m->errorOut(e, "DistanceCommand", "DistanceCommand");
207                 exit(1);
208         }
209 }
210
211 //**********************************************************************************************************************
212
213 DistanceCommand::~DistanceCommand(){
214         
215         for(int i=0;i<lines.size();i++){
216                 delete lines[i];
217         }
218         
219 }
220         
221 //**********************************************************************************************************************
222
223 void DistanceCommand::help(){
224         try {
225                 m->mothurOut("The dist.seqs command reads a file containing sequences and creates a distance file.\n");
226                 m->mothurOut("The dist.seqs command parameters are fasta, oldfasta, column, calc, countends, output, compress, cutoff and processors.  \n");
227                 m->mothurOut("The fasta parameter is required.\n");
228                 m->mothurOut("The oldfasta and column parameters allow you to append the distances calculated to the column file.\n");
229                 m->mothurOut("The calc parameter allows you to specify the method of calculating the distances.  Your options are: nogaps, onegap or eachgap. The default is onegap.\n");
230                 m->mothurOut("The countends parameter allows you to specify whether to include terminal gaps in distance.  Your options are: T or F. The default is T.\n");
231                 m->mothurOut("The cutoff parameter allows you to specify maximum distance to keep. The default is 1.0.\n");
232                 m->mothurOut("The output parameter allows you to specify format of your distance matrix. Options are column, lt, and square. The default is column.\n");
233                 m->mothurOut("The processors parameter allows you to specify number of processors to use.  The default is 1.\n");
234                 m->mothurOut("The compress parameter allows you to indicate that you want the resulting distance file compressed.  The default is false.\n");
235                 m->mothurOut("The dist.seqs command should be in the following format: \n");
236                 m->mothurOut("dist.seqs(fasta=yourFastaFile, calc=yourCalc, countends=yourEnds, cutoff= yourCutOff, processors=yourProcessors) \n");
237                 m->mothurOut("Example dist.seqs(fasta=amazon.fasta, calc=eachgap, countends=F, cutoff= 2.0, processors=3).\n");
238                 m->mothurOut("Note: No spaces between parameter labels (i.e. calc), '=' and parameters (i.e.yourCalc).\n\n");
239         }
240         catch(exception& e) {
241                 m->errorOut(e, "DistanceCommand", "help");
242                 exit(1);
243         }
244 }
245 //**********************************************************************************************************************
246
247 int DistanceCommand::execute(){
248         try {
249                 
250                 if (abort == true) { return 0; }
251                 
252                 int startTime = time(NULL);
253                 
254                 //save number of new sequence
255                 numNewFasta = alignDB.getNumSeqs();
256                 
257                 //sanity check the oldfasta and column file as well as add oldfasta sequences to alignDB
258                 if ((oldfastafile != "") && (column != ""))  {  if (!(sanityCheck())) { return 0; }  }
259                 
260                 if (m->control_pressed) { return 0; }
261                 
262                 int numSeqs = alignDB.getNumSeqs();
263                 cutoff += 0.005;
264                 
265                 string outputFile;
266                                 
267                 if (output == "lt") { //does the user want lower triangle phylip formatted file 
268                         outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "phylip.dist";
269                         remove(outputFile.c_str()); outputTypes["phylip"].push_back(outputFile);
270                         
271                         //output numSeqs to phylip formatted dist file
272                 }else if (output == "column") { //user wants column format
273                         outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "dist";
274                         outputTypes["column"].push_back(outputFile);
275                         
276                         //so we don't accidentally overwrite
277                         if (outputFile == column) { 
278                                 string tempcolumn = column + ".old"; 
279                                 rename(column.c_str(), tempcolumn.c_str());
280                         }
281                         
282                         remove(outputFile.c_str());
283                 }else { //assume square
284                         outputFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "square.dist";
285                         remove(outputFile.c_str());
286                         outputTypes["phylip"].push_back(outputFile);
287                 }
288                 
289
290 #ifdef USE_MPI
291                 
292                 int pid, start, end; 
293                 int tag = 2001;
294                                 
295                 MPI_Status status; 
296                 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running
297                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
298                 
299                 //each process gets where it should start and stop in the file
300                 if (output != "square") {
301                         start = int (sqrt(float(pid)/float(processors)) * numSeqs);
302                         end = int (sqrt(float(pid+1)/float(processors)) * numSeqs);
303                 }else{
304                         start = int ((float(pid)/float(processors)) * numSeqs);
305                         end = int ((float(pid+1)/float(processors)) * numSeqs);
306                 }
307                 
308                 if (output == "column") {
309                         MPI_File outMPI;
310                         int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
311
312                         //char* filename = new char[outputFile.length()];
313                         //memcpy(filename, outputFile.c_str(), outputFile.length());
314                         
315                         char filename[1024];
316                         strcpy(filename, outputFile.c_str());
317                         
318                         MPI_File_open(MPI_COMM_WORLD, filename, amode, MPI_INFO_NULL, &outMPI);
319                         //delete filename;
320
321                         if (pid == 0) { //you are the root process 
322                         
323                                 //do your part
324                                 string outputMyPart;
325                                 
326                                 driverMPI(start, end, outMPI, cutoff); 
327                                 
328                                 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&outMPI); delete distCalculator;  return 0; }
329                         
330                                 //wait on chidren
331                                 for(int i = 1; i < processors; i++) { 
332                                         if (m->control_pressed) { outputTypes.clear();  MPI_File_close(&outMPI);  delete distCalculator;  return 0; }
333                                         
334                                         char buf[5];
335                                         MPI_Recv(buf, 5, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status); 
336                                 }
337                         }else { //you are a child process
338                                 //do your part
339                                 driverMPI(start, end, outMPI, cutoff); 
340                                 
341                                 if (m->control_pressed) { outputTypes.clear();  MPI_File_close(&outMPI);  delete distCalculator;  return 0; }
342                         
343                                 char buf[5];
344                                 strcpy(buf, "done"); 
345                                 //tell parent you are done.
346                                 MPI_Send(buf, 5, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
347                         }
348                         
349                         MPI_File_close(&outMPI);
350                         
351                 }else { //lower triangle format
352                         if (pid == 0) { //you are the root process 
353                         
354                                 //do your part
355                                 string outputMyPart;
356                                 unsigned long int mySize;
357                                 
358                                 if (output != "square"){ driverMPI(start, end, outputFile, mySize); }
359                                 else { driverMPI(start, end, outputFile, mySize, output); }
360         
361                                 if (m->control_pressed) {  outputTypes.clear();  delete distCalculator;  return 0; }
362                                 
363                                 int amode=MPI_MODE_APPEND|MPI_MODE_WRONLY|MPI_MODE_CREATE; //
364                                 MPI_File outMPI;
365                                 MPI_File inMPI;
366
367                                 //char* filename = new char[outputFile.length()];
368                                 //memcpy(filename, outputFile.c_str(), outputFile.length());
369                                 
370                                 char filename[1024];
371                                 strcpy(filename, outputFile.c_str());
372
373                                 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
374                                 //delete filename;
375
376                                 //wait on chidren
377                                 for(int b = 1; b < processors; b++) { 
378                                         unsigned long int fileSize;
379                                         
380                                         if (m->control_pressed) { outputTypes.clear();  MPI_File_close(&outMPI);  delete distCalculator;  return 0; }
381                                         
382                                         MPI_Recv(&fileSize, 1, MPI_LONG, b, tag, MPI_COMM_WORLD, &status); 
383                                         
384                                         string outTemp = outputFile + toString(b) + ".temp";
385
386                                         char* buf = new char[outTemp.length()];
387                                         memcpy(buf, outTemp.c_str(), outTemp.length());
388                                         
389                                         MPI_File_open(MPI_COMM_SELF, buf, MPI_MODE_DELETE_ON_CLOSE|MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);
390                                         delete buf;
391
392                                         int count = 0;
393                                         while (count < fileSize) { 
394                                                 char buf2[1];
395                                                 MPI_File_read(inMPI, buf2, 1, MPI_CHAR, &status);
396                                                 MPI_File_write(outMPI, buf2, 1, MPI_CHAR, &status);
397                                                 count += 1;
398                                         }
399                                         
400                                         MPI_File_close(&inMPI); //deleted on close
401                                 }
402                                 
403                                 MPI_File_close(&outMPI);
404                         }else { //you are a child process
405                                 //do your part
406                                 unsigned long int size;
407                                 if (output != "square"){ driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size); }
408                                 else { driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size, output); }
409                                 
410                                 if (m->control_pressed) { delete distCalculator;  return 0; }
411                         
412                                 //tell parent you are done.
413                                 MPI_Send(&size, 1, MPI_LONG, 0, tag, MPI_COMM_WORLD);
414                         }
415                 }
416                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
417 #else           
418                                 
419         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
420                 //if you don't need to fork anything
421                 if(processors == 1){
422                         if (output != "square") {  driver(0, numSeqs, outputFile, cutoff); }
423                         else { driver(0, numSeqs, outputFile, "square");  }
424                 }else{ //you have multiple processors
425                         
426                         for (int i = 0; i < processors; i++) {
427                                 lines.push_back(new linePair());
428                                 if (output != "square") {
429                                         lines[i]->start = int (sqrt(float(i)/float(processors)) * numSeqs);
430                                         lines[i]->end = int (sqrt(float(i+1)/float(processors)) * numSeqs);
431                                 }else{
432                                         lines[i]->start = int ((float(i)/float(processors)) * numSeqs);
433                                         lines[i]->end = int ((float(i+1)/float(processors)) * numSeqs);
434                                 }
435                         }
436
437                         createProcesses(outputFile); 
438                 
439                         map<int, int>::iterator it = processIDS.begin();
440                         rename((outputFile + toString(it->second) + ".temp").c_str(), outputFile.c_str());
441                         it++;
442                         
443                         //append and remove temp files
444                         for (; it != processIDS.end(); it++) {
445                                 m->appendFiles((outputFile + toString(it->second) + ".temp"), outputFile);
446                                 remove((outputFile + toString(it->second) + ".temp").c_str());
447                         }
448                 }
449         #else
450                 //ifstream inFASTA;
451                 if (output != "square") {  driver(0, numSeqs, outputFile, cutoff); }
452                 else { driver(0, numSeqs, outputFile, "square");  }
453         #endif
454         
455 #endif
456                 if (m->control_pressed) { outputTypes.clear();  delete distCalculator; remove(outputFile.c_str()); return 0; }
457                 
458                 #ifdef USE_MPI
459                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
460                                         
461                         if (pid == 0) { //only one process should output to screen
462                 #endif
463                 
464                 //if (output == "square") {  convertMatrix(outputFile); }
465                 
466                 ifstream fileHandle;
467                 fileHandle.open(outputFile.c_str());
468                 if(fileHandle) {
469                         m->gobble(fileHandle);
470                         if (fileHandle.eof()) { m->mothurOut(outputFile + " is blank. This can result if there are no distances below your cutoff.");  m->mothurOutEndLine(); }
471                 }
472                 
473                 //append the old column file to the new one
474                 if ((oldfastafile != "") && (column != ""))  {
475                         //we had to rename the column file so we didnt overwrite above, but we want to keep old name
476                         if (outputFile == column) { 
477                                 string tempcolumn = column + ".old";
478                                 m->appendFiles(tempcolumn, outputFile);
479                                 remove(tempcolumn.c_str());
480                         }else{
481                                 m->appendFiles(outputFile, column);
482                                 remove(outputFile.c_str());
483                                 outputFile = column;
484                         }
485                         
486                         if (outputDir != "") { 
487                                 string newOutputName = outputDir + m->getSimpleName(outputFile);
488                                 rename(outputFile.c_str(), newOutputName.c_str());
489                                 remove(outputFile.c_str());
490                                 outputFile = newOutputName;
491                         }
492                 }
493
494                 
495                 #ifdef USE_MPI
496                         }
497                 #endif
498                 
499                 if (m->control_pressed) { outputTypes.clear();  delete distCalculator; remove(outputFile.c_str()); return 0; }
500                 
501                 delete distCalculator;
502                 
503                 m->mothurOutEndLine();
504                 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
505                 m->mothurOut(outputFile); m->mothurOutEndLine();
506                 m->mothurOutEndLine();
507                 m->mothurOut("It took " + toString(time(NULL) - startTime) + " to calculate the distances for " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
508
509
510                 if (m->isTrue(compress)) {
511                         m->mothurOut("Compressing..."); m->mothurOutEndLine();
512                         m->mothurOut("(Replacing " + outputFile + " with " + outputFile + ".gz)"); m->mothurOutEndLine();
513                         system(("gzip -v " + outputFile).c_str());
514                         outputNames.push_back(outputFile + ".gz");
515                 }else { outputNames.push_back(outputFile); }
516
517                 return 0;
518                 
519         }
520         catch(exception& e) {
521                 m->errorOut(e, "DistanceCommand", "execute");
522                 exit(1);
523         }
524 }
525 /**************************************************************************************************/
526 void DistanceCommand::createProcesses(string filename) {
527         try {
528 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
529                 int process = 0;
530                 processIDS.clear();
531                 
532                 //loop through and create all the processes you want
533                 while (process != processors) {
534                         int pid = fork();
535                         
536                         if (pid > 0) {
537                                 processIDS[lines[process]->end] = pid;  //create map from line number to pid so you can append files in correct order later
538                                 process++;
539                         }else if (pid == 0){
540                                 if (output != "square") {  driver(lines[process]->start, lines[process]->end, filename + toString(getpid()) + ".temp", cutoff); }
541                                 else { driver(lines[process]->start, lines[process]->end, filename + toString(getpid()) + ".temp", "square"); }
542                                 exit(0);
543                         }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
544                 }
545         
546                 //force parent to wait until all the processes are done
547                 for (map<int, int>::iterator it = processIDS.begin(); it != processIDS.end(); it++) { 
548                         int temp = it->second;
549                         wait(&temp);
550                 }
551 #endif
552         }
553         catch(exception& e) {
554                 m->errorOut(e, "DistanceCommand", "createProcesses");
555                 exit(1);
556         }
557 }
558
559 /**************************************************************************************************/
560 /////// need to fix to work with calcs and sequencedb
561 int DistanceCommand::driver(int startLine, int endLine, string dFileName, float cutoff){
562         try {
563
564                 int startTime = time(NULL);
565                 
566                 //column file
567                 ofstream outFile(dFileName.c_str(), ios::trunc);
568                 outFile.setf(ios::fixed, ios::showpoint);
569                 outFile << setprecision(4);
570                 
571                 if((output == "lt") && startLine == 0){ outFile << alignDB.getNumSeqs() << endl;        }
572                 
573                 for(int i=startLine;i<endLine;i++){
574                         if(output == "lt")      {       
575                                 string name = alignDB.get(i).getName();
576                                 if (name.length() < 10) { //pad with spaces to make compatible
577                                         while (name.length() < 10) {  name += " ";  }
578                                 }
579                                 outFile << name << '\t';        
580                         }
581                         for(int j=0;j<i;j++){
582                                 
583                                 if (m->control_pressed) { outFile.close(); return 0;  }
584                                 
585                                 //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
586                                 //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
587                                 if ((i >= numNewFasta) && (j >= numNewFasta)) { break; }
588                                 
589                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
590                                 double dist = distCalculator->getDist();
591                                 
592                                 if(dist <= cutoff){
593                                         if (output == "column") { outFile << alignDB.get(i).getName() << ' ' << alignDB.get(j).getName() << ' ' << dist << endl; }
594                                 }
595                                 if (output == "lt") {  outFile << dist << '\t'; }
596                         }
597                         
598                         if (output == "lt") { outFile << endl; }
599                         
600                         if(i % 100 == 0){
601                                 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
602                         }
603                         
604                 }
605                 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
606                 
607                 outFile.close();
608                 
609                 return 1;
610         }
611         catch(exception& e) {
612                 m->errorOut(e, "DistanceCommand", "driver");
613                 exit(1);
614         }
615 }
616 /**************************************************************************************************/
617 /////// need to fix to work with calcs and sequencedb
618 int DistanceCommand::driver(int startLine, int endLine, string dFileName, string square){
619         try {
620
621                 int startTime = time(NULL);
622                 
623                 //column file
624                 ofstream outFile(dFileName.c_str(), ios::trunc);
625                 outFile.setf(ios::fixed, ios::showpoint);
626                 outFile << setprecision(4);
627                 
628                 if(startLine == 0){     outFile << alignDB.getNumSeqs() << endl;        }
629                 
630                 for(int i=startLine;i<endLine;i++){
631                                 
632                         string name = alignDB.get(i).getName();
633                         //pad with spaces to make compatible
634                         if (name.length() < 10) { while (name.length() < 10) {  name += " ";  } }
635                                 
636                         outFile << name << '\t';        
637                         
638                         for(int j=0;j<alignDB.getNumSeqs();j++){
639                                 
640                                 if (m->control_pressed) { outFile.close(); return 0;  }
641                                 
642                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
643                                 double dist = distCalculator->getDist();
644                                 
645                                 outFile << dist << '\t'; 
646                         }
647                         
648                         outFile << endl; 
649                         
650                         if(i % 100 == 0){
651                                 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
652                         }
653                         
654                 }
655                 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
656                 
657                 outFile.close();
658                 
659                 return 1;
660         }
661         catch(exception& e) {
662                 m->errorOut(e, "DistanceCommand", "driver");
663                 exit(1);
664         }
665 }
666 #ifdef USE_MPI
667 /**************************************************************************************************/
668 /////// need to fix to work with calcs and sequencedb
669 int DistanceCommand::driverMPI(int startLine, int endLine, MPI_File& outMPI, float cutoff){
670         try {
671                 MPI_Status status;
672                 int startTime = time(NULL);
673                 
674                 string outputString = "";
675                 
676                 for(int i=startLine;i<endLine;i++){
677         
678                         for(int j=0;j<i;j++){
679                                 
680                                 if (m->control_pressed) {  return 0;  }
681                                 
682                                 //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
683                                 //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
684                                 if ((i >= numNewFasta) && (j >= numNewFasta)) { break; }
685                                 
686                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
687                                 double dist = distCalculator->getDist();
688                                 
689                                 if(dist <= cutoff){
690                                          outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n'); 
691                                 }
692                         }
693                         
694                         if(i % 100 == 0){
695                                 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
696                                 cout << i << '\t' << (time(NULL) - startTime) << endl;
697                         }
698                         
699                          
700                         //send results to parent
701                         int length = outputString.length();
702
703                         char* buf = new char[length];
704                         memcpy(buf, outputString.c_str(), length);
705                         
706                         MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status);
707                         outputString = "";
708                         delete buf;
709                         
710                 }
711                 
712                 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
713                 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;                
714                 return 1;
715         }
716         catch(exception& e) {
717                 m->errorOut(e, "DistanceCommand", "driverMPI");
718                 exit(1);
719         }
720 }
721 /**************************************************************************************************/
722 /////// need to fix to work with calcs and sequencedb
723 int DistanceCommand::driverMPI(int startLine, int endLine, string file, unsigned long int& size){
724         try {
725                 MPI_Status status;
726                 
727                 MPI_File outMPI;
728                 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
729
730                 //char* filename = new char[file.length()];
731                 //memcpy(filename, file.c_str(), file.length());
732                 
733                 char filename[1024];
734                 strcpy(filename, file.c_str());
735
736                 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
737                 //delete filename;
738
739                 int startTime = time(NULL);
740                 
741                 string outputString = "";
742                 size = 0;
743                 
744                 if(startLine == 0){     outputString += toString(alignDB.getNumSeqs()) + "\n";  }
745                 
746                 for(int i=startLine;i<endLine;i++){
747                                 
748                         string name = alignDB.get(i).getName();
749                         if (name.length() < 10) { //pad with spaces to make compatible
750                                 while (name.length() < 10) {  name += " ";  }
751                         }
752                         outputString += name + "\t";    
753                         
754                         for(int j=0;j<i;j++){
755                                 
756                                 if (m->control_pressed) {  return 0;  }
757                                 
758                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
759                                 double dist = distCalculator->getDist();
760                                 
761                                 outputString += toString(dist) + "\t"; 
762                         }
763                         
764                         outputString += "\n"; 
765
766                 
767                         if(i % 100 == 0){
768                                 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
769                                 cout << i << '\t' << (time(NULL) - startTime) << endl;
770                         }
771                         
772                         
773                         //send results to parent
774                         int length = outputString.length();
775                         char* buf = new char[length];
776                         memcpy(buf, outputString.c_str(), length);
777                         
778                         MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
779                         size += outputString.length();
780                         outputString = "";
781                         delete buf;
782                 }
783                 
784                 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
785                 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
786                 MPI_File_close(&outMPI);
787                 
788                 return 1;
789         }
790         catch(exception& e) {
791                 m->errorOut(e, "DistanceCommand", "driverMPI");
792                 exit(1);
793         }
794 }
795 /**************************************************************************************************/
796 /////// need to fix to work with calcs and sequencedb
797 int DistanceCommand::driverMPI(int startLine, int endLine, string file, unsigned long int& size, string square){
798         try {
799                 MPI_Status status;
800                 
801                 MPI_File outMPI;
802                 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
803
804                 //char* filename = new char[file.length()];
805                 //memcpy(filename, file.c_str(), file.length());
806                 
807                 char filename[1024];
808                 strcpy(filename, file.c_str());
809
810                 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
811                 //delete filename;
812
813                 int startTime = time(NULL);
814                 
815                 string outputString = "";
816                 size = 0;
817                 
818                 if(startLine == 0){     outputString += toString(alignDB.getNumSeqs()) + "\n";  }
819                 
820                 for(int i=startLine;i<endLine;i++){
821                                 
822                         string name = alignDB.get(i).getName();
823                         if (name.length() < 10) { //pad with spaces to make compatible
824                                 while (name.length() < 10) {  name += " ";  }
825                         }
826                         outputString += name + "\t";    
827                         
828                         for(int j=0;j<alignDB.getNumSeqs();j++){
829                                 
830                                 if (m->control_pressed) {  return 0;  }
831                                 
832                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
833                                 double dist = distCalculator->getDist();
834                                 
835                                 outputString += toString(dist) + "\t"; 
836                         }
837                         
838                         outputString += "\n"; 
839
840                 
841                         if(i % 100 == 0){
842                                 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
843                                 cout << i << '\t' << (time(NULL) - startTime) << endl;
844                         }
845                         
846                         
847                         //send results to parent
848                         int length = outputString.length();
849                         char* buf = new char[length];
850                         memcpy(buf, outputString.c_str(), length);
851                         
852                         MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
853                         size += outputString.length();
854                         outputString = "";
855                         delete buf;
856                 }
857                 
858                 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
859                 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
860                 MPI_File_close(&outMPI);
861                 
862                 return 1;
863         }
864         catch(exception& e) {
865                 m->errorOut(e, "DistanceCommand", "driverMPI");
866                 exit(1);
867         }
868 }
869 #endif
870 /**************************************************************************************************
871 int DistanceCommand::convertMatrix(string outputFile) {
872         try{
873
874                 //sort file by first column so the distances for each row are together
875                 string outfile = m->getRootName(outputFile) + "sorted.dist.temp";
876                 
877                 //use the unix sort 
878                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
879                         string command = "sort -n " + outputFile + " -o " + outfile;
880                         system(command.c_str());
881                 #else //sort using windows sort
882                         string command = "sort " + outputFile + " /O " + outfile;
883                         system(command.c_str());
884                 #endif
885                 
886
887                 //output to new file distance for each row and save positions in file where new row begins
888                 ifstream in;
889                 m->openInputFile(outfile, in);
890                 
891                 ofstream out;
892                 m->openOutputFile(outputFile, out);
893                 
894                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
895
896                 out << alignDB.getNumSeqs() << endl;
897                 
898                 //get first currentRow
899                 string first, currentRow, second;
900                 float dist;
901                 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key 
902                 map<string, float>::iterator it;
903                 
904                 in >> first;
905                 currentRow = first;
906                 
907                 rowDists[first] = 0.00; //distance to yourself is 0.0
908                 
909                 in.seekg(0);
910                 //m->openInputFile(outfile, in);
911                 
912                 while(!in.eof()) {
913                         if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
914                         
915                         in >> first >> second >> dist; m->gobble(in);
916                                 
917                         if (first != currentRow) {
918                                 //print out last row
919                                 out << currentRow << '\t'; //print name
920
921                                 //print dists
922                                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
923                                         out << it->second << '\t';
924                                 }
925                                 out << endl;
926                                 
927                                 //start new row
928                                 currentRow = first;
929                                 rowDists.clear();
930                                 rowDists[first] = 0.00;
931                                 rowDists[second] = dist;
932                         }else{
933                                 rowDists[second] = dist;
934                         }
935                 }
936                 //print out last row
937                 out << currentRow << '\t'; //print name
938                                 
939                 //print dists
940                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
941                         out << it->second << '\t';
942                 }
943                 out << endl;
944                 
945                 in.close();
946                 out.close();
947                 
948                 remove(outfile.c_str());
949                 
950                 return 1;
951                 
952         }
953         catch(exception& e) {
954                 m->errorOut(e, "DistanceCommand", "convertMatrix");
955                 exit(1);
956         }
957 }
958 /**************************************************************************************************
959 int DistanceCommand::convertToLowerTriangle(string outputFile) {
960         try{
961
962                 //sort file by first column so the distances for each row are together
963                 string outfile = m->getRootName(outputFile) + "sorted.dist.temp";
964                 
965                 //use the unix sort 
966                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
967                         string command = "sort -n " + outputFile + " -o " + outfile;
968                         system(command.c_str());
969                 #else //sort using windows sort
970                         string command = "sort " + outputFile + " /O " + outfile;
971                         system(command.c_str());
972                 #endif
973                 
974
975                 //output to new file distance for each row and save positions in file where new row begins
976                 ifstream in;
977                 m->openInputFile(outfile, in);
978                 
979                 ofstream out;
980                 m->openOutputFile(outputFile, out);
981                 
982                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
983
984                 out << alignDB.getNumSeqs() << endl;
985                 
986                 //get first currentRow
987                 string first, currentRow, second;
988                 float dist;
989                 int i, j;
990                 i = 0; j = 0;
991                 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key 
992                 map<string, float>::iterator it;
993                 
994                 in >> first;
995                 currentRow = first;
996                 
997                 rowDists[first] = 0.00; //distance to yourself is 0.0
998                 
999                 in.seekg(0);
1000                 //m->openInputFile(outfile, in);
1001                 
1002                 while(!in.eof()) {
1003                         if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
1004                         
1005                         in >> first >> second >> dist; m->gobble(in);
1006                                 
1007                         if (first != currentRow) {
1008                                 //print out last row
1009                                 out << currentRow << '\t'; //print name
1010
1011                                 //print dists
1012                                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1013                                         if (j >= i) { break; }
1014                                         out << it->second << '\t';
1015                                         j++;
1016                                 }
1017                                 out << endl;
1018                                 
1019                                 //start new row
1020                                 currentRow = first;
1021                                 rowDists.clear();
1022                                 rowDists[first] = 0.00;
1023                                 rowDists[second] = dist;
1024                                 j = 0;
1025                                 i++;
1026                         }else{
1027                                 rowDists[second] = dist;
1028                         }
1029                 }
1030                 //print out last row
1031                 out << currentRow << '\t'; //print name
1032                                 
1033                 //print dists
1034                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
1035                         out << it->second << '\t';
1036                 }
1037                 out << endl;
1038                 
1039                 in.close();
1040                 out.close();
1041                 
1042                 remove(outfile.c_str());
1043                 
1044                 return 1;
1045                 
1046         }
1047         catch(exception& e) {
1048                 m->errorOut(e, "DistanceCommand", "convertToLowerTriangle");
1049                 exit(1);
1050         }
1051 }
1052 /**************************************************************************************************/
1053 //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,
1054 //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.
1055 //also check to make sure the 2 files have the same alignment length.
1056 bool DistanceCommand::sanityCheck() {
1057         try{
1058                 bool good = true;
1059                 
1060                 //make sure the 2 fasta files have the same alignment length
1061                 ifstream in;
1062                 m->openInputFile(fastafile, in);
1063                 int fastaAlignLength = 0;
1064                 if (in) { 
1065                         Sequence tempIn(in);
1066                         fastaAlignLength = tempIn.getAligned().length();
1067                 }
1068                 in.close();
1069                 
1070                 ifstream in2;
1071                 m->openInputFile(oldfastafile, in2);
1072                 int oldfastaAlignLength = 0;
1073                 if (in2) { 
1074                         Sequence tempIn2(in2);
1075                         oldfastaAlignLength = tempIn2.getAligned().length();
1076                 }
1077                 in2.close();
1078                 
1079                 if (fastaAlignLength != oldfastaAlignLength) { m->mothurOut("fasta files do not have the same alignment length."); m->mothurOutEndLine(); return false;  }
1080                 
1081                 //read fasta file and save names as well as adding them to the alignDB
1082                 set<string> namesOldFasta;
1083                 
1084                 ifstream inFasta;
1085                 m->openInputFile(oldfastafile, inFasta);
1086                 
1087                 while (!inFasta.eof()) {
1088                         if (m->control_pressed) {  inFasta.close(); return good;  }
1089                 
1090                         Sequence temp(inFasta);
1091                         
1092                         if (temp.getName() != "") {
1093                                 namesOldFasta.insert(temp.getName());  //save name
1094                                 alignDB.push_back(temp);  //add to DB
1095                         }
1096                         
1097                         m->gobble(inFasta);
1098                 }
1099                 
1100                 inFasta.close();
1101                 
1102                 //read through the column file checking names and removing distances above the cutoff
1103                 ifstream inDist;
1104                 m->openInputFile(column, inDist);
1105                 
1106                 ofstream outDist;
1107                 string outputFile = column + ".temp";
1108                 m->openOutputFile(outputFile, outDist);
1109                 
1110                 string name1, name2;
1111                 float dist;
1112                 while (!inDist.eof()) {
1113                         if (m->control_pressed) {  inDist.close(); outDist.close(); remove(outputFile.c_str()); return good;  }
1114                 
1115                         inDist >> name1 >> name2 >> dist; m->gobble(inDist);
1116                         
1117                         //both names are in fasta file and distance is below cutoff
1118                         if ((namesOldFasta.count(name1) == 0) || (namesOldFasta.count(name2) == 0)) {  good = false; break;  }
1119                         else{
1120                                 if (dist <= cutoff) {
1121                                         outDist << name1 << '\t' << name2 << '\t' << dist << endl;
1122                                 }
1123                         }
1124                 }
1125                 
1126                 inDist.close();
1127                 outDist.close();
1128                 
1129                 if (good) {
1130                         remove(column.c_str());
1131                         rename(outputFile.c_str(), column.c_str());
1132                 }else{
1133                         remove(outputFile.c_str()); //temp file is bad because file mismatch above
1134                 }
1135                 
1136         }
1137         catch(exception& e) {
1138                 m->errorOut(e, "DistanceCommand", "m->appendFiles");
1139                 exit(1);
1140         }
1141 }
1142 /**************************************************************************************************/
1143
1144
1145
1146