]> git.donarmstrong.com Git - mothur.git/blob - distancecommand.cpp
added warning about merging with something above cutoff to cluster. working on chimeras
[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") { mothurOut("fasta is a required parameter for the dist.seqs command."); 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")) { mothurOut(output + " is not a valid output form. Options are column, lt and square. I will use column."); 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                 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                 mothurOut("The dist.seqs command reads a file containing sequences and creates a distance file.\n");
141                 mothurOut("The dist.seqs command parameters are fasta, calc, countends, output, cutoff and processors.  \n");
142                 mothurOut("The fasta parameter is required.\n");
143                 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                 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                 mothurOut("The cutoff parameter allows you to specify maximum distance to keep. The default is 1.0.\n");
146                 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                 mothurOut("The processors parameter allows you to specify number of processors to use.  The default is 1.\n");
148                 mothurOut("The dist.seqs command should be in the following format: \n");
149                 mothurOut("dist.seqs(fasta=yourFastaFile, calc=yourCalc, countends=yourEnds, cutoff= yourCutOff, processors=yourProcessors) \n");
150                 mothurOut("Example dist.seqs(fasta=amazon.fasta, calc=eachgap, countends=F, cutoff= 2.0, processors=3).\n");
151                 mothurOut("Note: No spaces between parameter labels (i.e. calc), '=' and parameters (i.e.yourCalc).\n\n");
152         }
153         catch(exception& e) {
154                 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 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
184                 //if you don't need to fork anything
185                 if(processors == 1){
186                         driver(0, numSeqs, outputFile, cutoff);
187                 }else{ //you have multiple processors
188                         
189                         for (int i = 0; i < processors; i++) {
190                                 lines.push_back(new linePair());
191                                 lines[i]->start = int (sqrt(float(i)/float(processors)) * numSeqs);
192                                 lines[i]->end = int (sqrt(float(i+1)/float(processors)) * numSeqs);
193                         }
194
195                         createProcesses(outputFile); 
196                 
197                         map<int, int>::iterator it = processIDS.begin();
198                         rename((outputFile + toString(it->second) + ".temp").c_str(), outputFile.c_str());
199                         it++;
200                         
201                         //append and remove temp files
202                         for (; it != processIDS.end(); it++) {
203                                 appendFiles((outputFile + toString(it->second) + ".temp"), outputFile);
204                                 remove((outputFile + toString(it->second) + ".temp").c_str());
205                         }
206                 }
207 #else
208                 ifstream inFASTA;
209                 driver(0, numSeqs, outputFile, cutoff);
210 #endif
211                 
212                 if (output == "square") {  convertMatrix(outputFile); }
213                 
214                 delete distCalculator;
215                 
216                 return 0;
217                 
218         }
219         catch(exception& e) {
220                 errorOut(e, "DistanceCommand", "execute");
221                 exit(1);
222         }
223 }
224 /**************************************************************************************************/
225 void DistanceCommand::createProcesses(string filename) {
226         try {
227 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
228                 int process = 0;
229                 processIDS.clear();
230                 
231                 //loop through and create all the processes you want
232                 while (process != processors) {
233                         int pid = fork();
234                         
235                         if (pid > 0) {
236                                 processIDS[lines[process]->end] = pid;  //create map from line number to pid so you can append files in correct order later
237                                 process++;
238                         }else if (pid == 0){
239                                 driver(lines[process]->start, lines[process]->end, filename + toString(getpid()) + ".temp", cutoff);
240                                 exit(0);
241                         }else { mothurOut("unable to spawn the necessary processes."); mothurOutEndLine(); exit(0); }
242                 }
243         
244                 //force parent to wait until all the processes are done
245                 for (map<int, int>::iterator it = processIDS.begin(); it != processIDS.end(); it++) { 
246                         int temp = it->second;
247                         wait(&temp);
248                 }
249 #endif
250         }
251         catch(exception& e) {
252                 errorOut(e, "DistanceCommand", "createProcesses");
253                 exit(1);
254         }
255 }
256
257 /**************************************************************************************************/
258 /////// need to fix to work with calcs and sequencedb
259 int DistanceCommand::driver(int startLine, int endLine, string dFileName, float cutoff){
260         try {
261
262                 int startTime = time(NULL);
263                 
264                 //column file
265                 ofstream outFile(dFileName.c_str(), ios::trunc);
266                 outFile.setf(ios::fixed, ios::showpoint);
267                 outFile << setprecision(4);
268                 
269                 if((output == "lt") && startLine == 0){ outFile << alignDB.getNumSeqs() << endl;        }
270                 
271                 for(int i=startLine;i<endLine;i++){
272                         if(output == "lt")      {       
273                                 string name = alignDB.get(i).getName();
274                                 if (name.length() < 10) { //pad with spaces to make compatible
275                                         while (name.length() < 10) {  name += " ";  }
276                                 }
277                                 outFile << name << '\t';        
278                         }
279                         for(int j=0;j<i;j++){
280                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
281                                 double dist = distCalculator->getDist();
282                                 
283                                 if(dist <= cutoff){
284                                         if (output == "column") { outFile << alignDB.get(i).getName() << ' ' << alignDB.get(j).getName() << ' ' << dist << endl; }
285                                 }
286                                 if (output == "lt") {  outFile << dist << '\t'; }
287                                 
288                                 if (output == "square") { //make a square column you can convert to square phylip
289                                         outFile << alignDB.get(i).getName() << '\t' << alignDB.get(j).getName() << '\t' << dist << endl;
290                                         outFile << alignDB.get(j).getName() << '\t' << alignDB.get(i).getName() << '\t' << dist << endl;
291                                 }
292
293                         }
294                         
295                         if (output == "lt") { outFile << endl; }
296                         
297                         if(i % 100 == 0){
298                                 mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); mothurOutEndLine();
299                         }
300                         
301                 }
302                 mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); mothurOutEndLine();
303                 
304                 outFile.close();
305                 
306                 return 1;
307         }
308         catch(exception& e) {
309                 errorOut(e, "DistanceCommand", "driver");
310                 exit(1);
311         }
312 }
313 /**************************************************************************************************/
314 void DistanceCommand::convertMatrix(string outputFile) {
315         try{
316
317                 //sort file by first column so the distances for each row are together
318                 string outfile = getRootName(outputFile) + "sorted.dist.temp";
319                 
320                 //use the unix sort 
321                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
322                         string command = "sort -n " + outputFile + " -o " + outfile;
323                         system(command.c_str());
324                 #else //sort using windows sort
325                         string command = "sort " + outputFile + " /O " + outfile;
326                         system(command.c_str());
327                 #endif
328                 
329
330                 //output to new file distance for each row and save positions in file where new row begins
331                 ifstream in;
332                 openInputFile(outfile, in);
333                 
334                 ofstream out;
335                 openOutputFile(outputFile, out);
336                 
337                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
338
339                 out << alignDB.getNumSeqs() << endl;
340                 
341                 //get first currentRow
342                 string first, currentRow, second;
343                 float dist;
344                 map<string, float> rowDists; //take advantage of the fact that maps are already sorted by key 
345                 map<string, float>::iterator it;
346                 
347                 in >> first;
348                 currentRow = first;
349                 
350                 rowDists[first] = 0.00; //distance to yourself is 0.0
351                 
352                 in.seekg(0);
353                 //openInputFile(outfile, in);
354                 
355                 while(!in.eof()) {
356                         in >> first >> second >> dist; gobble(in);
357                                 
358                         if (first != currentRow) {
359                                 //print out last row
360                                 out << currentRow << '\t'; //print name
361
362                                 //print dists
363                                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
364                                         out << it->second << '\t';
365                                 }
366                                 out << endl;
367                                 
368                                 //start new row
369                                 currentRow = first;
370                                 rowDists.clear();
371                                 rowDists[first] = 0.00;
372                                 rowDists[second] = dist;
373                         }else{
374                                 rowDists[second] = dist;
375                         }
376                 }
377                 //print out last row
378                 out << currentRow << '\t'; //print name
379                                 
380                 //print dists
381                 for (it = rowDists.begin(); it != rowDists.end(); it++) {
382                         out << it->second << '\t';
383                 }
384                 out << endl;
385                 
386                 in.close();
387                 out.close();
388                 
389                 remove(outfile.c_str());
390                 
391         }
392         catch(exception& e) {
393                 errorOut(e, "DistanceCommand", "convertMatrix");
394                 exit(1);
395         }
396 }
397 /**************************************************************************************************
398 void DistanceCommand::appendFiles(string temp, string filename) {
399         try{
400                 ofstream output;
401                 ifstream input;
402         
403                 //open output file in append mode
404                 openOutputFileAppend(filename, output);
405                 openInputFile(temp, input);
406                 
407                 while(char c = input.get()){
408                         if(input.eof())         {       break;                  }
409                         else                            {       output << c;    }
410                 }
411                 
412                 input.close();
413                 output.close();
414         }
415         catch(exception& e) {
416                 errorOut(e, "DistanceCommand", "appendFiles");
417                 exit(1);
418         }
419 }
420 /**************************************************************************************************/
421
422