2 * preclustercommand.cpp
5 * Created by westcott on 12/21/09.
6 * Copyright 2009 Schloss Lab. All rights reserved.
10 #include "preclustercommand.h"
11 #include "deconvolutecommand.h"
13 //**********************************************************************************************************************
14 vector<string> PreClusterCommand::setParameters(){
16 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
17 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
18 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pgroup);
19 CommandParameter pdiffs("diffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(pdiffs);
20 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
21 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
22 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
24 vector<string> myArray;
25 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
29 m->errorOut(e, "PreClusterCommand", "setParameters");
33 //**********************************************************************************************************************
34 string PreClusterCommand::getHelpString(){
36 string helpString = "";
37 helpString += "The pre.cluster command groups sequences that are within a given number of base mismatches.\n";
38 helpString += "The pre.cluster command outputs a new fasta and name file.\n";
39 helpString += "The pre.cluster command parameters are fasta, names and diffs. The fasta parameter is required. \n";
40 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";
41 helpString += "The group parameter allows you to provide a group file so you can cluster by group. \n";
42 helpString += "The diffs parameter allows you to specify maximum number of mismatched bases allowed between sequences in a grouping. The default is 1.\n";
43 helpString += "The pre.cluster command should be in the following format: \n";
44 helpString += "pre.cluster(fasta=yourFastaFile, names=yourNamesFile, diffs=yourMaxDiffs) \n";
45 helpString += "Example pre.cluster(fasta=amazon.fasta, diffs=2).\n";
46 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
50 m->errorOut(e, "PreClusterCommand", "getHelpString");
55 //**********************************************************************************************************************
56 PreClusterCommand::PreClusterCommand(){
58 abort = true; calledHelp = true;
60 vector<string> tempOutNames;
61 outputTypes["fasta"] = tempOutNames;
62 outputTypes["name"] = tempOutNames;
65 m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
69 //**********************************************************************************************************************
71 PreClusterCommand::PreClusterCommand(string option) {
73 abort = false; calledHelp = false;
75 //allow user to run help
76 if(option == "help") { help(); abort = true; calledHelp = true; }
77 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
80 vector<string> myArray = setParameters();
82 OptionParser parser(option);
83 map<string, string> parameters = parser.getParameters();
85 ValidParameters validParameter;
86 map<string, string>::iterator it;
88 //check to make sure all parameters are valid for command
89 for (map<string, string>::iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) {
90 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) { abort = true; }
93 //initialize outputTypes
94 vector<string> tempOutNames;
95 outputTypes["fasta"] = tempOutNames;
96 outputTypes["name"] = tempOutNames;
98 //if the user changes the input directory command factory will send this info to us in the output parameter
99 string inputDir = validParameter.validFile(parameters, "inputdir", false);
100 if (inputDir == "not found"){ inputDir = ""; }
103 it = parameters.find("fasta");
104 //user has given a template file
105 if(it != parameters.end()){
106 path = m->hasPath(it->second);
107 //if the user has not given a path then, add inputdir. else leave path alone.
108 if (path == "") { parameters["fasta"] = inputDir + it->second; }
111 it = parameters.find("name");
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["name"] = inputDir + it->second; }
119 it = parameters.find("group");
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["group"] = inputDir + it->second; }
128 //check for required parameters
129 fastafile = validParameter.validFile(parameters, "fasta", true);
130 if (fastafile == "not found") {
131 fastafile = m->getFastaFile();
132 if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
133 else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
135 else if (fastafile == "not open") { abort = true; }
136 else { m->setFastaFile(fastafile); }
138 //if the user changes the output directory command factory will send this info to us in the output parameter
139 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
141 outputDir += m->hasPath(fastafile); //if user entered a file with a path then preserve it
144 //check for optional parameter and set defaults
145 // ...at some point should added some additional type checking...
146 namefile = validParameter.validFile(parameters, "name", true);
147 if (namefile == "not found") { namefile = ""; }
148 else if (namefile == "not open") { abort = true; }
149 else { m->setNameFile(namefile); }
151 groupfile = validParameter.validFile(parameters, "group", true);
152 if (groupfile == "not found") { groupfile = ""; bygroup = false; }
153 else if (groupfile == "not open") { abort = true; groupfile = ""; }
154 else { m->setGroupFile(groupfile); bygroup = true; }
156 string temp = validParameter.validFile(parameters, "diffs", false); if(temp == "not found"){ temp = "1"; }
157 convert(temp, diffs);
159 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
160 m->setProcessors(temp);
161 convert(temp, processors);
167 catch(exception& e) {
168 m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
172 //**********************************************************************************************************************
174 int PreClusterCommand::execute(){
177 if (abort == true) { if (calledHelp) { return 0; } return 2; }
179 int start = time(NULL);
181 string fileroot = outputDir + m->getRootName(m->getSimpleName(fastafile));
182 string newFastaFile = fileroot + "precluster" + m->getExtension(fastafile);
183 string newNamesFile = fileroot + "precluster.names";
186 //clear out old files
187 ofstream outFasta; m->openOutputFile(newFastaFile, outFasta); outFasta.close();
188 ofstream outNames; m->openOutputFile(newNamesFile, outNames); outNames.close();
190 //parse fasta and name file by group
191 SequenceParser* parser;
192 if (namefile != "") { parser = new SequenceParser(groupfile, fastafile, namefile); }
193 else { parser = new SequenceParser(groupfile, fastafile); }
195 vector<string> groups = parser->getNamesOfGroups();
197 //#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
198 if(processors == 1) { driverGroups(parser, newFastaFile, newNamesFile, 0, groups.size(), groups); }
199 else { createProcessesGroups(parser, newFastaFile, newNamesFile, groups); }
201 // driverGroups(parser, newFastaFile, newNamesFile, 0, groups.size(), groups);
206 if (m->control_pressed) { m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
208 //run unique.seqs for deconvolute results
209 string inputString = "fasta=" + newFastaFile;
210 if (namefile != "") { inputString += ", name=" + newNamesFile; }
211 m->mothurOutEndLine();
212 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
213 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine();
215 Command* uniqueCommand = new DeconvoluteCommand(inputString);
216 uniqueCommand->execute();
218 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
220 delete uniqueCommand;
222 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
224 m->renameFile(filenames["fasta"][0], newFastaFile);
226 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run pre.cluster."); m->mothurOutEndLine();
229 if (namefile != "") { readNameFile(); }
231 //reads fasta file and return number of seqs
232 int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
234 if (m->control_pressed) { return 0; }
236 if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0; }
237 if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); return 0; }
239 int count = process();
241 if (m->control_pressed) { return 0; }
243 m->mothurOut("Total number of sequences before precluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
244 m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
245 printData(newFastaFile, newNamesFile);
247 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
250 if (m->control_pressed) { m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
252 m->mothurOutEndLine();
253 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
254 m->mothurOut(newFastaFile); m->mothurOutEndLine(); outputNames.push_back(newFastaFile); outputTypes["fasta"].push_back(newFastaFile);
255 m->mothurOut(newNamesFile); m->mothurOutEndLine(); outputNames.push_back(newNamesFile); outputTypes["name"].push_back(newNamesFile);
256 m->mothurOutEndLine();
258 //set fasta file as new current fastafile
260 itTypes = outputTypes.find("fasta");
261 if (itTypes != outputTypes.end()) {
262 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
265 itTypes = outputTypes.find("name");
266 if (itTypes != outputTypes.end()) {
267 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
273 catch(exception& e) {
274 m->errorOut(e, "PreClusterCommand", "execute");
278 /**************************************************************************************************/
279 int PreClusterCommand::createProcessesGroups(SequenceParser* parser, string newFName, string newNName, vector<string> groups) {
282 vector<int> processIDS;
287 if (groups.size() < processors) { processors = groups.size(); }
289 //divide the groups between the processors
290 vector<linePair> lines;
291 int numGroupsPerProcessor = groups.size() / processors;
292 for (int i = 0; i < processors; i++) {
293 int startIndex = i * numGroupsPerProcessor;
294 int endIndex = (i+1) * numGroupsPerProcessor;
295 if(i == (processors - 1)){ endIndex = groups.size(); }
296 lines.push_back(linePair(startIndex, endIndex));
299 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
301 //loop through and create all the processes you want
302 while (process != processors) {
306 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
309 num = driverGroups(parser, newFName + toString(getpid()) + ".temp", newNName + toString(getpid()) + ".temp", lines[process].start, lines[process].end, groups);
312 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
313 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
319 num = driverGroups(parser, newFName, newNName, lines[0].start, lines[0].end, groups);
321 //force parent to wait until all the processes are done
322 for (int i=0;i<processIDS.size();i++) {
323 int temp = processIDS[i];
329 //////////////////////////////////////////////////////////////////////////////////////////////////////
330 //Windows version shared memory, so be careful when passing variables through the preClusterData struct.
331 //Above fork() will clone, so memory is separate, but that's not the case with windows,
332 //////////////////////////////////////////////////////////////////////////////////////////////////////
334 vector<preClusterData*> pDataArray;
335 DWORD dwThreadIdArray[processors-1];
336 HANDLE hThreadArray[processors-1];
338 //Create processor worker threads.
339 for( int i=1; i<processors; i++ ){
340 // Allocate memory for thread data.
341 string extension = toString(i) + ".temp";
343 preClusterData* tempPreCluster = new preClusterData(fastafile, namefile, groupfile, (newFName+extension), (newNName+extension), groups, m, lines[i].start, lines[i].end, diffs, i);
344 pDataArray.push_back(tempPreCluster);
345 processIDS.push_back(i);
347 //MySeqSumThreadFunction is in header. It must be global or static to work with the threads.
348 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
349 hThreadArray[i-1] = CreateThread(NULL, 0, MyPreclusterThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);
353 //using the main process as a worker saves time and memory
354 num = driverGroups(parser, newFName, newNName, lines[0].start, lines[0].end, groups);
356 //Wait until all threads have terminated.
357 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
359 //Close all thread handles and free memory allocations.
360 for(int i=0; i < pDataArray.size(); i++){
361 CloseHandle(hThreadArray[i]);
362 delete pDataArray[i];
367 //append output files
368 for(int i=0;i<processIDS.size();i++){
369 m->appendFiles((newFName + toString(processIDS[i]) + ".temp"), newFName);
370 m->mothurRemove((newFName + toString(processIDS[i]) + ".temp"));
372 m->appendFiles((newNName + toString(processIDS[i]) + ".temp"), newNName);
373 m->mothurRemove((newNName + toString(processIDS[i]) + ".temp"));
379 catch(exception& e) {
380 m->errorOut(e, "PreClusterCommand", "createProcessesGroups");
384 /**************************************************************************************************/
385 int PreClusterCommand::driverGroups(SequenceParser* parser, string newFFile, string newNFile, int start, int end, vector<string> groups){
390 //precluster each group
391 for (int i = start; i < end; i++) {
395 if (m->control_pressed) { return 0; }
397 m->mothurOutEndLine(); m->mothurOut("Processing group " + groups[i] + ":"); m->mothurOutEndLine();
399 map<string, string> thisNameMap;
400 if (namefile != "") { thisNameMap = parser->getNameMap(groups[i]); }
401 vector<Sequence> thisSeqs = parser->getSeqs(groups[i]);
403 //fill alignSeqs with this groups info.
404 numSeqs = loadSeqs(thisNameMap, thisSeqs);
406 if (m->control_pressed) { return 0; }
408 if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
410 int count = process();
412 if (m->control_pressed) { return 0; }
414 m->mothurOut("Total number of sequences before pre.cluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
415 m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
416 printData(newFFile, newNFile);
418 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
424 catch(exception& e) {
425 m->errorOut(e, "PreClusterCommand", "driverGroups");
429 /**************************************************************************************************/
430 int PreClusterCommand::process(){
433 //sort seqs by number of identical seqs
434 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
437 int numSeqs = alignSeqs.size();
439 //think about running through twice...
440 for (int i = 0; i < numSeqs; i++) {
443 // itActive = active.find(alignSeqs[i].seq.getName());
445 if (alignSeqs[i].active) { //this sequence has not been merged yet
447 //try to merge it with all smaller seqs
448 for (int j = i+1; j < numSeqs; j++) {
450 if (m->control_pressed) { return 0; }
452 if (alignSeqs[j].active) { //this sequence has not been merged yet
453 //are you within "diff" bases
454 int mismatch = calcMisMatches(alignSeqs[i].seq.getAligned(), alignSeqs[j].seq.getAligned());
456 if (mismatch <= diffs) {
458 alignSeqs[i].names += ',' + alignSeqs[j].names;
459 alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
461 alignSeqs[j].active = 0;
462 alignSeqs[j].numIdentical = 0;
468 //remove from active list
469 alignSeqs[i].active = 0;
472 if(i % 100 == 0) { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
475 if(numSeqs % 100 != 0) { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
480 catch(exception& e) {
481 m->errorOut(e, "PreClusterCommand", "process");
485 /**************************************************************************************************/
486 int PreClusterCommand::readFASTA(){
491 //m->openInputFile(namefile, inNames);
492 m->openInputFile(fastafile, inFasta);
494 //string firstCol, secondCol, nameString;
497 while (!inFasta.eof()) {
499 if (m->control_pressed) { inFasta.close(); return 0; }
501 //inNames >> firstCol >> secondCol;
502 //nameString = secondCol;
504 //m->gobble(inNames);
506 //while (secondCol.find_first_of(',') != -1) {
508 // secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
511 Sequence seq(inFasta); m->gobble(inFasta);
513 if (seq.getName() != "") { //can get "" if commented line is at end of fasta file
514 if (namefile != "") {
515 itSize = sizes.find(seq.getName());
517 if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
519 seqPNode tempNode(itSize->second, seq, names[seq.getName()]);
520 alignSeqs.push_back(tempNode);
521 if (seq.getAligned().length() > length) { length = seq.getAligned().length(); }
523 }else { //no names file, you are identical to yourself
524 seqPNode tempNode(1, seq, seq.getName());
525 alignSeqs.push_back(tempNode);
526 if (seq.getAligned().length() > length) { length = seq.getAligned().length(); }
532 return alignSeqs.size();
535 catch(exception& e) {
536 m->errorOut(e, "PreClusterCommand", "readFASTA");
540 /**************************************************************************************************/
541 int PreClusterCommand::loadSeqs(map<string, string>& thisName, vector<Sequence>& thisSeqs){
545 map<string, string>::iterator it;
548 for (int i = 0; i < thisSeqs.size(); i++) {
550 if (m->control_pressed) { return 0; }
552 if (namefile != "") {
553 it = thisName.find(thisSeqs[i].getName());
555 //should never be true since parser checks for this
556 if (it == thisName.end()) { m->mothurOut(thisSeqs[i].getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); error = true; }
560 for(int j=0;j<(it->second).length();j++){
561 if((it->second)[j] == ','){ numReps++; }
564 seqPNode tempNode(numReps, thisSeqs[i], it->second);
565 alignSeqs.push_back(tempNode);
566 if (thisSeqs[i].getAligned().length() > length) { length = thisSeqs[i].getAligned().length(); }
568 }else { //no names file, you are identical to yourself
569 seqPNode tempNode(1, thisSeqs[i], thisSeqs[i].getName());
570 alignSeqs.push_back(tempNode);
571 if (thisSeqs[i].getAligned().length() > length) { length = thisSeqs[i].getAligned().length(); }
576 if (error) { m->control_pressed = true; }
580 return alignSeqs.size();
583 catch(exception& e) {
584 m->errorOut(e, "PreClusterCommand", "loadSeqs");
589 /**************************************************************************************************/
591 int PreClusterCommand::calcMisMatches(string seq1, string seq2){
595 for (int i = 0; i < seq1.length(); i++) {
597 if (seq1[i] != seq2[i]) { numBad++; }
598 if (numBad > diffs) { return length; } //to far to cluster
603 catch(exception& e) {
604 m->errorOut(e, "PreClusterCommand", "calcMisMatches");
609 /**************************************************************************************************/
611 void PreClusterCommand::printData(string newfasta, string newname){
617 m->openOutputFileAppend(newfasta, outFasta);
618 m->openOutputFileAppend(newname, outNames);
620 m->openOutputFile(newfasta, outFasta);
621 m->openOutputFile(newname, outNames);
624 for (int i = 0; i < alignSeqs.size(); i++) {
625 if (alignSeqs[i].numIdentical != 0) {
626 alignSeqs[i].seq.printSequence(outFasta);
627 outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;
635 catch(exception& e) {
636 m->errorOut(e, "PreClusterCommand", "printData");
640 /**************************************************************************************************/
642 void PreClusterCommand::readNameFile(){
645 m->openInputFile(namefile, in);
646 string firstCol, secondCol;
649 in >> firstCol >> secondCol; m->gobble(in);
650 names[firstCol] = secondCol;
653 for(int i=0;i<secondCol.size();i++){
654 if(secondCol[i] == ','){ size++; }
656 sizes[firstCol] = size;
660 catch(exception& e) {
661 m->errorOut(e, "PreClusterCommand", "readNameFile");
666 /**************************************************************************************************/