示例#1
0
    def _get_prmtop(self, mol, prm):
        from htmd.parameterization.writers import writeFRCMOD, getAtomTypeMapping
        from tempfile import TemporaryDirectory
        from subprocess import call
        from simtk.openmm import app

        with TemporaryDirectory() as tmpDir:
            frcFile = os.path.join(tmpDir, 'mol.frcmod')
            mapping = getAtomTypeMapping(prm)
            writeFRCMOD(mol, prm, frcFile, typemap=mapping)
            mol2 = mol.copy()
            mol2.atomtype[:] = np.vectorize(mapping.get)(mol2.atomtype)
            molFile = os.path.join(tmpDir, 'mol.mol2')
            mol2.write(molFile)

            with open(os.path.join(tmpDir, 'tleap.inp'), 'w') as file:
                file.writelines(
                    ('loadAmberParams %s\n' % frcFile,
                     'MOL = loadMol2 %s\n' % molFile,
                     'saveAmberParm MOL mol.prmtop mol.inpcrd\n', 'quit'))

            with open(os.path.join(tmpDir, 'tleap.out'), 'w') as out:
                call(('tleap', '-f', 'tleap.inp'), cwd=tmpDir, stdout=out)

            prmtop = app.AmberPrmtopFile(os.path.join(tmpDir, 'mol.prmtop'))

        return prmtop
示例#2
0
    def _system_from_prmtop(self, prmtop_path, impcrd_path):
        # load in Amber input files
        prmtop = app.AmberPrmtopFile(prmtop_path)
        inpcrd = app.AmberInpcrdFile(incrd_path)
        from numpy import array, float64
        from simtk import unit
        positions = 10 * array(inpcrd.positions.value_in_unit(unit.nanometers),
                               float64)  # Angstroms
        self._particle_positions = positions

        # Ordered atoms to match inpcrd order.
        # PDB can have atoms for a chain not contiguous, e.g. chain A hetatm at end of file.
        # But inpcrd has reordered so all chain atoms are contiguous.
        atom_pos = atoms.scene_coords
        from chimerax.geometry import find_closest_points
        i1, i2, near = find_closest_points(positions, atom_pos, 1.0)
        from numpy import empty, int32
        ai = empty((len(i1), ), int32)
        ai[i1] = near
        self.atoms = oatoms = atoms[ai]
        #        diff = oatoms.scene_coords - positions
        #        print ('diff', diff.max(), diff.min())
        #        p2a = {tuple(int(x) for x in a.scene_coord):a for a in atoms}
        #        oatoms = [p2a[tuple(int(x) for x in p)] for p in positions]
        #        print('\n'.join('%s %s' %(str(a1), str(a2)) for a1,a2 in zip(atoms, oatoms)))
        #        print ('inpcrd', positions[:10])
        #        print ('atoms', atom_pos[:10])

        # prepare system and integrator
        system = prmtop.createSystem(nonbondedMethod=app.CutoffNonPeriodic,
                                     nonbondedCutoff=1.0 * unit.nanometers,
                                     constraints=app.HBonds,
                                     rigidWater=True,
                                     ewaldErrorTolerance=0.0005)
        self._system = system
示例#3
0
    def equilibrate(self):
        
        if os.path.exists(self.equil_pdb_filename):
            return

        prmtop = app.AmberPrmtopFile(self.prmtop_filename)
        inpcrd = app.AmberInpcrdFile(self.inpcrd_filename)

        system = prmtop.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=CUTOFF, constraints=app.HBonds)
        integrator = mm.LangevinIntegrator(self.temperature, EQUIL_FRICTION, EQUIL_TIMESTEP)
        system.addForce(mm.MonteCarloBarostat(PRESSURE, self.temperature, BAROSTAT_FREQUENCY))

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

        state = simulation.context.getState(getEnergy=True)
        print(state.getPotentialEnergy())
        
        print('Minimizing.')
        simulation.minimizeEnergy()
        
        state = simulation.context.getState(getEnergy=True)
        print(state.getPotentialEnergy())

        simulation.context.setVelocitiesToTemperature(self.temperature)
        print('Equilibrating.')

        simulation.reporters.append(app.DCDReporter(self.equil_dcd_filename, OUTPUT_FREQUENCY_EQUIL))
        simulation.step(N_EQUIL_STEPS)

        # Re-write a better PDB with correct box sizes.
        traj = md.load(self.equil_dcd_filename, top=self.prmtop_filename)[-1]
        traj.save(self.equil_pdb_filename)
