Exemple #1
0
def test_combine_molecules_sites_deepdiff(openff, xml, acetone, rfree_data, tmpdir):
    """
    Test combining molecules with virtual sites and ensure they are correctly applied and the energy break down matches.
    """
    with tmpdir.as_cwd():
        openff.run(acetone)
        acetone_ref_system = xmltodict.parse(open("serialised.xml").read())
        pyridine = Ligand.from_file(file_name=get_data("pyridine.sdf"))
        xml.run(molecule=pyridine, input_files=[get_data("pyridine.xml")])
        pyridine_ref_system = xmltodict.parse(open("serialised.xml").read())

        combined_xml = _combine_molecules(
            molecules=[acetone, pyridine], parameters=elements, rfree_data=rfree_data
        ).getroot()
        messy = ET.tostring(combined_xml, "utf-8")

        pretty_xml = parseString(messy).toprettyxml(indent="")
        print(pretty_xml)
        with open("combined.xml", "w") as xml_doc:
            xml_doc.write(pretty_xml)
        root = combined_xml.find("QUBEKit")
        assert qubekit.__version__ == root.get("Version")

        # load up new systems and compare
        combinded_ff = app.ForceField("combined.xml")

        acetone_combine_system = xmltodict.parse(
            XmlSerializer.serialize(
                combinded_ff.createSystem(
                    acetone.to_openmm_topology(),
                    nonbondedCutoff=0.9,
                    removeCMMotion=False,
                )
            )
        )
        # slight differences in masses we need to ignore
        acetone_diff = DeepDiff(
            acetone_ref_system,
            acetone_combine_system,
            ignore_order=True,
            significant_digits=6,
            exclude_regex_paths="mass",
        )
        assert len(acetone_diff) == 0
        # add v-site
        pyridine_mod = app.Modeller(
            pyridine.to_openmm_topology(), pyridine.openmm_coordinates()
        )
        pyridine_mod.addExtraParticles(combinded_ff)
        pyridine_combine_system = xmltodict.parse(
            XmlSerializer.serialize(combinded_ff.createSystem(pyridine_mod.topology))
        )
        pyridine_diff = DeepDiff(
            pyridine_ref_system,
            pyridine_combine_system,
            ignore_order=True,
            significant_digits=6,
            exclude_regex_paths="mass",
        )
        assert len(pyridine_diff) == 0
Exemple #2
0
 def setUp(self):
     self.pdb = app.PDBFile('systems/alanine-dipeptide-implicit.pdb')
     self.forcefield = app.ForceField('amber99sbildn.xml')
     self.system = self.forcefield.createSystem(
         self.pdb.topology,
         nonbondedMethod=app.CutoffNonPeriodic,
         constraints=app.HBonds)
def test_local_coord_sites():
    """Make sure that the internal prep of vs positions matches that given by OpenMM."""
    # make a system
    mol = app.PDBFile(os.path.join("files", "vs_mol.pdb"))
    modeller = app.Modeller(topology=mol.topology, positions=mol.positions)
    forcefield = app.ForceField(
        os.path.join("files", "forcefield", "vs_mol.xml"))
    modeller.addExtraParticles(forcefield)
    system = forcefield.createSystem(modeller.topology, constraints=None)
    integrator = mm.VerletIntegrator(1.0 * unit.femtoseconds)
    platform = mm.Platform.getPlatformByName("Reference")
    simulation = app.Simulation(modeller.topology, system, integrator,
                                platform)
    simulation.context.setPositions(modeller.positions)
    # update the site positions
    simulation.context.computeVirtualSites()
    # one vs and it should be last
    vs_pos = simulation.context.getState(getPositions=True).getPositions(
        asNumpy=True)[-1]
    # now compute and compare
    vsinfo = PrepareVirtualSites(system=system)
    new_pos = ResetVirtualSites_fast(positions=modeller.positions,
                                     vsinfo=vsinfo)[-1]
    assert np.allclose(vs_pos._value,
                       np.array([new_pos.x, new_pos.y, new_pos.z]))
