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