Exemple #1
0
    def test_protocol_work_accumulation_waterbox_barostat(self):
        """
        Testing protocol work accumulation for ExternalPerturbationLangevinIntegrator with AlchemicalWaterBox
        with an active barostat. For brevity, only using CutoffPeriodic as the non-bonded method.
        """
        from simtk.openmm import app

        parameter_name = "lambda_electrostatics"
        parameter_initial = 1.0
        parameter_final = 0.0
        platform_names = [
            openmm.Platform.getPlatform(index).getName()
            for index in range(openmm.Platform.getNumPlatforms())
        ]
        nonbonded_method = "CutoffPeriodic"
        testsystem = testsystems.AlchemicalWaterBox(
            nonbondedMethod=getattr(app, nonbonded_method))

        # Adding the barostat with a high frequency
        testsystem.system.addForce(
            openmm.MonteCarloBarostat(1 * unit.atmospheres, 300 * unit.kelvin,
                                      2))

        for platform_name in platform_names:
            name = "%s %s %s" % (testsystem.name, nonbonded_method,
                                 platform_name)
            self.compare_external_protocol_work_accumulation(
                testsystem,
                parameter_name,
                parameter_initial,
                parameter_final,
                platform_name=platform_name,
                name=name,
            )
Exemple #2
0
def test_openmm_etoh_sim():
    path = './etoh_test/sim_openmm/'
    topology = 'etoh.prmtop'
    coordinates = 'etoh.rst7'
    md_out = 'etoh_openmm.csv'

    prmtop = app.AmberPrmtopFile(path+topology)
    inpcrd = app.AmberInpcrdFile(path+coordinates)

    settings = {
        'nonbonded_method': app.PME,
        'nonbonded_cutoff': 9*unit.angstrom,
        'constraints': app.HBonds,
        'temperature': 298.15*unit.kelvin,
        'friction': 1/unit.picosecond,
        'timestep': 0.002*unit.picosecond
    }

    system = prmtop.createSystem(
        nonbondedMethod = settings['nonbonded_method'],
        nonbondedCutoff = settings['nonbonded_cutoff'],
        constraints = settings['constraints']
    )
    barostat = mm.MonteCarloBarostat(1.0*unit.bar,298.15*unit.kelvin,25)
    system.addForce(barostat)

    integrator = LangevinIntegrator(
        settings['temperature'],
        settings['friction'],
        settings['timestep']
    )

    simulation = app.Simulation(prmtop.topology, system, integrator, mm.Platform.getPlatformByName('CPU'))
    simulation.context.setPositions(inpcrd.positions)
    simulation.context.setPeriodicBoxVectors(*inpcrd.boxVectors)

    simulation.reporters.append(NetCDFReporter(path+'etoh_openmm.nc', 250))
    simulation.reporters.append(
        app.StateDataReporter(
            path+md_out, 250,
            step=True,
            time=True,
            potentialEnergy=True,
            kineticEnergy=True,
            totalEnergy=True,
            temperature=True,
            volume=True,
            density=True
        )
    )
    
    simulation.step(100000)
Exemple #3
0
def make_explicit_system(pdb_filename="his_ala_his.pdb", outfile="his_ala_his"):
    """Solvate a pdb file and minimize the system"""

    temperature = 300.0 * unit.kelvin
    pressure = 1.0 * unit.atmospheres
    outfile1 = open("{}.sys.xml".format(outfile), "w")
    outfile2 = open("{}.state.xml".format(outfile), "w")
    app.Topology.loadBondDefinitions(bonds)
    pdb = app.PDBFile(pdb_filename)
    forcefield = app.ForceField(protonsff, ions_tip3p, "tip3p.xml")
    integrator = openmm.LangevinIntegrator(
        300 * unit.kelvin, 1.0 / unit.picoseconds, 2.0 * unit.femtoseconds
    )

    integrator.setConstraintTolerance(0.00001)

    modeller = app.Modeller(pdb.topology, pdb.positions)
    modeller.addSolvent(
        forcefield,
        boxSize=openmm.Vec3(3.5, 3.5, 3.5) * unit.nanometers,
        model="tip3p",
        ionicStrength=0.1 * unit.molar,
        positiveIon="Na+",
        negativeIon="Cl-",
    )
    system = forcefield.createSystem(
        modeller.topology,
        nonbondedMethod=app.PME,
        nonbondedCutoff=1.0 * unit.nanometers,
        constraints=app.HBonds,
        rigidWater=True,
        ewaldErrorTolerance=0.0005,
    )
    system.addForce(openmm.MonteCarloBarostat(pressure, temperature))

    simulation = app.Simulation(modeller.topology, system, integrator)
    simulation.context.setPositions(modeller.positions)

    simulation.minimizeEnergy()

    outfile1.write(openmm.XmlSerializer.serialize(simulation.system))
    positions = simulation.context.getState(getPositions=True)
    outfile2.write(openmm.XmlSerializer.serialize(positions))
    app.PDBxFile.writeFile(
        simulation.topology,
        modeller.positions,
        open("{}-solvated-minimized.cif".format(outfile), "w"),
    )
