]> git.donarmstrong.com Git - mothur.git/blob - distancecommand.cpp
reworked the classifiers summary file added groupfile option to classify.seqs, added...
[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) { 
282                                                 char buf2[1];
283                                                 MPI_File_read(inMPI, buf2, 1, MPI_CHAR, &status);
284                                                 MPI_File_write(outMPI, buf2, 1, MPI_CHAR, &status);
285                                                 count += 1;
286                                         }
287                                         
288                                         MPI_File_close(&inMPI); //deleted on close
289                                 }
290                                 
291                                 MPI_File_close(&outMPI);
292                         }else { //you are a child process
293                                 //do your part
294                                 long size;
295                                 driverMPI(start, end, (outputFile + toString(pid) + ".temp"), size);
296                                 
297                                 if (m->control_pressed) { delete distCalculator;  return 0; }
298                         
299                                 //tell parent you are done.
300                                 MPI_Send(&size, 1, MPI_LONG, 0, tag, MPI_COMM_WORLD);
301                         }
302                 }
303 #else           
304                                 
305         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
306                 //if you don't need to fork anything
307                 if(processors == 1){
308                         driver(0, numSeqs, outputFile, cutoff);
309                 }else{ //you have multiple processors
310                         
311                         for (int i = 0; i < processors; i++) {
312                                 lines.push_back(new linePair());
313                                 lines[i]->start = int (sqrt(float(i)/float(processors)) * numSeqs);
314                                 lines[i]->end = int (sqrt(float(i+1)/float(processors)) * numSeqs);
315                         }
316
317                         createProcesses(outputFile); 
318                 
319                         map<int, int>::iterator it = processIDS.begin();
320                         rename((outputFile + toString(it->second) + ".temp").c_str(), outputFile.c_str());
321                         it++;
322                         
323                         //append and remove temp files
324                         for (; it != processIDS.end(); it++) {
325                                 appendFiles((outputFile + toString(it->second) + ".temp"), outputFile);
326                                 remove((outputFile + toString(it->second) + ".temp").c_str());
327                         }
328                 }
329         #else
330                 ifstream inFASTA;
331                 driver(0, numSeqs, outputFile, cutoff);
332         #endif
333         
334 #endif
335                 if (m->control_pressed) { delete distCalculator; remove(outputFile.c_str()); return 0; }
336                 
337                 #ifdef USE_MPI
338                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
339                                         
340                         if (pid == 0) { //only one process should output to screen
341                 #endif
342                 
343                 if (output == "square") {  convertMatrix(outputFile); }
344                 
345                 #ifdef USE_MPI
346                         }
347                 #endif
348                 
349                 if (m->control_pressed) { delete distCalculator; remove(outputFile.c_str()); return 0; }
350                 
351                 delete distCalculator;
352                 
353                 m->mothurOutEndLine();
354                 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
355                 m->mothurOut(outputFile); m->mothurOutEndLine();
356                 m->mothurOutEndLine();
357                 m->mothurOut("It took " + toString(time(NULL) - startTime) + " to calculate the distances for " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
358                 return 0;
359                 
360         }
361         catch(exception& e) {
362                 m->errorOut(e, "DistanceCommand", "execute");
363                 exit(1);
364         }
365 }
366 /**************************************************************************************************/
367 void DistanceCommand::createProcesses(string filename) {
368         try {
369 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
370                 int process = 0;
371                 processIDS.clear();
372                 
373                 //loop through and create all the processes you want
374                 while (process != processors) {
375                         int pid = fork();
376                         
377                         if (pid > 0) {
378                                 processIDS[lines[process]->end] = pid;  //create map from line number to pid so you can append files in correct order later
379                                 process++;
380                         }else if (pid == 0){
381                                 driver(lines[process]->start, lines[process]->end, filename + toString(getpid()) + ".temp", cutoff);
382                                 exit(0);
383                         }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
384                 }
385         
386                 //force parent to wait until all the processes are done
387                 for (map<int, int>::iterator it = processIDS.begin(); it != processIDS.end(); it++) { 
388                         int temp = it->second;
389                         wait(&temp);
390                 }
391 #endif
392         }
393         catch(exception& e) {
394                 m->errorOut(e, "DistanceCommand", "createProcesses");
395                 exit(1);
396         }
397 }
398
399 /**************************************************************************************************/
400 /////// need to fix to work with calcs and sequencedb
401 int DistanceCommand::driver(int startLine, int endLine, string dFileName, float cutoff){
402         try {
403
404                 int startTime = time(NULL);
405                 
406                 //column file
407                 ofstream outFile(dFileName.c_str(), ios::trunc);
408                 outFile.setf(ios::fixed, ios::showpoint);
409                 outFile << setprecision(4);
410                 
411                 if((output == "lt") && startLine == 0){ outFile << alignDB.getNumSeqs() << endl;        }
412                 
413                 for(int i=startLine;i<endLine;i++){
414                         if(output == "lt")      {       
415                                 string name = alignDB.get(i).getName();
416                                 if (name.length() < 10) { //pad with spaces to make compatible
417                                         while (name.length() < 10) {  name += " ";  }
418                                 }
419                                 outFile << name << '\t';        
420                         }
421                         for(int j=0;j<i;j++){
422                                 
423                                 if (m->control_pressed) { outFile.close(); return 0;  }
424                                 
425                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
426                                 double dist = distCalculator->getDist();
427                                 
428                                 if(dist <= cutoff){
429                                         if (output == "column") { outFile << alignDB.get(i).getName() << ' ' << alignDB.get(j).getName() << ' ' << dist << endl; }
430                                 }
431                                 if (output == "lt") {  outFile << dist << '\t'; }
432                                 
433                                 if (output == "square") { //make a square column you can convert to square phylip
434                                         outFile << alignDB.get(i).getName() << '\t' << alignDB.get(j).getName() << '\t' << dist << endl;
435                                         outFile << alignDB.get(j).getName() << '\t' << alignDB.get(i).getName() << '\t' << dist << endl;
436                                 }
437
438                         }
439                         
440                         if (output == "lt") { outFile << endl; }
441                         
442                         if(i % 100 == 0){
443                                 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
444                         }
445                         
446                 }
447                 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
448                 
449                 outFile.close();
450                 
451                 return 1;
452         }
453         catch(exception& e) {
454                 m->errorOut(e, "DistanceCommand", "driver");
455                 exit(1);
456         }
457 }
458 #ifdef USE_MPI
459 /**************************************************************************************************/
460 /////// need to fix to work with calcs and sequencedb
461 int DistanceCommand::driverMPI(int startLine, int endLine, MPI_File& outMPI, float cutoff){
462         try {
463                 MPI_Status status;
464                 int startTime = time(NULL);
465                 
466                 string outputString = "";
467                 
468                 for(int i=startLine;i<endLine;i++){
469         
470                         for(int j=0;j<i;j++){
471                                 
472                                 if (m->control_pressed) {  return 0;  }
473                                 
474                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
475                                 double dist = distCalculator->getDist();
476                                 
477                                 if(dist <= cutoff){
478                                         if (output == "column") { outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n'); }
479                                 }
480                                 
481                                 if (output == "square") { //make a square column you can convert to square phylip
482                                         outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n');
483                                         outputString += (alignDB.get(j).getName() + ' ' + alignDB.get(i).getName() + ' ' + toString(dist) + '\n');
484                                 }
485                         }
486                         
487                         if(i % 100 == 0){
488                                 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
489                                 cout << i << '\t' << (time(NULL) - startTime) << endl;
490                         }
491                         
492                          
493                         //send results to parent
494                         int length = outputString.length();
495
496                         char* buf = new char[length];
497                         memcpy(buf, outputString.c_str(), length);
498                         
499                         MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status);
500                         outputString = "";
501                         delete buf;
502                         
503                 }
504                 
505                 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
506                 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;                
507                 return 1;
508         }
509         catch(exception& e) {
510                 m->errorOut(e, "DistanceCommand", "driverMPI");
511                 exit(1);
512         }
513 }
514 /**************************************************************************************************/
515 /////// need to fix to work with calcs and sequencedb
516 int DistanceCommand::driverMPI(int startLine, int endLine, string file, long& size){
517         try {
518                 MPI_Status status;
519                 
520                 MPI_File outMPI;
521                 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
522
523                 //char* filename = new char[file.length()];
524                 //memcpy(filename, file.c_str(), file.length());
525                 
526                 char filename[1024];
527                 strcpy(filename, file.c_str());
528
529                 MPI_File_open(MPI_COMM_SELF, filename, amode, MPI_INFO_NULL, &outMPI);
530                 //delete filename;
531
532                 int startTime = time(NULL);
533                 
534                 string outputString = "";
535                 size = 0;
536                 
537                 if((output == "lt") && startLine == 0){ outputString += toString(alignDB.getNumSeqs()) + "\n";  }
538                 
539                 for(int i=startLine;i<endLine;i++){
540                         if(output == "lt")      {       
541                                 string name = alignDB.get(i).getName();
542                                 if (name.length() < 10) { //pad with spaces to make compatible
543                                         while (name.length() < 10) {  name += " ";  }
544                                 }
545                                 outputString += name + "\t";    
546                         }
547                         for(int j=0;j<i;j++){
548                                 
549                                 if (m->control_pressed) {  return 0;  }
550                                 
551                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
552                                 double dist = distCalculator->getDist();
553                                 
554                                 if (output == "lt") {  outputString += toString(dist) + "\t"; }
555                         }
556                         
557                         if (output == "lt") { outputString += "\n"; }
558
559                 
560                         if(i % 100 == 0){
561                                 //m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
562                                 cout << i << '\t' << (time(NULL) - startTime) << endl;
563                         }
564                         
565                         
566                         //send results to parent
567                         int length = outputString.length();
568                         char* buf = new char[length];
569                         memcpy(buf, outputString.c_str(), length);
570                         
571                         MPI_File_write(outMPI, buf, length, MPI_CHAR, &status);
572                         size += outputString.length();
573                         outputString = "";
574                         delete buf;
575                 }
576                 
577                 //m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
578                 cout << (endLine-1) << '\t' << (time(NULL) - startTime) << endl;
579                 MPI_File_close(&outMPI);
580                 
581                 return 1;
582         }
583         catch(exception& e) {
584                 m->errorOut(e, "DistanceCommand", "driverMPI");
585                 exit(1);
586         }
587 }
588 #endif
589 /**************************************************************************************************/
590 int DistanceCommand::convertMatrix(string outputFile) {
591         try{
592
593                 //sort file by first column so the distances for each row are together
594                 string outfile = getRootName(outputFile) + "sorted.dist.temp";
595                 
596                 //use the unix sort 
597                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
598                         string command = "sort -n " + outputFile + " -o " + outfile;
599                         system(command.c_str());
600                 #else //sort using windows sort
601                         string command = "sort " + outputFile + " /O " + outfile;
602                         system(command.c_str());
603                 #endif
604                 
605
606                 //output to new file distance for each row and save positions in file where new row begins
607                 ifstream in;
608                 openInputFile(outfile, in);
609                 
610                 ofstream out;
611                 openOutputFile(outputFile, out);
612                 
613                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
614
615                 out << alignDB.getNumSeqs() << endl;
616                 
617                 //get first currentRow
618                 string first, currentRow, second;
619                 float dist;
620                 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key 
621                 map<string, float>::iterator it;
622                 
623                 in >> first;
624                 currentRow = first;
625                 
626                 rowDists[first] = 0.00; //distance to yourself is 0.0
627                 
628                 in.seekg(0);
629                 //openInputFile(outfile, in);
630                 
631                 while(!in.eof()) {
632                         if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
633                         
634                         in >> first >> second >> dist; gobble(in);
635                                 
636                         if (first != currentRow) {
637                                 //print out last row
638                                 out << currentRow << '\t'; //print name
639
640                                 //print dists
641                                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
642                                         out << it->second << '\t';
643                                 }
644                                 out << endl;
645                                 
646                                 //start new row
647                                 currentRow = first;
648                                 rowDists.clear();
649                                 rowDists[first] = 0.00;
650                                 rowDists[second] = dist;
651                         }else{
652                                 rowDists[second] = dist;
653                         }
654                 }
655                 //print out last row
656                 out << currentRow << '\t'; //print name
657                                 
658                 //print dists
659                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
660                         out << it->second << '\t';
661                 }
662                 out << endl;
663                 
664                 in.close();
665                 out.close();
666                 
667                 remove(outfile.c_str());
668                 
669                 return 1;
670                 
671         }
672         catch(exception& e) {
673                 m->errorOut(e, "DistanceCommand", "convertMatrix");
674                 exit(1);
675         }
676 }
677 /**************************************************************************************************/
678 int DistanceCommand::convertToLowerTriangle(string outputFile) {
679         try{
680
681                 //sort file by first column so the distances for each row are together
682                 string outfile = getRootName(outputFile) + "sorted.dist.temp";
683                 
684                 //use the unix sort 
685                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
686                         string command = "sort -n " + outputFile + " -o " + outfile;
687                         system(command.c_str());
688                 #else //sort using windows sort
689                         string command = "sort " + outputFile + " /O " + outfile;
690                         system(command.c_str());
691                 #endif
692                 
693
694                 //output to new file distance for each row and save positions in file where new row begins
695                 ifstream in;
696                 openInputFile(outfile, in);
697                 
698                 ofstream out;
699                 openOutputFile(outputFile, out);
700                 
701                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
702
703                 out << alignDB.getNumSeqs() << endl;
704                 
705                 //get first currentRow
706                 string first, currentRow, second;
707                 float dist;
708                 int i, j;
709                 i = 0; j = 0;
710                 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key 
711                 map<string, float>::iterator it;
712                 
713                 in >> first;
714                 currentRow = first;
715                 
716                 rowDists[first] = 0.00; //distance to yourself is 0.0
717                 
718                 in.seekg(0);
719                 //openInputFile(outfile, in);
720                 
721                 while(!in.eof()) {
722                         if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
723                         
724                         in >> first >> second >> dist; gobble(in);
725                                 
726                         if (first != currentRow) {
727                                 //print out last row
728                                 out << currentRow << '\t'; //print name
729
730                                 //print dists
731                                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
732                                         if (j >= i) { break; }
733                                         out << it->second << '\t';
734                                         j++;
735                                 }
736                                 out << endl;
737                                 
738                                 //start new row
739                                 currentRow = first;
740                                 rowDists.clear();
741                                 rowDists[first] = 0.00;
742                                 rowDists[second] = dist;
743                                 j = 0;
744                                 i++;
745                         }else{
746                                 rowDists[second] = dist;
747                         }
748                 }
749                 //print out last row
750                 out << currentRow << '\t'; //print name
751                                 
752                 //print dists
753                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
754                         out << it->second << '\t';
755                 }
756                 out << endl;
757                 
758                 in.close();
759                 out.close();
760                 
761                 remove(outfile.c_str());
762                 
763                 return 1;
764                 
765         }
766         catch(exception& e) {
767                 m->errorOut(e, "DistanceCommand", "convertToLowerTriangle");
768                 exit(1);
769         }
770 }
771 /**************************************************************************************************
772 void DistanceCommand::appendFiles(string temp, string filename) {
773         try{
774                 ofstream output;
775                 ifstream input;
776         
777                 //open output file in append mode
778                 openOutputFileAppend(filename, output);
779                 openInputFile(temp, input);
780                 
781                 while(char c = input.get()){
782                         if(input.eof())         {       break;                  }
783                         else                            {       output << c;    }
784                 }
785                 
786                 input.close();
787                 output.close();
788         }
789         catch(exception& e) {
790                 m->errorOut(e, "DistanceCommand", "appendFiles");
791                 exit(1);
792         }
793 }
794 /**************************************************************************************************/
795
796