]> git.donarmstrong.com Git - mothur.git/blob - clusterfragmentscommand.cpp
fixes while testing
[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
12 //**********************************************************************************************************************
13 //sort by unaligned
14 inline bool comparePriority(seqRNode first, seqRNode second) {  
15         bool better = false;
16         
17         if (first.length > second.length) { 
18                 better = true;
19         }else if (first.length == second.length) {
20                 if (first.numIdentical > second.numIdentical) {
21                         better = true;
22                 }
23         }
24         
25         return better; 
26 }
27 //**********************************************************************************************************************
28 vector<string> ClusterFragmentsCommand::getValidParameters(){   
29         try {
30                 string AlignArray[] =  {"fasta","name","outputdir","inputdir"};
31                 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
32                 return myArray;
33         }
34         catch(exception& e) {
35                 m->errorOut(e, "ClusterFragmentsCommand", "getValidParameters");
36                 exit(1);
37         }
38 }
39 //**********************************************************************************************************************
40 ClusterFragmentsCommand::ClusterFragmentsCommand(){     
41         try {
42                 abort = true;
43                 //initialize outputTypes
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;
80                 
81                 //allow user to run help
82                 if(option == "help") { help(); abort = true; }
83                 
84                 else {
85                         //valid paramters for this command
86                         string Array[] =  {"fasta","name","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                                 
143         }
144         catch(exception& e) {
145                 m->errorOut(e, "ClusterFragmentsCommand", "ClusterFragmentsCommand");
146                 exit(1);
147         }
148 }
149
150 //**********************************************************************************************************************
151 ClusterFragmentsCommand::~ClusterFragmentsCommand(){}   
152 //**********************************************************************************************************************
153 void ClusterFragmentsCommand::help(){
154         try {
155                 m->mothurOut("The cluster.fragments command groups sequences that are part of a larger sequence.\n");
156                 m->mothurOut("The cluster.fragments command outputs a new fasta and name file.\n");
157                 m->mothurOut("The cluster.fragments command parameters are fasta and name. The fasta parameter is required. \n");
158                 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");
159                 m->mothurOut("The cluster.fragments command should be in the following format: \n");
160                 m->mothurOut("cluster.fragments(fasta=yourFastaFile, names=yourNamesFile) \n");
161                 m->mothurOut("Example cluster.fragments(fasta=amazon.fasta).\n");
162                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n\n");
163         }
164         catch(exception& e) {
165                 m->errorOut(e, "ClusterFragmentsCommand", "help");
166                 exit(1);
167         }
168 }
169 //**********************************************************************************************************************
170 int ClusterFragmentsCommand::execute(){
171         try {
172                 
173                 if (abort == true) { return 0; }
174                 
175                 int start = time(NULL);
176                 
177                 //reads fasta file and return number of seqs
178                 int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
179                 
180                 if (m->control_pressed) { return 0; }
181         
182                 if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0;  }
183                 
184                 //sort seqs by length of unaligned sequence
185                 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
186         
187                 int count = 0;
188
189                 //think about running through twice...
190                 for (int i = 0; i < numSeqs; i++) {
191                         
192                         if (alignSeqs[i].active) {  //this sequence has not been merged yet
193                                 
194                                 string iBases = alignSeqs[i].seq.getUnaligned();
195                                 
196                                 //try to merge it with all smaller seqs
197                                 for (int j = i+1; j < numSeqs; j++) {
198                                         
199                                         if (m->control_pressed) { return 0; }
200                                         
201                                         if (alignSeqs[j].active) {  //this sequence has not been merged yet
202                                                 
203                                                 string jBases = alignSeqs[j].seq.getUnaligned();
204                                                 
205                                                 int pos = iBases.find(jBases);
206                                                                                                 
207                                                 if (pos != string::npos) {
208                                                         //merge
209                                                         alignSeqs[i].names += ',' + alignSeqs[j].names;
210                                                         alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
211
212                                                         alignSeqs[j].active = 0;
213                                                         alignSeqs[j].numIdentical = 0;
214                                                         count++;
215                                                 }
216                                         }//end if j active
217                                 }//end if i != j
218                         
219                                 //remove from active list 
220                                 alignSeqs[i].active = 0;
221                                 
222                         }//end if active i
223                         if(i % 100 == 0)        { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
224                 }
225                 
226                 if(numSeqs % 100 != 0)  { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine();   }
227         
228                 
229                 string fileroot = outputDir + m->getRootName(m->getSimpleName(fastafile));
230                 
231                 string newFastaFile = fileroot + "fragclust.fasta";
232                 string newNamesFile = fileroot + "names";
233                 
234                 if (m->control_pressed) { return 0; }
235                 
236                 m->mothurOutEndLine();
237                 m->mothurOut("Total number of sequences before cluster.fragments was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
238                 m->mothurOut("cluster.fragments removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
239                 
240                 printData(newFastaFile, newNamesFile);
241                 
242                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
243                 
244                 if (m->control_pressed) { remove(newFastaFile.c_str()); remove(newNamesFile.c_str()); return 0; }
245                 
246                 m->mothurOutEndLine();
247                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
248                 m->mothurOut(newFastaFile); m->mothurOutEndLine();      
249                 m->mothurOut(newNamesFile); m->mothurOutEndLine();      
250                 outputNames.push_back(newFastaFile);  outputNames.push_back(newNamesFile); outputTypes["fasta"].push_back(newFastaFile); outputTypes["name"].push_back(newNamesFile);
251                 m->mothurOutEndLine();
252
253                 return 0;
254                 
255         }
256         catch(exception& e) {
257                 m->errorOut(e, "ClusterFragmentsCommand", "execute");
258                 exit(1);
259         }
260 }
261
262 /**************************************************************************************************/
263 int ClusterFragmentsCommand::readFASTA(){
264         try {
265         
266                 ifstream inFasta;
267                 m->openInputFile(fastafile, inFasta);
268                 
269                 while (!inFasta.eof()) {
270                         
271                         if (m->control_pressed) { inFasta.close(); return 0; }
272                         
273                         Sequence seq(inFasta);  m->gobble(inFasta);
274                         
275                         if (seq.getName() != "") {  //can get "" if commented line is at end of fasta file
276                                 if (namefile != "") {
277                                         itSize = sizes.find(seq.getName());
278                                         
279                                         if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
280                                         else{
281                                                 seqRNode tempNode(itSize->second, seq, names[seq.getName()], seq.getUnaligned().length());
282                                                 alignSeqs.push_back(tempNode);
283                                         }       
284                                 }else { //no names file, you are identical to yourself 
285                                         seqRNode tempNode(1, seq, seq.getName(), seq.getUnaligned().length());
286                                         alignSeqs.push_back(tempNode);
287                                 }
288                         }
289                 }
290                 
291                 inFasta.close();
292                 return alignSeqs.size();
293         }
294         
295         catch(exception& e) {
296                 m->errorOut(e, "ClusterFragmentsCommand", "readFASTA");
297                 exit(1);
298         }
299 }
300 /**************************************************************************************************/
301 void ClusterFragmentsCommand::printData(string newfasta, string newname){
302         try {
303                 ofstream outFasta;
304                 ofstream outNames;
305                 
306                 m->openOutputFile(newfasta, outFasta);
307                 m->openOutputFile(newname, outNames);
308                 
309                 for (int i = 0; i < alignSeqs.size(); i++) {
310                         if (alignSeqs[i].numIdentical != 0) {
311                                 alignSeqs[i].seq.printSequence(outFasta); 
312                                 outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;
313                         }
314                 }
315                 
316                 outFasta.close();
317                 outNames.close();
318         }
319         catch(exception& e) {
320                 m->errorOut(e, "ClusterFragmentsCommand", "printData");
321                 exit(1);
322         }
323 }
324 /**************************************************************************************************/
325
326 void ClusterFragmentsCommand::readNameFile(){
327         try {
328                 ifstream in;
329                 m->openInputFile(namefile, in);
330                 string firstCol, secondCol;
331                                 
332                 while (!in.eof()) {
333                         in >> firstCol >> secondCol; m->gobble(in);
334                         names[firstCol] = secondCol;
335                         int size = 1;
336
337                         for(int i=0;i<secondCol.size();i++){
338                                 if(secondCol[i] == ','){        size++; }
339                         }
340                         sizes[firstCol] = size;
341                 }
342                 in.close();
343         }
344         catch(exception& e) {
345                 m->errorOut(e, "ClusterFragmentsCommand", "readNameFile");
346                 exit(1);
347         }
348 }
349
350 /**************************************************************************************************/
351