Exemple #4
0
def test_create_peptide_system_using_protons_xml():
    """Test if protons.xml can be used to successfully create a peptide System object in OpenMM."""
    app.Topology.loadBondDefinitions(bonds_path)

    # Load pdb file with protons compatible residue names
    pdbx = app.PDBxFile(
        get_test_data(
            "glu_ala_his-solvated-minimized-renamed.cif", "testsystems/tripeptides"
        )
    )
    forcefield = app.ForceField(ffxml_path, ions_spce_path, "spce.xml")

    # System Configuration
    nonbondedMethod = app.PME
    constraints = app.AllBonds
    rigidWater = True
    constraintTolerance = 1.0e-7

    # Integration Options
    dt = 0.5 * unit.femtoseconds
    temperature = 300.0 * unit.kelvin
    friction = 1.0 / unit.picosecond
    pressure = 1.0 * unit.atmospheres
    barostatInterval = 25

    # Simulation Options
    platform = mm.Platform.getPlatformByName("Reference")

    # Prepare the Simulation
    topology = pdbx.topology
    positions = pdbx.positions
    system = forcefield.createSystem(
        topology,
        nonbondedMethod=nonbondedMethod,
        constraints=constraints,
        rigidWater=rigidWater,
    )
    system.addForce(mm.MonteCarloBarostat(pressure, temperature, barostatInterval))

    integrator = GHMCIntegrator(temperature, friction, dt)
    integrator.setConstraintTolerance(constraintTolerance)

    # Clean up so that the classes remain unmodified
    # unit test specific errors might occur otherwise when loading files due
    # to class side effects
    app.Topology.unloadStandardBonds()
Exemple #5
0
pdb = app.PDBFile('2HYY-noH.pdb')

modeller = app.Modeller(pdb.topology, pdb.positions)

# The pdb contains solvent but not the right ions.
# This would mean we need to equilibrate again even if we just add new ions.
# In this case its easiest to just delete and re-add the solvent with the right amount of ions

modeller.deleteWater()
ions = [ atom for atom in modeller.topology.atoms() if atom.element.symbol in ['Cl', 'Na'] ]
modeller.delete(ions)


modeller.addHydrogens(forcefield=forcefield)
modeller.addSolvent(forcefield, model='tip3p', padding=1.0*nanometers, positiveIon='Na+', negativeIon='Cl-', ionicStrength=120*millimolar, neutralize=True)

system = forcefield.createSystem(modeller.topology, nonbondedMethod=app.PME, nonbondedCutoff=1.0 * nanometers,
                                 constraints=app.HBonds, rigidWater=True,
                                 ewaldErrorTolerance=0.0005)
system.addForce(openmm.MonteCarloBarostat(1.0 * atmosphere, 300.0 * kelvin))
simulation = app.Simulation(modeller.topology, system, GBAOABIntegrator() )
simulation.context.setPositions(modeller.positions)
rename_res = {"HIS": "HIP", "ASP":"AS4", "GLU":"GL4"}
for resi in modeller.topology.residues():
    if resi.name in rename_res:
        resi.name = rename_res[resi.name]

app.PDBFile.writeFile(modeller.topology, simulation.context.getState(getPositions=True).getPositions(),
                       open('2HYY-H.pdb', 'w'))

