示例#1
0
def LUTE_train(confEcalc,
               emat,
               pmat,
               maxRMSE=0.1,
               maxOverfittingScore=1.5,
               randomSeed=12345,
               confDBPath=None):
    '''
	Trains a LUTE model

	For examples using LUTE, see examples/python.GMEC/LUTE.*.py and examples/python.KStar/LUTE.*.py in your Osprey distribution.

	:param confEcalc: The conformation energy calculator
	:type confEcalc: :java:ref:`.energy.ConfEnergyCalculator`
	:param emat: An energy matrix
	:type emat: :java:ref:`.ematrix.EnergyMatrix`
	:param pmat: A pruning matrix, resulting from DEE
	:type pmat: :java:ref:`.pruning.PruningMatrix`

	:param float maxRMSE: The maximum tolerable fit RMS error
	:param float maxOverfittingScore: The maximum tolerable amount of overfitting (score = training set RMSE / test set RMSE)
	:param int randomSeed: Random seed to use for conformation sampling
	:param str confDBPath: Path to write/read confDB file, or None to omit saving the confDB to disk

	:returns: The LUTE model
	:rtype: :java:ref:`.lute.LUTEState`
	'''

    confSpace = confEcalc.confSpace

    # make a conf DB, saved to a file if needed
    if confDBPath is None:
        confDB = c.confspace.ConfDB(confSpace)
    else:
        confDB = c.confspace.ConfDB(confSpace, jvm.toFile(confDBPath))

    try:

        # make a conf table for LUTE
        confTable = jvm.getInnerClass(c.confspace.ConfDB, 'ConfTable')(confDB,
                                                                       'LUTE')

        # use the OLSCG fitter for LUTE (it's a little faster than LASSO in practice)
        fitter = jvm.getInnerClass(c.lute.LUTE, 'Fitter').OLSCG

        # train LUTE
        lute = c.lute.LUTE(confSpace)
        sampler = c.lute.UniformConfSampler(confSpace, pmat, randomSeed)
        lute.sampleTuplesAndFit(confEcalc, emat, pmat, confTable, sampler,
                                fitter, maxOverfittingScore, maxRMSE)
        lute.reportConfSpaceSize(pmat)

        # return the LUTE fit
        return c.lute.LUTEState(lute.getTrainingSystem())

    finally:
        confDB.close()
示例#2
0
def MSKStar_LMFE(weightsByState,
                 offset=useJavaDefault,
                 constrainLessThan=None):
    '''
	:java:classdoc:`.kstar.MSKStar$LMFE`

	:param weightsByState: map from states to weights
	:type weightsByState: map from :java:ref:`.kstar.MSKStar$State` to float

	:builder_option offset .kstar.MSKStar$LMFE$Builder#offset:
	:param float constrainLessThan: :java:methoddoc:`.kstar.MSKStar$LMFE$Builder#constrainLessThan`
	:builder_return .kstar.MSKStar$LMFE$Builder:
	'''

    builder = _get_builder(jvm.getInnerClass(c.kstar.MSKStar, 'LMFE'))()

    if offset is not useJavaDefault:
        builder.setOffset(offset)

    for (state, weight) in weightsByState.items():
        builder.addState(state, weight)

    if constrainLessThan is not None:
        builder.constrainLessThan(constrainLessThan)

    return builder.build()
示例#3
0
def wrapStrandBuilder(c):
	jtype = jvm.getInnerClass(c.confspace.Strand, 'Builder')

	# public Builder setResidues(int firstResNum, int lastResNum) {
	def newSetResidues(old, self, start, stop):

		# TEMP: check for integer-valued residue numbers, which are now deprecated
		checkDeprecatedResNumbers([start, stop], ['checkDeprecatedResNumbers', 'newSetResidues', 'curried', 'Strand'])

		old(self, start, stop)
	wrapMethod(jtype, 'setResidues', newSetResidues)