Exemple #4
0
def simulate(pdbcode, pdb_filename):
    from openmm import app
    import openmm.openmm as mm
    from openmm import unit
    from sys import stdout

    # Load the PDB file.
    pdb = app.PDBFile(pdb_filename)

    # Set up implicit solvent forcefield.
    #forcefield = app.ForceField('amber99sbildn.xml')
    forcefield = app.ForceField('amber10.xml')

    # Create the system.
    system = forcefield.createSystem(pdb.topology,
                                     nonbondedMethod=app.NoCutoff,
                                     constraints=app.HBonds)

    # Create an integrator.
    integrator = mm.LangevinIntegrator(300 * unit.kelvin,
                                       91.0 / unit.picoseconds,
                                       1.0 * unit.femtoseconds)

    # Create a context.
    context = mm.Context(system, integrator)
    context.setPositions(pdb.positions)

    # Check to make sure energy is finite.
    state = context.getState(getEnergy=True)
    potential = state.getPotentialEnergy() / unit.kilocalories_per_mole
    if numpy.isnan(potential):
        raise Exception("Initial energy for %s is NaN." % pdbcode)

    # Minimize.
    tolerance = 1.0 * unit.kilocalories_per_mole / unit.angstroms
    maxIterations = 50
    mm.LocalEnergyMinimizer.minimize(context, tolerance, maxIterations)

    # Check to make sure energy is finite.
    state = context.getState(getEnergy=True)
    potential = state.getPotentialEnergy() / unit.kilocalories_per_mole
    if numpy.isnan(potential):
        raise Exception("Energy for %s is NaN after minimization." % pdbcode)

    # Simulate.
    nsteps = 500
    integrator.step(nsteps)

    # Check to make sure energy is finite.
    state = context.getState(getEnergy=True)
    potential = state.getPotentialEnergy() / unit.kilocalories_per_mole
    if numpy.isnan(potential):
        raise Exception("Energy for %s is NaN after simulation." % pdbcode)

    del context, integrator

    print("Simulation completed: potential = %.3f kcal/mol" % potential)

    return
Exemple #5
0
def test_combine_molecules_deepdiff(acetone, openff, coumarin, tmpdir, rfree_data):

    with tmpdir.as_cwd():
        openff.run(acetone)
        acetone_ref_system = xmltodict.parse(open("serialised.xml").read())
        openff.run(coumarin)
        coumarin_ref_system = xmltodict.parse(open("serialised.xml").read())

        combined_xml = _combine_molecules(
            molecules=[acetone, coumarin], parameters=elements, rfree_data=rfree_data
        ).getroot()
        messy = ET.tostring(combined_xml, "utf-8")

        pretty_xml = parseString(messy).toprettyxml(indent="")

        with open("combined.xml", "w") as xml_doc:
            xml_doc.write(pretty_xml)
        root = combined_xml.find("QUBEKit")
        assert qubekit.__version__ == root.get("Version")

        # load up new systems and compare
        combinded_ff = app.ForceField("combined.xml")

        acetone_combine_system = xmltodict.parse(
            XmlSerializer.serialize(
                combinded_ff.createSystem(
                    acetone.to_openmm_topology(),
                    nonbondedCutoff=0.9,
                    removeCMMotion=False,
                )
            )
        )
        # slight differences in masses we need to ignore
        acetone_diff = DeepDiff(
            acetone_ref_system,
            acetone_combine_system,
            ignore_order=True,
            significant_digits=6,
            exclude_regex_paths="mass",
        )
        assert len(acetone_diff) == 0

        coumarin_combine_system = xmltodict.parse(
            XmlSerializer.serialize(
                combinded_ff.createSystem(
                    coumarin.to_openmm_topology(),
                    nonbondedCutoff=0.9,
                    removeCMMotion=False,
                )
            )
        )
        coumarin_diff = DeepDiff(
            coumarin_ref_system,
            coumarin_combine_system,
            ignore_order=True,
            significant_digits=6,
            exclude_regex_paths="mass",
        )
        assert len(coumarin_diff) == 0
Exemple #6
0
def test_combine_molecules_offxml_plugin_deepdiff(tmpdir, coumarin, rfree_data):
    """Make sure that systems made from molecules using the xml method match offxmls with plugins"""

    # we need to recalculate the Nonbonded terms using the fake Rfree
    coumarin_copy = coumarin.copy(deep=True)
    # apply symmetry to make sure systems match
    MBISCharges.apply_symmetrisation(coumarin_copy)
    with tmpdir.as_cwd():
        # make the offxml using the plugin interface
        _combine_molecules_offxml(
            molecules=[coumarin_copy],
            parameters=elements,
            rfree_data=rfree_data,
            filename="openff.offxml",
            water_model="tip3p",
        )
        offxml = ForceField(
            "openff.offxml", load_plugins=True, allow_cosmetic_attributes=True
        )
        # check the plugin is being used
        vdw = offxml.get_parameter_handler("QUBEKitvdWTS")
        # make sure we have the parameterize tags
        assert len(vdw._cosmetic_attribs) == 1
        assert len(vdw.parameters) == 28

        alpha = rfree_data.pop("alpha")
        beta = rfree_data.pop("beta")
        lj = LennardJones612(free_parameters=rfree_data, alpha=alpha, beta=beta)
        # get new Rfree data
        lj.run(coumarin_copy)
        coumarin_copy.write_parameters("coumarin.xml")
        coumarin_ref_system = xmltodict.parse(
            XmlSerializer.serialize(
                app.ForceField("coumarin.xml").createSystem(
                    topology=coumarin_copy.to_openmm_topology(),
                    nonbondedCutoff=9 * unit.angstroms,
                    removeCMMotion=False,
                )
            )
        )
        coumarin_off_system = xmltodict.parse(
            XmlSerializer.serialize(
                offxml.create_openmm_system(
                    Molecule.from_rdkit(coumarin_copy.to_rdkit()).to_topology()
                )
            )
        )

        coumarin_diff = DeepDiff(
            coumarin_ref_system,
            coumarin_off_system,
            ignore_order=True,
            significant_digits=6,
            exclude_regex_paths="mass",
        )
        assert len(coumarin_diff) == 1
        for item in coumarin_diff["iterable_item_added"].values():
            assert item["@k"] == "0"
 def setUp(self):
     with open('systems/alanine-dipeptide-implicit.pdb') as f:
         pdb = app.PDBFile(f)
     forcefield = app.ForceField('amber99sbildn.xml')
     system = forcefield.createSystem(pdb.topology,
         nonbondedMethod=app.CutoffNonPeriodic, nonbondedCutoff=1.0*unit.nanometers,
         constraints=app.HBonds)
     self.simulation = app.Simulation(pdb.topology, system, mm.VerletIntegrator(0.002*unit.picoseconds))
     self.simulation.context.setPositions(pdb.positions)