示例#4
0
def MinimizedEnergy(filepath, gpu=False):
    prmtop = app.AmberPrmtopFile(f'{filepath}.prmtop')
    inpcrd = app.AmberInpcrdFile(f'{filepath}.inpcrd')
    print(f'{filepath}.prmtop')
    system = prmtop.createSystem(implicitSolvent=app.GBn2,
                                 nonbondedMethod=app.CutoffNonPeriodic,
                                 nonbondedCutoff=1.0 * unit.nanometers,
                                 constraints=app.HBonds,
                                 rigidWater=True,
                                 ewaldErrorTolerance=0.0005)

    integrator = mm.LangevinIntegrator(310.15 * unit.kelvin,
                                       1.0 / unit.picoseconds,
                                       2.0 * unit.femtoseconds)
    integrator.setConstraintTolerance(0.00001)
    # TODO: This should just recognize whatever the computer is capable of, not force CUDA.

    if gpu:
        platform = 'CUDA'
    else:
        platform = 'CPU'
    platform = mm.Platform.getPlatformByName(platform)

    simulation = app.Simulation(prmtop.topology, system, integrator, platform)
    simulation.context.setPositions(inpcrd.positions)

    simulation.minimizeEnergy()
    energy = simulation.context.getState(
        getEnergy=True).getPotentialEnergy().value_in_unit(unit.kilojoule /
                                                           unit.mole)
    return energy
示例#5
0
def _openmm_init(fname_prmtop, platformName=None):

    prmtop = app.AmberPrmtopFile(fname_prmtop)
    system = prmtop.createSystem(nonbondedMethod=app.NoCutoff,
                                 constraints=app.HBonds,
                                 implicitSolvent=None)
    time_step = 1.0  # fs
    integrator = omm.LangevinIntegrator(300.0 * unit.kelvin,
                                        1.0 / unit.picoseconds,
                                        time_step * unit.femtoseconds)

    platform = omm.Platform.getPlatformByName('Reference')
    properties = {}
    if platformName == 'OpenCL':
        platform = omm.Platform.getPlatformByName('OpenCL')
        properties = {'OpenCLPrecision': 'mixed'}
    if platformName == 'CUDA':
        platform = omm.Platform.getPlatformByName('CUDA')
        properties = {'CudaPrecision': 'mixed'}

    simulation = app.Simulation(prmtop.topology, system, integrator, platform,
                                properties)

    charge_list = prmtop._prmtop.getCharges()
    natom = prmtop._prmtop.getNumAtoms()
    nonbond = np.array(prmtop._prmtop.getNonbondTerms())

    return simulation, natom, charge_list, nonbond
示例#6
0
def MinimizedEnergy(filepath):
    prmtop = app.AmberPrmtopFile(f'{filepath}.prmtop')
    inpcrd = app.AmberInpcrdFile(f'{filepath}.inpcrd')
    system = prmtop.createSystem(implicitSolvent=app.GBn2,
                                 nonbondedMethod=app.CutoffNonPeriodic,
                                 nonbondedCutoff=1.0*unit.nanometers,
                                 constraints=app.HBonds,
                                 rigidWater=True,
                                 ewaldErrorTolerance=0.0005)

    integrator = mm.LangevinIntegrator(300*unit.kelvin,
                                       1.0/unit.picoseconds,
                                       2.0*unit.femtoseconds)
    integrator.setConstraintTolerance(0.00001)
    # TODO: This should just recognize whatever the computer is capable of, not force CUDA.
    platform = mm.Platform.getPlatformByName('CUDA')
    # TODO: I am not sure if mixed precision is necessary. It dramatically changes the results.
    properties = {'CudaPrecision': 'mixed'}
    
    simulation = app.Simulation(prmtop.topology, system, integrator, platform)
    simulation.context.setPositions(inpcrd.positions)
    
    simulation.minimizeEnergy()
    energy = simulation.context.getState(getEnergy=True).getPotentialEnergy().value_in_unit(unit.kilojoule/unit.mole)
    return energy
示例#7
0
    def _create_implicit_solvent_openmm(self, mol):
        """
        Take a list of oemols, and generate openmm systems
        and positions for each.

        Parameters
        ----------
        mol : oemol
            oemol to be turned into system, positions

        Returns
        -------
        system : simtk.openmm.System
            openmm system corresponding to molecule
        positions : np.array, Quantity nm
           array of atomic positions
        """
        molecule_name = oeiupac.OECreateIUPACName(mol)
        openmoltools.openeye.enter_temp_directory()
        _, tripos_mol2_filename = openmoltools.openeye.molecule_to_mol2(
            mol,
            tripos_mol2_filename=molecule_name + '.tripos.mol2',
            conformer=0,
            residue_name='MOL')
        gaff_mol2, frcmod = openmoltools.amber.run_antechamber(
            molecule_name, tripos_mol2_filename)
        prmtop_file, inpcrd_file = openmoltools.amber.run_tleap(
            molecule_name, gaff_mol2, frcmod)
        prmtop = app.AmberPrmtopFile(prmtop_file)
        crd = app.AmberInpcrdFile(inpcrd_file)
        system = prmtop.createSystem(implicitSolvent=self.implicit_solvent,
                                     constraints=self.constraints,
                                     removeCMMotion=False)
        positions = crd.getPositions(asNumpy=True)
        return system, positions
