]> git.donarmstrong.com Git - mothur.git/blob - preclustercommand.cpp
added checks for ^C to quit command instead of program
[mothur.git] / preclustercommand.cpp
1 /*
2  *  preclustercommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 12/21/09.
6  *  Copyright 2009 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "preclustercommand.h"
11
12 //**********************************************************************************************************************
13 inline bool comparePriority(seqPNode first, seqPNode second) {  return (first.numIdentical > second.numIdentical); }
14 //**********************************************************************************************************************
15
16 PreClusterCommand::PreClusterCommand(string option) {
17         try {
18                 abort = false;
19                 
20                 //allow user to run help
21                 if(option == "help") { help(); abort = true; }
22                 
23                 else {
24                         //valid paramters for this command
25                         string Array[] =  {"fasta", "name", "diffs", "outputdir","inputdir"};
26                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
27                         
28                         OptionParser parser(option);
29                         map<string, string> parameters = parser.getParameters();
30                         
31                         ValidParameters validParameter;
32                         map<string, string>::iterator it;
33                 
34                         //check to make sure all parameters are valid for command
35                         for (map<string, string>::iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) { 
36                                 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) {  abort = true;  }
37                         }
38                         
39                         //if the user changes the input directory command factory will send this info to us in the output parameter 
40                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
41                         if (inputDir == "not found"){   inputDir = "";          }
42                         else {
43                                 string path;
44                                 it = parameters.find("fasta");
45                                 //user has given a template file
46                                 if(it != parameters.end()){ 
47                                         path = hasPath(it->second);
48                                         //if the user has not given a path then, add inputdir. else leave path alone.
49                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
50                                 }
51                                 
52                                 it = parameters.find("name");
53                                 //user has given a template file
54                                 if(it != parameters.end()){ 
55                                         path = hasPath(it->second);
56                                         //if the user has not given a path then, add inputdir. else leave path alone.
57                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
58                                 }
59                         }
60
61                         //check for required parameters
62                         fastafile = validParameter.validFile(parameters, "fasta", true);
63                         if (fastafile == "not found") { m->mothurOut("fasta is a required parameter for the pre.cluster command."); m->mothurOutEndLine(); abort = true; }
64                         else if (fastafile == "not open") { abort = true; }     
65                         
66                         //if the user changes the output directory command factory will send this info to us in the output parameter 
67                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
68                                 outputDir = ""; 
69                                 outputDir += hasPath(fastafile); //if user entered a file with a path then preserve it  
70                         }
71
72                         //check for optional parameter and set defaults
73                         // ...at some point should added some additional type checking...
74                         namefile = validParameter.validFile(parameters, "name", true);
75                         if (namefile == "not found") { namefile =  "";  }
76                         else if (namefile == "not open") { abort = true; }      
77                         else {  readNameFile();  }
78                         
79                         string temp     = validParameter.validFile(parameters, "diffs", false);                         if(temp == "not found"){        temp = "1"; }
80                         convert(temp, diffs); 
81                 }
82                                 
83         }
84         catch(exception& e) {
85                 m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
86                 exit(1);
87         }
88 }
89
90 //**********************************************************************************************************************
91 PreClusterCommand::~PreClusterCommand(){}       
92 //**********************************************************************************************************************
93
94 void PreClusterCommand::help(){
95         try {
96                 m->mothurOut("The pre.cluster command groups sequences that are within a given number of base mismatches.\n");
97                 m->mothurOut("The pre.cluster command outputs a new fasta and name file.\n");
98                 m->mothurOut("The pre.cluster command parameters are fasta, names and diffs. The fasta parameter is required. \n");
99                 m->mothurOut("The names parameter allows you to give a list of seqs that are identical. This file is 2 columns, first column is name or representative sequence, second column is a list of its identical sequences separated by commas.\n");
100                 m->mothurOut("The diffs parameter allows you to specify maximum number of mismatched bases allowed between sequences in a grouping. The default is 1.\n");
101                 m->mothurOut("The pre.cluster command should be in the following format: \n");
102                 m->mothurOut("pre.cluster(fasta=yourFastaFile, names=yourNamesFile, diffs=yourMaxDiffs) \n");
103                 m->mothurOut("Example pre.cluster(fasta=amazon.fasta, diffs=2).\n");
104                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n\n");
105         }
106         catch(exception& e) {
107                 m->errorOut(e, "PreClusterCommand", "help");
108                 exit(1);
109         }
110 }
111 //**********************************************************************************************************************
112
113 int PreClusterCommand::execute(){
114         try {
115                 
116                 if (abort == true) { return 0; }
117                 
118                 //reads fasta file and return number of seqs
119                 int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
120                 
121                 if (m->control_pressed) { return 0; }
122         
123                 if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0;  }
124                 if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); return 0;  }
125                 
126                 //clear sizes since you only needed this info to build the alignSeqs seqPNode structs
127 //              sizes.clear();
128         
129                 //sort seqs by number of identical seqs
130                 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
131         
132                 int count = 0;
133
134                 //think about running through twice...
135                 for (int i = 0; i < numSeqs; i++) {
136                         
137                         //are you active
138                         //                      itActive = active.find(alignSeqs[i].seq.getName());
139                         
140                         if (alignSeqs[i].active) {  //this sequence has not been merged yet
141                                 
142                                 //try to merge it with all smaller seqs
143                                 for (int j = i+1; j < numSeqs; j++) {
144                                         
145                                         if (m->control_pressed) { return 0; }
146                                         
147                                         if (alignSeqs[j].active) {  //this sequence has not been merged yet
148                                                 //are you within "diff" bases
149                                                 int mismatch = calcMisMatches(alignSeqs[i].seq.getAligned(), alignSeqs[j].seq.getAligned());
150                                                 
151                                                 if (mismatch <= diffs) {
152                                                         //merge
153                                                         alignSeqs[i].names += ',' + alignSeqs[j].names;
154                                                         alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
155
156                                                         alignSeqs[j].active = 0;
157                                                         alignSeqs[j].numIdentical = 0;
158                                                         count++;
159                                                 }
160                                         }//end if j active
161                                 }//end if i != j
162                         
163                         //remove from active list 
164                                 alignSeqs[i].active = 0;
165                         }//end if active i
166                         if(i % 100 == 0)        { cout << i << '\t' << numSeqs - count << '\t' << count << endl;        }
167                 }
168                 
169                 string fileroot = outputDir + getRootName(getSimpleName(fastafile));
170                 
171                 string newFastaFile = fileroot + "precluster" + getExtension(fastafile);
172                 string newNamesFile = fileroot + "precluster.names";
173                 
174                 if (m->control_pressed) { return 0; }
175                 
176                 m->mothurOut("Total number of sequences before precluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
177                 m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); 
178                 printData(newFastaFile, newNamesFile);
179                 
180                 if (m->control_pressed) { remove(newFastaFile.c_str()); remove(newNamesFile.c_str()); return 0; }
181                 
182                 m->mothurOutEndLine();
183                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
184                 m->mothurOut(newFastaFile); m->mothurOutEndLine();      
185                 m->mothurOut(newNamesFile); m->mothurOutEndLine();      
186                 m->mothurOutEndLine();
187
188                 return 0;
189                 
190         }
191         catch(exception& e) {
192                 m->errorOut(e, "PreClusterCommand", "execute");
193                 exit(1);
194         }
195 }
196
197 /**************************************************************************************************/
198
199 //this requires the names and fasta file to be in the same order
200
201 int PreClusterCommand::readFASTA(){
202         try {
203                 //ifstream inNames;
204                 ifstream inFasta;
205                 
206                 //openInputFile(namefile, inNames);
207                 openInputFile(fastafile, inFasta);
208                 
209                 //string firstCol, secondCol, nameString;
210                 length = 0;
211                 
212                 while (!inFasta.eof()) {
213                         
214                         if (m->control_pressed) { inFasta.close(); return 0; }
215                         
216                         //inNames >> firstCol >> secondCol;
217                         //nameString = secondCol;
218                         
219                         //gobble(inNames);
220                         //int size = 1;
221                         //while (secondCol.find_first_of(',') != -1) { 
222                         //      size++;
223                         //      secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
224                         //}
225                         
226                         Sequence seq(inFasta);  gobble(inFasta);
227                         
228                         if (seq.getName() != "") {  //can get "" if commented line is at end of fasta file
229                                 if (namefile != "") {
230                                         itSize = sizes.find(seq.getName());
231                                         
232                                         if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
233                                         else{
234                                                 seqPNode tempNode(itSize->second, seq, names[seq.getName()]);
235                                                 alignSeqs.push_back(tempNode);
236                                                 if (seq.getAligned().length() > length) {  length = alignSeqs[0].seq.getAligned().length();  }
237                                         }       
238                                 }else { //no names file, you are identical to yourself 
239                                         seqPNode tempNode(1, seq, seq.getName());
240                                         alignSeqs.push_back(tempNode);
241                                         if (seq.getAligned().length() > length) {  length = alignSeqs[0].seq.getAligned().length();  }
242                                 }
243                         }
244                 }
245                 inFasta.close();
246                 //inNames.close();
247                 return alignSeqs.size();
248         }
249         
250         catch(exception& e) {
251                 m->errorOut(e, "PreClusterCommand", "readFASTA");
252                 exit(1);
253         }
254 }
255
256 /**************************************************************************************************/
257
258 int PreClusterCommand::calcMisMatches(string seq1, string seq2){
259         try {
260                 int numBad = 0;
261                 
262                 for (int i = 0; i < seq1.length(); i++) {
263                         //do they match
264                         if (seq1[i] != seq2[i]) { numBad++; }
265                         if (numBad > diffs) { return length;  } //to far to cluster
266                 }
267                 
268                 return numBad;
269         }
270         catch(exception& e) {
271                 m->errorOut(e, "PreClusterCommand", "calcMisMatches");
272                 exit(1);
273         }
274 }
275
276 /**************************************************************************************************/
277
278 void PreClusterCommand::printData(string newfasta, string newname){
279         try {
280                 ofstream outFasta;
281                 ofstream outNames;
282                 
283                 openOutputFile(newfasta, outFasta);
284                 openOutputFile(newname, outNames);
285                                 
286                 
287                 for (int i = 0; i < alignSeqs.size(); i++) {
288                         if (alignSeqs[i].numIdentical != 0) {
289                                 alignSeqs[i].seq.printSequence(outFasta); 
290                                 outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;
291                         }
292                 }
293                 
294                 outFasta.close();
295                 outNames.close();
296                 
297         }
298         catch(exception& e) {
299                 m->errorOut(e, "PreClusterCommand", "printData");
300                 exit(1);
301         }
302 }
303
304 /**************************************************************************************************/
305
306 void PreClusterCommand::readNameFile(){
307         try {
308                 ifstream in;
309                 openInputFile(namefile, in);
310                 string firstCol, secondCol;
311                                 
312                 while (!in.eof()) {
313                         in >> firstCol >> secondCol; gobble(in);
314                         names[firstCol] = secondCol;
315                         int size = 1;
316                         while (secondCol.find_first_of(',') != -1) { 
317                                 size++;
318                                 secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
319                         }
320                         sizes[firstCol] = size;
321                 }
322                 in.close();
323         }
324         catch(exception& e) {
325                 m->errorOut(e, "PreClusterCommand", "readNameFile");
326                 exit(1);
327         }
328 }
329
330 /**************************************************************************************************/
331
332