Exemple #8
0
def _configure_amber_implicit(
    pdb_file: PathLike,
    top_file: Optional[PathLike],
    dt_ps: float,
    temperature_kelvin: float,
    heat_bath_friction_coef: float,
    platform: "openmm.Platform",
    platform_properties: dict,
) -> Tuple["app.Simulation", Optional["app.PDBFile"]]:

    # Configure system
    if top_file is not None:
        pdb = None
        top = app.AmberPrmtopFile(str(top_file))
        system = top.createSystem(
            nonbondedMethod=app.CutoffNonPeriodic,
            nonbondedCutoff=1.0 * u.nanometer,
            constraints=app.HBonds,
            implicitSolvent=app.OBC1,
        )
    else:
        pdb = app.PDBFile(str(pdb_file))
        top = pdb.topology
        forcefield = app.ForceField("amber99sbildn.xml", "amber99_obc.xml")
        system = forcefield.createSystem(
            top,
            nonbondedMethod=app.CutoffNonPeriodic,
            nonbondedCutoff=1.0 * u.nanometer,
            constraints=app.HBonds,
        )

    # Configure integrator
    integrator = openmm.LangevinIntegrator(
        temperature_kelvin * u.kelvin,
        heat_bath_friction_coef / u.picosecond,
        dt_ps * u.picosecond,
    )
    integrator.setConstraintTolerance(0.00001)

    sim = app.Simulation(top, system, integrator, platform,
                         platform_properties)

    # Returning the pdb file object for later use to reduce I/O.
    # If a topology file is passed, the pdb variable is None.
    return sim, pdb
Exemple #9
0
    def parse(filename):
        """
        Parses XML file and returns deserialized object. The return value
        depends on the serialized object, summarized below

            - System : returns openmm.System
            - State : returns openmm.State
            - Integrator : returns openmm.Integrator subclass
            - ForceField : returns openmm.app.ForceField

        Parameters
        ----------
        filename : str or file-like
            The file name or file object containing the XML-serialized object

        Returns
        -------
        obj : System, State, Integrator, or ForceField
            The deserialized object

        Notes
        -----
        OpenMM requires the entire contents of this file read into memory. As a
        result, this function may require a significant amount of memory.
        """
        import openmm as mm
        from openmm import app
        if isinstance(filename, str):
            with closing(genopen(filename, 'r')) as f:
                contents = f.read()
        else:
            contents = filename.read()
        # ForceField is not handled by XmlSerializer
        if '<ForceField' in contents:
            obj = StringIO()
            obj.write(contents)
            obj.seek(0)
            return app.ForceField(obj)

        obj = mm.XmlSerializer.deserialize(contents)
        if isinstance(obj, mm.State):
            return _OpenMMStateContents(obj)
        return obj
Exemple #10
0
    def testAppend(self):
        """Test appending to an existing trajectory."""
        fname = tempfile.mktemp(suffix='.dcd')
        pdb = app.PDBFile('systems/alanine-dipeptide-implicit.pdb')
        ff = app.ForceField('amber99sb.xml', 'tip3p.xml')
        system = ff.createSystem(pdb.topology)

        # Create a simulation and write some frames to a DCD file.

        integrator = mm.VerletIntegrator(0.001 * unit.picoseconds)
        simulation = app.Simulation(pdb.topology, system, integrator,
                                    mm.Platform.getPlatformByName('Reference'))
        dcd = app.DCDReporter(fname, 2)
        simulation.reporters.append(dcd)
        simulation.context.setPositions(pdb.positions)
        simulation.context.setVelocitiesToTemperature(300 * unit.kelvin)
        simulation.step(10)
        self.assertEqual(5, dcd._dcd._modelCount)
        del simulation
        del dcd
        len1 = os.stat(fname).st_size

        # Create a new simulation and have it append some more frames.

        integrator = mm.VerletIntegrator(0.001 * unit.picoseconds)
        simulation = app.Simulation(pdb.topology, system, integrator,
                                    mm.Platform.getPlatformByName('Reference'))
        dcd = app.DCDReporter(fname, 2, append=True)
        simulation.reporters.append(dcd)
        simulation.context.setPositions(pdb.positions)
        simulation.context.setVelocitiesToTemperature(300 * unit.kelvin)
        simulation.step(10)
        self.assertEqual(10, dcd._dcd._modelCount)
        len2 = os.stat(fname).st_size
        self.assertTrue(len2 - len1 > 3 * 4 * 5 * system.getNumParticles())
        del simulation
        del dcd
        os.remove(fname)