示例#4
0
def KStar(proteinConfSpace,
          ligandConfSpace,
          complexConfSpace,
          epsilon=useJavaDefault,
          stabilityThreshold=useJavaDefault,
          maxSimultaneousMutations=useJavaDefault,
          writeSequencesToConsole=False,
          writeSequencesToFile=None,
          useExternalMemory=useJavaDefault,
          showPfuncProgress=useJavaDefault):
    '''
	:java:classdoc:`.kstar.KStar`

	For examples using K*, see the examples/python.KStar directory in your Osprey distribution.

	:param proteinConfSpace: :java:fielddoc:`.kstar.KStar#protein`
	:type proteinConfSpace: :java:ref:`.confspace.SimpleConfSpace`
	:param ligandConfSpace: :java:fielddoc:`.kstar.KStar#ligand`
	:type ligandConfSpace: :java:ref:`.confspace.SimpleConfSpace`
	:param complexConfSpace: :java:fielddoc:`.kstar.KStar#complex`
	:type complexConfSpace: :java:ref:`.confspace.SimpleConfSpace`
	:builder_option epsilon .kstar.KStar$Settings$Builder#epsilon:
	:builder_option stabilityThreshold .kstar.KStar$Settings$Builder#stabilityThreshold:
	:builder_option maxSimultaneousMutations .kstar.KStar$Settings$Builder#maxSimultaneousMutations:
	:builder_option useExternalMemory .kstar.KStar$Settings$Builder#useExternalMemory:
	:builder_option showPfuncProgress .kstar.KStar$Settings$Builder#showPfuncProgress:
	:param bool writeSequencesToConsole: True to write sequences and scores to the console
	:param str writeSequencesToFile: Path to the log file to write sequences scores (in TSV format), or None to skip logging

	:rtype: :java:ref:`.kstar.KStar`
	'''

    # build settings
    settingsBuilder = _get_builder(jvm.getInnerClass(c.kstar.KStar,
                                                     'Settings'))()
    if epsilon is not useJavaDefault:
        settingsBuilder.setEpsilon(epsilon)
    if stabilityThreshold is not useJavaDefault:
        settingsBuilder.setStabilityThreshold(
            jvm.boxDouble(stabilityThreshold))
    if maxSimultaneousMutations is not useJavaDefault:
        settingsBuilder.setMaxSimultaneousMutations(maxSimultaneousMutations)
    if writeSequencesToConsole:
        settingsBuilder.addScoreConsoleWriter()
    if writeSequencesToFile is not None:
        settingsBuilder.addScoreFileWriter(jvm.toFile(writeSequencesToFile))
    if useExternalMemory is not useJavaDefault:
        settingsBuilder.setExternalMemory(useExternalMemory)
    if showPfuncProgress is not useJavaDefault:
        settingsBuilder.setShowPfuncProgress(showPfuncProgress)
    settings = settingsBuilder.build()

    return c.kstar.KStar(proteinConfSpace, ligandConfSpace, complexConfSpace,
                         settings)
示例#5
0
def wrapStrandFlex(c):
	jtype = jvm.getInnerClass(c.confspace.Strand, 'Flexibility')

	# use array access to call get()
	def getItem(self, key):

		# TEMP: check for integer-valued residue numbers, which are now deprecated
		checkDeprecatedResNumbers([key], ['checkDeprecatedResNumbers', 'getItem'])

		return self.get(key)
	jtype.__getitem__ = getItem
示例#6
0
def COMETS_State(name, confSpace):
    '''
	:java:classdoc:`.gmec.Comets$State`

	:param str name: :java:fielddoc:`.gmec.Comets$State#name`
	:param confSpace: :java:fielddoc:`.gmec.Comets$State#confSpace`
	:type confSpace: :java:ref:`.confspace.SimpleConfSpace`

	:rtype: :java:ref:`.gmec.Comets$State`
	'''

    return jvm.getInnerClass(c.gmec.Comets, 'State')(name, confSpace)
示例#7
0
def MSKStar_State(name, confSpace):
    '''
	:java:classdoc:`.kstar.MSKStar$State`

	:param str name: :java:fielddoc:`.kstar.MSKStar$State#name`
	:param confSpace: :java:fielddoc:`.kstar.MSKStar$State#confSpace`
	:type confSpace: :java:ref:`.confspace.SimpleConfSpace`

	:rtype: :java:ref:`.kstar.MSKStar$State`
	'''

    return jvm.getInnerClass(c.kstar.MSKStar, 'State')(name, confSpace)
