]> git.donarmstrong.com Git - mothur.git/blob - distancecommand.cpp
added set.dir command and modified commands to redirect input and output, removed...
[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", "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                         phylip = validParameter.validFile(parameters, "phylip", false);         if(phylip == "not found"){      phylip = "F"; }
94         
95                         
96                         ValidCalculators validCalculator;
97                         
98                         if (isTrue(countends) == true) {
99                                 for (int i=0; i<Estimators.size(); i++) {
100                                         if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) { 
101                                                 if (Estimators[i] == "nogaps")                  {       distCalculator = new ignoreGaps();      }
102                                                 else if (Estimators[i] == "eachgap")    {       distCalculator = new eachGapDist();     }
103                                                 else if (Estimators[i] == "onegap")             {       distCalculator = new oneGapDist();      }
104                                         }
105                                 }
106                         }else {
107                                 for (int i=0; i<Estimators.size(); i++) {
108                                         if (validCalculator.isValidCalculator("distance", Estimators[i]) == true) { 
109                                                 if (Estimators[i] == "nogaps")          {       distCalculator = new ignoreGaps();                                      }
110                                                 else if (Estimators[i] == "eachgap"){   distCalculator = new eachGapIgnoreTermGapDist();        }
111                                                 else if (Estimators[i] == "onegap")     {       distCalculator = new oneGapIgnoreTermGapDist();         }
112                                         }
113                                 }
114                         }
115
116                 }
117                                 
118         }
119         catch(exception& e) {
120                 errorOut(e, "DistanceCommand", "DistanceCommand");
121                 exit(1);
122         }
123 }
124
125 //**********************************************************************************************************************
126
127 DistanceCommand::~DistanceCommand(){
128         
129         for(int i=0;i<lines.size();i++){
130                 delete lines[i];
131         }
132         
133 }
134         
135 //**********************************************************************************************************************
136
137 void DistanceCommand::help(){
138         try {
139                 mothurOut("The dist.seqs command reads a file containing sequences and creates a distance file.\n");
140                 mothurOut("The dist.seqs command parameters are fasta, calc, countends, cutoff and processors.  \n");
141                 mothurOut("The fasta parameter is required.\n");
142                 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");
143                 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");
144                 mothurOut("The cutoff parameter allows you to specify maximum distance to keep. The default is 1.0.\n");
145                 mothurOut("The processors parameter allows you to specify number of processors to use.  The default is 1.\n");
146                 mothurOut("The dist.seqs command should be in the following format: \n");
147                 mothurOut("dist.seqs(fasta=yourFastaFile, calc=yourCalc, countends=yourEnds, cutoff= yourCutOff, processors=yourProcessors) \n");
148                 mothurOut("Example dist.seqs(fasta=amazon.fasta, calc=eachgap, countends=F, cutoff= 2.0, processors=3).\n");
149                 mothurOut("Note: No spaces between parameter labels (i.e. calc), '=' and parameters (i.e.yourCalc).\n\n");
150         }
151         catch(exception& e) {
152                 errorOut(e, "DistanceCommand", "help");
153                 exit(1);
154         }
155 }
156 //**********************************************************************************************************************
157
158 int DistanceCommand::execute(){
159         try {
160                 
161                 if (abort == true) { return 0; }
162                 
163                 int numSeqs = alignDB.getNumSeqs();
164                 cutoff += 0.005;
165                 
166                 string outputFile;
167                 
168                 //doses the user want the phylip formatted file as well
169                 if (isTrue(phylip) == true) {
170                         outputFile = outputDir + getRootName(getSimpleName(fastafile)) + "phylip.dist";
171                         remove(outputFile.c_str());
172                         
173                         //output numSeqs to phylip formatted dist file
174                 }else { //user wants column format
175                         outputFile = outputDir + getRootName(getSimpleName(fastafile)) + "dist";
176                         remove(outputFile.c_str());
177                 }
178                                 
179 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
180                 //if you don't need to fork anything
181                 if(processors == 1){
182                         driver(0, numSeqs, outputFile, cutoff);
183                 }else{ //you have multiple processors
184                         
185                         for (int i = 0; i < processors; i++) {
186                                 lines.push_back(new linePair());
187                                 lines[i]->start = int (sqrt(float(i)/float(processors)) * numSeqs);
188                                 lines[i]->end = int (sqrt(float(i+1)/float(processors)) * numSeqs);
189                         }
190
191                         createProcesses(outputFile); 
192                 
193                         map<int, int>::iterator it = processIDS.begin();
194                         rename((outputFile + toString(it->second) + ".temp").c_str(), outputFile.c_str());
195                         it++;
196                         
197                         //append and remove temp files
198                         for (; it != processIDS.end(); it++) {
199                                 appendFiles((outputFile + toString(it->second) + ".temp"), outputFile);
200                                 remove((outputFile + toString(it->second) + ".temp").c_str());
201                         }
202                 }
203 #else
204                 ifstream inFASTA;
205                 driver(0, numSeqs, outputFile, cutoff);
206 #endif
207                 
208                 delete distCalculator;
209                 
210                 return 0;
211                 
212         }
213         catch(exception& e) {
214                 errorOut(e, "DistanceCommand", "execute");
215                 exit(1);
216         }
217 }
218 /**************************************************************************************************/
219 void DistanceCommand::createProcesses(string filename) {
220         try {
221 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
222                 int process = 0;
223                 processIDS.clear();
224                 
225                 //loop through and create all the processes you want
226                 while (process != processors) {
227                         int pid = fork();
228                         
229                         if (pid > 0) {
230                                 processIDS[lines[process]->end] = pid;  //create map from line number to pid so you can append files in correct order later
231                                 process++;
232                         }else if (pid == 0){
233                                 driver(lines[process]->start, lines[process]->end, filename + toString(getpid()) + ".temp", cutoff);
234                                 exit(0);
235                         }else { mothurOut("unable to spawn the necessary processes."); mothurOutEndLine(); exit(0); }
236                 }
237         
238                 //force parent to wait until all the processes are done
239                 for (map<int, int>::iterator it = processIDS.begin(); it != processIDS.end(); it++) { 
240                         int temp = it->second;
241                         wait(&temp);
242                 }
243 #endif
244         }
245         catch(exception& e) {
246                 errorOut(e, "DistanceCommand", "createProcesses");
247                 exit(1);
248         }
249 }
250
251 /**************************************************************************************************/
252 /////// need to fix to work with calcs and sequencedb
253 int DistanceCommand::driver(int startLine, int endLine, string dFileName, float cutoff){
254         try {
255
256                 int startTime = time(NULL);
257                 
258                 //column file
259                 ofstream outFile(dFileName.c_str(), ios::trunc);
260                 outFile.setf(ios::fixed, ios::showpoint);
261                 outFile << setprecision(4);
262                 
263                 if(isTrue(phylip) && startLine == 0){   outFile << alignDB.getNumSeqs() << endl;        }
264                 
265                 for(int i=startLine;i<endLine;i++){
266                         if(isTrue(phylip))      {       
267                                 string name = alignDB.get(i).getName();
268                                 if (name.length() < 10) { //pad with spaces to make compatible
269                                         while (name.length() < 10) {  name += " ";  }
270                                 }
271                                 outFile << name << '\t';        
272                         }
273                         for(int j=0;j<i;j++){
274                                 distCalculator->calcDist(alignDB.get(i), alignDB.get(j));
275                                 double dist = distCalculator->getDist();
276                                 
277                                 if(dist <= cutoff){
278                                         if (!isTrue(phylip)) { outFile << alignDB.get(i).getName() << ' ' << alignDB.get(j).getName() << ' ' << dist << endl; }
279                                 }
280                                 if (isTrue(phylip)) {  outFile << dist << '\t'; }
281                                 
282                         }
283                         
284                         if (isTrue(phylip) == true) { outFile << endl; }
285                         
286                         if(i % 100 == 0){
287                                 mothurOut(toString(i) + "\t" + toString(time(NULL) - startTime)); mothurOutEndLine();
288                         }
289                         
290                 }
291                 mothurOut(toString(endLine-1) + "\t" + toString(time(NULL) - startTime)); mothurOutEndLine();
292                 
293                 outFile.close();
294                 
295                 return 1;
296         }
297         catch(exception& e) {
298                 errorOut(e, "DistanceCommand", "driver");
299                 exit(1);
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                 openInputFile(temp, input);
312                 
313                 while(char c = input.get()){
314                         if(input.eof())         {       break;                  }
315                         else                            {       output << c;    }
316                 }
317                 
318                 input.close();
319                 output.close();
320         }
321         catch(exception& e) {
322                 errorOut(e, "DistanceCommand", "appendFiles");
323                 exit(1);
324         }
325 }
326 /**************************************************************************************************/