]> git.donarmstrong.com Git - mothur.git/blob - clusterfragmentscommand.cpp
Merge remote-tracking branch 'mothur/master'
[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 string ClusterFragmentsCommand::getOutputFileNameTag(string type, string inputName=""){ 
71         try {
72         string outputFileName = "";
73                 map<string, vector<string> >::iterator it;
74         
75         //is this a type this command creates
76         it = outputTypes.find(type);
77         if (it == outputTypes.end()) {  m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
78         else {
79             if (type == "fasta") {  outputFileName =  "fragclust.fasta"; }
80             else if (type == "name") {  outputFileName =  "fragclust.names"; }
81             else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true;  }
82         }
83         return outputFileName;
84         }
85         catch(exception& e) {
86                 m->errorOut(e, "ClusterFragmentsCommand", "getOutputFileNameTag");
87                 exit(1);
88         }
89 }
90
91 //**********************************************************************************************************************
92 ClusterFragmentsCommand::ClusterFragmentsCommand(){     
93         try {
94                 abort = true; calledHelp = true; 
95                 setParameters();
96                 vector<string> tempOutNames;
97                 outputTypes["fasta"] = tempOutNames;
98                 outputTypes["name"] = tempOutNames;
99         }
100         catch(exception& e) {
101                 m->errorOut(e, "ClusterFragmentsCommand", "ClusterFragmentsCommand");
102                 exit(1);
103         }
104 }
105 //**********************************************************************************************************************
106 ClusterFragmentsCommand::ClusterFragmentsCommand(string option) {
107         try {
108                 abort = false; calledHelp = false;   
109                 
110                 //allow user to run help
111                 if(option == "help") { help(); abort = true; calledHelp = true; }
112                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
113                 
114                 else {
115                         vector<string> myArray = setParameters();
116                         
117                         OptionParser parser(option);
118                         map<string, string> parameters = parser.getParameters();
119                         
120                         ValidParameters validParameter;
121                         map<string, string>::iterator it;
122                 
123                         //check to make sure all parameters are valid for command
124                         for (map<string, string>::iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) { 
125                                 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) {  abort = true;  }
126                         }
127                         
128                         //initialize outputTypes
129                         vector<string> tempOutNames;
130                         outputTypes["fasta"] = tempOutNames;
131                         outputTypes["name"] = tempOutNames;
132                         
133                         //if the user changes the input directory command factory will send this info to us in the output parameter 
134                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
135                         if (inputDir == "not found"){   inputDir = "";          }
136                         else {
137                                 string path;
138                                 it = parameters.find("fasta");
139                                 //user has given a template file
140                                 if(it != parameters.end()){ 
141                                         path = m->hasPath(it->second);
142                                         //if the user has not given a path then, add inputdir. else leave path alone.
143                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
144                                 }
145                                 
146                                 it = parameters.find("name");
147                                 //user has given a template file
148                                 if(it != parameters.end()){ 
149                                         path = m->hasPath(it->second);
150                                         //if the user has not given a path then, add inputdir. else leave path alone.
151                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
152                                 }
153                         }
154
155                         //check for required parameters
156                         fastafile = validParameter.validFile(parameters, "fasta", true);
157                         if (fastafile == "not found") {                                 
158                                 fastafile = m->getFastaFile(); 
159                                 if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
160                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
161                         }
162                         else if (fastafile == "not open") { fastafile = ""; abort = true; }     
163                         else { m->setFastaFile(fastafile); }
164                         
165                         //if the user changes the output directory command factory will send this info to us in the output parameter 
166                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = m->hasPath(fastafile);      }
167
168                         //check for optional parameter and set defaults
169                         // ...at some point should added some additional type checking...
170                         namefile = validParameter.validFile(parameters, "name", true);
171                         if (namefile == "not found") { namefile =  "";  }
172                         else if (namefile == "not open") { namefile = ""; abort = true; }       
173                         else {  readNameFile(); m->setNameFile(namefile); }
174                         
175                         string temp;
176                         temp = validParameter.validFile(parameters, "diffs", false);            if (temp == "not found"){       temp = "0";                             }
177                         m->mothurConvert(temp, diffs); 
178                         
179                         temp = validParameter.validFile(parameters, "percent", false);          if (temp == "not found"){       temp = "0";                             }
180                         m->mothurConvert(temp, percent);
181                         
182                         if (namefile == "") {
183                                 vector<string> files; files.push_back(fastafile);
184                                 parser.getNameFile(files);
185                         }
186                         
187                 }
188                                 
189         }
190         catch(exception& e) {
191                 m->errorOut(e, "ClusterFragmentsCommand", "ClusterFragmentsCommand");
192                 exit(1);
193         }
194 }
195 //**********************************************************************************************************************
196 int ClusterFragmentsCommand::execute(){
197         try {
198                 
199                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
200                 
201                 int start = time(NULL);
202                 
203                 //reads fasta file and return number of seqs
204                 int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
205                 
206                 if (m->control_pressed) { return 0; }
207         
208                 if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0;  }
209                 
210                 //sort seqs by length of unaligned sequence
211                 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
212         
213                 int count = 0;
214
215                 //think about running through twice...
216                 for (int i = 0; i < numSeqs; i++) {
217                         
218                         if (alignSeqs[i].active) {  //this sequence has not been merged yet
219                                 
220                                 string iBases = alignSeqs[i].seq.getUnaligned();
221                                 
222                                 //try to merge it with all smaller seqs
223                                 for (int j = i+1; j < numSeqs; j++) {
224                                         
225                                         if (m->control_pressed) { return 0; }
226                                         
227                                         if (alignSeqs[j].active) {  //this sequence has not been merged yet
228                                                 
229                                                 string jBases = alignSeqs[j].seq.getUnaligned();
230                                                                                                         
231                                                 if (isFragment(iBases, jBases)) {
232                                                         //merge
233                                                         alignSeqs[i].names += ',' + alignSeqs[j].names;
234                                                         alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
235
236                                                         alignSeqs[j].active = 0;
237                                                         alignSeqs[j].numIdentical = 0;
238                                                         count++;
239                                                 }
240                                         }//end if j active
241                                 }//end if i != j
242                         
243                                 //remove from active list 
244                                 alignSeqs[i].active = 0;
245                                 
246                         }//end if active i
247                         if(i % 100 == 0)        { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
248                 }
249                 
250                 if(numSeqs % 100 != 0)  { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine();   }
251         
252                 
253                 string fileroot = outputDir + m->getRootName(m->getSimpleName(fastafile));
254                 
255                 string newFastaFile = fileroot + getOutputFileNameTag("fasta");
256                 string newNamesFile = fileroot + getOutputFileNameTag("name");
257                 
258                 if (m->control_pressed) { return 0; }
259                 
260                 m->mothurOutEndLine();
261                 m->mothurOut("Total number of sequences before cluster.fragments was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
262                 m->mothurOut("cluster.fragments removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
263                 
264                 printData(newFastaFile, newNamesFile);
265                 
266                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
267                 
268                 if (m->control_pressed) { m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
269                 
270                 m->mothurOutEndLine();
271                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
272                 m->mothurOut(newFastaFile); m->mothurOutEndLine();      
273                 m->mothurOut(newNamesFile); m->mothurOutEndLine();      
274                 outputNames.push_back(newFastaFile);  outputNames.push_back(newNamesFile); outputTypes["fasta"].push_back(newFastaFile); outputTypes["name"].push_back(newNamesFile);
275                 m->mothurOutEndLine();
276                 
277                 //set fasta file as new current fastafile
278                 string current = "";
279                 itTypes = outputTypes.find("fasta");
280                 if (itTypes != outputTypes.end()) {
281                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
282                 }
283                 
284                 itTypes = outputTypes.find("name");
285                 if (itTypes != outputTypes.end()) {
286                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
287                 }
288
289                 return 0;
290                 
291         }
292         catch(exception& e) {
293                 m->errorOut(e, "ClusterFragmentsCommand", "execute");
294                 exit(1);
295         }
296 }
297 //***************************************************************************************************************
298 bool ClusterFragmentsCommand::isFragment(string seq1, string seq2){
299         try {
300                 bool fragment = false;
301                 
302                 //exact match
303                 int pos = seq1.find(seq2);
304                 if (pos != string::npos) { return true; }
305                 //no match, no diffs wanted
306                 else if ((diffs == 0) && (percent == 0)) { return false; }
307                 else { //try aligning and see if you can find it
308                         
309                         //find number of acceptable differences for this sequence fragment
310                         int totalDiffs;
311                         if (diffs == 0) { //you didnt set diffs you want a percentage
312                                 totalDiffs = floor((seq2.length() * (percent / 100.0)));
313                         }else if (percent == 0) { //you didn't set percent you want diffs
314                                 totalDiffs = diffs;
315                         }else if ((percent != 0) && (diffs != 0)) { //you want both, set total diffs to smaller of 2
316                                 totalDiffs = diffs;
317                                 int percentDiff = floor((seq2.length() * (percent / 100.0)));
318                                 if (percentDiff < totalDiffs) { totalDiffs = percentDiff; }
319                         }
320                         
321                         Alignment* alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (seq1.length()+totalDiffs+1));
322                                                         
323                         //use needleman to align 
324                         alignment->align(seq2, seq1);
325                         string tempSeq2 = alignment->getSeqAAln();
326                         string temp = alignment->getSeqBAln();
327                         
328                         delete alignment;
329                         
330                         //chop gap ends
331                         int startPos = 0;
332                         int endPos = tempSeq2.length()-1;
333                         for (int i = 0; i < tempSeq2.length(); i++) {  if (isalpha(tempSeq2[i])) { startPos = i; break; } }
334                         for (int i = tempSeq2.length()-1; i >= 0; i--) {  if (isalpha(tempSeq2[i])) { endPos = i; break; } }
335                         
336                         //count number of diffs
337                         int numDiffs = 0;
338                         for (int i = startPos; i <= endPos; i++) {
339                                 if (tempSeq2[i] != temp[i]) { numDiffs++; }
340                         }
341                         
342                         if (numDiffs <= totalDiffs) { fragment = true; }
343                         
344                 }
345                 
346                 return fragment;
347                 
348         }
349         catch(exception& e) {
350                 m->errorOut(e, "ClusterFragmentsCommand", "isFragment");
351                 exit(1);
352         }
353 }
354 /**************************************************************************************************/
355 int ClusterFragmentsCommand::readFASTA(){
356         try {
357         
358                 ifstream inFasta;
359                 m->openInputFile(fastafile, inFasta);
360                 
361                 while (!inFasta.eof()) {
362                         
363                         if (m->control_pressed) { inFasta.close(); return 0; }
364                         
365                         Sequence seq(inFasta);  m->gobble(inFasta);
366                         
367                         if (seq.getName() != "") {  //can get "" if commented line is at end of fasta file
368                                 if (namefile != "") {
369                                         itSize = sizes.find(seq.getName());
370                                         
371                                         if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
372                                         else{
373                                                 seqRNode tempNode(itSize->second, seq, names[seq.getName()], seq.getUnaligned().length());
374                                                 alignSeqs.push_back(tempNode);
375                                         }       
376                                 }else { //no names file, you are identical to yourself 
377                                         seqRNode tempNode(1, seq, seq.getName(), seq.getUnaligned().length());
378                                         alignSeqs.push_back(tempNode);
379                                 }
380                         }
381                 }
382                 
383                 inFasta.close();
384                 return alignSeqs.size();
385         }
386         
387         catch(exception& e) {
388                 m->errorOut(e, "ClusterFragmentsCommand", "readFASTA");
389                 exit(1);
390         }
391 }
392 /**************************************************************************************************/
393 void ClusterFragmentsCommand::printData(string newfasta, string newname){
394         try {
395                 ofstream outFasta;
396                 ofstream outNames;
397                 
398                 m->openOutputFile(newfasta, outFasta);
399                 m->openOutputFile(newname, outNames);
400                 
401                 for (int i = 0; i < alignSeqs.size(); i++) {
402                         if (alignSeqs[i].numIdentical != 0) {
403                                 alignSeqs[i].seq.printSequence(outFasta); 
404                                 outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;
405                         }
406                 }
407                 
408                 outFasta.close();
409                 outNames.close();
410         }
411         catch(exception& e) {
412                 m->errorOut(e, "ClusterFragmentsCommand", "printData");
413                 exit(1);
414         }
415 }
416 /**************************************************************************************************/
417
418 void ClusterFragmentsCommand::readNameFile(){
419         try {
420                 ifstream in;
421                 m->openInputFile(namefile, in);
422                 string firstCol, secondCol;
423                                 
424                 while (!in.eof()) {
425                         in >> firstCol >> secondCol; m->gobble(in);
426                         names[firstCol] = secondCol;
427                         int size = 1;
428
429                         for(int i=0;i<secondCol.size();i++){
430                                 if(secondCol[i] == ','){        size++; }
431                         }
432                         sizes[firstCol] = size;
433                 }
434                 in.close();
435         }
436         catch(exception& e) {
437                 m->errorOut(e, "ClusterFragmentsCommand", "readNameFile");
438                 exit(1);
439         }
440 }
441
442 /**************************************************************************************************/
443