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