コード例 #1
0
ファイル: test_repex.py プロジェクト: GerardBCN/yank
def notest_hamiltonian_exchange(mpicomm=None, verbose=True):
    """
    Test that free energies and average potential energies of a 3D harmonic oscillator are correctly computed when running HamiltonianExchange.

    TODO

    * Integrate with test_replica_exchange.
    * Test with different combinations of input parameters.

    """

    if verbose and ((not mpicomm) or (mpicomm.rank==0)): sys.stdout.write("Testing Hamiltonian exchange facility with harmonic oscillators: ")

    # Create test system of harmonic oscillators
    testsystem = testsystems.HarmonicOscillatorArray()
    [system, coordinates] = [testsystem.system, testsystem.positions]

    # Define mass of carbon atom.
    mass = 12.0 * units.amu

    # Define thermodynamic states.
    sigmas = [0.2, 0.3, 0.4] * units.angstroms # standard deviations: beta K = 1/sigma^2 so K = 1/(beta sigma^2)
    temperature = 300.0 * units.kelvin # temperatures
    seed_positions = list()
    analytical_results = list()
    f_i_analytical = list() # dimensionless free energies
    u_i_analytical = list() # reduced potential
    systems = list() # Systems list for HamiltonianExchange
    for sigma in sigmas:
        # Compute corresponding spring constant.
        kB = units.BOLTZMANN_CONSTANT_kB * units.AVOGADRO_CONSTANT_NA
        kT = kB * temperature # thermal energy
        beta = 1.0 / kT # inverse temperature
        K = 1.0 / (beta * sigma**2)
        # Create harmonic oscillator system.
        testsystem = testsystems.HarmonicOscillator(K=K, mass=mass, mm=openmm)
        [system, positions] = [testsystem.system, testsystem.positions]
        # Append to systems list.
        systems.append(system)
        # Append positions.
        seed_positions.append(positions)
        # Store analytical results.
        results = computeHarmonicOscillatorExpectations(K, mass, temperature)
        analytical_results.append(results)
        f_i_analytical.append(results['f'])
        reduced_potential = results['potential']['mean'] / kT
        u_i_analytical.append(reduced_potential)

    # DEBUG
    print("")
    print(seed_positions)
    print(analytical_results)
    print(u_i_analytical)
    print(f_i_analytical)
    print("")

    # Compute analytical Delta_f_ij
    nstates = len(f_i_analytical)
    f_i_analytical = numpy.array(f_i_analytical)
    u_i_analytical = numpy.array(u_i_analytical)
    s_i_analytical = u_i_analytical - f_i_analytical
    Delta_f_ij_analytical = numpy.zeros([nstates,nstates], numpy.float64)
    Delta_u_ij_analytical = numpy.zeros([nstates,nstates], numpy.float64)
    Delta_s_ij_analytical = numpy.zeros([nstates,nstates], numpy.float64)
    for i in range(nstates):
        for j in range(nstates):
            Delta_f_ij_analytical[i,j] = f_i_analytical[j] - f_i_analytical[i]
            Delta_u_ij_analytical[i,j] = u_i_analytical[j] - u_i_analytical[i]
            Delta_s_ij_analytical[i,j] = s_i_analytical[j] - s_i_analytical[i]

    # Define file for temporary storage.
    import tempfile # use a temporary file
    file = tempfile.NamedTemporaryFile(delete=False)
    store_filename = file.name
    #print("Storing data in temporary file: %s" % str(store_filename))

    # Create reference thermodynamic state.
    reference_state = ThermodynamicState(systems[0], temperature=temperature)

    # Create and configure simulation object.
    simulation = HamiltonianExchange(store_filename, mpicomm=mpicomm)
    simulation.create(reference_state, systems, seed_positions)
    simulation.platform = openmm.Platform.getPlatformByName('Reference')
    simulation.number_of_iterations = 200
    simulation.timestep = 2.0 * units.femtoseconds
    simulation.nsteps_per_iteration = 500
    simulation.collision_rate = 9.2 / units.picosecond
    simulation.verbose = False
    simulation.show_mixing_statistics = False

    # Run simulation.
    utils.config_root_logger(True)
    simulation.run() # run the simulation
    utils.config_root_logger(False)

    # Stop here if not root node.
    if mpicomm and (mpicomm.rank != 0): return

    # Analyze simulation to compute free energies.
    analysis = simulation.analyze()

    # TODO: Check if deviations exceed tolerance.
    Delta_f_ij = analysis['Delta_f_ij']
    dDelta_f_ij = analysis['dDelta_f_ij']
    error = Delta_f_ij - Delta_f_ij_analytical
    indices = numpy.where(dDelta_f_ij > 0.0)
    nsigma = numpy.zeros([nstates,nstates], numpy.float32)
    nsigma[indices] = error[indices] / dDelta_f_ij[indices]
    MAX_SIGMA = 6.0 # maximum allowed number of standard errors
    if numpy.any(nsigma > MAX_SIGMA):
        print("Delta_f_ij")
        print(Delta_f_ij)
        print("Delta_f_ij_analytical")
        print(Delta_f_ij_analytical)
        print("error")
        print(error)
        print("stderr")
        print(dDelta_f_ij)
        print("nsigma")
        print(nsigma)
        raise Exception("Dimensionless free energy difference exceeds MAX_SIGMA of %.1f" % MAX_SIGMA)

    error = analysis['Delta_u_ij'] - Delta_u_ij_analytical
    nsigma = numpy.zeros([nstates,nstates], numpy.float32)
    nsigma[indices] = error[indices] / dDelta_f_ij[indices]
    if numpy.any(nsigma > MAX_SIGMA):
        print("Delta_u_ij")
        print(analysis['Delta_u_ij'])
        print("Delta_u_ij_analytical")
        print(Delta_u_ij_analytical)
        print("error")
        print(error)
        print("nsigma")
        print(nsigma)
        raise Exception("Dimensionless potential energy difference exceeds MAX_SIGMA of %.1f" % MAX_SIGMA)

    if verbose: print("PASSED.")
    return