Exemple #11
0
def create_openmm_system(sim_openmm,
                         model,
                         anchor,
                         frame=0,
                         load_state_file=None):
    """
    Create an openmm System() object.
    """
    building_directory = os.path.join(model.anchor_rootdir, anchor.directory,
                                      anchor.building_directory)
    box_vectors = None
    num_frames = 0
    positions_obj = None
    if anchor.__class__.__name__ in ["MMVT_toy_anchor", "Elber_toy_anchor"]:
        if load_state_file is not None:
            positions = None
            num_frames = 1
        elif anchor.starting_positions is not None:
            positions_frames = np.array(anchor.starting_positions) \
                * openmm.unit.nanometers
            positions = positions_frames[frame]
            num_frames = len(positions_frames)
        else:
            raise Exception(
                "No starting state or starting positions provided.")

    else:
        if anchor.amber_params is not None:
            prmtop_filename = os.path.join(building_directory,
                                           anchor.amber_params.prmtop_filename)
            prmtop = openmm_app.AmberPrmtopFile(prmtop_filename)
            #assert anchor.amber_params.pdb_coordinates_filename is not None
            if anchor.amber_params.pdb_coordinates_filename is None \
                    or anchor.amber_params.pdb_coordinates_filename == "":
                positions_obj = None
                positions = None
                sim_openmm.try_to_load_state = True
            else:
                pdb_coordinates_filename = os.path.join(
                    building_directory,
                    anchor.amber_params.pdb_coordinates_filename)
                positions_obj = openmm_app.PDBFile(pdb_coordinates_filename)

            #assert anchor.amber_params.box_vectors is not None
            box_vectors = anchor.amber_params.box_vectors
            topology = prmtop.topology

        elif anchor.forcefield_params is not None:
            forcefield_filenames = []
            for forcefield_filename in \
                    anchor.forcefield_params.built_in_forcefield_filenames:
                forcefield_filenames.append(forcefield_filename)
            for forcefield_filename in \
                    anchor.forcefield_params.custom_forcefield_filenames:
                forcefield_filenames.append(
                    os.path.join(building_directory, forcefield_filename))
            print("anchor.forcefield_params.pdb_filename:",
                  anchor.forcefield_params.pdb_coordinates_filename)
            pdb_filename = os.path.join(
                building_directory,
                anchor.forcefield_params.pdb_coordinates_filename)
            print("pdb_filename:", pdb_filename)
            pdb = openmm_app.PDBFile(pdb_filename)
            forcefield = openmm_app.ForceField(*forcefield_filenames)
            box_vectors = anchor.forcefield_params.box_vectors

            topology = pdb.topology
            positions_obj = pdb
            positions = None

        elif anchor.charmm_params is not None:
            raise Exception("Charmm systems not yet implemented")

        else:
            raise Exception("No Amber or Charmm input settings detected.")

    #assert box_vectors is not None, "No source of box vectors provided."
    nonbonded_method = model.openmm_settings.nonbonded_method.lower()
    if nonbonded_method == "pme":
        nonbondedMethod = openmm_app.PME

    elif nonbonded_method == "nocutoff":
        nonbondedMethod = openmm_app.NoCutoff

    elif nonbonded_method == "cutoffnonperiodic":
        nonbondedMethod = openmm_app.CutoffNonPeriodic

    elif nonbonded_method == "cutoffperiodic":
        nonbondedMethod = openmm_app.CutoffPeriodic

    elif nonbonded_method == "ewald":
        nonbondedMethod = openmm_app.Ewald

    else:
        raise Exception("nonbonded method not found: %s",
                        model.openmm_settings.nonbonded_method)

    if model.openmm_settings.constraints is None:
        constraints_str = None
    else:
        constraints_str = model.openmm_settings.constraints

    if constraints_str is None:
        constraints = None

    elif constraints_str.lower() == "none":
        constraints = None

    elif constraints_str.lower() == "hbonds":
        constraints = openmm_app.HBonds

    elif constraints_str.lower() == "allbonds":
        constraints = openmm_app.AllBonds

    elif constraints_str.lower() == "hangles":
        constraints = openmm_app.HAngles

    else:
        raise Exception("constraints not found: %s",
                        model.openmm_settings.constraints)

    if model.openmm_settings.hydrogenMass is not None:
        hydrogenMass = model.openmm_settings.hydrogenMass * openmm.unit.amu
    else:
        hydrogenMass = None

    rigidWater = model.openmm_settings.rigidWater

    if anchor.__class__.__name__ in ["MMVT_toy_anchor", "Elber_toy_anchor"]:
        system, topology = make_toy_system_object(model)
    else:
        if anchor.amber_params is not None:
            system = prmtop.createSystem(
                nonbondedMethod=nonbondedMethod,
                nonbondedCutoff=model.openmm_settings.nonbonded_cutoff,
                constraints=constraints,
                hydrogenMass=hydrogenMass,
                rigidWater=rigidWater)

        elif anchor.forcefield_params is not None:
            system = forcefield.createSystem(
                pdb.topology,
                nonbondedMethod=nonbondedMethod,
                nonbondedCutoff=model.openmm_settings.nonbonded_cutoff,
                constraints=constraints,
                hydrogenMass=hydrogenMass,
                rigidWater=rigidWater)

        elif anchor.charmm_params is not None:
            raise Exception("Charmm input settings not yet implemented")

        else:
            print("Settings for Amber or Charmm simulations not found")

    if positions_obj is not None:
        positions = positions_obj.getPositions(frame=frame)
        assert frame >= 0, "Cannot have negative frame index"
        assert frame < positions_obj.getNumFrames(), \
            "Frame index {} out of range.".format(frame)
        num_frames = positions_obj.getNumFrames()

    return system, topology, positions, box_vectors, num_frames
