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