コード例 #2
0
from openmmtools.mcmc import *

# =============================================================================
# GLOBAL TEST CONSTANTS
# =============================================================================

# Test various combinations of systems and MCMC schemes
analytical_testsystems = [
    ("HarmonicOscillator", testsystems.HarmonicOscillator(),
     GHMCMove(timestep=10.0 * unit.femtoseconds, n_steps=100)),
    ("HarmonicOscillator", testsystems.HarmonicOscillator(),
     WeightedMove([(GHMCMove(timestep=10.0 * unit.femtoseconds,
                             n_steps=100), 0.5),
                   (HMCMove(timestep=10 * unit.femtosecond,
                            n_steps=10), 0.5)])),
    ("HarmonicOscillatorArray", testsystems.HarmonicOscillatorArray(N=4),
     LangevinDynamicsMove(timestep=10.0 * unit.femtoseconds, n_steps=100)),
    ("IdealGas", testsystems.IdealGas(nparticles=216),
     SequenceMove([
         HMCMove(timestep=10 * unit.femtosecond, n_steps=10),
         MonteCarloBarostatMove()
     ]))
]

NSIGMA_CUTOFF = 6.0  # cutoff for significance testing

debug = True  # set to True only for manual debugging of this nose test

# =============================================================================
# TEST FUNCTIONS
# =============================================================================
コード例 #3
0
def load(sysname):
    cutoff = 0.9 * u.nanometers
    temperature = 300. * u.kelvin
    langevin_timestep = 0.5 * u.femtoseconds
    timestep = 2 * u.femtoseconds
    equil_steps = 40000
    groups = [(0, 1)]
    steps_per_hmc = 25

    if sysname == "chargedljbox":
        testsystem, system, positions, timestep, langevin_timestep = load_lj(
            charge=0.15 * u.elementary_charge)

    if sysname == "chargedswitchedljbox":
        testsystem, system, positions, timestep, langevin_timestep = load_lj(
            charge=0.15 * u.elementary_charge,
            switch_width=0.34 * u.nanometers)

    if sysname == "chargedlongljbox":
        testsystem, system, positions, timestep, langevin_timestep = load_lj(
            cutoff=1.333 * u.nanometers, charge=0.15 * u.elementary_charge)

    if sysname == "chargedswitchedlongljbox":
        testsystem, system, positions, timestep, langevin_timestep = load_lj(
            cutoff=1.333 * u.nanometers,
            charge=0.15 * u.elementary_charge,
            switch_width=0.34 * u.nanometers)

    if sysname == "chargedswitchedaccuratelongljbox":
        testsystem, system, positions, timestep, langevin_timestep = load_lj(
            cutoff=1.333 * u.nanometers,
            charge=0.15 * u.elementary_charge,
            switch_width=0.34 * u.nanometers,
            ewaldErrorTolerance=5E-5)

    if sysname == "chargedswitchedaccurateljbox":
        testsystem, system, positions, timestep, langevin_timestep = load_lj(
            charge=0.15 * u.elementary_charge,
            switch_width=0.34 * u.nanometers,
            ewaldErrorTolerance=5E-5)

    if sysname == "ljbox":
        testsystem, system, positions, timestep, langevin_timestep = load_lj()

    if sysname == "longljbox":
        testsystem, system, positions, timestep, langevin_timestep = load_lj(
            cutoff=1.333 * u.nanometers)

    if sysname == "shortljbox":
        testsystem, system, positions, timestep, langevin_timestep = load_lj(
            cutoff=0.90 * u.nanometers)

    if sysname == "shiftedljbox":
        testsystem, system, positions, timestep, langevin_timestep = load_lj(
            shift=True)

    if sysname == "switchedljbox":
        testsystem, system, positions, timestep, langevin_timestep = load_lj(
            switch_width=0.34 * u.nanometers)

    if sysname == "switchedshortljbox":
        testsystem, system, positions, timestep, langevin_timestep = load_lj(
            cutoff=0.90 * u.nanometers, switch_width=0.34 * u.nanometers)

    if sysname == "cluster":
        testsystem = testsystems.LennardJonesCluster(nx=8, ny=8, nz=8)
        system, positions = testsystem.system, testsystem.positions
        hmc_integrators.guess_force_groups(system, nonbonded=0)
        groups = [(0, 1)]
        temperature = 25. * u.kelvin
        timestep = 40 * u.femtoseconds

    if sysname == "shortbigcluster":
        testsystem = testsystems.LennardJonesCluster(nx=20,
                                                     ny=20,
                                                     nz=20,
                                                     cutoff=0.75 *
                                                     u.nanometers)
        system, positions = testsystem.system, testsystem.positions
        hmc_integrators.guess_force_groups(system, nonbonded=0)
        groups = [(0, 1)]
        temperature = 25. * u.kelvin
        timestep = 10 * u.femtoseconds

    if sysname == "switchedshortbigcluster":
        testsystem = testsystems.LennardJonesCluster(
            nx=20,
            ny=20,
            nz=20,
            cutoff=0.75 * u.nanometers,
            switch_width=0.1 * u.nanometers)
        system, positions = testsystem.system, testsystem.positions
        hmc_integrators.guess_force_groups(system, nonbonded=0)
        groups = [(0, 1)]
        temperature = 25. * u.kelvin
        timestep = 10 * u.femtoseconds

    if sysname == "bigcluster":
        testsystem = testsystems.LennardJonesCluster(nx=20,
                                                     ny=20,
                                                     nz=20,
                                                     cutoff=1.25 *
                                                     u.nanometers)
        system, positions = testsystem.system, testsystem.positions
        hmc_integrators.guess_force_groups(system, nonbonded=0)
        groups = [(0, 1)]
        temperature = 25. * u.kelvin
        timestep = 10 * u.femtoseconds

    if sysname == "shortcluster":
        testsystem = testsystems.LennardJonesCluster(nx=8,
                                                     ny=8,
                                                     nz=8,
                                                     cutoff=0.75 *
                                                     u.nanometers)
        system, positions = testsystem.system, testsystem.positions
        hmc_integrators.guess_force_groups(system, nonbonded=0)
        groups = [(0, 1)]
        temperature = 25. * u.kelvin
        timestep = 40 * u.femtoseconds

    if sysname == "shortwater":
        testsystem = testsystems.WaterBox(
            box_edge=3.18 * u.nanometers,
            cutoff=0.9 * u.nanometers,
            switch_width=None)  # Around 1060 molecules of water
        system, positions = testsystem.system, testsystem.positions

    if sysname == "shortswitchedwater":
        testsystem = testsystems.WaterBox(
            box_edge=3.18 * u.nanometers,
            cutoff=0.9 * u.nanometers,
            switch_width=3.0 * u.angstroms)  # Around 1060 molecules of water
        system, positions = testsystem.system, testsystem.positions

    if sysname == "water":
        testsystem = testsystems.WaterBox(
            box_edge=3.18 * u.nanometers,
            cutoff=1.1 * u.nanometers,
            switch_width=None)  # Around 1060 molecules of water
        system, positions = testsystem.system, testsystem.positions

    if sysname == "switchedwater":
        testsystem = testsystems.WaterBox(
            box_edge=3.18 * u.nanometers,
            cutoff=1.1 * u.nanometers,
            switch_width=3.0 * u.angstroms)  # Around 1060 molecules of water
        system, positions = testsystem.system, testsystem.positions

    if sysname == "switchedaccuratewater":
        testsystem = testsystems.WaterBox(
            box_edge=3.18 * u.nanometers,
            cutoff=1.1 * u.nanometers,
            switch_width=3.0 * u.angstroms,
            ewaldErrorTolerance=5E-5)  # Around 1060 molecules of water
        system, positions = testsystem.system, testsystem.positions
        hmc_integrators.guess_force_groups(
            system, nonbonded=0, fft=1, others=0)  # We may want to try reduce

    if sysname == "switchedaccurateflexiblewater":
        testsystem = testsystems.WaterBox(
            box_edge=3.18 * u.nanometers,
            cutoff=1.1 * u.nanometers,
            switch_width=3.0 * u.angstroms,
            ewaldErrorTolerance=5E-5,
            constrained=False)  # Around 1060 molecules of water
        system, positions = testsystem.system, testsystem.positions
        # Using these groups for hyperopt-optimal RESPA integrators
        #hmc_integrators.guess_force_groups(system, nonbonded=0, others=1, fft=0)
        hmc_integrators.guess_force_groups(system,
                                           nonbonded=1,
                                           others=1,
                                           fft=0)
        equil_steps = 100000
        langevin_timestep = 0.25 * u.femtoseconds

    if sysname == "switchedaccuratebigflexiblewater":
        testsystem = testsystems.WaterBox(
            box_edge=10.0 * u.nanometers,
            cutoff=1.1 * u.nanometers,
            switch_width=3.0 * u.angstroms,
            ewaldErrorTolerance=5E-5,
            constrained=False)  # Around 1060 molecules of water
        system, positions = testsystem.system, testsystem.positions
        # Using these groups for hyperopt-optimal RESPA integrators
        hmc_integrators.guess_force_groups(system,
                                           nonbonded=1,
                                           others=0,
                                           fft=1)
        equil_steps = 100000
        langevin_timestep = 0.1 * u.femtoseconds

    if sysname == "switchedaccuratestiffflexiblewater":

        testsystem = testsystems.WaterBox(
            box_edge=3.18 * u.nanometers,
            cutoff=1.1 * u.nanometers,
            switch_width=3.0 * u.angstroms,
            ewaldErrorTolerance=5E-5,
            constrained=False)  # Around 1060 molecules of water
        system, positions = testsystem.system, testsystem.positions
        # Using these groups for hyperopt-optimal RESPA integrators
        #hmc_integrators.guess_force_groups(system, nonbonded=0, others=1, fft=0)
        hmc_integrators.guess_force_groups(system,
                                           nonbonded=1,
                                           others=1,
                                           fft=0)
        equil_steps = 100000
        langevin_timestep = 0.25 * u.femtoseconds

        FACTOR = 10.0
        # Make bonded terms stiffer to highlight RESPA advantage
        for force in system.getForces():
            if type(force) == mm.HarmonicBondForce:
                for i in range(force.getNumBonds()):
                    (a0, a1, length, strength) = force.getBondParameters(i)
                    force.setBondParameters(i, a0, a1, length,
                                            strength * FACTOR)

            elif type(force) == mm.HarmonicAngleForce:
                for i in range(force.getNumAngles()):
                    (a0, a1, a2, length,
                     strength) = force.getAngleParameters(i)
                    force.setAngleParameters(i, a0, a1, a2, length,
                                             strength * FACTOR)

    if sysname == "switchedaccuratenptwater":
        testsystem = testsystems.WaterBox(
            box_edge=3.18 * u.nanometers,
            cutoff=1.1 * u.nanometers,
            switch_width=3.0 * u.angstroms,
            ewaldErrorTolerance=5E-5)  # Around 1060 molecules of water
        system, positions = testsystem.system, testsystem.positions
        system.addForce(
            mm.MonteCarloBarostat(1.0 * u.atmospheres, temperature, 1))

    if sysname == "longswitchedwater":
        testsystem = testsystems.WaterBox(
            box_edge=3.18 * u.nanometers,
            cutoff=1.5 * u.nanometers,
            switch_width=3.0 * u.angstroms)  # Around 1060 molecules of water
        system, positions = testsystem.system, testsystem.positions

    if sysname == "rfwater":
        testsystem = testsystems.WaterBox(
            box_edge=3.18 * u.nanometers,
            cutoff=1.1 * u.nanometers,
            nonbondedMethod=app.CutoffPeriodic,
            switch_width=None)  # Around 1060 molecules of water
        system, positions = testsystem.system, testsystem.positions

    if sysname == "switchedrfwater":
        testsystem = testsystems.WaterBox(
            box_edge=3.18 * u.nanometers,
            cutoff=1.1 * u.nanometers,
            nonbondedMethod=app.CutoffPeriodic,
            switch_width=3.0 * u.angstroms)  # Around 1060 molecules of water
        system, positions = testsystem.system, testsystem.positions

    if sysname == "longswitchedrfwater":
        testsystem = testsystems.WaterBox(
            box_edge=3.18 * u.nanometers,
            cutoff=1.5 * u.nanometers,
            nonbondedMethod=app.CutoffPeriodic,
            switch_width=3.0 * u.angstroms)  # Around 1060 molecules of water
        system, positions = testsystem.system, testsystem.positions

    if sysname == "density":
        system, positions = load_lb(hydrogenMass=3.0 * u.amu)
        hmc_integrators.guess_force_groups(system,
                                           nonbonded=1,
                                           fft=1,
                                           others=0)
        groups = [(0, 4), (1, 1)]
        timestep = 2.0 * u.femtoseconds

    if sysname == "dhfr":
        testsystem = testsystems.DHFRExplicit(nonbondedCutoff=1.1 *
                                              u.nanometers,
                                              nonbondedMethod=app.PME,
                                              switch_width=2.0 * u.angstroms,
                                              ewaldErrorTolerance=5E-5)
        system, positions = testsystem.system, testsystem.positions
        hmc_integrators.guess_force_groups(system,
                                           nonbonded=1,
                                           fft=2,
                                           others=0)
        groups = [(0, 4), (1, 2), (2, 1)]
        timestep = 0.75 * u.femtoseconds
        equil_steps = 10000

    if sysname == "src":
        testsystem = testsystems.SrcExplicit(nonbondedCutoff=1.1 *
                                             u.nanometers,
                                             nonbondedMethod=app.PME,
                                             switch_width=2.0 * u.angstroms,
                                             ewaldErrorTolerance=5E-5)
        system, positions = testsystem.system, testsystem.positions
        hmc_integrators.guess_force_groups(system,
                                           nonbonded=1,
                                           fft=1,
                                           others=0)
        groups = [(0, 2), (1, 1)]
        timestep = 0.25 * u.femtoseconds
        equil_steps = 1000

    if sysname == "ho":
        K = 90.0 * u.kilocalories_per_mole / u.angstroms**2
        mass = 39.948 * u.amu
        timestep = np.sqrt(mass / K) * 0.4
        testsystem = testsystems.HarmonicOscillatorArray()
        system, positions = testsystem.system, testsystem.positions
        groups = [(0, 1)]

    if sysname == "customho":
        timestep = 1000.0 * u.femtoseconds
        testsystem = testsystems.CustomExternalForcesTestSystem()
        system, positions = testsystem.system, testsystem.positions
        groups = [(0, 1)]

    if sysname == "customsplitho":
        timestep = 1000.0 * u.femtoseconds
        energy_expressions = ("0.75 * (x^2 + y^2 + z^2)",
                              "0.25 * (x^2 + y^2 + z^2)")
        testsystem = testsystems.CustomExternalForcesTestSystem(
            energy_expressions=energy_expressions)
        system, positions = testsystem.system, testsystem.positions
        groups = [(0, 2), (1, 1)]

    if sysname == "alanine":
        testsystem = testsystems.AlanineDipeptideImplicit()
        system, positions = testsystem.system, testsystem.positions
        groups = [(0, 2), (1, 1)]
        timestep = 2.0 * u.femtoseconds
        hmc_integrators.guess_force_groups(system, nonbonded=1, others=0)
        #remove_cmm(system)  # Unrolled shouldn't need this
        equil_steps = 10000

    if sysname == "alanineexplicit":
        testsystem = testsystems.AlanineDipeptideExplicit(
            cutoff=1.1 * u.nanometers,
            switch_width=2 * u.angstrom,
            ewaldErrorTolerance=5E-5)
        system, positions = testsystem.system, testsystem.positions
        #groups = [(0, 2), (1, 1), (2, 1)]
        #groups = [(0, 2), (1, 1)]
        timestep = 1.0 * u.femtoseconds
        #hmc_integrators.guess_force_groups(system, nonbonded=1, others=0, fft=2)
        #hmc_integrators.guess_force_groups(system, nonbonded=0, others=0, fft=1)
        groups = [(0, 1), (1, 2)]
        hmc_integrators.guess_force_groups(system,
                                           nonbonded=0,
                                           others=1,
                                           fft=0)

        #remove_cmm(system)  # Unrolled doesn't need this
        equil_steps = 4000

    # guess force groups

    if "ljbox" in sysname:
        timestep = 25 * u.femtoseconds
        temperature = 25. * u.kelvin
        system, positions = testsystem.system, testsystem.positions
        hmc_integrators.guess_force_groups(system, nonbonded=0, fft=1)
        groups = [(0, 2), (1, 1)]
        equil_steps = 10000
        steps_per_hmc = 15

    if sysname == "amoeba":
        testsystem = testsystems.AMOEBAIonBox()
        system, positions = testsystem.system, testsystem.positions
        hmc_integrators.guess_force_groups(system,
                                           nonbonded=0,
                                           fft=1,
                                           others=0)

    return system, positions, groups, temperature, timestep, langevin_timestep, testsystem, equil_steps, steps_per_hmc