示例#8
0
    def _get_prmtop(self):
        from parameterize.parameterization.writers import (
            writeFRCMOD,
            getAtomTypeMapping,
        )

        with TemporaryDirectory() as tmpDir:
            frcFile = os.path.join(tmpDir, "mol.frcmod")
            mapping = getAtomTypeMapping(self._parameters)
            writeFRCMOD(self.molecule,
                        self._parameters,
                        frcFile,
                        typemap=mapping)
            mol2 = self.molecule.copy()
            mol2.atomtype[:] = np.vectorize(mapping.get)(mol2.atomtype)
            molFile = os.path.join(tmpDir, "mol.mol2")
            mol2.write(molFile)

            with open(os.path.join(tmpDir, "tleap.inp"), "w") as file:
                file.writelines((
                    "loadAmberParams %s\n" % frcFile,
                    "MOL = loadMol2 %s\n" % molFile,
                    "saveAmberParm MOL mol.prmtop mol.inpcrd\n",
                    "quit",
                ))

            with open(os.path.join(tmpDir, "tleap.out"), "w") as out:
                call(("tleap", "-f", "tleap.inp"), cwd=tmpDir, stdout=out)

            prmtop = app.AmberPrmtopFile(os.path.join(tmpDir, "mol.prmtop"))

        return prmtop
示例#9
0
 def setUp(self):
     self.temperature = 300.0 * unit.kelvin
     self.pressure = 1.0 * unit.atmospheres
     self.timestep = 1.0 * unit.femtoseconds
     self.collision_rate = 9.1 / unit.picoseconds
     self.pH = 7.4
     self.platform_name = 'CPU'
     testsystems = get_data('edchky_explicit', 'testsystems')
     self.positions = openmm.XmlSerializer.deserialize(
         open('{}/edchky-explicit.state.xml'.format(
             testsystems)).read()).getPositions(asNumpy=True)
     self.system = openmm.XmlSerializer.deserialize(
         open('{}/edchky-explicit.sys.xml'.format(testsystems)).read())
     self.prmtop = app.AmberPrmtopFile(
         '{}/edchky-explicit.prmtop'.format(testsystems))
     self.cpin_filename = '{}/edchky-explicit.cpin'.format(testsystems)
     calibration_settings = dict()
     calibration_settings["temperature"] = self.temperature
     calibration_settings["timestep"] = self.timestep
     calibration_settings["pressure"] = self.pressure
     calibration_settings["collision_rate"] = self.collision_rate
     calibration_settings["pH"] = self.pH
     calibration_settings["solvent"] = "explicit"
     calibration_settings["nsteps_per_trial"] = 5
     self.calibration_settings = calibration_settings
示例#10
0
def create_system_from_amber(prmtop_filename, crd_filename, verbose=False):
    """Utility function. Create and return an OpenMM System given a prmtop and
       crd, AMBER format files.

    Parameters
    ----------
    prmtop_filename : str (filename)
        Filename of input AMBER format prmtop file
    crd_filename : str (filename)
        Filename of input AMBER format crd file

    Returns
    _______
    topology : OpenMM Topology
    system : OpenMM System
    positions : initial atomic positions (OpenMM)
"""

    # Create System object
    prmtop = app.AmberPrmtopFile(prmtop_filename)
    topology = prmtop.topology
    system = prmtop.createSystem(nonbondedMethod=app.NoCutoff,
                                 constraints=None,
                                 implicitSolvent=None)

    # Read coordinates
    crd = app.AmberInpcrdFile(crd_filename)
    positions = crd.getPositions()

    return (topology, system, positions)
示例#11
0
 def _setup_OpenMM(self, moiety, phase):
     if not hasattr(self, '_OpenMM_sims'):
         self._OpenMM_sims = {}
     key = moiety + phase
     if not key in self._OpenMM_sims.keys():
         import simtk.openmm
         import simtk.openmm.app as OpenMM_app
         prmtop = OpenMM_app.AmberPrmtopFile(
             self.args.FNs['prmtop'][moiety])
         inpcrd = OpenMM_app.AmberInpcrdFile(
             self.args.FNs['inpcrd'][moiety])
         OMM_system = prmtop.createSystem(nonbondedMethod=OpenMM_app.NoCutoff, \
           constraints=None, implicitSolvent={
             'OpenMM_Gas':None,
             'OpenMM_GBn':OpenMM_app.GBn,
             'OpenMM_GBn2':OpenMM_app.GBn2,
             'OpenMM_HCT':OpenMM_app.HCT,
             'OpenMM_OBC1':OpenMM_app.OBC1,
             'OpenMM_OBC2':OpenMM_app.OBC2}[phase])
         # Set receptor atom mass to zero to facilitate future minimization
         if moiety == 'R':
             for i in range(OMM_system.getNumParticles()):
                 OMM_system.setParticleMass(i, 0)
         elif moiety == 'RL':
             for i in range(self.top_RL.L_first_atom) + \
                 range(self.top_RL.L_first_atom + self.top.universe.numberOfAtoms(), \
                 OMM_system.getNumParticles()):
                 OMM_system.setParticleMass(i, 0)
         dummy_integrator = simtk.openmm.LangevinIntegrator(300*simtk.unit.kelvin, \
           1/simtk.unit.picosecond, 0.002*simtk.unit.picoseconds)
         self._OpenMM_sims[key] = OpenMM_app.Simulation(prmtop.topology, \
           OMM_system, dummy_integrator)
