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::getValidParameters(){
31 string AlignArray[] = {"fasta","name","diffs","percent","outputdir","inputdir"};
32 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
36 m->errorOut(e, "ClusterFragmentsCommand", "getValidParameters");
40 //**********************************************************************************************************************
41 ClusterFragmentsCommand::ClusterFragmentsCommand(){
44 //initialize outputTypes
45 vector<string> tempOutNames;
46 outputTypes["fasta"] = tempOutNames;
47 outputTypes["name"] = tempOutNames;
50 m->errorOut(e, "ClusterFragmentsCommand", "ClusterFragmentsCommand");
54 //**********************************************************************************************************************
55 vector<string> ClusterFragmentsCommand::getRequiredParameters(){
57 string Array[] = {"fasta"};
58 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
62 m->errorOut(e, "ClusterFragmentsCommand", "getRequiredParameters");
66 //**********************************************************************************************************************
67 vector<string> ClusterFragmentsCommand::getRequiredFiles(){
69 vector<string> myArray;
73 m->errorOut(e, "ClusterFragmentsCommand", "getRequiredFiles");
77 //**********************************************************************************************************************
78 ClusterFragmentsCommand::ClusterFragmentsCommand(string option) {
82 //allow user to run help
83 if(option == "help") { help(); abort = true; }
86 //valid paramters for this command
87 string Array[] = {"fasta","name","diffs","percent","outputdir","inputdir"};
88 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
90 OptionParser parser(option);
91 map<string, string> parameters = parser.getParameters();
93 ValidParameters validParameter;
94 map<string, string>::iterator it;
96 //check to make sure all parameters are valid for command
97 for (map<string, string>::iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) {
98 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) { abort = true; }
101 //initialize outputTypes
102 vector<string> tempOutNames;
103 outputTypes["fasta"] = tempOutNames;
104 outputTypes["name"] = tempOutNames;
106 //if the user changes the input directory command factory will send this info to us in the output parameter
107 string inputDir = validParameter.validFile(parameters, "inputdir", false);
108 if (inputDir == "not found"){ inputDir = ""; }
111 it = parameters.find("fasta");
112 //user has given a template file
113 if(it != parameters.end()){
114 path = m->hasPath(it->second);
115 //if the user has not given a path then, add inputdir. else leave path alone.
116 if (path == "") { parameters["fasta"] = inputDir + it->second; }
119 it = parameters.find("name");
120 //user has given a template file
121 if(it != parameters.end()){
122 path = m->hasPath(it->second);
123 //if the user has not given a path then, add inputdir. else leave path alone.
124 if (path == "") { parameters["name"] = inputDir + it->second; }
128 //check for required parameters
129 fastafile = validParameter.validFile(parameters, "fasta", true);
130 if (fastafile == "not found") { m->mothurOut("fasta is a required parameter for the cluster.fragments command."); m->mothurOutEndLine(); abort = true; }
131 else if (fastafile == "not open") { abort = true; }
133 //if the user changes the output directory command factory will send this info to us in the output parameter
134 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = m->hasPath(fastafile); }
136 //check for optional parameter and set defaults
137 // ...at some point should added some additional type checking...
138 namefile = validParameter.validFile(parameters, "name", true);
139 if (namefile == "not found") { namefile = ""; }
140 else if (namefile == "not open") { abort = true; }
141 else { readNameFile(); }
144 temp = validParameter.validFile(parameters, "diffs", false); if (temp == "not found"){ temp = "0"; }
145 convert(temp, diffs);
147 temp = validParameter.validFile(parameters, "percent", false); if (temp == "not found"){ temp = "0"; }
148 convert(temp, percent);
153 catch(exception& e) {
154 m->errorOut(e, "ClusterFragmentsCommand", "ClusterFragmentsCommand");
159 //**********************************************************************************************************************
160 ClusterFragmentsCommand::~ClusterFragmentsCommand(){}
161 //**********************************************************************************************************************
162 void ClusterFragmentsCommand::help(){
164 m->mothurOut("The cluster.fragments command groups sequences that are part of a larger sequence.\n");
165 m->mothurOut("The cluster.fragments command outputs a new fasta and name file.\n");
166 m->mothurOut("The cluster.fragments command parameters are fasta, name, diffs and percent. The fasta parameter is required. \n");
167 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");
168 m->mothurOut("The diffs parameter allows you to set the number of differences allowed, default=0. \n");
169 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");
170 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");
171 m->mothurOut("The cluster.fragments command should be in the following format: \n");
172 m->mothurOut("cluster.fragments(fasta=yourFastaFile, names=yourNamesFile) \n");
173 m->mothurOut("Example cluster.fragments(fasta=amazon.fasta).\n");
174 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n\n");
176 catch(exception& e) {
177 m->errorOut(e, "ClusterFragmentsCommand", "help");
181 //**********************************************************************************************************************
182 int ClusterFragmentsCommand::execute(){
185 if (abort == true) { return 0; }
187 int start = time(NULL);
189 //reads fasta file and return number of seqs
190 int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
192 if (m->control_pressed) { return 0; }
194 if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0; }
196 //sort seqs by length of unaligned sequence
197 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
201 //think about running through twice...
202 for (int i = 0; i < numSeqs; i++) {
204 if (alignSeqs[i].active) { //this sequence has not been merged yet
206 string iBases = alignSeqs[i].seq.getUnaligned();
208 //try to merge it with all smaller seqs
209 for (int j = i+1; j < numSeqs; j++) {
211 if (m->control_pressed) { return 0; }
213 if (alignSeqs[j].active) { //this sequence has not been merged yet
215 string jBases = alignSeqs[j].seq.getUnaligned();
217 if (isFragment(iBases, jBases)) {
219 alignSeqs[i].names += ',' + alignSeqs[j].names;
220 alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
222 alignSeqs[j].active = 0;
223 alignSeqs[j].numIdentical = 0;
229 //remove from active list
230 alignSeqs[i].active = 0;
233 if(i % 100 == 0) { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
236 if(numSeqs % 100 != 0) { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
239 string fileroot = outputDir + m->getRootName(m->getSimpleName(fastafile));
241 string newFastaFile = fileroot + "fragclust.fasta";
242 string newNamesFile = fileroot + "names";
244 if (m->control_pressed) { return 0; }
246 m->mothurOutEndLine();
247 m->mothurOut("Total number of sequences before cluster.fragments was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
248 m->mothurOut("cluster.fragments removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
250 printData(newFastaFile, newNamesFile);
252 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
254 if (m->control_pressed) { remove(newFastaFile.c_str()); remove(newNamesFile.c_str()); return 0; }
256 m->mothurOutEndLine();
257 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
258 m->mothurOut(newFastaFile); m->mothurOutEndLine();
259 m->mothurOut(newNamesFile); m->mothurOutEndLine();
260 outputNames.push_back(newFastaFile); outputNames.push_back(newNamesFile); outputTypes["fasta"].push_back(newFastaFile); outputTypes["name"].push_back(newNamesFile);
261 m->mothurOutEndLine();
266 catch(exception& e) {
267 m->errorOut(e, "ClusterFragmentsCommand", "execute");
271 //***************************************************************************************************************
272 bool ClusterFragmentsCommand::isFragment(string seq1, string seq2){
274 bool fragment = false;
277 int pos = seq1.find(seq2);
278 if (pos != string::npos) { return true; }
279 //no match, no diffs wanted
280 else if ((diffs == 0) && (percent == 0)) { return false; }
281 else { //try aligning and see if you can find it
283 //find number of acceptable differences for this sequence fragment
285 if (diffs == 0) { //you didnt set diffs you want a percentage
286 totalDiffs = floor((seq2.length() * (percent / 100.0)));
287 }else if (percent == 0) { //you didn't set percent you want diffs
289 }else if ((percent != 0) && (diffs != 0)) { //you want both, set total diffs to smaller of 2
291 int percentDiff = floor((seq2.length() * (percent / 100.0)));
292 if (percentDiff < totalDiffs) { totalDiffs = percentDiff; }
295 Alignment* alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (seq1.length()+totalDiffs+1));
297 //use needleman to align
298 alignment->align(seq2, seq1);
299 string tempSeq2 = alignment->getSeqAAln();
300 string temp = alignment->getSeqBAln();
306 int endPos = tempSeq2.length()-1;
307 for (int i = 0; i < tempSeq2.length(); i++) { if (isalpha(tempSeq2[i])) { startPos = i; break; } }
308 for (int i = tempSeq2.length()-1; i >= 0; i--) { if (isalpha(tempSeq2[i])) { endPos = i; break; } }
310 //count number of diffs
312 for (int i = startPos; i <= endPos; i++) {
313 if (tempSeq2[i] != temp[i]) { numDiffs++; }
316 if (numDiffs <= totalDiffs) { fragment = true; }
323 catch(exception& e) {
324 m->errorOut(e, "ClusterFragmentsCommand", "isFragment");
328 /**************************************************************************************************/
329 int ClusterFragmentsCommand::readFASTA(){
333 m->openInputFile(fastafile, inFasta);
335 while (!inFasta.eof()) {
337 if (m->control_pressed) { inFasta.close(); return 0; }
339 Sequence seq(inFasta); m->gobble(inFasta);
341 if (seq.getName() != "") { //can get "" if commented line is at end of fasta file
342 if (namefile != "") {
343 itSize = sizes.find(seq.getName());
345 if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
347 seqRNode tempNode(itSize->second, seq, names[seq.getName()], seq.getUnaligned().length());
348 alignSeqs.push_back(tempNode);
350 }else { //no names file, you are identical to yourself
351 seqRNode tempNode(1, seq, seq.getName(), seq.getUnaligned().length());
352 alignSeqs.push_back(tempNode);
358 return alignSeqs.size();
361 catch(exception& e) {
362 m->errorOut(e, "ClusterFragmentsCommand", "readFASTA");
366 /**************************************************************************************************/
367 void ClusterFragmentsCommand::printData(string newfasta, string newname){
372 m->openOutputFile(newfasta, outFasta);
373 m->openOutputFile(newname, outNames);
375 for (int i = 0; i < alignSeqs.size(); i++) {
376 if (alignSeqs[i].numIdentical != 0) {
377 alignSeqs[i].seq.printSequence(outFasta);
378 outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;
385 catch(exception& e) {
386 m->errorOut(e, "ClusterFragmentsCommand", "printData");
390 /**************************************************************************************************/
392 void ClusterFragmentsCommand::readNameFile(){
395 m->openInputFile(namefile, in);
396 string firstCol, secondCol;
399 in >> firstCol >> secondCol; m->gobble(in);
400 names[firstCol] = secondCol;
403 for(int i=0;i<secondCol.size();i++){
404 if(secondCol[i] == ','){ size++; }
406 sizes[firstCol] = size;
410 catch(exception& e) {
411 m->errorOut(e, "ClusterFragmentsCommand", "readNameFile");
416 /**************************************************************************************************/