5 * Created by westcott on 9/23/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "clusterfragmentscommand.h"
11 #include "needlemanoverlap.hpp"
13 //**********************************************************************************************************************
15 inline bool comparePriority(seqRNode first, seqRNode second) {
18 if (first.length > second.length) {
20 }else if (first.length == second.length) {
21 if (first.numIdentical > second.numIdentical) {
28 //**********************************************************************************************************************
29 vector<string> ClusterFragmentsCommand::setParameters(){
31 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none","fasta-name",false,true,true); parameters.push_back(pfasta);
32 CommandParameter pname("name", "InputTypes", "", "", "namecount", "none", "none","name",false,false,true); parameters.push_back(pname);
33 CommandParameter pcount("count", "InputTypes", "", "", "namecount", "none", "none","count",false,false,true); parameters.push_back(pcount);
34 CommandParameter pdiffs("diffs", "Number", "", "0", "", "", "","",false,false); parameters.push_back(pdiffs);
35 CommandParameter ppercent("percent", "Number", "", "0", "", "", "","",false,false); parameters.push_back(ppercent);
36 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
37 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
39 vector<string> myArray;
40 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
44 m->errorOut(e, "ClusterFragmentsCommand", "setParameters");
48 //**********************************************************************************************************************
49 string ClusterFragmentsCommand::getHelpString(){
51 string helpString = "";
52 helpString += "The cluster.fragments command groups sequences that are part of a larger sequence.\n";
53 helpString += "The cluster.fragments command outputs a new fasta and name or count file.\n";
54 helpString += "The cluster.fragments command parameters are fasta, name, count, diffs and percent. The fasta parameter is required, unless you have a valid current file. \n";
55 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";
56 helpString += "The diffs parameter allows you to set the number of differences allowed, default=0. \n";
57 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";
58 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";
59 helpString += "The cluster.fragments command should be in the following format: \n";
60 helpString += "cluster.fragments(fasta=yourFastaFile, names=yourNamesFile) \n";
61 helpString += "Example cluster.fragments(fasta=amazon.fasta).\n";
62 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
66 m->errorOut(e, "ClusterFragmentsCommand", "getHelpString");
70 //**********************************************************************************************************************
71 string ClusterFragmentsCommand::getOutputPattern(string type) {
75 if (type == "fasta") { pattern = "[filename],fragclust.fasta"; }
76 else if (type == "name") { pattern = "[filename],fragclust.names"; }
77 else if (type == "count") { pattern = "[filename],fragclust.count_table"; }
78 else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true; }
83 m->errorOut(e, "ClusterFragmentsCommand", "getOutputPattern");
87 //**********************************************************************************************************************
88 ClusterFragmentsCommand::ClusterFragmentsCommand(){
90 abort = true; calledHelp = true;
92 vector<string> tempOutNames;
93 outputTypes["fasta"] = tempOutNames;
94 outputTypes["name"] = tempOutNames;
95 outputTypes["count"] = tempOutNames;
98 m->errorOut(e, "ClusterFragmentsCommand", "ClusterFragmentsCommand");
102 //**********************************************************************************************************************
103 ClusterFragmentsCommand::ClusterFragmentsCommand(string option) {
105 abort = false; calledHelp = false;
107 //allow user to run help
108 if(option == "help") { help(); abort = true; calledHelp = true; }
109 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
112 vector<string> myArray = setParameters();
114 OptionParser parser(option);
115 map<string, string> parameters = parser.getParameters();
117 ValidParameters validParameter;
118 map<string, string>::iterator it;
120 //check to make sure all parameters are valid for command
121 for (map<string, string>::iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) {
122 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) { abort = true; }
125 //initialize outputTypes
126 vector<string> tempOutNames;
127 outputTypes["fasta"] = tempOutNames;
128 outputTypes["name"] = tempOutNames;
129 outputTypes["count"] = tempOutNames;
131 //if the user changes the input directory command factory will send this info to us in the output parameter
132 string inputDir = validParameter.validFile(parameters, "inputdir", false);
133 if (inputDir == "not found"){ inputDir = ""; }
136 it = parameters.find("fasta");
137 //user has given a template file
138 if(it != parameters.end()){
139 path = m->hasPath(it->second);
140 //if the user has not given a path then, add inputdir. else leave path alone.
141 if (path == "") { parameters["fasta"] = inputDir + it->second; }
144 it = parameters.find("name");
145 //user has given a template file
146 if(it != parameters.end()){
147 path = m->hasPath(it->second);
148 //if the user has not given a path then, add inputdir. else leave path alone.
149 if (path == "") { parameters["name"] = inputDir + it->second; }
152 it = parameters.find("count");
153 //user has given a template file
154 if(it != parameters.end()){
155 path = m->hasPath(it->second);
156 //if the user has not given a path then, add inputdir. else leave path alone.
157 if (path == "") { parameters["count"] = inputDir + it->second; }
161 //check for required parameters
162 fastafile = validParameter.validFile(parameters, "fasta", true);
163 if (fastafile == "not found") {
164 fastafile = m->getFastaFile();
165 if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
166 else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
168 else if (fastafile == "not open") { fastafile = ""; abort = true; }
169 else { m->setFastaFile(fastafile); }
171 //if the user changes the output directory command factory will send this info to us in the output parameter
172 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = m->hasPath(fastafile); }
174 //check for optional parameter and set defaults
175 // ...at some point should added some additional type checking...
176 namefile = validParameter.validFile(parameters, "name", true);
177 if (namefile == "not found") { namefile = ""; }
178 else if (namefile == "not open") { namefile = ""; abort = true; }
179 else { readNameFile(); m->setNameFile(namefile); }
181 countfile = validParameter.validFile(parameters, "count", true);
182 if (countfile == "not open") { abort = true; countfile = ""; }
183 else if (countfile == "not found") { countfile = ""; }
184 else { ct.readTable(countfile, true, false); m->setCountTableFile(countfile); }
186 if ((countfile != "") && (namefile != "")) { m->mothurOut("When executing a cluster.fragments command you must enter ONLY ONE of the following: count or name."); m->mothurOutEndLine(); abort = true; }
189 temp = validParameter.validFile(parameters, "diffs", false); if (temp == "not found"){ temp = "0"; }
190 m->mothurConvert(temp, diffs);
192 temp = validParameter.validFile(parameters, "percent", false); if (temp == "not found"){ temp = "0"; }
193 m->mothurConvert(temp, percent);
195 if (countfile == "") {
196 if (namefile == "") {
197 vector<string> files; files.push_back(fastafile);
198 parser.getNameFile(files);
205 catch(exception& e) {
206 m->errorOut(e, "ClusterFragmentsCommand", "ClusterFragmentsCommand");
210 //**********************************************************************************************************************
211 int ClusterFragmentsCommand::execute(){
214 if (abort == true) { if (calledHelp) { return 0; } return 2; }
216 int start = time(NULL);
218 //reads fasta file and return number of seqs
219 int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
221 if (m->control_pressed) { return 0; }
223 if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0; }
225 //sort seqs by length of unaligned sequence
226 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
230 //think about running through twice...
231 for (int i = 0; i < numSeqs; i++) {
233 if (alignSeqs[i].active) { //this sequence has not been merged yet
235 string iBases = alignSeqs[i].seq.getUnaligned();
237 //try to merge it with all smaller seqs
238 for (int j = i+1; j < numSeqs; j++) {
240 if (m->control_pressed) { return 0; }
242 if (alignSeqs[j].active) { //this sequence has not been merged yet
244 string jBases = alignSeqs[j].seq.getUnaligned();
246 if (isFragment(iBases, jBases)) {
247 if (countfile != "") {
248 ct.mergeCounts(alignSeqs[i].names, alignSeqs[j].names);
251 alignSeqs[i].names += ',' + alignSeqs[j].names;
252 alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
254 alignSeqs[j].active = 0;
255 alignSeqs[j].numIdentical = 0;
261 //remove from active list
262 alignSeqs[i].active = 0;
265 if(i % 100 == 0) { m->mothurOutJustToScreen(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)+"\n"); }
268 if(numSeqs % 100 != 0) { m->mothurOutJustToScreen(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)+"\n"); }
271 string fileroot = outputDir + m->getRootName(m->getSimpleName(fastafile));
272 map<string, string> variables;
273 variables["[filename]"] = fileroot;
274 string newFastaFile = getOutputFileName("fasta", variables);
275 string newNamesFile = getOutputFileName("name", variables);
276 if (countfile != "") { newNamesFile = getOutputFileName("count", variables); }
278 if (m->control_pressed) { return 0; }
280 m->mothurOutEndLine();
281 m->mothurOut("Total number of sequences before cluster.fragments was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
282 m->mothurOut("cluster.fragments removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
284 printData(newFastaFile, newNamesFile);
286 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
288 if (m->control_pressed) { m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
290 m->mothurOutEndLine();
291 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
292 m->mothurOut(newFastaFile); m->mothurOutEndLine();
293 m->mothurOut(newNamesFile); m->mothurOutEndLine();
294 outputNames.push_back(newFastaFile); outputNames.push_back(newNamesFile); outputTypes["fasta"].push_back(newFastaFile); outputTypes["name"].push_back(newNamesFile);
295 m->mothurOutEndLine();
297 //set fasta file as new current fastafile
299 itTypes = outputTypes.find("fasta");
300 if (itTypes != outputTypes.end()) {
301 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
304 itTypes = outputTypes.find("name");
305 if (itTypes != outputTypes.end()) {
306 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
309 itTypes = outputTypes.find("count");
310 if (itTypes != outputTypes.end()) {
311 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setCountTableFile(current); }
317 catch(exception& e) {
318 m->errorOut(e, "ClusterFragmentsCommand", "execute");
322 //***************************************************************************************************************
323 bool ClusterFragmentsCommand::isFragment(string seq1, string seq2){
325 bool fragment = false;
328 int pos = seq1.find(seq2);
329 if (pos != string::npos) { return true; }
330 //no match, no diffs wanted
331 else if ((diffs == 0) && (percent == 0)) { return false; }
332 else { //try aligning and see if you can find it
334 //find number of acceptable differences for this sequence fragment
336 if (diffs == 0) { //you didnt set diffs you want a percentage
337 totalDiffs = floor((seq2.length() * (percent / 100.0)));
338 }else if (percent == 0) { //you didn't set percent you want diffs
340 }else if ((percent != 0) && (diffs != 0)) { //you want both, set total diffs to smaller of 2
342 int percentDiff = floor((seq2.length() * (percent / 100.0)));
343 if (percentDiff < totalDiffs) { totalDiffs = percentDiff; }
346 Alignment* alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (seq1.length()+totalDiffs+1));
348 //use needleman to align
349 alignment->align(seq2, seq1);
350 string tempSeq2 = alignment->getSeqAAln();
351 string temp = alignment->getSeqBAln();
357 int endPos = tempSeq2.length()-1;
358 for (int i = 0; i < tempSeq2.length(); i++) { if (isalpha(tempSeq2[i])) { startPos = i; break; } }
359 for (int i = tempSeq2.length()-1; i >= 0; i--) { if (isalpha(tempSeq2[i])) { endPos = i; break; } }
361 //count number of diffs
363 for (int i = startPos; i <= endPos; i++) {
364 if (tempSeq2[i] != temp[i]) { numDiffs++; }
367 if (numDiffs <= totalDiffs) { fragment = true; }
374 catch(exception& e) {
375 m->errorOut(e, "ClusterFragmentsCommand", "isFragment");
379 /**************************************************************************************************/
380 int ClusterFragmentsCommand::readFASTA(){
384 m->openInputFile(fastafile, inFasta);
386 while (!inFasta.eof()) {
388 if (m->control_pressed) { inFasta.close(); return 0; }
390 Sequence seq(inFasta); m->gobble(inFasta);
392 if (seq.getName() != "") { //can get "" if commented line is at end of fasta file
393 if (namefile != "") {
394 itSize = sizes.find(seq.getName());
396 if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
398 seqRNode tempNode(itSize->second, seq, names[seq.getName()], seq.getUnaligned().length());
399 alignSeqs.push_back(tempNode);
401 }else if(countfile != "") {
402 seqRNode tempNode(ct.getNumSeqs(seq.getName()), seq, seq.getName(), seq.getUnaligned().length());
403 alignSeqs.push_back(tempNode);
404 }else { //no names file, you are identical to yourself
405 seqRNode tempNode(1, seq, seq.getName(), seq.getUnaligned().length());
406 alignSeqs.push_back(tempNode);
412 return alignSeqs.size();
415 catch(exception& e) {
416 m->errorOut(e, "ClusterFragmentsCommand", "readFASTA");
420 /**************************************************************************************************/
421 void ClusterFragmentsCommand::printData(string newfasta, string newname){
426 m->openOutputFile(newfasta, outFasta);
427 if (countfile == "") { m->openOutputFile(newname, outNames); }
429 for (int i = 0; i < alignSeqs.size(); i++) {
430 if (alignSeqs[i].numIdentical != 0) {
431 alignSeqs[i].seq.printSequence(outFasta);
432 if (countfile == "") { outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl; }
437 if (countfile == "") { outNames.close(); }
438 else { ct.printTable(newname); }
440 catch(exception& e) {
441 m->errorOut(e, "ClusterFragmentsCommand", "printData");
445 /**************************************************************************************************/
447 void ClusterFragmentsCommand::readNameFile(){
450 m->openInputFile(namefile, in);
451 string firstCol, secondCol;
454 in >> firstCol >> secondCol; m->gobble(in);
455 names[firstCol] = secondCol;
458 for(int i=0;i<secondCol.size();i++){
459 if(secondCol[i] == ','){ size++; }
461 sizes[firstCol] = size;
465 catch(exception& e) {
466 m->errorOut(e, "ClusterFragmentsCommand", "readNameFile");
470 /**************************************************************************************************/