]> git.donarmstrong.com Git - mothur.git/blob - distancecommand.cpp
a few modifications for 1.9
[mothur.git] / distancecommand.cpp
1 /*
2  *  distancecommand.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 5/7/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
10 #include "distancecommand.h"
11 #include "ignoregaps.h"
12 #include "eachgapdist.h"
13 #include "eachgapignore.h"
14 #include "onegapdist.h"
15 #include "onegapignore.h"
16
17 //**********************************************************************************************************************
18
19 DistanceCommand::DistanceCommand(string option) {
20         try {
21                 abort = false;
22                 Estimators.clear();
23                                 
24                 //allow user to run help
25                 if(option == "help") { help(); abort = true; }
26                 
27                 else {
28                         //valid paramters for this command
29                         string Array[] =  {"fasta", "output", "calc", "countends", "cutoff", "processors", "outputdir","inputdir"};
30                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
31                         
32                         OptionParser parser(option);
33                         map<string, string> parameters = parser.getParameters();
34                         
35                         ValidParameters validParameter;
36                         map<string, string>::iterator it2;
37                 
38                         //check to make sure all parameters are valid for command
39                         for (it2 = parameters.begin(); it2 != parameters.end(); it2++) { 
40                                 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) {  abort = true;  }
41                         }
42                         
43                         //if the user changes the input directory command factory will send this info to us in the output parameter 
44                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
45                         if (inputDir == "not found"){   inputDir = "";          }
46                         else {
47                                 string path;
48                                 it2 = parameters.find("fasta");
49                                 //user has given a template file
50                                 if(it2 != parameters.end()){ 
51                                         path = hasPath(it2->second);
52                                         //if the user has not given a path then, add inputdir. else leave path alone.
53                                         if (path == "") {       parameters["fasta"] = inputDir + it2->second;           }
54                                 }
55                         }
56
57                         //check for required parameters
58                         fastafile = validParameter.validFile(parameters, "fasta", true);
59                         if (fastafile == "not found") { m->mothurOut("fasta is a required parameter for the dist.seqs command."); m->mothurOutEndLine(); abort = true; }
60                         else if (fastafile == "not open") { abort = true; }     
61                         else{
62                                 ifstream inFASTA;
63                                 openInputFile(fastafile, inFASTA);
64                                 alignDB = SequenceDB(inFASTA); 
65                                 inFASTA.close();
66                         }
67                         
68                         //if the user changes the output directory command factory will send this info to us in the output parameter 
69                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
70                                 outputDir = ""; 
71                                 outputDir += hasPath(fastafile); //if user entered a file with a path then preserve it  
72                         }
73
74                         //check for optional parameter and set defaults
75                         // ...at some point should added some additional type checking...
76                         calc = validParameter.validFile(parameters, "calc", false);                     
77                         if (calc == "not found") { calc = "onegap";  }
78                         else { 
79                                  if (calc == "default")  {  calc = "onegap";  }
80                         }
81                         splitAtDash(calc, Estimators);
82
83                         string temp;
84                         temp = validParameter.validFile(parameters, "countends", false);        if(temp == "not found"){        temp = "T";     }
85                         convert(temp, countends); 
86                         
87                         temp = validParameter.validFile(parameters, "cutoff", false);           if(temp == "not found"){        temp = "1.0"; }
88                         convert(temp, cutoff); 
89                         
90                         temp = validParameter.validFile(parameters, "processors", false);       if(temp == "not found"){        temp = "1"; }
91                         convert(temp, processors); 
92                         
93                         output = validParameter.validFile(parameters, "output", false);         if(output == "not found"){      output = "column"; }
94                         
95                         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"; }
96                         
97                         ValidCalculators validCalculator;
98                         
99                         if (isTrue(countends) == true) {
100                                 for (int i=0; i<Estimators.size(); i++) {
101                                         if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) { 
102                                                 if (Estimators[i] == "nogaps")                  {       distCalculator = new ignoreGaps();      }
103                                                 else if (Estimators[i] == "eachgap")    {       distCalculator = new eachGapDist();     }
104                                                 else if (Estimators[i] == "onegap")             {       distCalculator = new oneGapDist();      }
105                                         }
106                                 }
107                         }else {
108                                 for (int i=0; i<Estimators.size(); i++) {
109                                         if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) { 
110                                                 if (Estimators[i] == "nogaps")          {       distCalculator = new ignoreGaps();                                      }
111                                                 else if (Estimators[i] == "eachgap"){   distCalculator = new eachGapIgnoreTermGapDist();        }
112                                                 else if (Estimators[i] == "onegap")     {       distCalculator = new oneGapIgnoreTermGapDist();         }
113                                         }
114                                 }
115                         }
116
117                 }
118                                 
119         }
120         catch(exception& e) {
121                 m->errorOut(e, "DistanceCommand", "DistanceCommand");
122                 exit(1);
123         }
124 }
125
126 //**********************************************************************************************************************
127
128 DistanceCommand::~DistanceCommand(){
129         
130         for(int i=0;i<lines.size();i++){
131                 delete lines[i];
132         }
133         
134 }
135         
136 //**********************************************************************************************************************
137
138 void DistanceCommand::help(){
139         try {
140                 m->mothurOut("The dist.seqs command reads a file containing sequences and creates a distance file.\n");
141                 m->mothurOut("The dist.seqs command parameters are fasta, calc, countends, output, cutoff and processors.  \n");
142                 m->mothurOut("The fasta parameter is required.\n");
143                 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");
144                 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");
145                 m->mothurOut("The cutoff parameter allows you to specify maximum distance to keep. The default is 1.0.\n");
146                 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");
147                 m->mothurOut("The processors parameter allows you to specify number of processors to use.  The default is 1.\n");
148                 m->mothurOut("The dist.seqs command should be in the following format: \n");
149                 m->mothurOut("dist.seqs(fasta=yourFastaFile, calc=yourCalc, countends=yourEnds, cutoff= yourCutOff, processors=yourProcessors) \n");
150                 m->mothurOut("Example dist.seqs(fasta=amazon.fasta, calc=eachgap, countends=F, cutoff= 2.0, processors=3).\n");
151                 m->mothurOut("Note: No spaces between parameter labels (i.e. calc), '=' and parameters (i.e.yourCalc).\n\n");
152         }
153         catch(exception& e) {
154                 m->errorOut(e, "DistanceCommand", "help");
155                 exit(1);
156         }
157 }
158 //**********************************************************************************************************************
159
160 int DistanceCommand::execute(){
161         try {
162                 
163                 if (abort == true) { return 0; }
164                 
165                 int startTime = time(NULL);
166                 
167                 int numSeqs = alignDB.getNumSeqs();
168                 cutoff += 0.005;
169                 
170                 string outputFile;
171                                 
172                 if (output == "lt") { //does the user want lower triangle phylip formatted file 
173                         outputFile = outputDir + getRootName(getSimpleName(fastafile)) + "phylip.dist";
174                         remove(outputFile.c_str());
175                         
176                         //output numSeqs to phylip formatted dist file
177                 }else if (output == "column") { //user wants column format
178                         outputFile = outputDir + getRootName(getSimpleName(fastafile)) + "dist";
179                         remove(outputFile.c_str());
180                 }else { //assume square
181                         outputFile = outputDir + getRootName(getSimpleName(fastafile)) + "square.dist";
182                         remove(outputFile.c_str());
183                 }
184                 
185
186 #ifdef USE_MPI
187                 
188                 int pid, start, end; 
189                 int tag = 2001;
190                                 
191                 MPI_Status status; 
192                 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running
193                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
194                 
195                 //each process gets where it should start and stop in the file
196                 start = int (sqrt(float(pid)/float(processors)) * numSeqs);
197                 end = int (sqrt(float(pid+1)/float(processors)) * numSeqs);
198                 
199                 if (output != "lt") {
200                         MPI_File outMPI;
201                         int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
202
203                         //char* filename = new char[outputFile.length()];
204                         //memcpy(filename, outputFile.c_str(), outputFile.length());
205                         
206                         char filename[1024];
207                         strcpy(filename, outputFile.c_str());
208                         
209                         MPI_File_open(MPI_COMM_WORLD, filename, amode, MPI_INFO_NULL, &outMPI);
210                         //delete filename;
211
212                         if (pid == 0) { //you are the root process 
213                         
214                                 //do your part
215                                 string outputMyPart;
216                                 driverMPI(start, end, outMPI, cutoff);
217                                 
218                                 if (m->control_pressed) { MPI_File_close(&outMPI);  delete distCalculator;  return 0; }
219                         
220                                 //wait on chidren
221                                 for(int i = 1; i < processors; i++) { 
222                                         if (m->control_pressed) { MPI_File_close(&outMPI);  delete distCalculator;  return 0; }
223                                         
224                                         char buf[4];
225                                         MPI_Recv(buf, 4, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status); 
226                                 }
227                         }else { //you are a child process
228                                 //do your part
229                                 driverMPI(start, end, outMPI, cutoff);
230                                 
231                                 if (m->control_pressed) { MPI_File_close(&outMPI);  delete distCalculator;  return 0; }
232                         
233                                 char buf[4];
234                                 strcpy(buf, "done"); 
235                                 //tell parent you are done.
236                                 MPI_Send(buf, 4, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
237                         }
238                         
239                         MPI_File_close(&outMPI);
240                         
241                 }else { //lower triangle format
242                         if (pid == 0) { //you are the root process 
243                         
244                                 //do your part
245                                 string outputMyPart;
246                                 long mySize;
247                                 driverMPI(start, end, outputFile, mySize);
248         
249                                 if (m->control_pressed) {  delete distCalculator;  return 0; }
250                                 
251                                 int amode=MPI_MODE_APPEND|MPI_MODE_WRONLY|MPI_MODE_CREATE; //
252                                 MPI_File outMPI;
253                                 MPI_File inMPI;
254
255                                 //char* filename = new char[outputFile.length()];
256                                 //memcpy(filename, outputFile.c_str(), outputFile.length());
257                                 
258                                 char filename[1024];
259                                 strcpy(filename, outputFile.c_str());
260
261                                 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
262                                 //delete filename;
263
264                                 //wait on chidren
265                                 for(int b = 1; b < processors; b++) { 
266                                         long fileSize;
267                                         
268                                         if (m->control_pressed) { MPI_File_close(&outMPI);  delete distCalculator;  return 0; }
269                                         
270                                         MPI_Recv(&fileSize, 1, MPI_LONG, b, tag, MPI_COMM_WORLD, &status); 
271                                         
272                                         string outTemp = outputFile + toString(b) + ".temp";
273
274                                         char* buf = new char[outTemp.length()];
275                                         memcpy(buf, outTemp.c_str(), outTemp.length());
276                                         
277                                         MPI_File_open(MPI_COMM_SELF, buf, MPI_MODE_DELETE_ON_CLOSE|MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);
278                                         delete buf;
279
280                                         int count = 0;
281                                         while (count < fileSize) { //read 1000 characters at a time
282                                                 //send freqs
283                                                 char buf2[1];
284                                                 MPI_File_read(inMPI, buf2, 1, MPI_CHAR, &status);
285                                                 MPI_File_write(outMPI, buf2, 1, MPI_CHAR, &status);
286                                                 count += 1;
287                                         }
288                                         
289                                         MPI_File_close(&inMPI); //deleted on close
290                                 }
291                                 
292                                 MPI_File_close(&outMPI);
293                         }else { //you are a child process
294                                 //do your part
295                                 long size;
296                                 driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size);
297                                 
298                                 if (m->control_pressed) { delete distCalculator;  return 0; }
299                         
300                                 //tell parent you are done.
301                                 MPI_Send(&size, 1, MPI_LONG, 0, tag, MPI_COMM_WORLD);
302                         }
303                 }
304 #else           
305                                 
306         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
307                 //if you don't need to fork anything
308                 if(processors == 1){
309                         driver(0, numSeqs, outputFile, cutoff);
310                 }else{ //you have multiple processors
311                         
312                         for (int i = 0; i < processors; i++) {
313                                 lines.push_back(new linePair());
314                                 lines[i]->start = int (sqrt(float(i)/float(processors)) * numSeqs);
315                                 lines[i]->end = int (sqrt(float(i+1)/float(processors)) * numSeqs);
316                         }
317
318                         createProcesses(outputFile); 
319                 
320                         map<int, int>::iterator it = processIDS.begin();
321                         rename((outputFile + toString(it->second) + ".temp").c_str(), outputFile.c_str());
322                         it++;
323                         
324                         //append and remove temp files
325                         for (; it != processIDS.end(); it++) {
326                                 appendFiles((outputFile + toString(it->second) + ".temp"), outputFile);
327                                 remove((outputFile + toString(it->second) + ".temp").c_str());
328                         }
329                 }
330         #else
331                 ifstream inFASTA;
332                 driver(0, numSeqs, outputFile, cutoff);
333         #endif
334         
335 #endif
336                 if (m->control_pressed) { delete distCalculator; remove(outputFile.c_str()); return 0; }
337                 
338                 #ifdef USE_MPI
339                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
340                                         
341                         if (pid == 0) { //only one process should output to screen
342                 #endif
343                 
344                 if (output == "square") {  convertMatrix(outputFile); }
345                 
346                 #ifdef USE_MPI
347                         }
348                 #endif
349                 
350                 if (m->control_pressed) { delete distCalculator; remove(outputFile.c_str()); return 0; }
351                 
352                 delete distCalculator;
353                 
354                 m->mothurOutEndLine();
355                 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
356                 m->mothurOut(outputFile); m->mothurOutEndLine();
357                 m->mothurOutEndLine();
358                 m->mothurOut("It took " + toString(time(NULL) - startTime) + " to calculate the distances for " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
359                 return 0;
360                 
361         }
362         catch(exception& e) {
363                 m->errorOut(e, "DistanceCommand", "execute");
364                 exit(1);
365         }
366 }
367 /**************************************************************************************************/
368 void DistanceCommand::createProcesses(string filename) {
369         try {
370 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
371                 int process = 0;
372                 processIDS.clear();
373                 
374                 //loop through and create all the processes you want
375                 while (process != processors) {
376                         int pid = fork();
377                         
378                         if (pid > 0) {
379                                 processIDS[lines[process]->end] = pid;  //create map from line number to pid so you can append files in correct order later
380                                 process++;
381                         }else if (pid == 0){
382                                 driver(lines[process]->start, lines[process]->end, filename + toString(getpid()) + ".temp", cutoff);
383                                 exit(0);
384                         }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
385                 }
386         
387                 //force parent to wait until all the processes are done
388                 for (map<int, int>::iterator it = processIDS.begin(); it != processIDS.end(); it++) { 
389                         int temp = it->second;
390                         wait(&temp);
391                 }
392 #endif
393         }
394         catch(exception& e) {
395                 m->errorOut(e, "DistanceCommand", "createProcesses");
396                 exit(1);
397         }
398 }
399
400 /**************************************************************************************************/
401 /////// need to fix to work with calcs and sequencedb
402 int DistanceCommand::driver(int startLine, int endLine, string dFileName, float cutoff){
403         try {
404
405                 int startTime = time(NULL);
406                 
407                 //column file
408                 ofstream outFile(dFileName.c_str(), ios::trunc);
409                 outFile.setf(ios::fixed, ios::showpoint);
410                 outFile << setprecision(4);
411                 
412                 if((output == "lt") && startLine == 0){ outFile << alignDB.getNumSeqs() << endl;        }
413                 
414                 for(int i=startLine;i<endLine;i++){
415                         if(output == "lt")      {       
416                                 string name = alignDB.get(i).getName();
417                                 if (name.length() < 10) { //pad with spaces to make compatible
418                                         while (name.length() < 10) {  name += " ";  }
419                                 }
420                                 outFile << name << '\t';        
421                         }
422                         for(int j=0;j<i;j++){
423                                 
424                                 if (m->control_pressed) { outFile.close(); return 0;  }
425                                 
426                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
427                                 double dist = distCalculator->getDist();
428                                 
429                                 if(dist <= cutoff){
430                                         if (output == "column") { outFile << alignDB.get(i).getName() << ' ' << alignDB.get(j).getName() << ' ' << dist << endl; }
431                                 }
432                                 if (output == "lt") {  outFile << dist << '\t'; }
433                                 
434                                 if (output == "square") { //make a square column you can convert to square phylip
435                                         outFile << alignDB.get(i).getName() << '\t' << alignDB.get(j).getName() << '\t' << dist << endl;
436                                         outFile << alignDB.get(j).getName() << '\t' << alignDB.get(i).getName() << '\t' << dist << endl;
437                                 }
438
439                         }
440                         
441                         if (output == "lt") { outFile << endl; }
442                         
443                         if(i % 100 == 0){
444                                 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
445                         }
446                         
447                 }
448                 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
449                 
450                 outFile.close();
451                 
452                 return 1;
453         }
454         catch(exception& e) {
455                 m->errorOut(e, "DistanceCommand", "driver");
456                 exit(1);
457         }
458 }
459 #ifdef USE_MPI
460 /**************************************************************************************************/
461 /////// need to fix to work with calcs and sequencedb
462 int DistanceCommand::driverMPI(int startLine, int endLine, MPI_File& outMPI, float cutoff){
463         try {
464                 MPI_Status status;
465                 int startTime = time(NULL);
466                 
467                 string outputString = "";
468                 
469                 for(int i=startLine;i<endLine;i++){
470         
471                         for(int j=0;j<i;j++){
472                                 
473                                 if (m->control_pressed) {  return 0;  }
474                                 
475                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
476                                 double dist = distCalculator->getDist();
477                                 
478                                 if(dist <= cutoff){
479                                         if (output == "column") { outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n'); }
480                                 }
481                                 
482                                 if (output == "square") { //make a square column you can convert to square phylip
483                                         outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n');
484                                         outputString += (alignDB.get(j).getName() + ' ' + alignDB.get(i).getName() + ' ' + toString(dist) + '\n');
485                                 }
486                         }
487                         
488                         if(i % 100 == 0){
489                                 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
490                                 cout << i << '\t' << (time(NULL) - startTime) << endl;
491                         }
492                         
493                          
494                         //send results to parent
495                         int length = outputString.length();
496
497                         char* buf = new char[length];
498                         memcpy(buf, outputString.c_str(), length);
499                         
500                         MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status);
501                         outputString = "";
502                         delete buf;
503                         
504                 }
505                 
506                 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
507                 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;                
508                 return 1;
509         }
510         catch(exception& e) {
511                 m->errorOut(e, "DistanceCommand", "driverMPI");
512                 exit(1);
513         }
514 }
515 /**************************************************************************************************/
516 /////// need to fix to work with calcs and sequencedb
517 int DistanceCommand::driverMPI(int startLine, int endLine, string file, long& size){
518         try {
519                 MPI_Status status;
520                 
521                 MPI_File outMPI;
522                 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
523
524                 //char* filename = new char[file.length()];
525                 //memcpy(filename, file.c_str(), file.length());
526                 
527                 char filename[1024];
528                 strcpy(filename, file.c_str());
529
530                 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
531                 //delete filename;
532
533                 int startTime = time(NULL);
534                 
535                 string outputString = "";
536                 size = 0;
537                 
538                 if((output == "lt") && startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n";  }
539                 
540                 for(int i=startLine;i<endLine;i++){
541                         if(output == "lt")      {       
542                                 string name = alignDB.get(i).getName();
543                                 if (name.length() < 10) { //pad with spaces to make compatible
544                                         while (name.length() < 10) {  name += " ";  }
545                                 }
546                                 outputString += name + "\t";    
547                         }
548                         for(int j=0;j<i;j++){
549                                 
550                                 if (m->control_pressed) {  return 0;  }
551                                 
552                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
553                                 double dist = distCalculator->getDist();
554                                 
555                                 if (output == "lt") {  outputString += toString(dist) + "\t"; }
556                         }
557                         
558                         if (output == "lt") { outputString += "\n"; }
559
560                 
561                         if(i % 100 == 0){
562                                 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
563                                 cout << i << '\t' << (time(NULL) - startTime) << endl;
564                         }
565                         
566                         
567                         //send results to parent
568                         int length = outputString.length();
569                         char* buf = new char[length];
570                         memcpy(buf, outputString.c_str(), length);
571                         
572                         MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
573                         size += outputString.length();
574                         outputString = "";
575                         delete buf;
576                 }
577                 
578                 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
579                 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
580                 MPI_File_close(&outMPI);
581                 
582                 return 1;
583         }
584         catch(exception& e) {
585                 m->errorOut(e, "DistanceCommand", "driverMPI");
586                 exit(1);
587         }
588 }
589 #endif
590 /**************************************************************************************************/
591 int DistanceCommand::convertMatrix(string outputFile) {
592         try{
593
594                 //sort file by first column so the distances for each row are together
595                 string outfile = getRootName(outputFile) + "sorted.dist.temp";
596                 
597                 //use the unix sort 
598                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
599                         string command = "sort -n " + outputFile + " -o " + outfile;
600                         system(command.c_str());
601                 #else //sort using windows sort
602                         string command = "sort " + outputFile + " /O " + outfile;
603                         system(command.c_str());
604                 #endif
605                 
606
607                 //output to new file distance for each row and save positions in file where new row begins
608                 ifstream in;
609                 openInputFile(outfile, in);
610                 
611                 ofstream out;
612                 openOutputFile(outputFile, out);
613                 
614                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
615
616                 out << alignDB.getNumSeqs() << endl;
617                 
618                 //get first currentRow
619                 string first, currentRow, second;
620                 float dist;
621                 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key 
622                 map<string, float>::iterator it;
623                 
624                 in >> first;
625                 currentRow = first;
626                 
627                 rowDists[first] = 0.00; //distance to yourself is 0.0
628                 
629                 in.seekg(0);
630                 //openInputFile(outfile, in);
631                 
632                 while(!in.eof()) {
633                         if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
634                         
635                         in >> first >> second >> dist; gobble(in);
636                                 
637                         if (first != currentRow) {
638                                 //print out last row
639                                 out << currentRow << '\t'; //print name
640
641                                 //print dists
642                                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
643                                         out << it->second << '\t';
644                                 }
645                                 out << endl;
646                                 
647                                 //start new row
648                                 currentRow = first;
649                                 rowDists.clear();
650                                 rowDists[first] = 0.00;
651                                 rowDists[second] = dist;
652                         }else{
653                                 rowDists[second] = dist;
654                         }
655                 }
656                 //print out last row
657                 out << currentRow << '\t'; //print name
658                                 
659                 //print dists
660                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
661                         out << it->second << '\t';
662                 }
663                 out << endl;
664                 
665                 in.close();
666                 out.close();
667                 
668                 remove(outfile.c_str());
669                 
670                 return 1;
671                 
672         }
673         catch(exception& e) {
674                 m->errorOut(e, "DistanceCommand", "convertMatrix");
675                 exit(1);
676         }
677 }
678 /**************************************************************************************************/
679 int DistanceCommand::convertToLowerTriangle(string outputFile) {
680         try{
681
682                 //sort file by first column so the distances for each row are together
683                 string outfile = getRootName(outputFile) + "sorted.dist.temp";
684                 
685                 //use the unix sort 
686                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
687                         string command = "sort -n " + outputFile + " -o " + outfile;
688                         system(command.c_str());
689                 #else //sort using windows sort
690                         string command = "sort " + outputFile + " /O " + outfile;
691                         system(command.c_str());
692                 #endif
693                 
694
695                 //output to new file distance for each row and save positions in file where new row begins
696                 ifstream in;
697                 openInputFile(outfile, in);
698                 
699                 ofstream out;
700                 openOutputFile(outputFile, out);
701                 
702                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
703
704                 out << alignDB.getNumSeqs() << endl;
705                 
706                 //get first currentRow
707                 string first, currentRow, second;
708                 float dist;
709                 int i, j;
710                 i = 0; j = 0;
711                 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key 
712                 map<string, float>::iterator it;
713                 
714                 in >> first;
715                 currentRow = first;
716                 
717                 rowDists[first] = 0.00; //distance to yourself is 0.0
718                 
719                 in.seekg(0);
720                 //openInputFile(outfile, in);
721                 
722                 while(!in.eof()) {
723                         if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
724                         
725                         in >> first >> second >> dist; gobble(in);
726                                 
727                         if (first != currentRow) {
728                                 //print out last row
729                                 out << currentRow << '\t'; //print name
730
731                                 //print dists
732                                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
733                                         if (j >= i) { break; }
734                                         out << it->second << '\t';
735                                         j++;
736                                 }
737                                 out << endl;
738                                 
739                                 //start new row
740                                 currentRow = first;
741                                 rowDists.clear();
742                                 rowDists[first] = 0.00;
743                                 rowDists[second] = dist;
744                                 j = 0;
745                                 i++;
746                         }else{
747                                 rowDists[second] = dist;
748                         }
749                 }
750                 //print out last row
751                 out << currentRow << '\t'; //print name
752                                 
753                 //print dists
754                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
755                         out << it->second << '\t';
756                 }
757                 out << endl;
758                 
759                 in.close();
760                 out.close();
761                 
762                 remove(outfile.c_str());
763                 
764                 return 1;
765                 
766         }
767         catch(exception& e) {
768                 m->errorOut(e, "DistanceCommand", "convertToLowerTriangle");
769                 exit(1);
770         }
771 }
772 /**************************************************************************************************
773 void DistanceCommand::appendFiles(string temp, string filename) {
774         try{
775                 ofstream output;
776                 ifstream input;
777         
778                 //open output file in append mode
779                 openOutputFileAppend(filename, output);
780                 openInputFile(temp, input);
781                 
782                 while(char c = input.get()){
783                         if(input.eof())         {       break;                  }
784                         else                            {       output << c;    }
785                 }
786                 
787                 input.close();
788                 output.close();
789         }
790         catch(exception& e) {
791                 m->errorOut(e, "DistanceCommand", "appendFiles");
792                 exit(1);
793         }
794 }
795 /**************************************************************************************************/
796
797