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