]> git.donarmstrong.com Git - mothur.git/blob - distancecommand.cpp
finished mpi for filter.seqs
[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 numSeqs = alignDB.getNumSeqs();
166                 cutoff += 0.005;
167                 
168                 string outputFile;
169                                 
170                 if (output == "lt") { //does the user want lower triangle phylip formatted file 
171                         outputFile = outputDir + getRootName(getSimpleName(fastafile)) + "phylip.dist";
172                         remove(outputFile.c_str());
173                         
174                         //output numSeqs to phylip formatted dist file
175                 }else if (output == "column") { //user wants column format
176                         outputFile = outputDir + getRootName(getSimpleName(fastafile)) + "dist";
177                         remove(outputFile.c_str());
178                 }else { //assume square
179                         outputFile = outputDir + getRootName(getSimpleName(fastafile)) + "square.dist";
180                         remove(outputFile.c_str());
181                 }
182                 
183
184 #ifdef USE_MPI
185                 
186                 int pid, start, end; 
187                 int tag = 2001;
188                                 
189                 MPI_Status status; 
190                 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running
191                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
192                 
193                 //each process gets where it should start and stop in the file
194                 start = int (sqrt(float(pid)/float(processors)) * numSeqs);
195                 end = int (sqrt(float(pid+1)/float(processors)) * numSeqs);
196         
197                 MPI_File outMPI;
198                 int amode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
199                 
200                 char filename[outputFile.length()];
201                 strcpy(filename, outputFile.c_str());
202                 
203                 MPI_File_open(MPI_COMM_WORLD, filename, amode, MPI_INFO_NULL, &outMPI);
204                 
205                 if (pid == 0) { //you are the root process 
206                 
207                         //do your part
208                         string outputMyPart;
209                         driverMPI(start, end, outMPI, cutoff);
210                         
211                         //wait on chidren
212                         for(int i = 1; i < processors; i++) { 
213                                 char buf[4];
214                                 MPI_Recv(buf, 4, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status); 
215                         }
216                         
217                         if (output == "lt") {
218                                 convertToLowerTriangle(outputFile);
219                         }
220                         
221                 }else { //you are a child process
222                         //do your part
223                         driverMPI(start, end, outMPI, cutoff);
224                 
225                         char buf[4];
226                         strcpy(buf, "done"); 
227                         
228                         //tell parent you are done.
229                         MPI_Send(buf, 4, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
230                 }
231                 
232                 MPI_File_close(&outMPI);
233 #else           
234                                 
235         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
236                 //if you don't need to fork anything
237                 if(processors == 1){
238                         driver(0, numSeqs, outputFile, cutoff);
239                 }else{ //you have multiple processors
240                         
241                         for (int i = 0; i < processors; i++) {
242                                 lines.push_back(new linePair());
243                                 lines[i]->start = int (sqrt(float(i)/float(processors)) * numSeqs);
244                                 lines[i]->end = int (sqrt(float(i+1)/float(processors)) * numSeqs);
245                         }
246
247                         createProcesses(outputFile); 
248                 
249                         map<int, int>::iterator it = processIDS.begin();
250                         rename((outputFile + toString(it->second) + ".temp").c_str(), outputFile.c_str());
251                         it++;
252                         
253                         //append and remove temp files
254                         for (; it != processIDS.end(); it++) {
255                                 appendFiles((outputFile + toString(it->second) + ".temp"), outputFile);
256                                 remove((outputFile + toString(it->second) + ".temp").c_str());
257                         }
258                 }
259         #else
260                 ifstream inFASTA;
261                 driver(0, numSeqs, outputFile, cutoff);
262         #endif
263         
264 #endif
265                 if (m->control_pressed) { delete distCalculator; remove(outputFile.c_str()); return 0; }
266                 
267                 #ifdef USE_MPI
268                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
269                                         
270                         if (pid == 0) { //only one process should output to screen
271                 #endif
272                 
273                 if (output == "square") {  convertMatrix(outputFile); }
274                 
275                 #ifdef USE_MPI
276                         }
277                 #endif
278                 
279                 if (m->control_pressed) { delete distCalculator; remove(outputFile.c_str()); return 0; }
280                 
281                 delete distCalculator;
282                 
283                 m->mothurOutEndLine();
284                 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
285                 m->mothurOut(outputFile); m->mothurOutEndLine();
286                 m->mothurOutEndLine();
287
288                 return 0;
289                 
290         }
291         catch(exception& e) {
292                 m->errorOut(e, "DistanceCommand", "execute");
293                 exit(1);
294         }
295 }
296 /**************************************************************************************************/
297 void DistanceCommand::createProcesses(string filename) {
298         try {
299 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
300                 int process = 0;
301                 processIDS.clear();
302                 
303                 //loop through and create all the processes you want
304                 while (process != processors) {
305                         int pid = fork();
306                         
307                         if (pid > 0) {
308                                 processIDS[lines[process]->end] = pid;  //create map from line number to pid so you can append files in correct order later
309                                 process++;
310                         }else if (pid == 0){
311                                 driver(lines[process]->start, lines[process]->end, filename + toString(getpid()) + ".temp", cutoff);
312                                 exit(0);
313                         }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
314                 }
315         
316                 //force parent to wait until all the processes are done
317                 for (map<int, int>::iterator it = processIDS.begin(); it != processIDS.end(); it++) { 
318                         int temp = it->second;
319                         wait(&temp);
320                 }
321 #endif
322         }
323         catch(exception& e) {
324                 m->errorOut(e, "DistanceCommand", "createProcesses");
325                 exit(1);
326         }
327 }
328
329 /**************************************************************************************************/
330 /////// need to fix to work with calcs and sequencedb
331 int DistanceCommand::driver(int startLine, int endLine, string dFileName, float cutoff){
332         try {
333
334                 int startTime = time(NULL);
335                 
336                 //column file
337                 ofstream outFile(dFileName.c_str(), ios::trunc);
338                 outFile.setf(ios::fixed, ios::showpoint);
339                 outFile << setprecision(4);
340                 
341                 if((output == "lt") && startLine == 0){ outFile << alignDB.getNumSeqs() << endl;        }
342                 
343                 for(int i=startLine;i<endLine;i++){
344                         if(output == "lt")      {       
345                                 string name = alignDB.get(i).getName();
346                                 if (name.length() < 10) { //pad with spaces to make compatible
347                                         while (name.length() < 10) {  name += " ";  }
348                                 }
349                                 outFile << name << '\t';        
350                         }
351                         for(int j=0;j<i;j++){
352                                 
353                                 if (m->control_pressed) { outFile.close(); return 0;  }
354                                 
355                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
356                                 double dist = distCalculator->getDist();
357                                 
358                                 if(dist <= cutoff){
359                                         if (output == "column") { outFile << alignDB.get(i).getName() << ' ' << alignDB.get(j).getName() << ' ' << dist << endl; }
360                                 }
361                                 if (output == "lt") {  outFile << dist << '\t'; }
362                                 
363                                 if (output == "square") { //make a square column you can convert to square phylip
364                                         outFile << alignDB.get(i).getName() << '\t' << alignDB.get(j).getName() << '\t' << dist << endl;
365                                         outFile << alignDB.get(j).getName() << '\t' << alignDB.get(i).getName() << '\t' << dist << endl;
366                                 }
367
368                         }
369                         
370                         if (output == "lt") { outFile << endl; }
371                         
372                         if(i % 100 == 0){
373                                 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
374                         }
375                         
376                 }
377                 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
378                 
379                 outFile.close();
380                 
381                 return 1;
382         }
383         catch(exception& e) {
384                 m->errorOut(e, "DistanceCommand", "driver");
385                 exit(1);
386         }
387 }
388 #ifdef USE_MPI
389 /**************************************************************************************************/
390 /////// need to fix to work with calcs and sequencedb
391 int DistanceCommand::driverMPI(int startLine, int endLine, MPI_File& outMPI, float cutoff){
392         try {
393                 MPI_Status status;
394                 int startTime = time(NULL);
395                 
396                 string outputString = "";
397                 
398                 for(int i=startLine;i<endLine;i++){
399         
400                         for(int j=0;j<i;j++){
401                                 
402                                 if (m->control_pressed) {  return 0;  }
403                                 
404                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
405                                 double dist = distCalculator->getDist();
406                                 
407                                 if(dist <= cutoff){
408                                         if (output == "column") { outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n'); }
409                                 }
410                                 
411                                 if ((output == "square") || (output == "lt")){ //make a square column you can convert to square phylip
412                                         outputString += (alignDB.get(i).getName() + ' ' + alignDB.get(j).getName() + ' ' + toString(dist) + '\n');
413                                         outputString += (alignDB.get(j).getName() + ' ' + alignDB.get(i).getName() + ' ' + toString(dist) + '\n');
414                                 }
415
416                         }
417                         
418                         if(i % 100 == 0){
419                                 m->mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
420                         }
421                         
422                         if(i % 10 == 0){ //output to file 
423                                 //send results to parent
424                                 int length = outputString.length();
425                                 char buf[length];
426                                 strcpy(buf, outputString.c_str()); 
427                                 
428                                 MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status);
429                                 outputString = "";
430                         }
431                         
432                 }
433                 
434                 m->mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); m->mothurOutEndLine();
435                 if(outputString != ""){ //output to file 
436                                 //send results to parent
437                                 int length = outputString.length();
438                                 char buf[length];
439                                 strcpy(buf, outputString.c_str()); 
440                                 
441                                 MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status);
442                                 outputString = "";
443                 }
444                 
445                 return 1;
446         }
447         catch(exception& e) {
448                 m->errorOut(e, "DistanceCommand", "driverMPI");
449                 exit(1);
450         }
451 }
452 #endif
453 /**************************************************************************************************/
454 int DistanceCommand::convertMatrix(string outputFile) {
455         try{
456
457                 //sort file by first column so the distances for each row are together
458                 string outfile = getRootName(outputFile) + "sorted.dist.temp";
459                 
460                 //use the unix sort 
461                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
462                         string command = "sort -n " + outputFile + " -o " + outfile;
463                         system(command.c_str());
464                 #else //sort using windows sort
465                         string command = "sort " + outputFile + " /O " + outfile;
466                         system(command.c_str());
467                 #endif
468                 
469
470                 //output to new file distance for each row and save positions in file where new row begins
471                 ifstream in;
472                 openInputFile(outfile, in);
473                 
474                 ofstream out;
475                 openOutputFile(outputFile, out);
476                 
477                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
478
479                 out << alignDB.getNumSeqs() << endl;
480                 
481                 //get first currentRow
482                 string first, currentRow, second;
483                 float dist;
484                 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key 
485                 map<string, float>::iterator it;
486                 
487                 in >> first;
488                 currentRow = first;
489                 
490                 rowDists[first] = 0.00; //distance to yourself is 0.0
491                 
492                 in.seekg(0);
493                 //openInputFile(outfile, in);
494                 
495                 while(!in.eof()) {
496                         if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
497                         
498                         in >> first >> second >> dist; gobble(in);
499                                 
500                         if (first != currentRow) {
501                                 //print out last row
502                                 out << currentRow << '\t'; //print name
503
504                                 //print dists
505                                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
506                                         out << it->second << '\t';
507                                 }
508                                 out << endl;
509                                 
510                                 //start new row
511                                 currentRow = first;
512                                 rowDists.clear();
513                                 rowDists[first] = 0.00;
514                                 rowDists[second] = dist;
515                         }else{
516                                 rowDists[second] = dist;
517                         }
518                 }
519                 //print out last row
520                 out << currentRow << '\t'; //print name
521                                 
522                 //print dists
523                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
524                         out << it->second << '\t';
525                 }
526                 out << endl;
527                 
528                 in.close();
529                 out.close();
530                 
531                 remove(outfile.c_str());
532                 
533                 return 1;
534                 
535         }
536         catch(exception& e) {
537                 m->errorOut(e, "DistanceCommand", "convertMatrix");
538                 exit(1);
539         }
540 }
541 /**************************************************************************************************/
542 int DistanceCommand::convertToLowerTriangle(string outputFile) {
543         try{
544
545                 //sort file by first column so the distances for each row are together
546                 string outfile = getRootName(outputFile) + "sorted.dist.temp";
547                 
548                 //use the unix sort 
549                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
550                         string command = "sort -n " + outputFile + " -o " + outfile;
551                         system(command.c_str());
552                 #else //sort using windows sort
553                         string command = "sort " + outputFile + " /O " + outfile;
554                         system(command.c_str());
555                 #endif
556                 
557
558                 //output to new file distance for each row and save positions in file where new row begins
559                 ifstream in;
560                 openInputFile(outfile, in);
561                 
562                 ofstream out;
563                 openOutputFile(outputFile, out);
564                 
565                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
566
567                 out << alignDB.getNumSeqs() << endl;
568                 
569                 //get first currentRow
570                 string first, currentRow, second;
571                 float dist;
572                 int i, j;
573                 i = 0; j = 0;
574                 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key 
575                 map<string, float>::iterator it;
576                 
577                 in >> first;
578                 currentRow = first;
579                 
580                 rowDists[first] = 0.00; //distance to yourself is 0.0
581                 
582                 in.seekg(0);
583                 //openInputFile(outfile, in);
584                 
585                 while(!in.eof()) {
586                         if (m->control_pressed) { in.close(); remove(outfile.c_str()); out.close(); return 0; }
587                         
588                         in >> first >> second >> dist; gobble(in);
589                                 
590                         if (first != currentRow) {
591                                 //print out last row
592                                 out << currentRow << '\t'; //print name
593
594                                 //print dists
595                                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
596                                         if (j >= i) { break; }
597                                         out << it->second << '\t';
598                                         j++;
599                                 }
600                                 out << endl;
601                                 
602                                 //start new row
603                                 currentRow = first;
604                                 rowDists.clear();
605                                 rowDists[first] = 0.00;
606                                 rowDists[second] = dist;
607                                 j = 0;
608                                 i++;
609                         }else{
610                                 rowDists[second] = dist;
611                         }
612                 }
613                 //print out last row
614                 out << currentRow << '\t'; //print name
615                                 
616                 //print dists
617                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
618                         out << it->second << '\t';
619                 }
620                 out << endl;
621                 
622                 in.close();
623                 out.close();
624                 
625                 remove(outfile.c_str());
626                 
627                 return 1;
628                 
629         }
630         catch(exception& e) {
631                 m->errorOut(e, "DistanceCommand", "convertToLowerTriangle");
632                 exit(1);
633         }
634 }
635 /**************************************************************************************************
636 void DistanceCommand::appendFiles(string temp, string filename) {
637         try{
638                 ofstream output;
639                 ifstream input;
640         
641                 //open output file in append mode
642                 openOutputFileAppend(filename, output);
643                 openInputFile(temp, input);
644                 
645                 while(char c = input.get()){
646                         if(input.eof())         {       break;                  }
647                         else                            {       output << c;    }
648                 }
649                 
650                 input.close();
651                 output.close();
652         }
653         catch(exception& e) {
654                 m->errorOut(e, "DistanceCommand", "appendFiles");
655                 exit(1);
656         }
657 }
658 /**************************************************************************************************/
659
660