Exemple #6
0
def test_peptide_system_integrity():
    """
    Set up peptide, and assure that the systems particles have not been modified after driver instantiation.
    """

    sys_details = SystemSetup()
    sys_details.timestep = 0.5 * unit.femtoseconds
    sys_details.temperature = 300.0 * unit.kelvin
    sys_details.collision_rate = 1.0 / unit.picosecond
    sys_details.pressure = 1.0 * unit.atmospheres
    sys_details.barostatInterval = 25
    sys_details.constraint_tolerance = 1.0e-7

    app.Topology.loadBondDefinitions(bonds_path)

    # Load pdb file with protons compatible residue names
    pdbx = app.PDBxFile(
        get_test_data(
            "glu_ala_his-solvated-minimized-renamed.cif", "testsystems/tripeptides"
        )
    )
    forcefield = app.ForceField(ffxml_path, ions_spce_path, "spce.xml")

    # System Configuration
    nonbondedMethod = app.PME
    constraints = app.AllBonds
    rigidWater = True
    sys_details.constraintTolerance = 1.0e-7

    # Simulation Options
    platform = mm.Platform.getPlatformByName("Reference")

    # Prepare the Simulation
    topology = pdbx.topology
    positions = pdbx.positions
    system = forcefield.createSystem(
        topology,
        nonbondedMethod=nonbondedMethod,
        constraints=constraints,
        rigidWater=rigidWater,
    )
    system.addForce(
        mm.MonteCarloBarostat(
            sys_details.pressure, sys_details.temperature, sys_details.barostatInterval
        )
    )

    integrator = create_compound_gbaoab_integrator(testsystem=sys_details)

    original_system = pattern_from_multiline(
        mm.XmlSerializer.serialize(system), "<Particle"
    )

    driver = ForceFieldProtonDrive(
        sys_details.temperature,
        topology,
        system,
        forcefield,
        ffxml_path,
        pressure=sys_details.pressure,
        perturbations_per_trial=1,
    )

    after_driver = pattern_from_multiline(
        mm.XmlSerializer.serialize(system), "<Particle"
    )

    # Clean up so that the classes remain unmodified
    # unit test specific errors might occur otherwise when loading files due
    # to class side effects
    app.Topology.unloadStandardBonds()

    # Make sure there are no differences between the particles in each system
    assert original_system == after_driver
Exemple #7
0
def test_create_peptide_calibration_with_residue_pools_using_protons_xml():
    """Test if protons.xml can be used to successfully create a peptide Simulation object in OpenMM and
    Instantiate a ForceFieldProtonDrive, while using pools of residues to sample from,
    and calibrate histidine."""

    sys_details = SystemSetup()
    sys_details.timestep = 0.5 * unit.femtoseconds
    sys_details.temperature = 300.0 * unit.kelvin
    sys_details.collision_rate = 1.0 / unit.picosecond
    sys_details.pressure = 1.0 * unit.atmospheres
    sys_details.barostatInterval = 25
    sys_details.constraint_tolerance = 1.0e-7

    app.Topology.loadBondDefinitions(bonds_path)

    # Load pdb file with protons compatible residue names
    pdbx = app.PDBxFile(
        get_test_data(
            "glu_ala_his-solvated-minimized-renamed.cif", "testsystems/tripeptides"
        )
    )
    forcefield = app.ForceField(ffxml_path, ions_spce_path, "spce.xml")

    # System Configuration
    nonbondedMethod = app.PME
    constraints = app.AllBonds
    rigidWater = True
    sys_details.constraintTolerance = 1.0e-7

    # Simulation Options
    platform = mm.Platform.getPlatformByName("Reference")

    # Prepare the Simulation
    topology = pdbx.topology
    positions = pdbx.positions
    system = forcefield.createSystem(
        topology,
        nonbondedMethod=nonbondedMethod,
        constraints=constraints,
        rigidWater=rigidWater,
    )
    system.addForce(
        mm.MonteCarloBarostat(
            sys_details.pressure, sys_details.temperature, sys_details.barostatInterval
        )
    )

    integrator = create_compound_gbaoab_integrator(testsystem=sys_details)

    driver = ForceFieldProtonDrive(
        sys_details.temperature,
        topology,
        system,
        forcefield,
        ffxml_path,
        pressure=sys_details.pressure,
        perturbations_per_trial=1,
    )

    pools = {"glu": [0], "his": [1], "glu-his": [0, 1]}

    driver.define_pools(pools)
    driver.enable_calibration(SAMSApproach.ONESITE, group_index=1)
    sams_sampler = SAMSCalibrationEngine(driver)  # SAMS on HIS
    simulation = app.Simulation(topology, system, integrator, platform)
    simulation.context.setPositions(positions)
    simulation.context.setVelocitiesToTemperature(sys_details.temperature)
    driver.attach_context(simulation.context)
    # run one step and one update
    simulation.step(1)
    driver.update(UniformProposal(), nattempts=1, residue_pool="his")
    sams_sampler.adapt_zetas()
    # Clean up so that the classes remain unmodified
    # unit test specific errors might occur otherwise when loading files due
    # to class side effects
    app.Topology.unloadStandardBonds()