示例#12
0
def test_amber_implicit(prmtop_filename, inpcrd_filename):
    logger.info("====================================================================")
    logger.info("Creating system...")

    from simtk.openmm import app
    prmtop = app.AmberPrmtopFile(prmtop_filename)
    reference_system = prmtop.createSystem(constraints=app.HBonds, nonbondedMethod=app.NoCutoff, implicitSolvent=app.OBC1)

    # Read positions.
    inpcrd = app.AmberInpcrdFile(inpcrd_filename, loadBoxVectors=False)
    positions = inpcrd.getPositions(asNumpy=True)

    # Set box vectors.
    #box_vectors = inpcrd.getBoxVectors(asNumpy=True)
    #system.setDefaultPeriodicBoxVectors(box_vectors[0], box_vectors[1], box_vectors[2])

    receptor_atoms = range(0,1326)
    ligand_atoms = range(1326, 1356)

    # Minimize.
    logger.info("Minimizing...")
    timestep = 1.0 * units.femtoseconds
    integrator = openmm.VerletIntegrator(timestep)
    context = openmm.Context(reference_system, integrator)
    context.setPositions(positions)
    openmm.LocalEnergyMinimizer.minimize(context, 1.0, 100)
    state = context.getState(getEnergy=True, getPositions=True)
    positions = state.getPositions(asNumpy=True)
    del context, integrator
    logger.info("Done.")

    alchemical_factory_check(reference_system, positions, receptor_atoms, ligand_atoms)
    #benchmark(reference_system, positions, receptor_atoms, ligand_atoms)
    logger.info("====================================================================")
    logger.info("")
示例#13
0
def oemol_to_openmm_system(oemol, molecule_name):
    """
    Create an openmm system out of an oemol

    Returns
    -------
    system : openmm.System object
        the system from the molecule
    positions : [n,3] np.array of floats
    """
    _, tripos_mol2_filename = openmoltools.openeye.molecule_to_mol2(
        oemol,
        tripos_mol2_filename=molecule_name + '.tripos.mol2',
        conformer=0,
        residue_name='MOL')
    gaff_mol2, frcmod = openmoltools.openeye.run_antechamber(
        molecule_name, tripos_mol2_filename)
    prmtop_file, inpcrd_file = openmoltools.utils.run_tleap(
        molecule_name, gaff_mol2, frcmod)
    prmtop = app.AmberPrmtopFile(prmtop_file)
    # NOTE implicit solvent not supported by this SystemGenerator
    #system = prmtop.createSystem(implicitSolvent=app.OBC1)
    system = prmtop.createSystem(implicitSolvent=None)
    crd = app.AmberInpcrdFile(inpcrd_file)
    return system, crd.getPositions(asNumpy=True), prmtop.topology
示例#14
0
 def build(self, target_path="", file_name="out"):
     build_string = self.build_string 
     if self.chains:
         for chain in self.chains:
             self.build_string += chain.structure.init_string
         for index, chain in enumerate(self.chains):
             if chain.sequence:
                 self.build_string +="""
                                     CHAIN%s = sequence {%s}
                                     """%(index, chain.sequence)
             else:
                 raise ValueError("Empty Chain Index: %s"%index)
         chain_string = " ".join(["CHAIN%s"%index for index in range(len(self.chains))])
         self.build_string +="""
                             UNION = combine {%s}
                             saveamberparm UNION %s.prmtop %s.inpcrd
                             quit
                             """%(chain_string, target_path+file_name, target_path+file_name)
         infile = open("%s%s.in"%(target_path, file_name),"w")
         infile.write(self.build_string)
         infile.close()
         self.build_string = build_string
         #os.remove("%s%s.in"%(target_path, file_name))
         result = subprocess.call("tleap -f %s%s.in"%(target_path,file_name),shell=True)
         self.prmtop = app.AmberPrmtopFile(target_path+file_name+".prmtop")
         self.inpcrd = app.AmberInpcrdFile(target_path+file_name+".inpcrd")
         self.topology = self.prmtop.topology
         self.positions = self.inpcrd.positions
         self.system = self.prmtop.createSystem(nonbondedMethod=app.NoCutoff, constraints=None, implicitSolvent=app.OBC1)
         self.integrator = mm.LangevinIntegrator(300.*unit.kelvin, 1./unit.picosecond, 0.002*unit.picoseconds)
         self.simulation = app.Simulation(self.topology, self.system, self.integrator)
     else:
         raise ValueError('Empty Complex! CANNOT build!')
