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 ClusterFragmentsCommand::ClusterFragmentsCommand(){
72 abort = true; calledHelp = true;
74 vector<string> tempOutNames;
75 outputTypes["fasta"] = tempOutNames;
76 outputTypes["name"] = tempOutNames;
79 m->errorOut(e, "ClusterFragmentsCommand", "ClusterFragmentsCommand");
83 //**********************************************************************************************************************
84 ClusterFragmentsCommand::ClusterFragmentsCommand(string option) {
86 abort = false; calledHelp = false;
88 //allow user to run help
89 if(option == "help") { help(); abort = true; calledHelp = true; }
90 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
93 vector<string> myArray = setParameters();
95 OptionParser parser(option);
96 map<string, string> parameters = parser.getParameters();
98 ValidParameters validParameter;
99 map<string, string>::iterator it;
101 //check to make sure all parameters are valid for command
102 for (map<string, string>::iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) {
103 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) { abort = true; }
106 //initialize outputTypes
107 vector<string> tempOutNames;
108 outputTypes["fasta"] = tempOutNames;
109 outputTypes["name"] = tempOutNames;
111 //if the user changes the input directory command factory will send this info to us in the output parameter
112 string inputDir = validParameter.validFile(parameters, "inputdir", false);
113 if (inputDir == "not found"){ inputDir = ""; }
116 it = parameters.find("fasta");
117 //user has given a template file
118 if(it != parameters.end()){
119 path = m->hasPath(it->second);
120 //if the user has not given a path then, add inputdir. else leave path alone.
121 if (path == "") { parameters["fasta"] = inputDir + it->second; }
124 it = parameters.find("name");
125 //user has given a template file
126 if(it != parameters.end()){
127 path = m->hasPath(it->second);
128 //if the user has not given a path then, add inputdir. else leave path alone.
129 if (path == "") { parameters["name"] = inputDir + it->second; }
133 //check for required parameters
134 fastafile = validParameter.validFile(parameters, "fasta", true);
135 if (fastafile == "not found") {
136 fastafile = m->getFastaFile();
137 if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
138 else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
140 else if (fastafile == "not open") { fastafile = ""; abort = true; }
141 else { m->setFastaFile(fastafile); }
143 //if the user changes the output directory command factory will send this info to us in the output parameter
144 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = m->hasPath(fastafile); }
146 //check for optional parameter and set defaults
147 // ...at some point should added some additional type checking...
148 namefile = validParameter.validFile(parameters, "name", true);
149 if (namefile == "not found") { namefile = ""; }
150 else if (namefile == "not open") { abort = true; }
151 else { readNameFile(); m->setNameFile(namefile); }
154 temp = validParameter.validFile(parameters, "diffs", false); if (temp == "not found"){ temp = "0"; }
155 convert(temp, diffs);
157 temp = validParameter.validFile(parameters, "percent", false); if (temp == "not found"){ temp = "0"; }
158 convert(temp, percent);
163 catch(exception& e) {
164 m->errorOut(e, "ClusterFragmentsCommand", "ClusterFragmentsCommand");
168 //**********************************************************************************************************************
169 int ClusterFragmentsCommand::execute(){
172 if (abort == true) { if (calledHelp) { return 0; } return 2; }
174 int start = time(NULL);
176 //reads fasta file and return number of seqs
177 int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
179 if (m->control_pressed) { return 0; }
181 if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0; }
183 //sort seqs by length of unaligned sequence
184 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
188 //think about running through twice...
189 for (int i = 0; i < numSeqs; i++) {
191 if (alignSeqs[i].active) { //this sequence has not been merged yet
193 string iBases = alignSeqs[i].seq.getUnaligned();
195 //try to merge it with all smaller seqs
196 for (int j = i+1; j < numSeqs; j++) {
198 if (m->control_pressed) { return 0; }
200 if (alignSeqs[j].active) { //this sequence has not been merged yet
202 string jBases = alignSeqs[j].seq.getUnaligned();
204 if (isFragment(iBases, jBases)) {
206 alignSeqs[i].names += ',' + alignSeqs[j].names;
207 alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
209 alignSeqs[j].active = 0;
210 alignSeqs[j].numIdentical = 0;
216 //remove from active list
217 alignSeqs[i].active = 0;
220 if(i % 100 == 0) { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
223 if(numSeqs % 100 != 0) { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
226 string fileroot = outputDir + m->getRootName(m->getSimpleName(fastafile));
228 string newFastaFile = fileroot + "fragclust.fasta";
229 string newNamesFile = fileroot + "fragclust.names";
231 if (m->control_pressed) { return 0; }
233 m->mothurOutEndLine();
234 m->mothurOut("Total number of sequences before cluster.fragments was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
235 m->mothurOut("cluster.fragments removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
237 printData(newFastaFile, newNamesFile);
239 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
241 if (m->control_pressed) { m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
243 m->mothurOutEndLine();
244 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
245 m->mothurOut(newFastaFile); m->mothurOutEndLine();
246 m->mothurOut(newNamesFile); m->mothurOutEndLine();
247 outputNames.push_back(newFastaFile); outputNames.push_back(newNamesFile); outputTypes["fasta"].push_back(newFastaFile); outputTypes["name"].push_back(newNamesFile);
248 m->mothurOutEndLine();
250 //set fasta file as new current fastafile
252 itTypes = outputTypes.find("fasta");
253 if (itTypes != outputTypes.end()) {
254 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
257 itTypes = outputTypes.find("name");
258 if (itTypes != outputTypes.end()) {
259 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
265 catch(exception& e) {
266 m->errorOut(e, "ClusterFragmentsCommand", "execute");
270 //***************************************************************************************************************
271 bool ClusterFragmentsCommand::isFragment(string seq1, string seq2){
273 bool fragment = false;
276 int pos = seq1.find(seq2);
277 if (pos != string::npos) { return true; }
278 //no match, no diffs wanted
279 else if ((diffs == 0) && (percent == 0)) { return false; }
280 else { //try aligning and see if you can find it
282 //find number of acceptable differences for this sequence fragment
284 if (diffs == 0) { //you didnt set diffs you want a percentage
285 totalDiffs = floor((seq2.length() * (percent / 100.0)));
286 }else if (percent == 0) { //you didn't set percent you want diffs
288 }else if ((percent != 0) && (diffs != 0)) { //you want both, set total diffs to smaller of 2
290 int percentDiff = floor((seq2.length() * (percent / 100.0)));
291 if (percentDiff < totalDiffs) { totalDiffs = percentDiff; }
294 Alignment* alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (seq1.length()+totalDiffs+1));
296 //use needleman to align
297 alignment->align(seq2, seq1);
298 string tempSeq2 = alignment->getSeqAAln();
299 string temp = alignment->getSeqBAln();
305 int endPos = tempSeq2.length()-1;
306 for (int i = 0; i < tempSeq2.length(); i++) { if (isalpha(tempSeq2[i])) { startPos = i; break; } }
307 for (int i = tempSeq2.length()-1; i >= 0; i--) { if (isalpha(tempSeq2[i])) { endPos = i; break; } }
309 //count number of diffs
311 for (int i = startPos; i <= endPos; i++) {
312 if (tempSeq2[i] != temp[i]) { numDiffs++; }
315 if (numDiffs <= totalDiffs) { fragment = true; }
322 catch(exception& e) {
323 m->errorOut(e, "ClusterFragmentsCommand", "isFragment");
327 /**************************************************************************************************/
328 int ClusterFragmentsCommand::readFASTA(){
332 m->openInputFile(fastafile, inFasta);
334 while (!inFasta.eof()) {
336 if (m->control_pressed) { inFasta.close(); return 0; }
338 Sequence seq(inFasta); m->gobble(inFasta);
340 if (seq.getName() != "") { //can get "" if commented line is at end of fasta file
341 if (namefile != "") {
342 itSize = sizes.find(seq.getName());
344 if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
346 seqRNode tempNode(itSize->second, seq, names[seq.getName()], seq.getUnaligned().length());
347 alignSeqs.push_back(tempNode);
349 }else { //no names file, you are identical to yourself
350 seqRNode tempNode(1, seq, seq.getName(), seq.getUnaligned().length());
351 alignSeqs.push_back(tempNode);
357 return alignSeqs.size();
360 catch(exception& e) {
361 m->errorOut(e, "ClusterFragmentsCommand", "readFASTA");
365 /**************************************************************************************************/
366 void ClusterFragmentsCommand::printData(string newfasta, string newname){
371 m->openOutputFile(newfasta, outFasta);
372 m->openOutputFile(newname, outNames);
374 for (int i = 0; i < alignSeqs.size(); i++) {
375 if (alignSeqs[i].numIdentical != 0) {
376 alignSeqs[i].seq.printSequence(outFasta);
377 outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;
384 catch(exception& e) {
385 m->errorOut(e, "ClusterFragmentsCommand", "printData");
389 /**************************************************************************************************/
391 void ClusterFragmentsCommand::readNameFile(){
394 m->openInputFile(namefile, in);
395 string firstCol, secondCol;
398 in >> firstCol >> secondCol; m->gobble(in);
399 names[firstCol] = secondCol;
402 for(int i=0;i<secondCol.size();i++){
403 if(secondCol[i] == ','){ size++; }
405 sizes[firstCol] = size;
409 catch(exception& e) {
410 m->errorOut(e, "ClusterFragmentsCommand", "readNameFile");
415 /**************************************************************************************************/