Exemple #8
0
    elif window[0] == 'p':
        phase = "pull"
    elif window[0] == 'r':
        phase = "release"
    window_num = int(window[1:])

    if os.path.exists(path + window + "/openmm_prod.rst7"):
        continue

    integrator = LangevinIntegrator(
        settings["temperature"],
        settings["friction"],
        settings["timestep"],
    )

    barostat = mm.MonteCarloBarostat(1.0 * unit.bar, settings["temperature"],
                                     25)

    structure = pmd.load_file(path + window + topology,
                              path + window + coordinates,
                              structure=True)
    # Set mass of Dummy atoms to 0 so they are non-interacting
    for atom in structure.atoms:
        if atom.name == "DUM":
            atom.mass = 0

    topology_0m = "/cb6-but-dum-0m.prmtop"
    coordinates_0m = "/cb6-but-dum-0m.rst7"

    structure.save(path + window + topology_0m, overwrite=True)
    structure.save(path + window + coordinates_0m, overwrite=True)
Exemple #9
0
    def test_create_simulation(self):
        """Instantiate a ConstantPHSimulation at 300K/1 atm for a small peptide."""

        pdb = app.PDBxFile(
            get_test_data("glu_ala_his-solvated-minimized-renamed.cif",
                          "testsystems/tripeptides"))
        forcefield = app.ForceField("amber10-constph.xml", "ions_tip3p.xml",
                                    "tip3p.xml")

        system = forcefield.createSystem(
            pdb.topology,
            nonbondedMethod=app.PME,
            nonbondedCutoff=1.0 * unit.nanometers,
            constraints=app.HBonds,
            rigidWater=True,
            ewaldErrorTolerance=0.0005,
        )

        temperature = 300 * unit.kelvin
        integrator = GBAOABIntegrator(
            temperature=temperature,
            collision_rate=1.0 / unit.picoseconds,
            timestep=2.0 * unit.femtoseconds,
            constraint_tolerance=1.0e-7,
            external_work=False,
        )
        ncmcintegrator = GBAOABIntegrator(
            temperature=temperature,
            collision_rate=1.0 / unit.picoseconds,
            timestep=2.0 * unit.femtoseconds,
            constraint_tolerance=1.0e-7,
            external_work=True,
        )

        compound_integrator = mm.CompoundIntegrator()
        compound_integrator.addIntegrator(integrator)
        compound_integrator.addIntegrator(ncmcintegrator)
        pressure = 1.0 * unit.atmosphere

        system.addForce(mm.MonteCarloBarostat(pressure, temperature))
        driver = ForceFieldProtonDrive(
            temperature,
            pdb.topology,
            system,
            forcefield,
            ["amber10-constph.xml"],
            pressure=pressure,
            perturbations_per_trial=0,
        )

        simulation = app.ConstantPHSimulation(
            pdb.topology,
            system,
            compound_integrator,
            driver,
            platform=self._default_platform,
        )
        simulation.context.setPositions(pdb.positions)
        simulation.context.setVelocitiesToTemperature(temperature)

        # Regular MD step
        simulation.step(1)
        # Update the titration states using the uniform proposal
        simulation.update(1)
        print("Done!")