示例#15
0
    def production(self):  

        if os.path.exists(self.production_dcd_filename) and os.path.exists(self.production_data_filename):
            return

        prmtop = app.AmberPrmtopFile(self.prmtop_filename)
        pdb = app.PDBFile(self.equil_pdb_filename)

        system = prmtop.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=CUTOFF, constraints=app.HBonds)

        integrator = mm.LangevinIntegrator(self.temperature, FRICTION, TIMESTEP)
        system.addForce(mm.MonteCarloBarostat(PRESSURE, self.temperature, BAROSTAT_FREQUENCY))

        simulation = app.Simulation(prmtop.topology, system, integrator)
        
        simulation.context.setPositions(pdb.positions)
        simulation.context.setPeriodicBoxVectors(*pdb.topology.getPeriodicBoxVectors())
        simulation.context.setVelocitiesToTemperature(self.temperature)
        
        print('Production.')
        
        simulation.reporters.append(app.DCDReporter(self.production_dcd_filename, OUTPUT_FREQUENCY))
        simulation.reporters.append(app.StateDataReporter(self.production_data_filename, OUTPUT_DATA_FREQUENCY, step=True, potentialEnergy=True, temperature=True, density=True))

        converged = False
        while not converged:
            simulation.step(N_STEPS)
            d = pd.read_csv(self.production_data_filename, names=["step", "U", "Temperature", "Density"], skiprows=1)
            density_ts = np.array(d.Density)
            [t0, g, Neff] = ts.detectEquilibration(density_ts, nskip=1000)
            density_ts = density_ts[t0:]
            density_mean_stderr = density_ts.std() / np.sqrt(Neff)
            if density_mean_stderr < STD_ERROR_TOLERANCE:
                converged = True
示例#16
0
def parameterize_molecule(molecule, implicitSolvent=app.OBC1, constraints=None, cleanup=True, verbose=False):
    """
    Parameterize the specified molecule for AMBER.

    Parameters
    ----------
    molecule : openeye.oechem.OEMol
        The molecule to be parameterized.
    implicitSolvent : default=app.OBC1
        The implicit solvent model to use; one of [None, HCT, OBC1, OBC2, GBn, GBn2]
    constraints : default=None
        Constraints to use; one of [None, HBonds, AllBonds, HAngles]
    cleanup : bool, optional, default=False
        If True, work done in a temporary working directory will be deleted.

    Returns
    -------
    system : simtk.openmm.System
        The OpenMM System of the molecule.
    topology : simtk.openmm.app.Topology
        The OpenMM topology of the molecule.
    positions :
        The positions of the molecule.
    gaff_molecule : oechem.OEMol
        The OEMol molecule with GAFF atom and bond types.

    """
    # Create molecule and geometry.
    molecule = gaff2xml.openeye.iupac_to_oemol(iupac_name)
    # Create a a temporary directory.
    working_directory = tempfile.mkdtemp()
    old_directory = os.getcwd()
    os.chdir(working_directory)
    # Parameterize molecule for AMBER (currently using old machinery for convenience)
    # TODO: Replace this with gaff2xml stuff
    amber_prmtop_filename = 'molecule.prmtop'
    amber_inpcrd_filename = 'molecule.inpcrd'
    amber_off_filename = 'molecule.off'
    oldmmtools.parameterizeForAmber(molecule, amber_prmtop_filename, amber_inpcrd_filename, charge_model=None, offfile=amber_off_filename)
    # Read in the molecule with GAFF atom and bond types
    print "Overwriting OEMol with GAFF atom and bond types..."
    gaff_molecule = oldmmtools.loadGAFFMolecule(molecule, amber_off_filename)

    # Load positions.
    inpcrd = app.AmberInpcrdFile(amber_inpcrd_filename)
    positions = inpcrd.getPositions()

    # Load system (with GB parameters).
    prmtop = app.AmberPrmtopFile(amber_prmtop_filename)
    system = prmtop.createSystem(implicitSolvent=implicitSolvent, constraints=constraints)

    # Clean up temporary files.
    os.chdir(old_directory)
    if cleanup:
        commands.getoutput('rm -r %s' % working_directory)
    else:
        print "Work done in %s..." % working_directory

    return [system, topology, positions, gaff_molecule]
示例#17
0
 def setup_simulation(self, system, settings):
     inpcrd = app.AmberInpcrdFile(settings['coordinates'])
     prmtop = app.AmberPrmtopFile(self.topology)
     platform, prop = self.setup_platform(settings)
     simulation = app.Simulation(prmtop.topology, system, self.integrator,
                                 platform, prop)
     simulation.context.setPositions(inpcrd.positions)
     return simulation