Exemple #12
0
def _equil_NPT_OpenMM_protocol_0(topology,
                                 positions,
                                 temperature=300.0 * _unit.kelvin,
                                 pressure=1.0 * _unit.atmosphere,
                                 time=1.0 * _unit.nanosecond,
                                 forcefield=None,
                                 verbose=True,
                                 progress_bar=True):

    import numpy as np
    import openmm.app as app
    import openmm as mm
    from openmmtools.integrators import LangevinIntegrator, GeodesicBAOABIntegrator

    if progress_bar:
        from tqdm import tqdm
    else:

        def tqdm(arg):
            return arg

    #item needs to be openmm.modeller

    forcefield = app.ForceField("amber99sbildn.xml", "tip3p.xml")
    topology = item.topology
    positions = item.positions

    system = forcefield_generator.createSystem(topology,
                                               contraints=app.HBonds,
                                               nonbondedMethod=app.PME,
                                               nonbondedCutoff=1.0 *
                                               _unit.nanometers,
                                               rigidWater=True,
                                               ewaldErrorTolerance=0.0005)

    ## Thermodynamic State
    kB = _unit.BOLTZMANN_CONSTANT_kB * _unit.AVOGADRO_CONSTANT_NA
    temperature = temperature
    pressure = pressure

    ## Barostat
    barostat_frequency = 25  # steps
    barostat = mm.MonteCarloBarostat(pressure, temperature, barostat_frequency)
    system.addForce(barostat)

    ## Integrator
    friction = 1.0 / _unit.picosecond
    step_size = 2.0 * _unit.femtoseconds
    integrator = LangevinIntegrator(temperature, friction, step_size)
    integrator.setConstraintTolerance(0.00001)

    ## Platform
    platform = mm.Platform.getPlatformByName('CUDA')
    properties = {'CudaPrecision': 'mixed'}

    ## Simulation
    simulation = app.Simulation(topology, system, integrator, platform,
                                properties)
    simulation.context.setPositions(positions)
    simulation.context.setVelocitiesToTemperature(temperature)

    time_equilibration = time
    time_iteration = 0.2 * _unit.picoseconds
    number_iterations = int(time_equilibration / time_iteration)
    steps_iteration = int(time_iteration / step_size)
    steps_equilibration = number_iterations * steps_iteration

    ## Reporters

    net_mass, n_degrees_of_freedom = m3t.get(system,
                                             net_mass=True,
                                             n_degrees_of_freedom=True)
    niters = number_iterations
    data = dict()
    data['time'] = _unit.Quantity(np.zeros([niters], np.float64),
                                  _unit.picoseconds)
    data['potential'] = _unit.Quantity(np.zeros([niters], np.float64),
                                       _unit.kilocalories_per_mole)
    data['kinetic'] = _unit.Quantity(np.zeros([niters], np.float64),
                                     _unit.kilocalories_per_mole)
    data['volume'] = _unit.Quantity(np.zeros([niters], np.float64),
                                    _unit.angstroms**3)
    data['density'] = _unit.Quantity(np.zeros([niters], np.float64),
                                     _unit.gram / _unit.centimeters**3)
    data['kinetic_temperature'] = unit.Quantity(np.zeros([niters], np.float64),
                                                _unit.kelvin)

    for iteration in tqdm(range(number_iterations)):
        integrator.step(steps_iteration)
        state = simulation.context.getState(getEnergy=True)
        time = state.getTime()
        potential_energy = state.getPotentialEnergy()
        kinetic_energy = state.getKineticEnergy()
        volume = state.getPeriodicBoxVolume()
        density = (net_mass / volume).in_units_of(unit.gram /
                                                  unit.centimeter**3)
        kinetic_temperature = (2.0 * kinetic_energy /
                               kB / n_degrees_of_freedom).in_units_of(
                                   unit.kelvin)  # (1/2) ndof * kB * T = KE
        data['time'][iteration] = time
        data['potential'] = potential_energy
        data['kinetic'] = kinetic_energy
        data['volume'] = volume
        data['density'] = density
        data['kinetic_temperature'] = kinetic_temperature

    final_state = simulation.context.getState(getPositions=True,
                                              getVelocities=True)
    final_positions = final_state.getPositions()
    final_velocities = final_state.getVelocities()

    return final_positions, final_velocities, data