Exemple #10
0
    def test_create_constantphcalibration_with_reporters(self):
        """Test running a calibration using constant-pH with reporters."""
        pdb = app.PDBxFile(
            get_test_data("glu_ala_his-solvated-minimized-renamed.cif",
                          "testsystems/tripeptides"))
        forcefield = app.ForceField("amber10-constph.xml", "ions_tip3p.xml",
                                    "tip3p.xml")

        system = forcefield.createSystem(
            pdb.topology,
            nonbondedMethod=app.PME,
            nonbondedCutoff=1.0 * unit.nanometers,
            constraints=app.HBonds,
            rigidWater=True,
            ewaldErrorTolerance=0.0005,
        )

        temperature = 300 * unit.kelvin
        integrator = GBAOABIntegrator(
            temperature=temperature,
            collision_rate=1.0 / unit.picoseconds,
            timestep=2.0 * unit.femtoseconds,
            constraint_tolerance=1.0e-7,
            external_work=False,
        )
        ncmcintegrator = GBAOABIntegrator(
            temperature=temperature,
            collision_rate=1.0 / unit.picoseconds,
            timestep=2.0 * unit.femtoseconds,
            constraint_tolerance=1.0e-7,
            external_work=True,
        )

        compound_integrator = mm.CompoundIntegrator()
        compound_integrator.addIntegrator(integrator)
        compound_integrator.addIntegrator(ncmcintegrator)
        pressure = 1.0 * unit.atmosphere

        system.addForce(mm.MonteCarloBarostat(pressure, temperature))
        driver = ForceFieldProtonDrive(
            temperature,
            pdb.topology,
            system,
            forcefield,
            ["amber10-constph.xml"],
            pressure=pressure,
            perturbations_per_trial=2,
            propagations_per_step=1,
        )

        # prep the driver for calibration
        driver.enable_calibration(SAMSApproach.ONESITE, group_index=-1)
        simulation = app.ConstantPHSimulation(
            pdb.topology,
            system,
            compound_integrator,
            driver,
            platform=self._default_platform,
        )
        simulation.context.setPositions(pdb.positions)
        simulation.context.setVelocitiesToTemperature(temperature)
        # Outputfile for reporters
        newname = uuid4().hex + ".nc"
        ncfile = netCDF4.Dataset(newname, "w")
        tr = TitrationReporter(ncfile, 1)
        mr = MetadataReporter(ncfile)
        nr = NCMCReporter(ncfile, 1)
        sr = SAMSReporter(ncfile, 1)
        simulation.update_reporters.append(tr)
        simulation.update_reporters.append(mr)
        simulation.update_reporters.append(nr)
        simulation.calibration_reporters.append(sr)

        simulation.step(1)
        # Update the titration states using the uniform proposal
        simulation.update(1)
        # Adapt the weights using binary update.
        simulation.adapt()
        # Attempt to prevent segfaults by closing files
        ncfile.close()
Exemple #11
0
    def test_create_constantphcalibration_resume(self):
        """Test running a calibration using constant-pH."""
        pdb = app.PDBxFile(
            get_test_data("glu_ala_his-solvated-minimized-renamed.cif",
                          "testsystems/tripeptides"))
        forcefield = app.ForceField("amber10-constph.xml", "ions_tip3p.xml",
                                    "tip3p.xml")

        system = forcefield.createSystem(
            pdb.topology,
            nonbondedMethod=app.PME,
            nonbondedCutoff=1.0 * unit.nanometers,
            constraints=app.HBonds,
            rigidWater=True,
            ewaldErrorTolerance=0.0005,
        )

        temperature = 300 * unit.kelvin
        integrator = GBAOABIntegrator(
            temperature=temperature,
            collision_rate=1.0 / unit.picoseconds,
            timestep=2.0 * unit.femtoseconds,
            constraint_tolerance=1.0e-7,
            external_work=False,
        )
        ncmcintegrator = GBAOABIntegrator(
            temperature=temperature,
            collision_rate=1.0 / unit.picoseconds,
            timestep=2.0 * unit.femtoseconds,
            constraint_tolerance=1.0e-7,
            external_work=True,
        )

        compound_integrator = mm.CompoundIntegrator()
        compound_integrator.addIntegrator(integrator)
        compound_integrator.addIntegrator(ncmcintegrator)
        pressure = 1.0 * unit.atmosphere

        system.addForce(mm.MonteCarloBarostat(pressure, temperature))
        driver = ForceFieldProtonDrive(
            temperature,
            pdb.topology,
            system,
            forcefield,
            ["amber10-constph.xml"],
            pressure=pressure,
            perturbations_per_trial=0,
        )
        driver.enable_calibration(SAMSApproach.ONESITE, group_index=-1)

        simulation = app.ConstantPHSimulation(
            pdb.topology,
            system,
            compound_integrator,
            driver,
            platform=self._default_platform,
        )
        simulation.context.setPositions(pdb.positions)
        simulation.context.setVelocitiesToTemperature(temperature)
        simulation.step(1)
        # Update the titration states using the uniform proposal
        simulation.update(1)
        # Adapt the weights using binary update, a few times just to rack up the counters.
        for x in range(5):
            simulation.adapt()
        # retrieve the samsProperties
        # TODO use deserialize proton drive for this
        xml = simulation.drive.state_to_xml()

        driver2 = NCMCProtonDrive(
            temperature,
            pdb.topology,
            system,
            pressure=pressure,
            perturbations_per_trial=0,
        )
        driver2.state_from_xml_tree(etree.fromstring(xml))
        integrator2 = GBAOABIntegrator(
            temperature=temperature,
            collision_rate=1.0 / unit.picoseconds,
            timestep=2.0 * unit.femtoseconds,
            constraint_tolerance=1.0e-7,
            external_work=False,
        )
        ncmcintegrator2 = GBAOABIntegrator(
            temperature=temperature,
            collision_rate=1.0 / unit.picoseconds,
            timestep=2.0 * unit.femtoseconds,
            constraint_tolerance=1.0e-7,
            external_work=True,
        )
        compound_integrator2 = mm.CompoundIntegrator()
        compound_integrator2.addIntegrator(integrator2)
        compound_integrator2.addIntegrator(ncmcintegrator2)

        # Make a new calibration and do another step, ignore the state for this example
        simulation2 = app.ConstantPHSimulation(
            pdb.topology,
            system,
            compound_integrator2,
            driver2,
            platform=self._default_platform,
        )

        assert (simulation2.drive.calibration_state._stage is
                simulation.drive.calibration_state._stage)
        # get going then
        simulation2.context.setPositions(pdb.positions)
        simulation2.context.setVelocitiesToTemperature(temperature)
        simulation2.step(1)
        # Update the titration states using the uniform proposal
        simulation2.update(1)
        # Adapt the weights using binary update.
        simulation2.adapt()

        assert (
            simulation2.drive.calibration_state._current_adaptation ==
            -simulation.drive.calibration_state._min_burn + 6
        ), "The resumed calibration does not have the right adaptation_index"