示例#18
0
    def serialise_system(self):
        """Serialise the amber style files into an openmm object."""

        prmtop = app.AmberPrmtopFile(self.prmtop)
        system = prmtop.createSystem(nonbondedMethod=app.NoCutoff, constraints=None)

        with open('serialised.xml', 'w+') as out:
            out.write(XmlSerializer.serializeSystem(system))
示例#19
0
    def build_simulation_from_dictionary(self):
        d = {}
        d = json.load(open(self.lot_inp_file))
        print(d)

        # crystal
        use_crystal = d.get('use_crystal', 'no')

        # PME
        use_pme = d.get('use_pme', 'no')
        cutoff = d.get('cutoff', 1.0)

        # prmtop, inpcrd
        prmtopfile = d.get('prmtop', None)
        inpcrdfile = d.get('inpcrd', None)

        # Integrator will never be used (Simulation requires one)
        integrator = openmm.VerletIntegrator(1.0)

        # create simulation object
        if use_crystal == 'yes':
            crystal = load_file(prmtopfile, inpcrdfile)

            if use_pme == 'yes':
                system = crystal.createSystem(
                    nonbondedMethod=openmm_app.PME,
                    nonbondedCutoff=cutoff * openmm_units.nanometer,
                )
            else:
                system = crystal.createSystem(
                    nonbondedMethod=openmm_app.NoCutoff, )
            self.simulation = openmm_app.Simulation(crystal.topology, system,
                                                    integrator)
            # set the box vectors
            inpcrd = openmm_app.AmberInpcrdFile(inpcrdfile)
            if inpcrd.boxVectors is not None:
                print(" setting box vectors")
                print(inpcrd.boxVectors)
                self.simulation.context.setPeriodicBoxVectors(
                    *inpcrd.boxVectors)
        else:
            prmtop = openmm_app.AmberPrmtopFile(prmtopfile)
            if use_pme == 'yes':
                system = prmtop.createSystem(
                    nonbondedMethod=openmm_app.PME,
                    nonbondedCutoff=cutoff * openmm_units.nanometer,
                )
            else:
                system = prmtop.createSystem(
                    nonbondedMethod=openmm_app.NoCutoff, )
            self.simulation = openmm_app.Simulation(
                prmtop.topology,
                system,
                integrator,
            )
示例#20
0
def simulate(inpcrd_filenames, prmtop_filenames, path, niterations=10000, implicit=True, gpu=True, niters=0):
    """
    The program simulates three systems: the ligand alone, protein alone, and complex.
    Input is a dict of files to the input coordinates (.inpcrd) and parameters (.prmtop) 
      as well as the number of iterations. One iteration is one picosecond. 
    Output is a dict of a list of the ennthalpies calculated using mmgbsa for each system.
    """
    from simtk.openmm import app
    import simtk.openmm as mm
    from simtk import unit
    
    phases = inpcrd_filenames.keys()
    nsteps_per_iteration = 500 # 1 picosecond
    
    enthalpies = dict()
    for phase in phases:
        print("on phase", phase)
        enthalpies[phase] = np.zeros([niterations])
        prmtop = app.AmberPrmtopFile(prmtop_filenames[phase])
        inpcrd = app.AmberInpcrdFile(inpcrd_filenames[phase])
        
        system = prmtop.createSystem(implicitSolvent=app.GBn2, 
                 nonbondedMethod=app.CutoffNonPeriodic,
                 nonbondedCutoff=2.0*unit.nanometers, 
                 constraints=app.HBonds)
        integrator = mm.LangevinIntegrator(310.15*unit.kelvin, 1.0/unit.picoseconds, 2.0*unit.femtoseconds)
        integrator.setConstraintTolerance(0.00001)
        if gpu:
            platform = 'CUDA'
        else:
            platform = 'CPU'
        platform = mm.Platform.getPlatformByName(platform)
        if gpu:
            properties = {'CudaPrecision': 'mixed', 'CudaDeviceIndex' : '0'}
        else:
            properties = {}
        simulation = app.Simulation(prmtop.topology, system, integrator, platform, properties)
        simulation.context.setPositions(inpcrd.positions)
        if phase == 'com':
            simulation.reporters.append(app.PDBReporter(path + '/' + phase + '_output.pdb', 10000))
        # Minimize & equilibrate
        simulation.minimizeEnergy()
        simulation.context.setVelocitiesToTemperature(310.15*unit.kelvin)
        simulation.step(100)

        # Run simulation
        for iteration in range(niterations):
            simulation.step(nsteps_per_iteration)
            state = simulation.context.getState(getEnergy=True)
            potential_energy = state.getPotentialEnergy()
            enthalpies[phase][iteration] = potential_energy.value_in_unit(unit.kilojoules_per_mole)
        del simulation
        del system
        del platform
    return enthalpies
