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