Exemple #12
0
    def test_create_importance_sampling_reporters(self):
        """Instantiate a ConstantPHSimulation at 300K/1 atm for a small peptide using importance sampling with reporters."""

        pdb = app.PDBxFile(
            get_test_data("glu_ala_his-solvated-minimized-renamed.cif",
                          "testsystems/tripeptides"))
        forcefield = app.ForceField("amber10-constph.xml", "ions_tip3p.xml",
                                    "tip3p.xml")

        system = forcefield.createSystem(
            pdb.topology,
            nonbondedMethod=app.PME,
            nonbondedCutoff=1.0 * unit.nanometers,
            constraints=app.HBonds,
            rigidWater=True,
            ewaldErrorTolerance=0.0005,
        )

        temperature = 300 * unit.kelvin
        integrator = GBAOABIntegrator(
            temperature=temperature,
            collision_rate=1.0 / unit.picoseconds,
            timestep=2.0 * unit.femtoseconds,
            constraint_tolerance=1.0e-7,
            external_work=False,
        )
        ncmcintegrator = GBAOABIntegrator(
            temperature=temperature,
            collision_rate=1.0 / unit.picoseconds,
            timestep=2.0 * unit.femtoseconds,
            constraint_tolerance=1.0e-7,
            external_work=True,
        )

        compound_integrator = mm.CompoundIntegrator()
        compound_integrator.addIntegrator(integrator)
        compound_integrator.addIntegrator(ncmcintegrator)
        pressure = 1.0 * unit.atmosphere

        system.addForce(mm.MonteCarloBarostat(pressure, temperature))
        driver = ForceFieldProtonDrive(
            temperature,
            pdb.topology,
            system,
            forcefield,
            ["amber10-constph.xml"],
            pressure=pressure,
            perturbations_per_trial=0,
            sampling_method=SamplingMethod.IMPORTANCE,
        )

        simulation = app.ConstantPHSimulation(
            pdb.topology,
            system,
            compound_integrator,
            driver,
            platform=self._default_platform,
        )
        simulation.context.setPositions(pdb.positions)
        simulation.context.setVelocitiesToTemperature(temperature)

        newname = uuid4().hex + ".nc"
        ncfile = netCDF4.Dataset(newname, "w")
        tr = TitrationReporter(ncfile, 1)
        mr = MetadataReporter(ncfile)
        nr = NCMCReporter(ncfile, 1)
        simulation.update_reporters.append(tr)
        simulation.update_reporters.append(mr)
        simulation.update_reporters.append(nr)

        # Regular MD step
        simulation.step(1)
        # Update the titration states using the uniform proposal
        niters = 3
        for x in range(niters):
            simulation.update(1)

        n_total_states = np.product(
            [len(group) for group in driver.titrationGroups])
        assert (len(ncfile["Protons/Titration/update"][:]) == n_total_states *
                niters), "The wrong number of updates were recorded"

        work_values = np.split(ncfile["Protons/NCMC/total_work"][:], niters)
        init_states = ncfile["Protons/NCMC/initial_state"][:, :]
        assert np.all(
            init_states == 0), "States should all be zero at the start."
        first_run = work_values[0]
        assert np.all(np.unique(first_run) == np.sort(
            first_run)), "No work values should be duplicated."

        # Since instanteneous switching is used, this should be true
        for x in range(1, niters):
            assert np.all(
                np.isclose(work_values[x],
                           first_run)), "Work should be equal for all states."

        # Switch state
        driver.set_titration_state(0,
                                   3,
                                   updateContextParameters=True,
                                   updateIons=True)
        driver.set_titration_state(1,
                                   1,
                                   updateContextParameters=True,
                                   updateIons=True)
        simulation.update(1)

        assert (ncfile["Protons/NCMC/initial_state"][-n_total_states, 0] == 3
                ), "Initial state was not changed correctly."
        assert (ncfile["Protons/NCMC/initial_state"][-n_total_states, 1] == 1
                ), "Initial state was not changed correctly."
        work_values = np.split(ncfile["Protons/NCMC/total_work"][:],
                               niters + 1)
        assert not np.all(
            np.isclose(work_values[0], work_values[-1])
        ), "Work values starting from different state should differ."

        return