Exemple #13
0
def runOneTest(testName, options):
    """Perform a single benchmarking simulation."""
    explicit = (testName not in ('gbsa', 'amoebagk'))
    amoeba = (testName in ('amoebagk', 'amoebapme'))
    apoa1 = testName.startswith('apoa1')
    amber = (testName.startswith('amber'))
    hydrogenMass = None
    print()
    if amoeba:
        print('Test: %s (epsilon=%g)' % (testName, options.epsilon))
    elif testName == 'pme':
        print('Test: pme (cutoff=%g)' % options.cutoff)
    else:
        print('Test: %s' % testName)
    print('Ensemble: %s' % options.ensemble)
    platform = mm.Platform.getPlatformByName(options.platform)

    # Create the System.

    temperature = 300 * unit.kelvin
    if explicit:
        friction = 1 * (1 / unit.picoseconds)
    else:
        friction = 91 * (1 / unit.picoseconds)
    if amoeba:
        constraints = None
        epsilon = float(options.epsilon)
        if explicit:
            ff = app.ForceField('amoeba2009.xml')
            pdb = app.PDBFile('5dfr_solv-cube_equil.pdb')
            cutoff = 0.7 * unit.nanometers
            vdwCutoff = 0.9 * unit.nanometers
            system = ff.createSystem(pdb.topology,
                                     nonbondedMethod=app.PME,
                                     nonbondedCutoff=cutoff,
                                     vdwCutoff=vdwCutoff,
                                     constraints=constraints,
                                     ewaldErrorTolerance=0.00075,
                                     mutualInducedTargetEpsilon=epsilon,
                                     polarization=options.polarization)
        else:
            ff = app.ForceField('amoeba2009.xml', 'amoeba2009_gk.xml')
            pdb = app.PDBFile('5dfr_minimized.pdb')
            cutoff = 2.0 * unit.nanometers
            vdwCutoff = 1.2 * unit.nanometers
            system = ff.createSystem(pdb.topology,
                                     nonbondedMethod=app.NoCutoff,
                                     constraints=constraints,
                                     mutualInducedTargetEpsilon=epsilon,
                                     polarization=options.polarization)
        for f in system.getForces():
            if isinstance(f, mm.AmoebaMultipoleForce) or isinstance(
                    f, mm.AmoebaVdwForce) or isinstance(
                        f, mm.AmoebaGeneralizedKirkwoodForce) or isinstance(
                            f, mm.AmoebaWcaDispersionForce):
                f.setForceGroup(1)
        dt = 0.002 * unit.picoseconds
        if options.ensemble == 'NVE':
            integ = mm.MTSIntegrator(dt, [(0, 2), (1, 1)])
        else:
            integ = mm.MTSLangevinIntegrator(temperature, friction, dt,
                                             [(0, 2), (1, 1)])
        positions = pdb.positions
    elif amber:
        dirname = downloadAmberSuite()
        names = {
            'amber20-dhfr': 'JAC',
            'amber20-factorix': 'FactorIX',
            'amber20-cellulose': 'Cellulose',
            'amber20-stmv': 'STMV'
        }
        fileName = names[testName]
        prmtop = app.AmberPrmtopFile(
            os.path.join(dirname, f'PME/Topologies/{fileName}.prmtop'))
        inpcrd = app.AmberInpcrdFile(
            os.path.join(dirname, f'PME/Coordinates/{fileName}.inpcrd'))
        topology = prmtop.topology
        positions = inpcrd.positions
        dt = 0.004 * unit.picoseconds
        method = app.PME
        cutoff = options.cutoff
        constraints = app.HBonds
        system = prmtop.createSystem(nonbondedMethod=method,
                                     nonbondedCutoff=cutoff,
                                     constraints=constraints)
        if options.ensemble == 'NVE':
            integ = mm.VerletIntegrator(dt)
        else:
            integ = mm.LangevinMiddleIntegrator(temperature, friction, dt)
    else:
        if apoa1:
            ff = app.ForceField('amber14/protein.ff14SB.xml',
                                'amber14/lipid17.xml', 'amber14/tip3p.xml')
            pdb = app.PDBFile('apoa1.pdb')
            if testName == 'apoa1pme':
                method = app.PME
                cutoff = options.cutoff
            elif testName == 'apoa1ljpme':
                method = app.LJPME
                cutoff = options.cutoff
            else:
                method = app.CutoffPeriodic
                cutoff = 1 * unit.nanometers
            hydrogenMass = 1.5 * unit.amu
        elif explicit:
            ff = app.ForceField('amber99sb.xml', 'tip3p.xml')
            pdb = app.PDBFile('5dfr_solv-cube_equil.pdb')
            if testName == 'pme':
                method = app.PME
                cutoff = options.cutoff
            else:
                method = app.CutoffPeriodic
                cutoff = 1 * unit.nanometers
        else:
            ff = app.ForceField('amber99sb.xml', 'amber99_obc.xml')
            pdb = app.PDBFile('5dfr_minimized.pdb')
            method = app.CutoffNonPeriodic
            cutoff = 2 * unit.nanometers
        if options.heavy:
            dt = 0.005 * unit.picoseconds
            constraints = app.AllBonds
            hydrogenMass = 4 * unit.amu
            if options.ensemble == 'NVE':
                integ = mm.VerletIntegrator(dt)
            else:
                integ = mm.LangevinIntegrator(temperature, friction, dt)
        else:
            dt = 0.004 * unit.picoseconds
            constraints = app.HBonds
            if options.ensemble == 'NVE':
                integ = mm.VerletIntegrator(dt)
            else:
                integ = mm.LangevinMiddleIntegrator(temperature, friction, dt)
        positions = pdb.positions
        system = ff.createSystem(pdb.topology,
                                 nonbondedMethod=method,
                                 nonbondedCutoff=cutoff,
                                 constraints=constraints,
                                 hydrogenMass=hydrogenMass)
    if options.ensemble == 'NPT':
        system.addForce(mm.MonteCarloBarostat(1 * unit.bar, temperature, 100))
    print('Step Size: %g fs' % dt.value_in_unit(unit.femtoseconds))
    properties = {}
    initialSteps = 5
    if options.device is not None and platform.getName() in ('CUDA', 'OpenCL'):
        properties['DeviceIndex'] = options.device
        if ',' in options.device or ' ' in options.device:
            initialSteps = 250
    if options.precision is not None and platform.getName() in ('CUDA',
                                                                'OpenCL'):
        properties['Precision'] = options.precision

    # Run the simulation.

    integ.setConstraintTolerance(1e-5)
    if len(properties) > 0:
        context = mm.Context(system, integ, platform, properties)
    else:
        context = mm.Context(system, integ, platform)
    context.setPositions(positions)
    if amber:
        if inpcrd.boxVectors is not None:
            context.setPeriodicBoxVectors(*inpcrd.boxVectors)
        mm.LocalEnergyMinimizer.minimize(
            context, 100 * unit.kilojoules_per_mole / unit.nanometer)
    context.setVelocitiesToTemperature(temperature)

    steps = 20
    while True:
        time = timeIntegration(context, steps, initialSteps)
        if time >= 0.5 * options.seconds:
            break
        if time < 0.5:
            steps = int(
                steps * 1.0 / time
            )  # Integrate enough steps to get a reasonable estimate for how many we'll need.
        else:
            steps = int(steps * options.seconds / time)
    print('Integrated %d steps in %g seconds' % (steps, time))
    print('%g ns/day' %
          (dt * steps * 86400 / time).value_in_unit(unit.nanoseconds))
