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