示例#8
0
文件: wraps.py 项目: plin1112/OSPREY3
def wrapStrandFlex(c):
    jtype = jvm.getInnerClass(c.confspace.Strand, 'Flexibility')

    # use array access to call get()
    def getItem(self, key):

        # TEMP: check for integer-valued residue numbers, which are now deprecated
        checkDeprecatedResNumbers([key],
                                  ['checkDeprecatedResNumbers', 'getItem'])

        return self.get(key)

    jtype.__getitem__ = getItem
示例#9
0
文件: wraps.py 项目: plin1112/OSPREY3
def wrapStrandBuilder(c):
    jtype = jvm.getInnerClass(c.confspace.Strand, 'Builder')

    # public Builder setResidues(int firstResNum, int lastResNum) {
    def newSetResidues(old, self, start, stop):

        # TEMP: check for integer-valued residue numbers, which are now deprecated
        checkDeprecatedResNumbers([start, stop], [
            'checkDeprecatedResNumbers', 'newSetResidues', 'curried', 'Strand'
        ])

        old(self, start, stop)

    wrapMethod(jtype, 'setResidues', newSetResidues)
示例#10
0
def wrapResidueFlex(c):
	jtype = jvm.getInnerClass(c.confspace.Strand, 'ResidueFlex')

	# wrap setLibraryRotamers() to accept varargs
	def newSetLibraryRotamers(old, self, *mutations):
		return old(self, mutations)
	wrapMethod(jtype, 'setLibraryRotamers', newSetLibraryRotamers)

	# autocast setContinuous() to float
	def newSetContinuous(old, self, angle=None):
		if angle is None:
			return old(self)
		else:
			return old(self, float(angle))
	wrapMethod(jtype, 'setContinuous', newSetContinuous)
示例#11
0
def SharedEnergyCalculator(ecalc, isMinimizing=None):
    '''
	:java:classdoc:`.energy.EnergyCalculator$SharedBuilder`

	:param ecalc: The existing energy calculator with which to share resources
	:type ecalc: :java:ref:`.energy.EnergyCalculator`
	:builder_option isMinimizing .energy.EnergyCalculator$Builder#isMinimizing:
	:builder_return .energy.EnergyCalculator$SharedBuilder:
	'''
    builder = jvm.getInnerClass(c.energy.EnergyCalculator,
                                'SharedBuilder')(ecalc)

    if isMinimizing is not None:
        builder.setIsMinimizing(isMinimizing)

    return builder.build()
示例#12
0
文件: wraps.py 项目: plin1112/OSPREY3
def wrapResidueFlex(c):
    jtype = jvm.getInnerClass(c.confspace.Strand, 'ResidueFlex')

    # wrap setLibraryRotamers() to accept varargs
    def newSetLibraryRotamers(old, self, *mutations):
        return old(self, mutations)

    wrapMethod(jtype, 'setLibraryRotamers', newSetLibraryRotamers)

    # autocast setContinuous() to float
    def newSetContinuous(old, self, angle=None):
        if angle is None:
            return old(self)
        else:
            return old(self, float(angle))

    wrapMethod(jtype, 'setContinuous', newSetContinuous)
示例#13
0
def writePdb(mol, path, comment=None):
    '''
	save a molecule to a PDB file

	:param mol: the molecule to save
	:type mol: :java:ref:`.structure.Molecule`
	:param str path: path of the PDB file
	:param str comment: Optional comment to add to the PDB file headers
	'''

    # deal with different molecule types
    if isinstance(
            mol,
            jvm.getInnerClass(c.energy.EnergyCalculator,
                              'EnergiedParametricMolecule')):
        c.structure.PDBIO.writeFile(mol, comment, path)
    elif isinstance(mol, c.confspace.ParametricMolecule):
        c.structure.PDBIO.writeFile(mol.mol, comment, None, path)
    else:
        c.structure.PDBIO.writeFile(mol, path)

    print('write PDB file to file: %s' % path)