Exemple #14
0
def create_openmm_system(sim_openmm, model, anchor):
    """
    Create an openmm System() object.
    """
    building_directory = os.path.join(model.anchor_rootdir, anchor.directory,
                                      anchor.building_directory)
    box_vectors = None
    if anchor.amber_params is not None:
        prmtop_filename = os.path.join(building_directory,
                                       anchor.amber_params.prmtop_filename)
        prmtop = openmm_app.AmberPrmtopFile(prmtop_filename)
        assert anchor.amber_params.pdb_coordinates_filename is not None
        pdb_coordinates_filename = os.path.join(
            building_directory, anchor.amber_params.pdb_coordinates_filename)
        positions = openmm_app.PDBFile(pdb_coordinates_filename)
        #assert anchor.amber_params.box_vectors is not None
        box_vectors = anchor.amber_params.box_vectors
        topology = prmtop

    elif anchor.forcefield_params is not None:
        forcefield_filenames = []
        for forcefield_filename in \
                anchor.forcefield_params.built_in_forcefield_filenames:
            forcefield_filenames.append(forcefield_filename)
        for forcefield_filename in \
                anchor.forcefield_params.custom_forcefield_filenames:
            forcefield_filenames.append(
                os.path.join(building_directory, forcefield_filename))
        pdb_filename = os.path.join(building_directory,
                                    anchor.forcefield_params.pdb_filename)
        pdb = openmm_app.PDBFile(pdb_filename)
        forcefield = openmm_app.ForceField(*forcefield_filenames)
        box_vectors = anchor.forcefield_params.box_vectors

        topology = pdb
        positions = pdb

    elif anchor.charmm_params is not None:
        raise Exception("Charmm systems not yet implemented")

    else:
        raise Exception("No Amber or Charmm input settings detected.")

    #assert box_vectors is not None, "No source of box vectors provided."
    nonbonded_method = model.openmm_settings.nonbonded_method.lower()
    if nonbonded_method == "pme":
        nonbondedMethod = openmm_app.PME

    elif nonbonded_method == "nocutoff":
        nonbondedMethod = openmm_app.NoCutoff

    elif nonbonded_method == "cutoffnonperiodic":
        nonbondedMethod = openmm_app.CutoffNonPeriodic

    elif nonbonded_method == "cutoffperiodic":
        nonbondedMethod = openmm_app.CutoffPeriodic

    elif nonbonded_method == "ewald":
        nonbondedMethod = openmm_app.Ewald

    else:
        raise Exception("nonbonded method not found: %s",
                        model.openmm_settings.nonbonded_method)

    if model.openmm_settings.constraints is None:
        constraints_str = None
    else:
        constraints_str = model.openmm_settings.constraints

    if constraints_str is None:
        constraints = None

    elif constraints_str.lower() == "none":
        constraints = None

    elif constraints_str.lower() == "hbonds":
        constraints = openmm_app.HBonds

    elif constraints_str.lower() == "allbonds":
        constraints = openmm_app.AllBonds

    elif constraints_str.lower() == "hangles":
        constraints = openmm_app.HAngles

    else:
        raise Exception("constraints not found: %s",
                        model.openmm_settings.constraints)

    if model.openmm_settings.hydrogenMass:
        hydrogenMass = model.openmm_settings.hydrogenMass * openmm.unit.amu
    else:
        hydrogenMass = model.openmm_settings.hydrogenMass
    rigidWater = model.openmm_settings.rigidWater

    if anchor.amber_params is not None:
        system = prmtop.createSystem(
            nonbondedMethod=nonbondedMethod,
            nonbondedCutoff=model.openmm_settings.nonbonded_cutoff,
            constraints=constraints,
            hydrogenMass=hydrogenMass,
            rigidWater=rigidWater)

    elif anchor.forcefield_params is not None:
        system = forcefield.createSystem(
            pdb.topology,
            nonbondedMethod=nonbondedMethod,
            nonbondedCutoff=model.openmm_settings.nonbonded_cutoff,
            constraints=constraints,
            hydrogenMass=hydrogenMass,
            rigidWater=rigidWater)

    elif anchor.charmm_params is not None:
        raise Exception("Charmm input settings not yet implemented")

    else:
        print("Settings for Amber or Charmm simulations not found")

    return system, topology, positions, box_vectors
