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",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);
38 vector<string> myArray;
39 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
43 m->errorOut(e, "ClusterFragmentsCommand", "setParameters");
47 //**********************************************************************************************************************
48 string ClusterFragmentsCommand::getHelpString(){
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";
65 m->errorOut(e, "ClusterFragmentsCommand", "getHelpString");
69 //**********************************************************************************************************************
70 string ClusterFragmentsCommand::getOutputFileNameTag(string type, string inputName=""){
72 string outputFileName = "";
73 map<string, vector<string> >::iterator it;
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"); }
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; }
83 return outputFileName;
86 m->errorOut(e, "ClusterFragmentsCommand", "getOutputFileNameTag");
91 //**********************************************************************************************************************
92 ClusterFragmentsCommand::ClusterFragmentsCommand(){
94 abort = true; calledHelp = true;
96 vector<string> tempOutNames;
97 outputTypes["fasta"] = tempOutNames;
98 outputTypes["name"] = tempOutNames;
100 catch(exception& e) {
101 m->errorOut(e, "ClusterFragmentsCommand", "ClusterFragmentsCommand");
105 //**********************************************************************************************************************
106 ClusterFragmentsCommand::ClusterFragmentsCommand(string option) {
108 abort = false; calledHelp = false;
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;}
115 vector<string> myArray = setParameters();
117 OptionParser parser(option);
118 map<string, string> parameters = parser.getParameters();
120 ValidParameters validParameter;
121 map<string, string>::iterator it;
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; }
128 //initialize outputTypes
129 vector<string> tempOutNames;
130 outputTypes["fasta"] = tempOutNames;
131 outputTypes["name"] = tempOutNames;
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 = ""; }
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; }
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; }
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; }
162 else if (fastafile == "not open") { fastafile = ""; abort = true; }
163 else { m->setFastaFile(fastafile); }
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); }
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); }
176 temp = validParameter.validFile(parameters, "diffs", false); if (temp == "not found"){ temp = "0"; }
177 m->mothurConvert(temp, diffs);
179 temp = validParameter.validFile(parameters, "percent", false); if (temp == "not found"){ temp = "0"; }
180 m->mothurConvert(temp, percent);
182 if (namefile == "") {
183 vector<string> files; files.push_back(fastafile);
184 parser.getNameFile(files);
190 catch(exception& e) {
191 m->errorOut(e, "ClusterFragmentsCommand", "ClusterFragmentsCommand");
195 //**********************************************************************************************************************
196 int ClusterFragmentsCommand::execute(){
199 if (abort == true) { if (calledHelp) { return 0; } return 2; }
201 int start = time(NULL);
203 //reads fasta file and return number of seqs
204 int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
206 if (m->control_pressed) { return 0; }
208 if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0; }
210 //sort seqs by length of unaligned sequence
211 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
215 //think about running through twice...
216 for (int i = 0; i < numSeqs; i++) {
218 if (alignSeqs[i].active) { //this sequence has not been merged yet
220 string iBases = alignSeqs[i].seq.getUnaligned();
222 //try to merge it with all smaller seqs
223 for (int j = i+1; j < numSeqs; j++) {
225 if (m->control_pressed) { return 0; }
227 if (alignSeqs[j].active) { //this sequence has not been merged yet
229 string jBases = alignSeqs[j].seq.getUnaligned();
231 if (isFragment(iBases, jBases)) {
233 alignSeqs[i].names += ',' + alignSeqs[j].names;
234 alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
236 alignSeqs[j].active = 0;
237 alignSeqs[j].numIdentical = 0;
243 //remove from active list
244 alignSeqs[i].active = 0;
247 if(i % 100 == 0) { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
250 if(numSeqs % 100 != 0) { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
253 string fileroot = outputDir + m->getRootName(m->getSimpleName(fastafile));
255 string newFastaFile = fileroot + getOutputFileNameTag("fasta");
256 string newNamesFile = fileroot + getOutputFileNameTag("name");
258 if (m->control_pressed) { return 0; }
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();
264 printData(newFastaFile, newNamesFile);
266 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
268 if (m->control_pressed) { m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
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();
277 //set fasta file as new current fastafile
279 itTypes = outputTypes.find("fasta");
280 if (itTypes != outputTypes.end()) {
281 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
284 itTypes = outputTypes.find("name");
285 if (itTypes != outputTypes.end()) {
286 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
292 catch(exception& e) {
293 m->errorOut(e, "ClusterFragmentsCommand", "execute");
297 //***************************************************************************************************************
298 bool ClusterFragmentsCommand::isFragment(string seq1, string seq2){
300 bool fragment = false;
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
309 //find number of acceptable differences for this sequence fragment
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
315 }else if ((percent != 0) && (diffs != 0)) { //you want both, set total diffs to smaller of 2
317 int percentDiff = floor((seq2.length() * (percent / 100.0)));
318 if (percentDiff < totalDiffs) { totalDiffs = percentDiff; }
321 Alignment* alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (seq1.length()+totalDiffs+1));
323 //use needleman to align
324 alignment->align(seq2, seq1);
325 string tempSeq2 = alignment->getSeqAAln();
326 string temp = alignment->getSeqBAln();
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; } }
336 //count number of diffs
338 for (int i = startPos; i <= endPos; i++) {
339 if (tempSeq2[i] != temp[i]) { numDiffs++; }
342 if (numDiffs <= totalDiffs) { fragment = true; }
349 catch(exception& e) {
350 m->errorOut(e, "ClusterFragmentsCommand", "isFragment");
354 /**************************************************************************************************/
355 int ClusterFragmentsCommand::readFASTA(){
359 m->openInputFile(fastafile, inFasta);
361 while (!inFasta.eof()) {
363 if (m->control_pressed) { inFasta.close(); return 0; }
365 Sequence seq(inFasta); m->gobble(inFasta);
367 if (seq.getName() != "") { //can get "" if commented line is at end of fasta file
368 if (namefile != "") {
369 itSize = sizes.find(seq.getName());
371 if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
373 seqRNode tempNode(itSize->second, seq, names[seq.getName()], seq.getUnaligned().length());
374 alignSeqs.push_back(tempNode);
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);
384 return alignSeqs.size();
387 catch(exception& e) {
388 m->errorOut(e, "ClusterFragmentsCommand", "readFASTA");
392 /**************************************************************************************************/
393 void ClusterFragmentsCommand::printData(string newfasta, string newname){
398 m->openOutputFile(newfasta, outFasta);
399 m->openOutputFile(newname, outNames);
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;
411 catch(exception& e) {
412 m->errorOut(e, "ClusterFragmentsCommand", "printData");
416 /**************************************************************************************************/
418 void ClusterFragmentsCommand::readNameFile(){
421 m->openInputFile(namefile, in);
422 string firstCol, secondCol;
425 in >> firstCol >> secondCol; m->gobble(in);
426 names[firstCol] = secondCol;
429 for(int i=0;i<secondCol.size();i++){
430 if(secondCol[i] == ','){ size++; }
432 sizes[firstCol] = size;
436 catch(exception& e) {
437 m->errorOut(e, "ClusterFragmentsCommand", "readNameFile");
442 /**************************************************************************************************/