示例#21
0
 def _build_system(self,
                   molecule: Ligand,
                   input_files: Optional[List[str]] = None) -> System:
     """
     Build a system using the amber prmtop files, first we must use antechamber to prep the molecule.
     """
     prmtoop_file = self._get_prmtop(molecule=molecule)
     prmtop = app.AmberPrmtopFile(prmtoop_file)
     system = prmtop.createSystem(nonbondedMethod=app.NoCutoff,
                                  constraints=None)
     return system
示例#22
0
    def __init__(self, config: Config):
        """

        :param resource_root:
        """
        super().__init__()
        self.systemloader_config = config
        self.prmtop = app.AmberPrmtopFile(
            self.systemloader_config.resource_root + 'com.prmtop')
        self.inpcrd = app.AmberInpcrdFile(
            self.systemloader_config.resource_root + 'com.inpcrd')
示例#23
0
 def setUp(self):
     prmtop = app.AmberPrmtopFile('systems/water-box-216.prmtop')
 
     system = prmtop.createSystem(nonbondedMethod=app.PME, 
                                      nonbondedCutoff=0.9*unit.nanometers,
                                      constraints=app.HBonds, rigidWater=True, 
                                      ewaldErrorTolerance=0.0005)
     integrator = mm.LangevinIntegrator(300*unit.kelvin, 1.0/unit.picoseconds, 
                                        2.0*unit.femtoseconds)
     self.simulation = app.Simulation(prmtop.topology, system, integrator,
                                 mm.Platform.getPlatformByName('Reference'))
示例#24
0
def runEquilibration(equilibrationFiles, reportName, parameters, worker):
    """
    Function that runs the whole equilibration process and returns the final pdb

    :param equilibrationFiles: tuple with the topology (prmtop) in the first position and the coordinates
    in the second (inpcrd)
    :type equilibrationFiles: tuple
    :param outputPDB: string with the pdb to save
    :type outputPDB: str
    :param parameters: Object with the parameters for the simulation
    :type parameters: :py:class:`/simulationrunner/SimulationParameters` -- SimulationParameters object
    :param worker: Number of the subprocess
    :type worker: int

    :returns: str -- a string with the outputPDB
    """
    prmtop, inpcrd = equilibrationFiles
    prmtop = app.AmberPrmtopFile(prmtop)
    inpcrd = app.AmberInpcrdFile(inpcrd)
    PLATFORM = mm.Platform_getPlatformByName(str(parameters.runningPlatform))
    if parameters.runningPlatform == "CUDA":
        platformProperties = {"Precision": "mixed", "DeviceIndex": getDeviceIndexStr(worker, parameters.devicesPerTrajectory, devicesPerReplica=parameters.maxDevicesPerReplica), "UseCpuPme": "false"}
    else:
        platformProperties = {}
    if worker == 0:
        utilities.print_unbuffered("Running %d steps of minimization" % parameters.minimizationIterations)

    if parameters.boxCenter or parameters.cylinderBases:
        dummies = findDummyAtom(prmtop)
        assert dummies is not None
    else:
        dummies = None
    simulation = minimization(prmtop, inpcrd, PLATFORM, parameters.constraintsMin, parameters, platformProperties, dummies)
    # Retrieving the state is expensive (especially when running on GPUs) so we
    # only called it once and then separate positions and velocities
    state = simulation.context.getState(getPositions=True, getVelocities=True)
    positions = state.getPositions()
    velocities = state.getVelocities()
    if worker == 0:
        utilities.print_unbuffered("Running %d steps of NVT equilibration" % parameters.equilibrationLengthNVT)
    simulation = NVTequilibration(prmtop, positions, PLATFORM, parameters.equilibrationLengthNVT, parameters.constraintsNVT, parameters, reportName, platformProperties, velocities=velocities, dummy=dummies)
    state = simulation.context.getState(getPositions=True, getVelocities=True)
    positions = state.getPositions()
    velocities = state.getVelocities()
    if worker == 0:
        utilities.print_unbuffered("Running %d steps of NPT equilibration" % parameters.equilibrationLengthNPT)
    simulation = NPTequilibration(prmtop, positions, PLATFORM, parameters.equilibrationLengthNPT, parameters.constraintsNPT, parameters, reportName, platformProperties, velocities=velocities, dummy=dummies)
    state = simulation.context.getState(getPositions=True)
    root, _ = os.path.splitext(reportName)
    outputPDB = "%s_NPT.pdb" % root
    with open(outputPDB, 'w') as fw:
        app.PDBFile.writeFile(simulation.topology, state.getPositions(), fw)
    return outputPDB