Exemple #13
0
    def test_create_importance_sampling(self):
        """Instantiate a ConstantPHSimulation at 300K/1 atm for a small peptide using importance sampling."""

        pdb = app.PDBxFile(
            get_test_data("glu_ala_his-solvated-minimized-renamed.cif",
                          "testsystems/tripeptides"))
        forcefield = app.ForceField("amber10-constph.xml", "ions_tip3p.xml",
                                    "tip3p.xml")

        system = forcefield.createSystem(
            pdb.topology,
            nonbondedMethod=app.PME,
            nonbondedCutoff=1.0 * unit.nanometers,
            constraints=app.HBonds,
            rigidWater=True,
            ewaldErrorTolerance=0.0005,
        )

        temperature = 300 * unit.kelvin
        integrator = GBAOABIntegrator(
            temperature=temperature,
            collision_rate=1.0 / unit.picoseconds,
            timestep=2.0 * unit.femtoseconds,
            constraint_tolerance=1.0e-7,
            external_work=False,
        )
        ncmcintegrator = GBAOABIntegrator(
            temperature=temperature,
            collision_rate=1.0 / unit.picoseconds,
            timestep=2.0 * unit.femtoseconds,
            constraint_tolerance=1.0e-7,
            external_work=True,
        )

        compound_integrator = mm.CompoundIntegrator()
        compound_integrator.addIntegrator(integrator)
        compound_integrator.addIntegrator(ncmcintegrator)
        pressure = 1.0 * unit.atmosphere

        system.addForce(mm.MonteCarloBarostat(pressure, temperature))
        driver = ForceFieldProtonDrive(
            temperature,
            pdb.topology,
            system,
            forcefield,
            ["amber10-constph.xml"],
            pressure=pressure,
            perturbations_per_trial=0,
            sampling_method=SamplingMethod.IMPORTANCE,
        )

        simulation = app.ConstantPHSimulation(
            pdb.topology,
            system,
            compound_integrator,
            driver,
            platform=self._default_platform,
        )
        simulation.context.setPositions(pdb.positions)
        simulation.context.setVelocitiesToTemperature(temperature)

        # Regular MD step
        simulation.step(1)
        # Update the titration states using the uniform proposal
        simulation.update(1)

        # Total states is 15 but proposing the same state as current does not get added to statistics.
        assert simulation.drive.nattempted == 14, "Not enough switch were attempted."
        assert simulation.drive.naccepted == 0, "No acceptance should have occurred."
        assert (simulation.drive.nattempted == simulation.drive.nrejected
                ), "The rejection count should match the number of attempts"

        print("Done!")