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