示例#25
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)
示例#26
0
def ligand_energy():
        #self.command("saveamberparm ligand ligand.prmtop ligand.inpcrd")
        #time.sleep(1)
        from  mpmath import mp as math
        math.prec = 200
        lig_top = app.AmberPrmtopFile("ligand.prmtop")
        lig_crd = app.AmberInpcrdFile("ligand.inpcrd")
        lig_system = lig_top.createSystem(nonbondedMethod=NoCutoff, nonbondedCutoff=10*nanometer, constraints=HAngles, implicitSolvent=OBC1)
        lig_integrator = LangevinIntegrator(300*kelvin, 1/picosecond, 0.002*picoseconds)
        lig_simulation = Simulation(lig_top.topology, lig_system, lig_integrator)
        lig_simulation.context.setPositions(lig_crd.positions)
        lig_state = lig_simulation.context.getState(getEnergy = True)
        lig_energy = lig_state.getPotentialEnergy().value_in_unit(kilojoule_per_mole)
        return lig_energy
示例#27
0
def step(array):
    global _INFILE
    global _BETA
    global _NSTEP
    beta = _BETA
    old_positions, Ntides, is_3prime = array
    internal = Aptamer("leaprc.ff12SB",_INFILE)
    identifier = Ntides.replace(" ","")
    internal.sequence(identifier,Ntides.strip())
    internal.unify(identifier)
    internal.command("saveamberparm union %s.prmtop %s.inpcrd"%(identifier,identifier))
    time.sleep(2)
    
    #print("WhereamI?")
    print("Identifier: "+Ntides)

    volume = (2*math.pi)**5
    aptamer_top = app.AmberPrmtopFile("%s.prmtop"%identifier)
    aptamer_crd = app.AmberInpcrdFile("%s.inpcrd"%identifier)
    
#    print("loaded")
    
#    if is_3prime == 1:
    en_pos = [mcmc_sample(aptamer_top, aptamer_crd, old_positions, index, Nsteps=_NSTEP) for index in range(10)]
#    else:
#        en_pos_task = [mcmc_sample_five(aptamer_top, aptamer_crd, old_positions, index, Nsteps=200) for index in range(20)]
#    barrier()
#    en_pos = value(en_pos_task)
    en = []
    positions = []
    positions_s = []
    for elem in en_pos:
        en += elem[0]
        #print(elem[2], elem[1])
        positions_s.append([elem[2], elem[1]])
    
    positions = min(positions_s)[1]
    
    fil = open("best_structure%s.pdb"%Ntides,"w")
    app.PDBFile.writeModel(aptamer_top.topology,positions,file=fil)
    fil.close()
    del fil
    
    Z = volume*math.fsum([math.exp(-beta*elem) for elem in en])/len(en)
    P = [math.exp(-beta*elem)/Z for elem in en]
    S = volume*math.fsum([-elem*math.log(elem*volume) for elem in P])/len(P)
    
    print("%s : %s"%(Ntides,S))
    
    return positions, Ntides, S
示例#28
0
    def from_amber(cls, prmtop, inpcrd, temperature=50 * u.kelvin):
        prmtop = app.AmberPrmtopFile(prmtop)
        inpcrd = app.AmberInpcrdFile(inpcrd)
        system = prmtop.createSystem(nonbondedMethod=app.PME,
                                     constraints=app.HBonds,
                                     nonbondedCutoff=10 * u.angstroms,
                                     switchDistance=8 * u.angstroms)

        thermodynamic_state = ThermodynamicState(system,
                                                 temperature=temperature)
        sampler_state = SamplerState(
            positions=inpcrd.getPositions(asNumpy=True),
            box_vectors=inpcrd.boxVectors)

        return Esmacs(thermodynamic_state, sampler_state, prmtop.topology)
示例#29
0
 def setUp(self):
     self.temperature = 300.0 * unit.kelvin
     self.pressure = 1.0 * unit.atmospheres
     self.timestep = 1.0 * unit.femtoseconds
     self.collision_rate = 9.1 / unit.picoseconds
     self.pH = 9.6
     self.platform_name = 'CPU'
     testsystems = get_data('tyr_explicit', 'testsystems')
     self.positions = openmm.XmlSerializer.deserialize(
         open('{}/tyr.state.xml'.format(testsystems)).read()).getPositions(
             asNumpy=True)
     self.system = openmm.XmlSerializer.deserialize(
         open('{}/tyr.sys.xml'.format(testsystems)).read())
     self.prmtop = app.AmberPrmtopFile('{}/tyr.prmtop'.format(testsystems))
     self.cpin_filename = '{}/tyr.cpin'.format(testsystems)
示例#30
0
def load_lb(cutoff=1.1 * u.nanometers,
            constraints=app.HBonds,
            hydrogenMass=1.0 * u.amu):
    prmtop_filename = "./input/126492-54-4_1000_300.6.prmtop"
    pdb_filename = "./input/126492-54-4_1000_300.6_equil.pdb"

    pdb = app.PDBFile(pdb_filename)
    prmtop = app.AmberPrmtopFile(prmtop_filename)
    system = prmtop.createSystem(
        nonbondedMethod=app.PME,
        nonbondedCutoff=cutoff,
        constraints=constraints,
        hydrogenMass=hydrogenMass
    )  # Force rigid water here for comparison to other code
    return system, pdb.positions