]> git.donarmstrong.com Git - mothur.git/blob - distancecommand.cpp
added logfile feature
[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", "phylip", "calc", "countends", "cutoff", "processors"};
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                 
37                         //check to make sure all parameters are valid for command
38                         for (map<string, string>::iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) { 
39                                 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) {  abort = true;  }
40                         }
41                         
42                         //check for required parameters
43                         fastafile = validParameter.validFile(parameters, "fasta", true);
44                         if (fastafile == "not found") { mothurOut("fasta is a required parameter for the dist.seqs command."); mothurOutEndLine(); abort = true; }
45                         else if (fastafile == "not open") { abort = true; }     
46                         else{
47                                 ifstream inFASTA;
48                                 openInputFile(fastafile, inFASTA);
49                                 alignDB = SequenceDB(inFASTA); 
50                                 inFASTA.close();
51                         }
52
53                         //check for optional parameter and set defaults
54                         // ...at some point should added some additional type checking...
55                         calc = validParameter.validFile(parameters, "calc", false);                     
56                         if (calc == "not found") { calc = "onegap";  }
57                         else { 
58                                  if (calc == "default")  {  calc = "onegap";  }
59                         }
60                         splitAtDash(calc, Estimators);
61
62                         string temp;
63                         temp = validParameter.validFile(parameters, "countends", false);        if(temp == "not found"){        temp = "T";     }
64                         convert(temp, countends); 
65                         
66                         temp = validParameter.validFile(parameters, "cutoff", false);           if(temp == "not found"){        temp = "1.0"; }
67                         convert(temp, cutoff); 
68                         
69                         temp = validParameter.validFile(parameters, "processors", false);       if(temp == "not found"){        temp = "1"; }
70                         convert(temp, processors); 
71                         
72                         phylip = validParameter.validFile(parameters, "phylip", false);         if(phylip == "not found"){      phylip = "F"; }
73         
74                         
75                         ValidCalculators validCalculator;
76                         
77                         if (isTrue(countends) == true) {
78                                 for (int i=0; i<Estimators.size(); i++) {
79                                         if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) { 
80                                                 if (Estimators[i] == "nogaps")                  {       distCalculator = new ignoreGaps();      }
81                                                 else if (Estimators[i] == "eachgap")    {       distCalculator = new eachGapDist();     }
82                                                 else if (Estimators[i] == "onegap")             {       distCalculator = new oneGapDist();      }
83                                         }
84                                 }
85                         }else {
86                                 for (int i=0; i<Estimators.size(); i++) {
87                                         if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) { 
88                                                 if (Estimators[i] == "nogaps")          {       distCalculator = new ignoreGaps();                                      }
89                                                 else if (Estimators[i] == "eachgap"){   distCalculator = new eachGapIgnoreTermGapDist();        }
90                                                 else if (Estimators[i] == "onegap")     {       distCalculator = new oneGapIgnoreTermGapDist();         }
91                                         }
92                                 }
93                         }
94
95                 }
96                                 
97         }
98         catch(exception& e) {
99                 errorOut(e, "DistanceCommand", "DistanceCommand");
100                 exit(1);
101         }
102 }
103
104 //**********************************************************************************************************************
105
106 DistanceCommand::~DistanceCommand(){
107         
108         for(int i=0;i<lines.size();i++){
109                 delete lines[i];
110         }
111         
112 }
113         
114 //**********************************************************************************************************************
115
116 void DistanceCommand::help(){
117         try {
118                 mothurOut("The dist.seqs command reads a file containing sequences and creates a distance file.\n");
119                 mothurOut("The dist.seqs command parameters are fasta, calc, countends, cutoff and processors.  \n");
120                 mothurOut("The fasta parameter is required.\n");
121                 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");
122                 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");
123                 mothurOut("The cutoff parameter allows you to specify maximum distance to keep. The default is 1.0.\n");
124                 mothurOut("The processors parameter allows you to specify number of processors to use.  The default is 1.\n");
125                 mothurOut("The dist.seqs command should be in the following format: \n");
126                 mothurOut("dist.seqs(fasta=yourFastaFile, calc=yourCalc, countends=yourEnds, cutoff= yourCutOff, processors=yourProcessors) \n");
127                 mothurOut("Example dist.seqs(fasta=amazon.fasta, calc=eachgap, countends=F, cutoff= 2.0, processors=3).\n");
128                 mothurOut("Note: No spaces between parameter labels (i.e. calc), '=' and parameters (i.e.yourCalc).\n\n");
129         }
130         catch(exception& e) {
131                 errorOut(e, "DistanceCommand", "help");
132                 exit(1);
133         }
134 }
135 //**********************************************************************************************************************
136
137 int DistanceCommand::execute(){
138         try {
139                 
140                 if (abort == true) { return 0; }
141                 
142                 int numSeqs = alignDB.getNumSeqs();
143                 cutoff += 0.005;
144                 
145                 string outputFile;
146                 
147                 //doses the user want the phylip formatted file as well
148                 if (isTrue(phylip) == true) {
149                         outputFile = getRootName(fastafile) + "phylip.dist";
150                         remove(outputFile.c_str());
151                         
152                         //output numSeqs to phylip formatted dist file
153                 }else { //user wants column format
154                         outputFile = getRootName(fastafile) + "dist";
155                         remove(outputFile.c_str());
156                 }
157                                 
158                 //#     if defined (_WIN32)
159                 //figure out how to implement the fork and wait commands in windows
160                 //      driver(distCalculator, seqDB, 0, numSeqs, distFile, phylipFile, cutoff);
161                 //#     endif
162                 
163                                 
164 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
165                 //if you don't need to fork anything
166                 if(processors == 1){
167                         driver(0, numSeqs, outputFile, cutoff);
168                 }else{ //you have multiple processors
169                         
170                         for (int i = 0; i < processors; i++) {
171                                 lines.push_back(new linePair());
172                                 lines[i]->start = int (sqrt(float(i)/float(processors)) * numSeqs);
173                                 lines[i]->end = int (sqrt(float(i+1)/float(processors)) * numSeqs);
174                         }
175
176                         createProcesses(outputFile); 
177                 
178                         map<int, int>::iterator it = processIDS.begin();
179                         rename((outputFile + toString(it->second) + ".temp").c_str(), outputFile.c_str());
180                         it++;
181                         
182                         //append and remove temp files
183                         for (; it != processIDS.end(); it++) {
184                                 appendFiles((outputFile + toString(it->second) + ".temp"), outputFile);
185                                 remove((outputFile + toString(it->second) + ".temp").c_str());
186                         }
187                 }
188 #else
189                 ifstream inFASTA;
190                 driver(0, numSeqs, outputFile, cutoff);
191 #endif
192                 
193                 delete distCalculator;
194                 
195                 return 0;
196                 
197         }
198         catch(exception& e) {
199                 errorOut(e, "DistanceCommand", "execute");
200                 exit(1);
201         }
202 }
203 /**************************************************************************************************/
204 void DistanceCommand::createProcesses(string filename) {
205         try {
206 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
207                 int process = 0;
208                 processIDS.clear();
209                 
210                 //loop through and create all the processes you want
211                 while (process != processors) {
212                         int pid = fork();
213                         
214                         if (pid > 0) {
215                                 processIDS[lines[process]->end] = pid;  //create map from line number to pid so you can append files in correct order later
216                                 process++;
217                         }else if (pid == 0){
218                                 driver(lines[process]->start, lines[process]->end, filename + toString(getpid()) + ".temp", cutoff);
219                                 exit(0);
220                         }else { mothurOut("unable to spawn the necessary processes."); mothurOutEndLine(); exit(0); }
221                 }
222         
223                 //force parent to wait until all the processes are done
224                 for (map<int, int>::iterator it = processIDS.begin(); it != processIDS.end(); it++) { 
225                         int temp = it->second;
226                         wait(&temp);
227                 }
228 #endif
229         }
230         catch(exception& e) {
231                 errorOut(e, "DistanceCommand", "createProcesses");
232                 exit(1);
233         }
234 }
235
236 /**************************************************************************************************/
237 /////// need to fix to work with calcs and sequencedb
238 int DistanceCommand::driver(int startLine, int endLine, string dFileName, float cutoff){
239         try {
240
241                 int startTime = time(NULL);
242                 
243                 //column file
244                 ofstream outFile(dFileName.c_str(), ios::trunc);
245                 outFile.setf(ios::fixed, ios::showpoint);
246                 outFile << setprecision(4);
247                 
248                 if(isTrue(phylip) && startLine == 0){   outFile << alignDB.getNumSeqs() << endl;        }
249                 for(int i=startLine;i<endLine;i++){
250                         if(isTrue(phylip))      {       outFile << alignDB.get(i).getName() << '\t';    }
251                         for(int j=0;j<i;j++){
252                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
253                                 double dist = distCalculator->getDist();
254                                 
255                                 if(dist <= cutoff){
256                                         if (!isTrue(phylip)) { outFile << alignDB.get(i).getName() << ' ' << alignDB.get(j).getName() << ' ' << dist << endl; }
257                                 }
258                                 if (isTrue(phylip)) {  outFile << dist << '\t'; }
259                                 
260                         }
261                         
262                         if (isTrue(phylip) == true) { outFile << endl; }
263                         
264                         if(i % 100 == 0){
265                                 mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); mothurOutEndLine();
266                         }
267                         
268                 }
269                 mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); mothurOutEndLine();
270                 
271                 outFile.close();
272                 
273                 return 1;
274         }
275         catch(exception& e) {
276                 errorOut(e, "DistanceCommand", "driver");
277                 exit(1);
278         }
279 }
280
281 /**************************************************************************************************/
282 void DistanceCommand::appendFiles(string temp, string filename) {
283         try{
284                 ofstream output;
285                 ifstream input;
286         
287                 //open output file in append mode
288                 openOutputFileAppend(filename, output);
289                 openInputFile(temp, input);
290                 
291                 while(char c = input.get()){
292                         if(input.eof())         {       break;                  }
293                         else                            {       output << c;    }
294                 }
295                 
296                 input.close();
297                 output.close();
298         }
299         catch(exception& e) {
300                 errorOut(e, "DistanceCommand", "appendFiles");
301                 exit(1);
302         }
303 }
304 /**************************************************************************************************/