Exemple #15
0
molsys = msm.build.solvate(
    [molsys, {
        'forcefield': 'AMBER14',
        'water_model': 'TIP3P'
    }],
    box_geometry='truncated octahedral',
    clearance='14.0 angstroms',
    to_form='molsysmt.MolSys',
    engine="OpenMM",
    verbose=False)
_ = msm.convert(molsys, to_form='villin_hp35_solvated.msmpk')

# simulation
print('Trajectory files...')
modeller = msm.convert(molsys, to_form='openmm.Modeller')
forcefield = app.ForceField("amber14-all.xml", "amber14/tip3p.xml")
system = forcefield.createSystem(modeller.topology,
                                 nonbondedMethod=app.PME,
                                 nonbondedCutoff=1.2 * unit.nanometer,
                                 constraints=app.HBonds)
integrator = mm.LangevinIntegrator(300 * unit.kelvin, 1.0 / unit.picosecond,
                                   2.0 * unit.femtoseconds)
platform = mm.Platform.getPlatformByName('CUDA')
simulation = app.Simulation(modeller.topology, system, integrator, platform)
simulation.context.setPositions(modeller.positions)
simulation.minimizeEnergy()
simulation.context.setVelocitiesToTemperature(300 * unit.kelvin)
simulation.reporters.append(
    app.StateDataReporter(stdout,
                          50000,
                          progress=True,