示例#14
0
def _KStarConfSearchFactory(func):

    # convert the python lambda to a JVM interface implementation
    return jpype.JProxy(jvm.getInnerClass(c.kstar.KStar, 'ConfSearchFactory'),
                        dict={'make': func})
示例#15
0
def start(heapSizeMiB=1024,
          enableAssertions=False,
          stackSizeMiB=16,
          garbageSizeMiB=128):
    '''
	Starts the Java Virtual Machine (JVM) that runs Osprey's computation libraries.

	Call :meth:`start` before using any of Osprey's other functions.

	:param int heapSizeMiB: Size of the JVM heap in megabytes. This is essentially the amount of memory
		Osprey will have to do computations. 1024 MiB is 1 GiB, but for larger designs,
		you may want to use 2048 MiB (2 GiB), 4096 MiB (4 GiB), or even more memory.
	
	:param bool enableAssertions: pass ``True`` to enable JVM assertions. Only useful for debugging.

	:param int stackSizeMiB: Size of the JVM stack portion of the heap in megabytes.
		Generally leave this at the default value, unless Osprey crashes because it's too small. Then try increasing it.

	:param int garbageSizeMiB: Size of the garbage portion of the JVM heap that is reserved for temporary objects.
		This default value is appropriate for the default heap size, but if using larger heap sizes, then increasing
		the garbage size to 256, 512, or even 1024 MiB can give a modest improvement in performance.
	'''

    # disable buffered output on stdout, so python log messages line up with java log messages
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

    # setup a global exception handler to show java exception info
    sys.excepthook = _java_aware_excepthook

    # is this the real life, or is this just fantasy?
    lib_dir = os.path.join(os.path.dirname(__file__), 'lib')
    no_escape_from_reality = os.path.exists(lib_dir)

    # build jvm classpath
    if no_escape_from_reality:

        # release environment: use jars in lib folder
        for file in os.listdir(lib_dir):
            jvm.addClasspath(os.path.join(lib_dir, file))

    else:

        # development environment: use the gradle-defined classpath
        osprey_dir = os.path.join(os.path.dirname(__file__), '../../')
        classpath_path = os.path.join(osprey_dir, 'build/python/classpath.txt')
        if not os.path.isfile(classpath_path):
            raise Exception(
                'dev classpath for python not generated yet. run ./gradlew pythonDevelop'
            )

        for path in open(classpath_path, 'r').readlines():
            jvm.addClasspath(path.strip())

    # start the jvm
    jvm.start(heapSizeMiB, enableAssertions, stackSizeMiB, garbageSizeMiB)

    # set up class factories
    global c
    c = jpype.JPackage('edu.duke.cs.osprey')

    wraps.init(c)

    # init other globals
    global WILD_TYPE
    WILD_TYPE = c.confspace.Strand.WildType
    global Forcefield
    Forcefield = jvm.getInnerClass(c.energy.forcefield.ForcefieldParams,
                                   'Forcefield')
    global SolvationForcefield
    SolvationForcefield = jvm.getInnerClass(
        c.energy.forcefield.ForcefieldParams, 'SolvationForcefield')
    global EnergyPartition
    EnergyPartition = c.energy.EnergyPartition
    global ExternalMemory
    ExternalMemory = c.externalMemory.ExternalMemory
    global ConfSpaceType
    ConfSpaceType = jvm.getInnerClass(c.kstar.KStar, 'ConfSpaceType')
    global BreakdownType
    BreakdownType = jvm.getInnerClass(c.energy.ResidueForcefieldBreakdown,
                                      'Type')

    # expose static builder methods too
    Parallelism.makeCpu = c.parallelism.Parallelism.makeCpu
    Parallelism.make = c.parallelism.Parallelism.make

    # print the preamble
    print("OSPREY %s" % c.control.Main.Version)
示例#16
0
def _get_builder(jclass, builder_name='Builder'):
    return jvm.getInnerClass(jclass, builder_name)
示例#17
0
def EwakstarDoer_State(name, confSpace):

    return jvm.getInnerClass(c.ewakstar.EwakstarDoer, 'State')(name, confSpace)