Mercurial > repos > yufei-luo > s_mart
view commons/tools/LaunchBlasterInParallel.py @ 19:9bcfa7936eec
Deleted selected files
author | m-zytnicki |
---|---|
date | Mon, 29 Apr 2013 03:23:29 -0400 |
parents | 94ab73e8a190 |
children |
line wrap: on
line source
#!/usr/bin/env python # Copyright INRA (Institut National de la Recherche Agronomique) # http://www.inra.fr # http://urgi.versailles.inra.fr # # This software is governed by the CeCILL license under French law and # abiding by the rules of distribution of free software. You can use, # modify and/ or redistribute the software under the terms of the CeCILL # license as circulated by CEA, CNRS and INRIA at the following URL # "http://www.cecill.info". # # As a counterpart to the access to the source code and rights to copy, # modify and redistribute granted by the license, users are provided only # with a limited warranty and the software's author, the holder of the # economic rights, and the successive licensors have only limited # liability. # # In this respect, the user's attention is drawn to the risks associated # with loading, using, modifying and/or developing or reproducing the # software by the user in light of its specific status of free software, # that may mean that it is complicated to manipulate, and that also # therefore means that it is reserved for developers and experienced # professionals having in-depth computer knowledge. Users are therefore # encouraged to load and test the software's suitability as regards their # requirements in conditions enabling the security of their systems and/or # data to be ensured and, more generally, to use and operate it in the # same conditions as regards security. # # The fact that you are presently reading this means that you have had # knowledge of the CeCILL license and that you accept its terms. import os import shutil from commons.core.LoggerFactory import LoggerFactory from commons.core.sql.DbFactory import DbFactory from commons.core.sql.TableJobAdaptatorFactory import TableJobAdaptatorFactory from commons.core.launcher.Launcher import Launcher from commons.core.utils.FileUtils import FileUtils from commons.core.utils.RepetOptionParser import RepetOptionParser from commons.core.checker.ConfigChecker import ConfigRules, ConfigChecker from commons.tools.MergeMatchsFiles import MergeMatchsFiles LOG_DEPTH = "repet.tools" ##Launch BLASTER in parallel # class LaunchBlasterInParallel(object): def __init__(self, queryDirectory = "", subjectFilePath = "", outFileName = "", configFileName = "", groupId = "", queryPattern = ".*\.fa", \ doAllByall = False, nbCPU = 1, eValue="1e-300", type = "ncbi", program="blastn", extraParams="", verbosity = 0): self._queryDirectory = queryDirectory self._queryPattern = queryPattern self.setSubjectFilePath(subjectFilePath) self._outFileName = outFileName self._configFileName = configFileName self.setGroupId(groupId) self._doAllByall = doAllByall self._blastType = type self._program = program self._extraParams = extraParams self._nbCPU = nbCPU self._jobSectionName = "jobs" self._blasterSectionName = "alignment" self._prepareDataSectionName = "prepare_data" self._eValue = eValue self._doClean = None self._verbosity = verbosity self._log = LoggerFactory.createLogger("%s.%s" % (LOG_DEPTH, self.__class__.__name__), self._verbosity) def setAttributesFromCmdLine(self): description = "Launch Blaster in parallel." epilog = "\nExample 1: launch without verbosity and keep temporary files.\n" epilog += "\t$ python LaunchBlasterInParallel.py -q query -o query.align -v 0" epilog += "\n\t" epilog += "\nExample 2: launch with verbosity to have errors (level 1) and basic information (level 2), and delete temporary files.\n" epilog += "\t$ python LaunchBlasterInParallel.py -q query -o query.align -s nr.fa -c -v 2" parser = RepetOptionParser(description = description, epilog = epilog) parser.add_option("-q", "--query", dest = "query", action = "store", type = "string", help = "query fasta directory absolute path [compulsory]", default = "") parser.add_option("-s", "--subject", dest = "subject", action = "store", type = "string", help = "subject fasta absolute path [compulsory] [format: fasta]", default = "") parser.add_option("-o", "--out", dest = "outFileName", action = "store", type = "string", help = "output align file name [compulsory] [format: align]", default = "") parser.add_option("-C", "--config", dest = "configFileName",action = "store", type = "string", help = "configuration file name [compulsory] [format: cfg]", default = "") parser.add_option("-g", "--groupId", dest = "groupId", action = "store", type = "string", help = "jobs groupId [default: Blaster_<pid>]", default = "") parser.add_option("-p", "--queryPattern",dest = "queryPattern", action = "store", type = "string", help = "query file pattern [default: .*\.fa]", default = ".*\.fa") parser.add_option("-a", "--aba", dest = "doAllByall", action = "store_true", help = "all-by-all Blast [default: False]", default = False) parser.add_option("-e", "--eValue", dest = "eValue", action = "store", type = "string", help = "Blast e-value [default: 1e300]", default = "1e-300") parser.add_option("-t", "--type", dest = "type", action = "store", type = "string", help = "Blast type [ncbi, wu, blastplus] [default: ncbi]", default = "ncbi") parser.add_option("-u", "--program", dest = "program", action = "store", type = "string", help = "Blast program type [blastn, blastx, blastx] [default: blastn]", default = "blastn") parser.add_option("-x", "--extraParams",dest = "extraParams", action = "store", type = "string", help = "Additional blast program parameters[default: '']", default = "") parser.add_option("-n", "--ncpu", dest = "cpu", action = "store", type = "int", help = "Number of CPUs to use [default: 1]", default = 1) parser.add_option("-v", "--verbosity", dest = "verbosity", action = "store", type = "int", help = "verbosity [default: 1]", default = 1) options = parser.parse_args()[0] self._setAttributesFromOptions(options) def _setAttributesFromOptions(self, options): self.setQueryDirectory(options.query) self.setQueryPattern(options.queryPattern) self.setSubjectFilePath(options.subject) self.setOutFileName(options.outFileName) self.setConfigFileName(options.configFileName) self.setGroupId(options.groupId) self.setDoAllByall(options.doAllByall) self.setEValue(options.eValue) self.setType(options.type) self.setProgram(options.program) self.setExtraParams(options.extraParams) self.setCPU(options.cpu) self.setVerbosity(options.verbosity) def setQueryDirectory(self, queryDirectory): self._queryDirectory = queryDirectory def setQueryPattern(self, queryPattern): self._queryPattern = queryPattern def setSubjectFilePath(self, subjectFilePath): self._subjectFilePath = subjectFilePath self._subjectFileName = os.path.basename(subjectFilePath) def setOutFileName(self, outFileName): self._outFileName = outFileName def setConfigFileName(self, configFileName): self._configFileName = configFileName def setGroupId(self, groupId): if groupId == "": self._groupId = "Blaster_%s" % os.getpid() else: self._groupId = groupId def setDoAllByall(self, doAllByall): self._doAllByall = doAllByall def setType(self, blastType): self._blastType = blastType def setProgram(self, program): self._program = program def setExtraParams(self, extraParams): self._extraParams = extraParams def setEValue(self, eValue): self._eValue = eValue def setCPU(self, cpu): self._nbCPU = cpu def setDoClean(self, doClean): self._doClean = doClean def setVerbosity(self, verbosity): self._verbosity = verbosity def _checkOptions(self): if self._queryPattern == "": self._logAndRaise("ERROR: Missing input fasta file name") def _logAndRaise(self, errorMsg): self._log.error(errorMsg) raise Exception(errorMsg) def _checkConfig(self): iConfigRules = ConfigRules() iConfigRules.addRuleSection(section=self._jobSectionName, mandatory=True) iConfigRules.addRuleOption(section=self._jobSectionName, option ="resources", mandatory=True, type="string") iConfigRules.addRuleOption(section=self._jobSectionName, option ="tmpDir", mandatory=True, type="string") iConfigRules.addRuleOption(section=self._jobSectionName, option ="copy", mandatory=True, type="bool") iConfigRules.addRuleOption(section=self._jobSectionName, option ="clean", mandatory=True, type="bool") iConfigRules.addRuleOption(section=self._blasterSectionName, option ="blast", mandatory=True, type="string", set = ("ncbi", "blastplus", "wu")) iConfigRules.addRuleOption(section=self._blasterSectionName, option ="Evalue", mandatory=True, type="string") iConfigRules.addRuleOption(section=self._blasterSectionName, option ="length", mandatory=True, type="string") iConfigRules.addRuleOption(section=self._blasterSectionName, option ="identity", mandatory=True, type="string") iConfigChecker = ConfigChecker(self._configFileName, iConfigRules) self._iConfig = iConfigChecker.getConfig() self._setAttributesFromConfig() def _setAttributesFromConfig(self): self._chunkLength = self._iConfig.get(self._prepareDataSectionName, "chunk_length") self._chunkOverlap = self._iConfig.get(self._prepareDataSectionName, "chunk_overlap") self._resources = self._iConfig.get(self._jobSectionName, "resources") self._tmpDir = self._iConfig.get(self._jobSectionName, "tmpDir") self._isCopyOnNode = self._iConfig.get(self._jobSectionName, "copy") self._doClean = self._iConfig.get(self._jobSectionName, "clean") self._blastType = self._iConfig.get(self._blasterSectionName, "blast") self._eValue = self._iConfig.get(self._blasterSectionName, "Evalue") self._length = self._iConfig.get(self._blasterSectionName, "length") self._identity = self._iConfig.get(self._blasterSectionName, "identity") if self._isCopyOnNode and not self._tmpDir: self._isCopyOnNode = False self._log.debug("The copy option is: %s." % self._isCopyOnNode) def _getLaunchBlasterCmd(self, iLauncher, file): lArgs = [] lArgs.append("-u %s" % self._program) lArgs.append("-q %s" % file) lArgs.append("-s %s" % self._subjectFileName) if self._doAllByall: lArgs.append("-a") lArgs.append("-e %s" % self._eValue) lArgs.append("-l %s" % self._length) lArgs.append("-d %s" % self._identity) lArgs.append("-t %s" % self._blastType) lArgs.append("-x '%s'" % self._extraParams) if self._doClean: lArgs.append("-c") lArgs.append("-v %i" % (self._verbosity - 1)) return iLauncher.getSystemCommand("LaunchBlaster.py", lArgs) def _getRmvPairAlignInChunkOverlapsCmd(self, iLauncher, inFileName, outFileName): lArgs = [] lArgs.append("-i %s" % inFileName) lArgs.append("-l %s" % self._chunkLength) lArgs.append("-o %s" % self._chunkOverlap) lArgs.append("-m 10") lArgs.append("-O %s" % outFileName) lArgs.append("-v %d" % (self._verbosity - 1)) return iLauncher.getSystemCommand("RmvPairAlignInChunkOverlaps.py", lArgs) def run(self): LoggerFactory.setLevel(self._log, self._verbosity) self._checkConfig() self._checkOptions() self._log.info("START LaunchBlasterInParallel") self._log.debug("Query file name: %s" % self._queryPattern) self._log.debug("Subject file name: %s" % self._subjectFileName) cDir = os.getcwd() if not self._tmpDir: self._tmpDir = cDir acronym = "Blaster" iDb = DbFactory.createInstance() jobdb = TableJobAdaptatorFactory.createInstance(iDb, "jobs") iLauncher = Launcher(jobdb, os.getcwd(), "", "", cDir, self._tmpDir, "jobs", self._resources, self._groupId, acronym, chooseTemplateWithCopy = self._isCopyOnNode) lCmdsTuples = [] fileSize = float(os.path.getsize(self._subjectFilePath) + 5000000) / 1000000000 lCmdSize = [] lCmdCopy = [] if self._isCopyOnNode: lCmdSize.append("fileSize = %f" % fileSize) lCmdCopy.append("shutil.copy(\"%s\", \".\")" % self._subjectFilePath) lFiles = FileUtils.getFileNamesList(self._queryDirectory, self._queryPattern) for file in lFiles: lCmds = [] lCmds.append(self._getLaunchBlasterCmd(iLauncher, file)) lCmdStart = [] if self._isCopyOnNode: lCmdStart.append("os.symlink(\"../%s\", \"%s\")" % (self._subjectFileName, self._subjectFileName)) lCmdStart.append("shutil.copy(\"%s/%s\", \".\")" % (self._queryDirectory, file)) else: lCmdStart.append("os.symlink(\"%s\", \"%s\")" % (self._subjectFilePath, self._subjectFileName)) lCmdStart.append("os.symlink(\"%s/%s\", \"%s\")" % (self._queryDirectory, file, file)) lCmdFinish = [] lCmdFinish.append("if os.path.exists(\"%s.align\"):" % file) lCmdFinish.append("\tshutil.move(\"%s.align\", \"%s/.\" )" % (file, cDir)) lCmdFinish.append("shutil.move(\"%s.param\", \"%s/.\" )" % (file, cDir)) lCmdsTuples.append(iLauncher.prepareCommands_withoutIndentation(lCmds, lCmdStart, lCmdFinish, lCmdSize, lCmdCopy)) iLauncher.runLauncherForMultipleJobs("Blaster", lCmdsTuples, self._doClean, self._isCopyOnNode) tmpFileName = "tmp_%s.align" % os.getpid() iMMF = MergeMatchsFiles("align", "tmp_%s" % os.getpid(), allByAll = self._doAllByall, clean = self._doClean) iMMF.run() if self._doAllByall: iDb = DbFactory.createInstance() jobdb = TableJobAdaptatorFactory.createInstance(iDb, "jobs") iLauncher = Launcher(jobdb, os.getcwd(), "", "", cDir, self._tmpDir, "jobs", self._resources, "%s_RmvPairAlignInChunkOverlaps" % self._groupId) lCmdsTuples = [] lCmds = [] lCmds.append(self._getRmvPairAlignInChunkOverlapsCmd(iLauncher, tmpFileName, self._outFileName)) lCmdStart = [] lCmdStart.append("os.symlink(\"%s/%s\", \"%s\")" % (cDir, tmpFileName, tmpFileName)) lCmdFinish = [] lCmdFinish.append("shutil.move(\"%s\", \"%s/.\")" % (self._outFileName, cDir)) lCmdsTuples.append(iLauncher.prepareCommands_withoutIndentation(lCmds, lCmdStart, lCmdFinish)) iLauncher.runLauncherForMultipleJobs("RmvPairAlignInChunkOverlaps", lCmdsTuples, self._doClean) if self._doClean: os.remove(tmpFileName) else: shutil.move(tmpFileName, self._outFileName) if self._doClean: FileUtils.removeFilesByPattern("*.param") self._log.info("END LaunchBlasterInParallel") if __name__ == "__main__": iLaunch = LaunchBlasterInParallel() iLaunch.setAttributesFromCmdLine() iLaunch.run()