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