コード例 #4
0
ファイル: test_mcmc.py プロジェクト: jchodera/openmmmcmc
import simtk.unit as units

import openmmtools.testsystems
from openmmtools import testsystems

from pymbar import timeseries
from functools import partial

from openmmmcmc.mcmc import HMCMove, GHMCMove, LangevinDynamicsMove, MonteCarloBarostatMove
import logging

# Test various combinations of systems and MCMC schemes
analytical_testsystems = [
    ("HarmonicOscillator", testsystems.HarmonicOscillator(), [ GHMCMove(timestep=10.0*units.femtoseconds,nsteps=100) ]),
    ("HarmonicOscillator", testsystems.HarmonicOscillator(), { GHMCMove(timestep=10.0*units.femtoseconds,nsteps=100) : 0.5, HMCMove(timestep=10*units.femtosecond, nsteps=10) : 0.5 }),
    ("HarmonicOscillatorArray", testsystems.HarmonicOscillatorArray(N=4), [ LangevinDynamicsMove(timestep=10.0*units.femtoseconds,nsteps=100) ]),
    ("IdealGas", testsystems.IdealGas(nparticles=216), [ HMCMove(timestep=10*units.femtosecond, nsteps=10), MonteCarloBarostatMove() ])
    ]

NSIGMA_CUTOFF = 6.0 # cutoff for significance testing

debug = False # set to True only for manual debugging of this nose test

def test_minimizer_all_testsystems():
    #testsystem_classes = testsystems.TestSystem.__subclasses__()
    testsystem_classes = [ testsystems.AlanineDipeptideVacuum ]

    for testsystem_class in testsystem_classes:
        class_name = testsystem_class.__name__
        logging.info("Testing minimization with testsystem %s" % class_name)