]> git.donarmstrong.com Git - mothur.git/blob - clusterfragmentscommand.cpp
fixed bug with shhh.flow from file path name in write functions, added "smart" featur...
[mothur.git] / clusterfragmentscommand.cpp
1 /*
2  *  ryanscommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 9/23/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "clusterfragmentscommand.h"
11 #include "needlemanoverlap.hpp"
12
13 //**********************************************************************************************************************
14 //sort by unaligned
15 inline bool comparePriority(seqRNode first, seqRNode second) {  
16         bool better = false;
17         
18         if (first.length > second.length) { 
19                 better = true;
20         }else if (first.length == second.length) {
21                 if (first.numIdentical > second.numIdentical) {
22                         better = true;
23                 }
24         }
25         
26         return better; 
27 }
28 //**********************************************************************************************************************
29 vector<string> ClusterFragmentsCommand::setParameters(){        
30         try {
31                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
32                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
33                 CommandParameter pdiffs("diffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(pdiffs);
34                 CommandParameter ppercent("percent", "Number", "", "0", "", "", "",false,false); parameters.push_back(ppercent);
35                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
36                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
37                 
38                 vector<string> myArray;
39                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
40                 return myArray;
41         }
42         catch(exception& e) {
43                 m->errorOut(e, "ClusterFragmentsCommand", "setParameters");
44                 exit(1);
45         }
46 }
47 //**********************************************************************************************************************
48 string ClusterFragmentsCommand::getHelpString(){        
49         try {
50                 string helpString = "";
51                 helpString += "The cluster.fragments command groups sequences that are part of a larger sequence.\n";
52                 helpString += "The cluster.fragments command outputs a new fasta and name file.\n";
53                 helpString += "The cluster.fragments command parameters are fasta, name, diffs and percent. The fasta parameter is required, unless you have a valid current file. \n";
54                 helpString += "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";
55                 helpString += "The diffs parameter allows you to set the number of differences allowed, default=0. \n";
56                 helpString += "The percent parameter allows you to set percentage of differences allowed, default=0. percent=2 means if the number of difference is less than or equal to two percent of the length of the fragment, then cluster.\n";
57                 helpString += "You may use diffs and percent at the same time to say something like: If the number or differences is greater than 1 or more than 2% of the fragment length, don't merge. \n";
58                 helpString += "The cluster.fragments command should be in the following format: \n";
59                 helpString += "cluster.fragments(fasta=yourFastaFile, names=yourNamesFile) \n";
60                 helpString += "Example cluster.fragments(fasta=amazon.fasta).\n";
61                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
62                 return helpString;
63         }
64         catch(exception& e) {
65                 m->errorOut(e, "ClusterFragmentsCommand", "getHelpString");
66                 exit(1);
67         }
68 }
69 //**********************************************************************************************************************
70 ClusterFragmentsCommand::ClusterFragmentsCommand(){     
71         try {
72                 abort = true; calledHelp = true; 
73                 setParameters();
74                 vector<string> tempOutNames;
75                 outputTypes["fasta"] = tempOutNames;
76                 outputTypes["name"] = tempOutNames;
77         }
78         catch(exception& e) {
79                 m->errorOut(e, "ClusterFragmentsCommand", "ClusterFragmentsCommand");
80                 exit(1);
81         }
82 }
83 //**********************************************************************************************************************
84 ClusterFragmentsCommand::ClusterFragmentsCommand(string option) {
85         try {
86                 abort = false; calledHelp = false;   
87                 
88                 //allow user to run help
89                 if(option == "help") { help(); abort = true; calledHelp = true; }
90                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
91                 
92                 else {
93                         vector<string> myArray = setParameters();
94                         
95                         OptionParser parser(option);
96                         map<string, string> parameters = parser.getParameters();
97                         
98                         ValidParameters validParameter;
99                         map<string, string>::iterator it;
100                 
101                         //check to make sure all parameters are valid for command
102                         for (map<string, string>::iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) { 
103                                 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) {  abort = true;  }
104                         }
105                         
106                         //initialize outputTypes
107                         vector<string> tempOutNames;
108                         outputTypes["fasta"] = tempOutNames;
109                         outputTypes["name"] = tempOutNames;
110                         
111                         //if the user changes the input directory command factory will send this info to us in the output parameter 
112                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
113                         if (inputDir == "not found"){   inputDir = "";          }
114                         else {
115                                 string path;
116                                 it = parameters.find("fasta");
117                                 //user has given a template file
118                                 if(it != parameters.end()){ 
119                                         path = m->hasPath(it->second);
120                                         //if the user has not given a path then, add inputdir. else leave path alone.
121                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
122                                 }
123                                 
124                                 it = parameters.find("name");
125                                 //user has given a template file
126                                 if(it != parameters.end()){ 
127                                         path = m->hasPath(it->second);
128                                         //if the user has not given a path then, add inputdir. else leave path alone.
129                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
130                                 }
131                         }
132
133                         //check for required parameters
134                         fastafile = validParameter.validFile(parameters, "fasta", true);
135                         if (fastafile == "not found") {                                 
136                                 fastafile = m->getFastaFile(); 
137                                 if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
138                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
139                         }
140                         else if (fastafile == "not open") { fastafile = ""; abort = true; }     
141                         else { m->setFastaFile(fastafile); }
142                         
143                         //if the user changes the output directory command factory will send this info to us in the output parameter 
144                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = m->hasPath(fastafile);      }
145
146                         //check for optional parameter and set defaults
147                         // ...at some point should added some additional type checking...
148                         namefile = validParameter.validFile(parameters, "name", true);
149                         if (namefile == "not found") { namefile =  "";  }
150                         else if (namefile == "not open") { namefile = ""; abort = true; }       
151                         else {  readNameFile(); m->setNameFile(namefile); }
152                         
153                         string temp;
154                         temp = validParameter.validFile(parameters, "diffs", false);            if (temp == "not found"){       temp = "0";                             }
155                         m->mothurConvert(temp, diffs); 
156                         
157                         temp = validParameter.validFile(parameters, "percent", false);          if (temp == "not found"){       temp = "0";                             }
158                         m->mothurConvert(temp, percent);
159                         
160                         if (namefile == "") {
161                                 vector<string> files; files.push_back(fastafile);
162                                 parser.getNameFile(files);
163                         }
164                         
165                 }
166                                 
167         }
168         catch(exception& e) {
169                 m->errorOut(e, "ClusterFragmentsCommand", "ClusterFragmentsCommand");
170                 exit(1);
171         }
172 }
173 //**********************************************************************************************************************
174 int ClusterFragmentsCommand::execute(){
175         try {
176                 
177                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
178                 
179                 int start = time(NULL);
180                 
181                 //reads fasta file and return number of seqs
182                 int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
183                 
184                 if (m->control_pressed) { return 0; }
185         
186                 if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0;  }
187                 
188                 //sort seqs by length of unaligned sequence
189                 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
190         
191                 int count = 0;
192
193                 //think about running through twice...
194                 for (int i = 0; i < numSeqs; i++) {
195                         
196                         if (alignSeqs[i].active) {  //this sequence has not been merged yet
197                                 
198                                 string iBases = alignSeqs[i].seq.getUnaligned();
199                                 
200                                 //try to merge it with all smaller seqs
201                                 for (int j = i+1; j < numSeqs; j++) {
202                                         
203                                         if (m->control_pressed) { return 0; }
204                                         
205                                         if (alignSeqs[j].active) {  //this sequence has not been merged yet
206                                                 
207                                                 string jBases = alignSeqs[j].seq.getUnaligned();
208                                                                                                         
209                                                 if (isFragment(iBases, jBases)) {
210                                                         //merge
211                                                         alignSeqs[i].names += ',' + alignSeqs[j].names;
212                                                         alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
213
214                                                         alignSeqs[j].active = 0;
215                                                         alignSeqs[j].numIdentical = 0;
216                                                         count++;
217                                                 }
218                                         }//end if j active
219                                 }//end if i != j
220                         
221                                 //remove from active list 
222                                 alignSeqs[i].active = 0;
223                                 
224                         }//end if active i
225                         if(i % 100 == 0)        { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
226                 }
227                 
228                 if(numSeqs % 100 != 0)  { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine();   }
229         
230                 
231                 string fileroot = outputDir + m->getRootName(m->getSimpleName(fastafile));
232                 
233                 string newFastaFile = fileroot + "fragclust.fasta";
234                 string newNamesFile = fileroot + "fragclust.names";
235                 
236                 if (m->control_pressed) { return 0; }
237                 
238                 m->mothurOutEndLine();
239                 m->mothurOut("Total number of sequences before cluster.fragments was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
240                 m->mothurOut("cluster.fragments removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
241                 
242                 printData(newFastaFile, newNamesFile);
243                 
244                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
245                 
246                 if (m->control_pressed) { m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
247                 
248                 m->mothurOutEndLine();
249                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
250                 m->mothurOut(newFastaFile); m->mothurOutEndLine();      
251                 m->mothurOut(newNamesFile); m->mothurOutEndLine();      
252                 outputNames.push_back(newFastaFile);  outputNames.push_back(newNamesFile); outputTypes["fasta"].push_back(newFastaFile); outputTypes["name"].push_back(newNamesFile);
253                 m->mothurOutEndLine();
254                 
255                 //set fasta file as new current fastafile
256                 string current = "";
257                 itTypes = outputTypes.find("fasta");
258                 if (itTypes != outputTypes.end()) {
259                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
260                 }
261                 
262                 itTypes = outputTypes.find("name");
263                 if (itTypes != outputTypes.end()) {
264                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
265                 }
266
267                 return 0;
268                 
269         }
270         catch(exception& e) {
271                 m->errorOut(e, "ClusterFragmentsCommand", "execute");
272                 exit(1);
273         }
274 }
275 //***************************************************************************************************************
276 bool ClusterFragmentsCommand::isFragment(string seq1, string seq2){
277         try {
278                 bool fragment = false;
279                 
280                 //exact match
281                 int pos = seq1.find(seq2);
282                 if (pos != string::npos) { return true; }
283                 //no match, no diffs wanted
284                 else if ((diffs == 0) && (percent == 0)) { return false; }
285                 else { //try aligning and see if you can find it
286                         
287                         //find number of acceptable differences for this sequence fragment
288                         int totalDiffs;
289                         if (diffs == 0) { //you didnt set diffs you want a percentage
290                                 totalDiffs = floor((seq2.length() * (percent / 100.0)));
291                         }else if (percent == 0) { //you didn't set percent you want diffs
292                                 totalDiffs = diffs;
293                         }else if ((percent != 0) && (diffs != 0)) { //you want both, set total diffs to smaller of 2
294                                 totalDiffs = diffs;
295                                 int percentDiff = floor((seq2.length() * (percent / 100.0)));
296                                 if (percentDiff < totalDiffs) { totalDiffs = percentDiff; }
297                         }
298                         
299                         Alignment* alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (seq1.length()+totalDiffs+1));
300                                                         
301                         //use needleman to align 
302                         alignment->align(seq2, seq1);
303                         string tempSeq2 = alignment->getSeqAAln();
304                         string temp = alignment->getSeqBAln();
305                         
306                         delete alignment;
307                         
308                         //chop gap ends
309                         int startPos = 0;
310                         int endPos = tempSeq2.length()-1;
311                         for (int i = 0; i < tempSeq2.length(); i++) {  if (isalpha(tempSeq2[i])) { startPos = i; break; } }
312                         for (int i = tempSeq2.length()-1; i >= 0; i--) {  if (isalpha(tempSeq2[i])) { endPos = i; break; } }
313                         
314                         //count number of diffs
315                         int numDiffs = 0;
316                         for (int i = startPos; i <= endPos; i++) {
317                                 if (tempSeq2[i] != temp[i]) { numDiffs++; }
318                         }
319                         
320                         if (numDiffs <= totalDiffs) { fragment = true; }
321                         
322                 }
323                 
324                 return fragment;
325                 
326         }
327         catch(exception& e) {
328                 m->errorOut(e, "ClusterFragmentsCommand", "isFragment");
329                 exit(1);
330         }
331 }
332 /**************************************************************************************************/
333 int ClusterFragmentsCommand::readFASTA(){
334         try {
335         
336                 ifstream inFasta;
337                 m->openInputFile(fastafile, inFasta);
338                 
339                 while (!inFasta.eof()) {
340                         
341                         if (m->control_pressed) { inFasta.close(); return 0; }
342                         
343                         Sequence seq(inFasta);  m->gobble(inFasta);
344                         
345                         if (seq.getName() != "") {  //can get "" if commented line is at end of fasta file
346                                 if (namefile != "") {
347                                         itSize = sizes.find(seq.getName());
348                                         
349                                         if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
350                                         else{
351                                                 seqRNode tempNode(itSize->second, seq, names[seq.getName()], seq.getUnaligned().length());
352                                                 alignSeqs.push_back(tempNode);
353                                         }       
354                                 }else { //no names file, you are identical to yourself 
355                                         seqRNode tempNode(1, seq, seq.getName(), seq.getUnaligned().length());
356                                         alignSeqs.push_back(tempNode);
357                                 }
358                         }
359                 }
360                 
361                 inFasta.close();
362                 return alignSeqs.size();
363         }
364         
365         catch(exception& e) {
366                 m->errorOut(e, "ClusterFragmentsCommand", "readFASTA");
367                 exit(1);
368         }
369 }
370 /**************************************************************************************************/
371 void ClusterFragmentsCommand::printData(string newfasta, string newname){
372         try {
373                 ofstream outFasta;
374                 ofstream outNames;
375                 
376                 m->openOutputFile(newfasta, outFasta);
377                 m->openOutputFile(newname, outNames);
378                 
379                 for (int i = 0; i < alignSeqs.size(); i++) {
380                         if (alignSeqs[i].numIdentical != 0) {
381                                 alignSeqs[i].seq.printSequence(outFasta); 
382                                 outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;
383                         }
384                 }
385                 
386                 outFasta.close();
387                 outNames.close();
388         }
389         catch(exception& e) {
390                 m->errorOut(e, "ClusterFragmentsCommand", "printData");
391                 exit(1);
392         }
393 }
394 /**************************************************************************************************/
395
396 void ClusterFragmentsCommand::readNameFile(){
397         try {
398                 ifstream in;
399                 m->openInputFile(namefile, in);
400                 string firstCol, secondCol;
401                                 
402                 while (!in.eof()) {
403                         in >> firstCol >> secondCol; m->gobble(in);
404                         names[firstCol] = secondCol;
405                         int size = 1;
406
407                         for(int i=0;i<secondCol.size();i++){
408                                 if(secondCol[i] == ','){        size++; }
409                         }
410                         sizes[firstCol] = size;
411                 }
412                 in.close();
413         }
414         catch(exception& e) {
415                 m->errorOut(e, "ClusterFragmentsCommand", "readNameFile");
416                 exit(1);
417         }
418 }
419
420 /**************************************************************************************************/
421