def _initialize(self): # Create an integrator integrator_name = 'Langevin' if integrator_name == 'GHMC': from openmmtools.integrators import GHMCIntegrator self.integrator = GHMCIntegrator( temperature=self.thermodynamic_state.temperature, collision_rate=self.collision_rate, timestep=self.timestep) elif integrator_name == 'Langevin': from simtk.openmm import LangevinIntegrator self.integrator = LangevinIntegrator( self.thermodynamic_state.temperature, self.collision_rate, self.timestep) else: raise Exception("integrator_name '%s' not valid." % (integrator_name)) # Create a Context if self.platform is not None: self.context = openmm.Context(self.thermodynamic_state.system, self.integrator, self.platform) else: self.context = openmm.Context(self.thermodynamic_state.system, self.integrator) self.thermodynamic_state.update_context(self.context, self.integrator) self.sampler_state.update_context(self.context) self.context.setVelocitiesToTemperature( self.thermodynamic_state.temperature) self._initialized = True
def _initialize(self): system = self._explorer.context.getSystem() platform = self._explorer.context.getPlatform() properties = {} if platform.getName() == 'CUDA': properties['CudaPrecision'] = 'mixed' self._integrator = LangevinIntegrator(self._temperature, self._collision_rate, self._timestep) self._context = Context(system, self._integrator, platform, properties) self._initialized = True
def get_potential_energy(item, coordinates=None, platform_name='CUDA'): from simtk.openmm import LangevinIntegrator, Platform, Context from simtk import unit import numpy as np integrator = LangevinIntegrator(0.0 * unit.kelvin, 0.0 / unit.picoseconds, 2.0 * unit.femtoseconds) platform = Platform.getPlatformByName(platform_name) context = Context(item.system, integrator, platform) if coordinates is None: context.setPositions(item.coordinates) else: context.setPositions(coordinates) if item.box is not None: context.setPeriodicBoxVectors(item.box[0], item.box[1], item.box[2]) state = context.getState(getEnergy=True) potential_energy = state.getPotentialEnergy() return potential_energy
def _calc_energy(self, coords): """ Given some coords, it calculates periodic torsion contribution to the energy, according to OpenMM. Parameters ---------- coords : a simtk.unit.Quantity object The coordinates of a certain conformation of the molecule Returns ------- omm_energy : a simtk.unit.Quantity The dihedral energy from OpenMM """ from simtk.openmm import app, LangevinIntegrator, unit omm_idx_to_force = {} for idx, force in enumerate(self.omm_system.getForces()): force.setForceGroup(idx) omm_idx_to_force[str(type(force).__name__)] = idx omm_integrator = LangevinIntegrator(300 * unit.kelvin, 1 / unit.picosecond, 0.002 * unit.picoseconds) omm_simulation = app.Simulation(self.omm_top, self.omm_system, omm_integrator) omm_simulation.context.setPositions(coords) omm_energy = omm_simulation.context.getState( getEnergy=True, groups={omm_idx_to_force['PeriodicTorsionForce'] }).getPotentialEnergy() return omm_energy
def energy_minimization(item, platform_name='CUDA', verbose=True): from simtk.openmm import LangevinIntegrator, Platform, Context, LocalEnergyMinimizer_minimize from simtk import unit # Integrator. integrator = LangevinIntegrator(0 * unit.kelvin, 1.0 / unit.picoseconds, 2.0 * unit.femtoseconds) # Platform. platform = Platform.getPlatformByName(platform_name) # Context. context = Context(item.system, integrator, platform) context.setPositions(item.coordinates) # Minimization. if verbose == True: energy = context.getState(getEnergy=True).getPotentialEnergy() print('Potential energy before minimization: {}'.format(energy)) LocalEnergyMinimizer_minimize(context) if verbose == True: energy = context.getState(getEnergy=True).getPotentialEnergy() print('Potential energy after minimization: {}'.format(energy)) item.coordinates = context.getState(getPositions=True).getPositions( asNumpy=True) pass
def _prep_sim(self, coords, external_forces=[]): try: from simtk.openmm import Platform, LangevinIntegrator, Vec3 from simtk.openmm.app import Modeller, ForceField, \ CutoffNonPeriodic, PME, Simulation, HBonds from simtk.unit import angstrom, nanometers, picosecond, \ kelvin, Quantity, molar except ImportError: raise ImportError( 'Please install PDBFixer and OpenMM in order to use ClustENM.') positions = Quantity([Vec3(*xyz) for xyz in coords], angstrom) modeller = Modeller(self._topology, positions) if self._sol == 'imp': forcefield = ForceField(*self._force_field) system = forcefield.createSystem(modeller.topology, nonbondedMethod=CutoffNonPeriodic, nonbondedCutoff=1.0 * nanometers, constraints=HBonds) if self._sol == 'exp': forcefield = ForceField(*self._force_field) modeller.addSolvent(forcefield, padding=self._padding * nanometers, ionicStrength=self._ionicStrength * molar) system = forcefield.createSystem(modeller.topology, nonbondedMethod=PME, nonbondedCutoff=1.0 * nanometers, constraints=HBonds) for force in external_forces: system.addForce(force) integrator = LangevinIntegrator(self._temp * kelvin, 1 / picosecond, 0.002 * picosecond) # precision could be mixed, but single is okay. platform = self._platform if self._platform is None else Platform.getPlatformByName( self._platform) properties = None if self._platform is None: properties = {'Precision': 'single'} elif self._platform in ['CUDA', 'OpenCL']: properties = {'Precision': 'single'} simulation = Simulation(modeller.topology, system, integrator, platform, properties) simulation.context.setPositions(modeller.positions) return simulation
def minimise_energy_all_confs(mol, models = None, epsilon = 4, allow_undefined_stereo = True, **kwargs ): from simtk import unit from simtk.openmm import LangevinIntegrator from simtk.openmm.app import Simulation, HBonds, NoCutoff from rdkit import Chem from rdkit.Geometry import Point3D import mlddec import copy import tqdm mol = Chem.AddHs(mol, addCoords = True) if models is None: models = mlddec.load_models(epsilon) charges = mlddec.get_charges(mol, models) from openforcefield.utils.toolkits import RDKitToolkitWrapper, ToolkitRegistry from openforcefield.topology import Molecule, Topology from openforcefield.typing.engines.smirnoff import ForceField # from openforcefield.typing.engines.smirnoff.forcefield import PME import parmed import numpy as np forcefield = ForceField(get_data_filename("modified_smirnoff99Frosst.offxml")) #FIXME better way of identifying file location tmp = copy.deepcopy(mol) tmp.RemoveAllConformers() #XXX workround for speed beacuse seemingly openforcefield records all conformer informations, which takes a long time. but I think this is a ill-practice molecule = Molecule.from_rdkit(tmp, allow_undefined_stereo = allow_undefined_stereo) molecule.partial_charges = unit.Quantity(np.array(charges), unit.elementary_charge) topology = Topology.from_molecules(molecule) openmm_system = forcefield.create_openmm_system(topology, charge_from_molecules= [molecule]) structure = parmed.openmm.topsystem.load_topology(topology.to_openmm(), openmm_system) system = structure.createSystem(nonbondedMethod=NoCutoff, nonbondedCutoff=1*unit.nanometer, constraints=HBonds) integrator = LangevinIntegrator(273*unit.kelvin, 1/unit.picosecond, 0.002*unit.picoseconds) simulation = Simulation(structure.topology, system, integrator) out_mol = copy.deepcopy(mol) for i in tqdm.tqdm(range(out_mol.GetNumConformers())): conf = mol.GetConformer(i) structure.coordinates = unit.Quantity(np.array([np.array(conf.GetAtomPosition(i)) for i in range(mol.GetNumAtoms())]), unit.angstroms) simulation.context.setPositions(structure.positions) simulation.minimizeEnergy() # simulation.step(1) coords = simulation.context.getState(getPositions = True).getPositions(asNumpy = True).value_in_unit(unit.angstrom) conf = out_mol.GetConformer(i) for j in range(out_mol.GetNumAtoms()): conf.SetAtomPosition(j, Point3D(*coords[j])) return out_mol
def _create_integrator(temperature, use_big_timestep, use_bigger_timestep): if use_big_timestep: logger.info("Creating integrator with 3.5 fs timestep") timestep = 3.5 * femtosecond elif use_bigger_timestep: logger.info("Creating integrator with 4.5 fs timestep") timestep = 4.5 * femtosecond else: logger.info("Creating integrator with 2.0 fs timestep") timestep = 2.0 * femtosecond return LangevinIntegrator(temperature * kelvin, 1.0 / picosecond, timestep)
def __init__(self, topology=None, system=None, pbc=False, platform='CUDA'): from .md import MD from .quench import Quench from .move import Move from .distance import Distance from .acceptance import Acceptance if topology is None: raise ValueError('topology is needed') if system is None: raise ValueError('system is needed') integrator = LangevinIntegrator(0 * u.kelvin, 1.0 / u.picoseconds, 2.0 * u.femtoseconds) #integrator.setConstraintTolerance(0.00001) if platform == 'CUDA': platform = Platform.getPlatformByName('CUDA') properties = {'CudaPrecision': 'mixed'} elif platform == 'CPU': platform = Platform.getPlatformByName('CPU') properties = {} self.topology = topology self.context = Context(system, integrator, platform, properties) self.n_atoms = msm.get(self.context, target='system', n_atoms=True) self.n_dof = 0 for i in range(system.getNumParticles()): if system.getParticleMass(i) > 0 * u.dalton: self.n_dof += 3 for i in range(system.getNumConstraints()): p1, p2, distance = system.getConstraintParameters(i) if system.getParticleMass( p1) > 0 * u.dalton or system.getParticleMass( p2) > 0 * u.dalton: self.n_dof -= 1 if any( type(system.getForce(i)) == CMMotionRemover for i in range(system.getNumForces())): self.n_dof -= 3 self.pbc = pbc if self.pbc: raise NotImplementedError self.md = MD(self) self.quench = Quench(self) self.move = Move(self) self.distance = Distance(self) self.acceptance = Acceptance(self)
def test_xtc_reporter_append(tmpdir, get_fn): pdb = PDBFile(get_fn('native.pdb')) forcefield = ForceField('amber99sbildn.xml', 'amber99_obc.xml') # NO PERIODIC BOUNDARY CONDITIONS system = forcefield.createSystem(pdb.topology, nonbondedMethod=CutoffNonPeriodic, nonbondedCutoff=1.0 * nanometers, constraints=HBonds, rigidWater=True) integrator = LangevinIntegrator(300 * kelvin, 1.0 / picoseconds, 2.0 * femtoseconds) integrator.setConstraintTolerance(0.00001) platform = Platform.getPlatformByName('Reference') simulation = Simulation(pdb.topology, system, integrator, platform) simulation.context.setPositions(pdb.positions) simulation.context.setVelocitiesToTemperature(300 * kelvin) tmpdir = str(tmpdir) xtcfile = os.path.join(tmpdir, 'traj.xtc') xtcfile_cp = os.path.join(tmpdir, 'traj_cp.xtc') checkpoint = os.path.join(tmpdir, 'checkpoint.chk') reporter = XTCReporter(xtcfile, 2) simulation.reporters.append(reporter) simulation.reporters.append(CheckpointReporter(checkpoint, 10)) simulation.step(10) reporter.close() shutil.copyfile(xtcfile, xtcfile_cp) system = forcefield.createSystem(pdb.topology, nonbondedMethod=CutoffNonPeriodic, nonbondedCutoff=1.0 * nanometers, constraints=HBonds, rigidWater=True) integrator = LangevinIntegrator(300 * kelvin, 1.0 / picoseconds, 2.0 * femtoseconds) integrator.setConstraintTolerance(0.00001) platform = Platform.getPlatformByName('Reference') simulation = Simulation(pdb.topology, system, integrator, platform) simulation.loadCheckpoint(checkpoint) reporter = XTCReporter(xtcfile, 2, append=True) simulation.reporters.append(reporter) simulation.step(10) reporter.close() xtc_traj = md.load(xtcfile, top=get_fn('native.pdb')) xtc_traj_cp = md.load(xtcfile_cp, top=get_fn('native.pdb')) eq(xtc_traj.xyz[:5], xtc_traj_cp.xyz) eq(xtc_traj.n_frames, 10) eq(xtc_traj_cp.n_frames, 5) eq(xtc_traj.time[:5], xtc_traj_cp.time)
def _initialize(self): # Create an integrator integrator_name = 'Langevin' if integrator_name == 'GHMC': from openmmtools.integrators import GHMCIntegrator self.integrator = GHMCIntegrator(temperature=self.thermodynamic_state.temperature, collision_rate=self.collision_rate, timestep=self.timestep) elif integrator_name == 'Langevin': from simtk.openmm import LangevinIntegrator self.integrator = LangevinIntegrator(self.thermodynamic_state.temperature, self.collision_rate, self.timestep) else: raise Exception("integrator_name '%s' not valid." % (integrator_name)) # Create a Context if self.platform is not None: self.context = openmm.Context(self.thermodynamic_state.system, self.integrator, self.platform) else: self.context = openmm.Context(self.thermodynamic_state.system, self.integrator) self.thermodynamic_state.update_context(self.context, self.integrator) self.sampler_state.update_context(self.context) self.context.setVelocitiesToTemperature(self.thermodynamic_state.temperature) self._initialized = True
def calculate_fragment_energetics(frag_no=1): """ * Create an OpenMM system with a fragment. * Calculate the energy of the system and print. :param frag_no: The number of the fragment being analysed (used to access files). """ os.chdir(f'group2/frag{frag_no}') # Necessary due to size of calculation sys.setrecursionlimit(15000) pdb = PDBFile(f'QUBE_pro_frag{frag_no}.pdb') forcefield = ForceField(f'QUBE_pro_frag{frag_no}_plus.xml') system = forcefield.createSystem( pdb.topology, nonbondedMethod=NoCutoff, ) system = apply_opls_combo(system) with open(f'QUBE_pro_frag{frag_no}_out.xml', 'w') as outfile: serialized_system = XmlSerializer.serialize(system) outfile.write(serialized_system) # Create the integrator to do Langevin dynamics integrator = LangevinIntegrator( 298.15 * unit.kelvin, # Temperature of heat bath 1.0 / unit.picoseconds, # Friction coefficient 2.0 * unit.femtoseconds, # Time step ) platform = Platform.getPlatformByName('CPU') simulation = Simulation(pdb.topology, system, integrator, platform) simulation.context.setPositions(pdb.positions) print('energy from openmm library') print(simulation.context.getState(getEnergy=True).getPotentialEnergy()) structure = parmed.load_file(f'QUBE_pro_frag{frag_no}.pdb') energy_comps = parmed.openmm.energy_decomposition_system(structure, system) total_energy = 0.0 for comp in energy_comps: total_energy += comp[1] print(*comp) print(f'Total energy {total_energy: 6.6f}')
def calc_energy(omm_sys, omm_top, coords): omm_idx_to_force = {} for idx, force in enumerate(omm_sys.getForces()): force.setForceGroup(idx) omm_idx_to_force[idx] = str(type(force).__name__) omm_integrator = LangevinIntegrator(300*unit.kelvin, 1/unit.picosecond, 0.002*unit.picoseconds) omm_simulation = app.Simulation(omm_top, omm_sys, omm_integrator) #simulation.context.setPositions(positions) omm_simulation.context.setPositions(coords) for group in omm_idx_to_force.keys(): omm_energy = omm_simulation.context.getState(getEnergy=True,groups={group}).getPotentialEnergy() print(omm_idx_to_force[group], omm_energy) omm_energy = omm_simulation.context.getState(getEnergy=True).getPotentialEnergy() return omm_energy
def __init__(self, pdb_path, offset_size=2): # OpenMM init self.pdb_path = pdb_path self.pdb = PDBFile(self.pdb_path) self.forcefield = ForceField('amber14-all.xml', 'amber14/tip3pfb.xml') self.modeller = Modeller(self.pdb.topology, self.pdb.positions) # Remove any water that might be present in the PDB file self.modeller.deleteWater() # Add any hydrogens not present self.modeller.addHydrogens(self.forcefield) self.system = self.forcefield.createSystem(self.modeller.topology, nonbondedMethod=PME, nonbondedCutoff=1 * u.nanometer, constraints=HBonds) self.integrator = LangevinIntegrator(300 * u.kelvin, 1 / u.picosecond, 0.002 * u.picoseconds) self.simulation = Simulation(self.modeller.topology, self.system, self.integrator) self.pdb_positions = self.modeller.getPositions() # Initialize bond dictionary and positions for chemcoord self.cc_bonds = {} self.offset_size = offset_size self._init_pdb_bonds() self.set_cc_positions(self.pdb_positions) # Perform initial minimization, which updates self.pdb_positions min_energy, min_positions = self.run_simulation() # Reset the positions after the minimization self.set_cc_positions(self.pdb_positions) self.torsion_indices = self._get_torsion_indices() self.starting_positions = min_positions self.starting_torsions = np.array([ self.zmat.loc[self.torsion_indices[:, 0], 'dihedral'], self.zmat.loc[self.torsion_indices[:, 1], 'dihedral'] ]).T self.seed_offsets()
def test_xtc_reporter_append(tmpdir, get_fn): pdb = PDBFile(get_fn('native.pdb')) forcefield = ForceField('amber99sbildn.xml', 'amber99_obc.xml') # NO PERIODIC BOUNDARY CONDITIONS system = forcefield.createSystem(pdb.topology, nonbondedMethod=CutoffNonPeriodic, nonbondedCutoff=1.0 * nanometers, constraints=HBonds, rigidWater=True) integrator = LangevinIntegrator(300 * kelvin, 1.0 / picoseconds, 2.0 * femtoseconds) integrator.setConstraintTolerance(0.00001) platform = Platform.getPlatformByName('Reference') simulation = Simulation(pdb.topology, system, integrator, platform) simulation.context.setPositions(pdb.positions) simulation.context.setVelocitiesToTemperature(300 * kelvin) tmpdir = str(tmpdir) xtcfile = os.path.join(tmpdir, 'traj.xtc') xtcfile_cp = os.path.join(tmpdir, 'traj_cp.xtc') checkpoint = os.path.join(tmpdir, 'checkpoint.chk') reporter = XTCReporter(xtcfile, 2) simulation.reporters.append(reporter) simulation.reporters.append(CheckpointReporter(checkpoint, 10)) simulation.step(10) reporter.close() shutil.copyfile(xtcfile, xtcfile_cp) system = forcefield.createSystem(pdb.topology, nonbondedMethod=CutoffNonPeriodic, nonbondedCutoff=1.0 * nanometers, constraints=HBonds, rigidWater=True) integrator = LangevinIntegrator(300 * kelvin, 1.0 / picoseconds, 2.0 * femtoseconds) integrator.setConstraintTolerance(0.00001) platform = Platform.getPlatformByName('Reference') simulation = Simulation(pdb.topology, system, integrator, platform) simulation.loadCheckpoint(checkpoint) reporter = XTCReporter(xtcfile, 2, append=True) simulation.reporters.append(reporter) simulation.step(10) reporter.close() xtc_traj = md.load(xtcfile, top=get_fn('native.pdb')) xtc_traj_cp = md.load(xtcfile_cp, top=get_fn('native.pdb')) eq(xtc_traj.xyz[:5], xtc_traj_cp.xyz) eq(xtc_traj.n_frames, 10) eq(xtc_traj_cp.n_frames, 5) eq(xtc_traj.time[:5], xtc_traj_cp.time)
def test_reporter_subset(tmpdir, get_fn): pdb = PDBFile(get_fn('native2.pdb')) pdb.topology.setUnitCellDimensions([2, 2, 2]) forcefield = ForceField('amber99sbildn.xml', 'amber99_obc.xml') system = forcefield.createSystem(pdb.topology, nonbondedMethod=CutoffPeriodic, nonbondedCutoff=1 * nanometers, constraints=HBonds, rigidWater=True) integrator = LangevinIntegrator(300 * kelvin, 1.0 / picoseconds, 2.0 * femtoseconds) integrator.setConstraintTolerance(0.00001) platform = Platform.getPlatformByName('Reference') simulation = Simulation(pdb.topology, system, integrator, platform) simulation.context.setPositions(pdb.positions) simulation.context.setVelocitiesToTemperature(300 * kelvin) tmpdir = str(tmpdir) hdf5file = os.path.join(tmpdir, 'traj.h5') ncfile = os.path.join(tmpdir, 'traj.nc') dcdfile = os.path.join(tmpdir, 'traj.dcd') xtcfile = os.path.join(tmpdir, 'traj.xtc') atomSubset = [0, 1, 2, 4, 5] reporter = HDF5Reporter(hdf5file, 2, coordinates=True, time=True, cell=True, potentialEnergy=True, kineticEnergy=True, temperature=True, velocities=True, atomSubset=atomSubset) reporter2 = NetCDFReporter(ncfile, 2, coordinates=True, time=True, cell=True, atomSubset=atomSubset) reporter3 = DCDReporter(dcdfile, 2, atomSubset=atomSubset) reporter4 = XTCReporter(xtcfile, 2, atomSubset=atomSubset) simulation.reporters.append(reporter) simulation.reporters.append(reporter2) simulation.reporters.append(reporter3) simulation.reporters.append(reporter4) simulation.step(100) reporter.close() reporter2.close() reporter3.close() reporter4.close() t = md.load(get_fn('native.pdb')) t.restrict_atoms(atomSubset) with HDF5TrajectoryFile(hdf5file) as f: got = f.read() eq(got.temperature.shape, (50,)) eq(got.potentialEnergy.shape, (50,)) eq(got.kineticEnergy.shape, (50,)) eq(got.coordinates.shape, (50, len(atomSubset), 3)) eq(got.velocities.shape, (50, len(atomSubset), 3)) eq(got.cell_lengths, 2 * np.ones((50, 3))) eq(got.cell_angles, 90 * np.ones((50, 3))) eq(got.time, 0.002 * 2 * (1 + np.arange(50))) assert f.topology == md.load(get_fn('native.pdb'), atom_indices=atomSubset).topology with NetCDFTrajectoryFile(ncfile) as f: xyz, time, cell_lengths, cell_angles = f.read() eq(cell_lengths, 20 * np.ones((50, 3))) eq(cell_angles, 90 * np.ones((50, 3))) eq(time, 0.002 * 2 * (1 + np.arange(50))) eq(xyz.shape, (50, len(atomSubset), 3)) hdf5_traj = md.load(hdf5file) dcd_traj = md.load(dcdfile, top=hdf5_traj) netcdf_traj = md.load(ncfile, top=hdf5_traj) xtc_traj = md.load(xtcfile, top=hdf5_traj) # we don't have to convert units here, because md.load already handles that eq(hdf5_traj.xyz, netcdf_traj.xyz) eq(hdf5_traj.unitcell_vectors, netcdf_traj.unitcell_vectors) eq(hdf5_traj.time, netcdf_traj.time) eq(xtc_traj.time, netcdf_traj.time) eq(dcd_traj.xyz, hdf5_traj.xyz) eq(xtc_traj.xyz, hdf5_traj.xyz) eq(dcd_traj.unitcell_vectors, hdf5_traj.unitcell_vectors)
def langevin_NVT(item, time = None, saving_timestep = None, integration_timestep= 2*unit.femtoseconds, friction=1.0/unit.picoseconds, temperature=300.0*unit.kelvin, initial_coordinates=None, initial_velocities=None, platform_name='CUDA', reporters=None, tqdm=True): """Newtonian classical dynamics of a molecular system with OpenMM. The trajectory of a newtonian classical dynamics of a molecular system is obtained together with the values of potential and kinetic energy. This method is nothing but a short cut to run quick molecular dynamics with the test systems of this library by means of OpenMM. Parameters ---------- system: simtk.openmm.System Molecular system as a system class of OpenMM (see: link) friction: unit.Quantity Damping parameter of the Langevin dynamics (in units of 1/time). initial_coordinates: unit.Quantity Initial coordinates of the system as a numpy array with shape [n_particles, 3] and units of length. Where 'n_particles' is the number of particles of the system. initial_velocities: unit.Quantity Initial velocities of the system as a numpy array with shape [n_particles, 3] and units of length/time. Where 'n_particles' is the number of particles of the system. integration_timestep: unit.Quantity Time step used by the integrator of the equations of motion. The parameter needs to have units of time. saving_timestep: unit.Quantity Time step used to report the output trajectory. The parameter needs to have units of time. total_time: unit.Quantity Total runing time of the simulation. The parameter needs to have units of time. platform_name: str (default: 'CPU') Platform to run the dynamics: 'CPU', 'OPENCL' or 'CUDA' (according to those options to run OpenMM, see documentation), verbose: bool (default: True) Verbose switcher. The method will print out information if the value is True. Returns ------- time: unit.Quantity Time as numpy array of shape [n_frames] with units of picoseconds. position: unit.Quantity Positions of the systems particles in every reported frame as numpy array of shape [n_frames, n_particles, 3] with units of nanometers. velocity: unit.Quantity Velocities of the systems particles in every reported frame as numpy array of shape [n_frames, n_particles, 3] with units of nanometers/picoseconds. kinetic_energy: unit.Quantity Kinetic energy of the system in every reported frame as numpy array of shape [n_frames] with units of kilocalories/mole. potential_energy: unit.Quantity Potential energy of the system in every reported frame as numpy array of shape [n_frames] with units of kilocalories/mole. Examples -------- >>> from uibcdf_test_systems import DoubleWell >>> from uibcdf_test_systems.simulation import newtonian >>> from simtk import unit >>> double_well = DoubleWell(n_particles = 1, mass = 64 * unit.amu, Eo=4.0 * unit.kilocalories_per_mole, a=1.0 * unit.nanometers, b=0.0 * unit.kilocalories_per_mole)) >>> initial_coordinates = np.zeros([1, 3], np.float32) * unit.nanometers >>> initial_velocities = np.zeros([1, 3], np.float32) * unit.nanometers/unit.picoseconds >>> initial_coordinates[0,0] = 1.0 * unit.nanometers >>> time, position, velocity, kinetic_energy, potential_energy = langevin_NVT(double_well, >>> friction = 0.1/unit.picoseconds, >>> initial_coordinates = initial_coordinates, >>> initial_velocities = initial_velocities, >>> integration_timestep = 0.02 * unit.picoseconds, >>> saving_timestep = 0.5 * unit.picoseconds, >>> total_time = 100 * unit.picoseconds) Notes ----- See the `corresponding documentation in the user guide regarding this method <../../simulations/newtonian.html>`_. Some simple examples on how this method is used can be found in the users guide sections corresponding to `the free particle <../../systems/free_particle.html>`_, `the harmonic well potential <../../systems/harmonic_well_potential.html>`_ or `the double well potential <../../systems/double_well_potential.html>`_. """ from simtk.openmm import LangevinIntegrator, Platform, Context from simtk import unit import numpy as np # System parameters. n_particles = item.system.getNumParticles() # Integrator. integrator = LangevinIntegrator(temperature, friction, integration_timestep) # Platform. platform = Platform.getPlatformByName(platform_name) # Simulation. simulation = Simulation(item.topology, item.system, integrator, platform) # Initial Context. if initial_coordinates is None: initial_coordinates = item.coordinates simulation.context.setPositions(initial_coordinates) if initial_velocities=='zeros' or initial_velocities is None: initial_velocities = np.zeros([n_particles, 3], np.float32) * unit.nanometers/unit.picosecond simulation.context.setVelocities(initial_velocities) elif initial_velocities=='boltzmann': simulation.context.setVelocitiesToTemperature(temperature) else: simulation.context.setVelocities(initial_velocities) # Reporters. default_reporter = False tqdm_reporter = False if reporters is None: reporters = [] if saving_timestep is not None and len(reporters)==0: saving_steps_interval = int(saving_timestep/integration_timestep) default_reporter = MolSysMTTrajectoryDictReporter(saving_steps_interval, time=True, coordinates=True, potentialEnergy=True, kineticEnergy=True, box=True) reporters.append(default_reporter) for reporter in reporters: simulation.reporters.append(reporter) # Initial report initial_state = simulation.context.getState(getEnergy=True, getPositions=True, getVelocities=True) for reporter in reporters: reporter.report(simulation, initial_state) n_steps = int(time/integration_timestep) if tqdm: tqdm_reporter = TQDMReporter(100, n_steps) simulation.reporters.append(tqdm_reporter) simulation.step(n_steps) if tqdm_reporter: tqdm_reporter.finalize() if default_reporter: return default_reporter.finalize() else: pass
def calculate_protein_energetics(): """ * Create an OpenMM system using the first fragment. * Add each fragment into the system. * Calculate the energy of the system and print. """ os.chdir('group2') # Necessary due to size of calculation sys.setrecursionlimit(15000) frag1 = PDBFile('frag1/no_QUP_frag1.pdb') forcefield = ForceField( 'frag1/QUBE_pro_frag1.xml', 'frag2/QUBE_pro_frag2_plus.xml', 'frag3/QUBE_pro_frag3_plus.xml', 'frag4/QUBE_pro_frag4_plus.xml', ) modeller = Modeller(frag1.topology, frag1.positions) frag2 = PDBFile('frag2/no_QUP_frag2.pdb') modeller.add(frag2.topology, frag2.positions) frag3 = PDBFile('frag3/no_QUP_frag3.pdb') modeller.add(frag3.topology, frag3.positions) frag4 = PDBFile('frag4/no_QUP_frag4.pdb') modeller.add(frag4.topology, frag4.positions) system = forcefield.createSystem( modeller.topology, nonbondedMethod=NoCutoff, ) system = apply_opls_combo(system) integrator = LangevinIntegrator( 298.15 * unit.kelvin, # Temperature of heat bath 1.0 / unit.picoseconds, # Friction coefficient 2.0 * unit.femtoseconds, # Time step ) platform = Platform.getPlatformByName('CPU') simulation = Simulation(modeller.topology, system, integrator, platform) simulation.context.setPositions(modeller.positions) print('energy from openmm library') print(simulation.context.getState(getEnergy=True).getPotentialEnergy()) positions = simulation.context.getState(getPositions=True).getPositions() with open('output.pdb', 'w') as out_file: PDBFile.writeFile(simulation.topology, positions, out_file) structure = parmed.load_file('output.pdb') energy_comps = parmed.openmm.energy_decomposition_system(structure, system) total_energy = 0.0 for comp in energy_comps: total_energy += comp[1] print(*comp) print(f'Total energy {total_energy: 6.6f}')
class Langevin(): _explorer = None _initialized = False _context = None _integrator = None _timestep = Quantity(value=2.0, unit=u.femtosecond) _temperature = Quantity(value=298.0, unit=u.kelvin) _collision_rate = Quantity(value=1.0, unit=1.0 / u.picosecond) def __init__(self, explorer): self._explorer = explorer def _initialize(self): system = self._explorer.context.getSystem() platform = self._explorer.context.getPlatform() properties = {} if platform.getName() == 'CUDA': properties['CudaPrecision'] = 'mixed' self._integrator = LangevinIntegrator(self._temperature, self._collision_rate, self._timestep) self._context = Context(system, self._integrator, platform, properties) self._initialized = True def set_parameters(self, temperature=Quantity(value=298.0, unit=u.kelvin), collision_rate=Quantity(value=1.0, unit=1.0 / u.picosecond), timestep=Quantity(value=2.0, unit=u.femtosecond)): self._timestep = timestep self._temperature = temperature self._collision_rate = collision_rate if self._initialized: self._integrator.setFriction( self._collision_rate.value_in_unit(u.picosecond**-1)) self._integrator.setTemperature( self._temperature.value_in_unit(u.kelvin)) self._integrator.setStepSize( self._timestep.value_in_unit(u.picoseconds)) else: self._initialize() def get_parameters(self): parameters = { 'timestep': self._timestep, 'temperature': self._temperature, 'collision_rate': self._collision_rate } return parameters def replicate_parameters(self, explorer): timestep = explorer.md.langevin._timestep temperature = explorer.md.langevin._temperature collision_rate = explorer.md.langevin._collision_rate self.set_paramters(temperature, collision_rate, timestep) def _set_coordinates(self, coordinates): self._context.setPositions(coordinates) def _get_coordinates(self): return self._context.getState(getPositions=True).getPositions( asNumpy=True) def _set_velocities(self, velocities): self._context.setVelocities(velocities) def _get_velocities(self): return self._context.getState(getVelocities=True).getVelocities( asNumpy=True) def _coordinates_to_explorer(self): self._explorer.set_coordinates(self._get_coordinates()) def _coordinates_from_explorer(self): self._set_coordinates(self._explorer.get_coordinates()) def _velocities_to_explorer(self): self._explorer.set_velocities(self._get_velocities()) def _velocities_from_explorer(self): self._set_velocities(self._explorer.get_velocities()) def get_time(self): return self._context.getState().getTime() def run(self, steps=0): if not self._initialized: self._initialize() self._coordinates_from_explorer() self._velocities_from_explorer() self._integrator.step(steps) self._coordinates_to_explorer() self._velocities_to_explorer() def __call__(self, *args, **kwargs): return self.run(*args, **kwargs)
from simtk.openmm import XmlSerializer, LangevinIntegrator, MonteCarloBarostat, Platform # Initialization with open("restrained.xml", "r") as f: system = XmlSerializer.deserialize(f.read()) coords = PDBFile(os.path.join('simulations', 'npt_production', 'input.pdb')) dt = 4.0 * unit.femtoseconds Temp = 298.15 * unit.kelvin Pres = 1.01325 * unit.bar out_freq = 2500 print_freq = 50000 MD_steps = 12500000 bar_freq = int(MD_steps / print_freq) integrator = LangevinIntegrator(Temp, 1.0 / unit.picoseconds, dt) barostat = MonteCarloBarostat(Pres, Temp, 100) system.addForce(barostat) # Simulation Object simulation = Simulation(coords.topology, system, integrator, Platform.getPlatformByName('CUDA'), { 'CudaDeviceIndex': '0', 'CudaPrecision': 'single' }) simulation.context.setPositions(coords.positions) simulation.reporters.append( DCDReporter(os.path.join('simulations', 'npt_production', 'test.dcd'), out_freq, False)) simulation.reporters.append(
def main(): parser = argparse.ArgumentParser(description='Runs local minimization on \ the protein-ligand complex using OpenMM') parser.add_argument('-l', '--ligand', action='store', nargs=1, dest='ligand', help='The ligand .pdb file to generate \ parameters for') parser.add_argument('-x', '--xml_ligand', action='store', nargs=1, dest='xml', help='The xml file containing ligand \ parameters - use full path if not in directory where \ this script is being executed from') parser.add_argument('-p', '--protein', action='store', nargs=1, dest='protein', help='The protein complex .pdb file') parser.add_argument('-i', '--input_directory', action='store', nargs=1, dest='input', default=['./'], help='Directory where \ input pdb files are stored') parser.add_argument('-o', '--output_directory', action='store', nargs=1, dest='output', default=['./'], help='Directory where \ output log should be written') args = vars(parser.parse_args()) #Load in ligand file and parameters ligand_pdbfile = PDBFile(args['input'][0] + '/' + args['ligand'][0]) ligand_system = parmed.load_file(args['xml'][0]) ligand_structure = load_topology(ligand_pdbfile.topology, ligand_system, xyz=ligand_pdbfile.positions) #Load in protein complex file and force field receptor_pdbfile = PDBFile(args['input'][0] + '/' + args['protein'][0]) receptor_pdbfile_name = args['protein'][0].split('.pdb')[-2] omm_forcefield = ForceField('amber14-all.xml') receptor_system = omm_forcefield.createSystem(receptor_pdbfile.topology) receptor_structure = load_topology(receptor_pdbfile.topology, receptor_system, xyz=receptor_pdbfile.positions) #Generate ligand-protein complex complex_structure = receptor_structure + ligand_structure complex_system = (complex_structure.createSystem(nonbondedMethod=NoCutoff, nonbondedCutoff=9.0 * angstrom, constraints=HBonds, removeCMMotion=False)) #Set up simulation parameters integrator = LangevinIntegrator(300 * kelvin, 1 / picosecond, 0.002 * picoseconds) simulation = Simulation(complex_structure.topology, complex_system, integrator) simulation.context.setPositions(complex_structure.positions) #Run local minimization simulation.minimizeEnergy() positions = simulation.context.getState(getPositions=True).getPositions() #Save minimized complex structure PDBFile.writeFile( simulation.topology, positions, open(args['output'][0] + '/' + receptor_pdbfile_name + '_min.pdb', 'w'))
def test_reporter(tmpdir, get_fn): pdb = PDBFile(get_fn('native.pdb')) forcefield = ForceField('amber99sbildn.xml', 'amber99_obc.xml') # NO PERIODIC BOUNDARY CONDITIONS system = forcefield.createSystem(pdb.topology, nonbondedMethod=CutoffNonPeriodic, nonbondedCutoff=1.0 * nanometers, constraints=HBonds, rigidWater=True) integrator = LangevinIntegrator(300 * kelvin, 1.0 / picoseconds, 2.0 * femtoseconds) integrator.setConstraintTolerance(0.00001) platform = Platform.getPlatformByName('Reference') simulation = Simulation(pdb.topology, system, integrator, platform) simulation.context.setPositions(pdb.positions) simulation.context.setVelocitiesToTemperature(300 * kelvin) tmpdir = str(tmpdir) hdf5file = os.path.join(tmpdir, 'traj.h5') ncfile = os.path.join(tmpdir, 'traj.nc') dcdfile = os.path.join(tmpdir, 'traj.dcd') reporter = HDF5Reporter(hdf5file, 2, coordinates=True, time=True, cell=True, potentialEnergy=True, kineticEnergy=True, temperature=True, velocities=True) reporter2 = NetCDFReporter(ncfile, 2, coordinates=True, time=True, cell=True) reporter3 = DCDReporter(dcdfile, 2) simulation.reporters.append(reporter) simulation.reporters.append(reporter2) simulation.reporters.append(reporter3) simulation.step(100) reporter.close() reporter2.close() reporter3.close() with HDF5TrajectoryFile(hdf5file) as f: got = f.read() eq(got.temperature.shape, (50, )) eq(got.potentialEnergy.shape, (50, )) eq(got.kineticEnergy.shape, (50, )) eq(got.coordinates.shape, (50, 22, 3)) eq(got.velocities.shape, (50, 22, 3)) eq(got.cell_lengths, None) eq(got.cell_angles, None) eq(got.time, 0.002 * 2 * (1 + np.arange(50))) assert f.topology == md.load(get_fn('native.pdb')).top with NetCDFTrajectoryFile(ncfile) as f: xyz, time, cell_lengths, cell_angles = f.read() eq(cell_lengths, None) eq(cell_angles, None) eq(time, 0.002 * 2 * (1 + np.arange(50))) hdf5_traj = md.load(hdf5file) dcd_traj = md.load(dcdfile, top=get_fn('native.pdb')) netcdf_traj = md.load(ncfile, top=get_fn('native.pdb')) # we don't have to convert units here, because md.load already # handles that assert hdf5_traj.unitcell_vectors is None eq(hdf5_traj.xyz, netcdf_traj.xyz) eq(hdf5_traj.unitcell_vectors, netcdf_traj.unitcell_vectors) eq(hdf5_traj.time, netcdf_traj.time) eq(dcd_traj.xyz, hdf5_traj.xyz)
# Solvate print('Adding solvent...') # we use the 'padding' option to define the periodic box. The PDB file does not contain any # unit cell information so we just create a box that has a 10A padding around the complex. modeller.addSolvent(system_generator.forcefield, model='tip3p', padding=10.0 * unit.angstroms) print('System has %d atoms' % modeller.topology.getNumAtoms()) with open(output_complex, 'w') as outfile: PDBFile.writeFile(modeller.topology, modeller.positions, outfile) # Create the system using the SystemGenerator system = system_generator.create_system(modeller.topology, molecules=ligand_mol) integrator = LangevinIntegrator(temperature, 1 / unit.picosecond, 0.002 * unit.picoseconds) system.addForce( openmm.MonteCarloBarostat(1 * unit.atmospheres, temperature, 25)) print('Default Periodic box:', system.getDefaultPeriodicBoxVectors()) simulation = Simulation(modeller.topology, system, integrator, platform=platform) context = simulation.context context.setPositions(modeller.positions) print('Minimising ...') simulation.minimizeEnergy() # Write out the minimised PDB. The 'enforcePeriodicBox=False' bit is important otherwise the different
class MCMCSampler(object): """ Markov chain Monte Carlo (MCMC) sampler. This is a minimal functional implementation placeholder until we can replace this with MCMCSampler from `openmmmcmc`. Properties ---------- positions : simtk.unit.Quantity of size [nparticles,3] with units compatible with nanometers The current positions. iteration : int Iterations completed. verbose : bool If True, verbose output is printed Examples -------- >>> # Create a test system >>> test = testsystems.AlanineDipeptideVacuum() >>> # Create a sampler state. >>> sampler_state = SamplerState(positions=test.positions) >>> # Create a thermodynamic state. >>> thermodynamic_state = ThermodynamicState(system=test.system, temperature=298.0*unit.kelvin) >>> # Create an MCMC sampler >>> sampler = MCMCSampler(thermodynamic_state, sampler_state) >>> # Run the sampler >>> sampler.verbose = False >>> sampler.run() """ def __init__(self, thermodynamic_state=None, sampler_state=None, platform=None, ncfile=None): """ Create an MCMC sampler. Parameters ---------- thermodynamic_state : ThermodynamicState The thermodynamic state to simulate sampler_state : SamplerState The initial sampler state to simulate from. platform : simtk.openmm.Platform, optional, default=None If specified, this platform will be used ncfile : netCDF4.Dataset, optional, default=None NetCDF storage file. """ if thermodynamic_state is None: raise Exception("'thermodynamic_state' must be specified") if sampler_state is None: raise Exception("'sampler_state' must be specified") self.thermodynamic_state = thermodynamic_state self.sampler_state = sampler_state # Initialize self.iteration = 0 # For GHMC / Langevin integrator self.collision_rate = 1.0 / unit.picoseconds self.timestep = 2.0 * unit.femtoseconds self.nsteps = 500 # number of steps per update self.verbose = True self.platform = platform # For writing PDB files self.pdbfile = None self.topology = None self._timing = dict() self._initializeNetCDF(ncfile) self._initialized = False def _initialize(self): # Create an integrator integrator_name = 'Langevin' if integrator_name == 'GHMC': from openmmtools.integrators import GHMCIntegrator self.integrator = GHMCIntegrator(temperature=self.thermodynamic_state.temperature, collision_rate=self.collision_rate, timestep=self.timestep) elif integrator_name == 'Langevin': from simtk.openmm import LangevinIntegrator self.integrator = LangevinIntegrator(self.thermodynamic_state.temperature, self.collision_rate, self.timestep) else: raise Exception("integrator_name '%s' not valid." % (integrator_name)) # Create a Context if self.platform is not None: self.context = openmm.Context(self.thermodynamic_state.system, self.integrator, self.platform) else: self.context = openmm.Context(self.thermodynamic_state.system, self.integrator) self.thermodynamic_state.update_context(self.context, self.integrator) self.sampler_state.update_context(self.context) self.context.setVelocitiesToTemperature(self.thermodynamic_state.temperature) self._initialized = True def _initializeNetCDF(self, ncfile): self.ncfile = ncfile if self.ncfile == None: return natoms = self.thermodynamic_state.system.getNumParticles() self.ncfile.createDimension('iterations', None) self.ncfile.createDimension('atoms', natoms) # TODO: What do we do if dimension can change? self.ncfile.createDimension('spatial', 3) self.ncfile.createVariable('positions', 'f4', dimensions=('iterations', 'atoms', 'spatial'), zlib=True, chunksizes=(1,natoms,3)) self.ncfile.createVariable('box_vectors', 'f4', dimensions=('iterations', 'spatial', 'spatial'), zlib=True, chunksizes=(1,3,3)) self.ncfile.createVariable('potential', 'f8', dimensions=('iterations',), chunksizes=(1,)) self.ncfile.createVariable('sample_positions_time', 'f4', dimensions=('iterations',), chunksizes=(1,)) # Weight adaptation information self.ncfile.createVariable('stage', 'i2', dimensions=('iterations',), chunksizes=(1,)) self.ncfile.createVariable('gamma', 'f8', dimensions=('iterations',), chunksizes=(1,)) def update(self): """ Update the sampler with one step of sampling. """ if not self._initialized: self._initialize() if self.verbose: print("." * 80) print("MCMC sampler iteration %d" % self.iteration) initial_time = time.time() # Reset statistics if hasattr(self.integrator, 'setGlobalVariableByName'): self.integrator.setGlobalVariableByName('naccept', 0) # Take some steps self.integrator.step(self.nsteps) # Get new sampler state. self.sampler_state = SamplerState.createFromContext(self.context) # Report statistics if hasattr(self.integrator, 'getGlobalVariableByName'): naccept = self.integrator.getGlobalVariableByName('naccept') fraction_accepted = float(naccept) / float(self.nsteps) if self.verbose: print("Accepted %d / %d GHMC steps (%.2f%%)." % (naccept, self.nsteps, fraction_accepted * 100)) final_time = time.time() elapsed_time = final_time - initial_time self._timing['sample positions'] = elapsed_time if self.verbose: final_energy = self.context.getState(getEnergy=True).getPotentialEnergy() * self.thermodynamic_state.beta print('Final energy is %12.3f kT' % (final_energy)) print('elapsed time %8.3f s' % elapsed_time) if self.ncfile: self.ncfile.variables['positions'][self.iteration,:,:] = self.sampler_state.positions[:,:] / unit.nanometers for k in range(3): self.ncfile.variables['box_vectors'][self.iteration,k,:] = self.sampler_state.box_vectors[k,:] / unit.nanometers self.ncfile.variables['potential'][self.iteration] = self.thermodynamic_state.beta * self.context.getState(getEnergy=True).getPotentialEnergy() self.ncfile.variables['sample_positions_time'][self.iteration] = elapsed_time # Increment iteration count self.iteration += 1 if self.verbose: print("." * 80) if self.pdbfile is not None: print("Writing frame...") from simtk.openmm.app import PDBFile PDBFile.writeModel(self.topology, self.sampler_state.positions, self.pdbfile, self.iteration) self.pdbfile.flush() def run(self, niterations=1): """ Run the sampler for the specified number of iterations Parameters ---------- niterations : int, optional, default=1 Number of iterations to run the sampler for. """ for iteration in range(niterations): self.update()
'nonbondedMethod': app.LJPME, 'nonbondedCutoff': 1 * nanometer } membrane_barostat = MonteCarloMembraneBarostat( 1 * bar, 0.0 * bar * nanometer, 308 * kelvin, MonteCarloMembraneBarostat.XYIsotropic, MonteCarloMembraneBarostat.ZFree, 15) system_generator = SystemGenerator( forcefields=['amber/lipid17.xml', 'amber/tip3p_standard.xml'], small_molecule_forcefield='gaff-2.11', barostat=membrane_barostat, forcefield_kwargs=forcefield_kwargs, periodic_forcefield_kwargs=periodic_forcefield_kwargs) system = system_generator.create_system(pdb.topology, molecules=molecule) integrator = LangevinIntegrator(300 * kelvin, 1 / picosecond, 0.002 * picosecond) platform = Platform.getPlatformByName('CUDA') simulation = app.Simulation(pdb.topology, system, integrator, platform) simulation.context.setPositions(pdb.positions) simulation.loadState('parent.xml') simulation.reporters.append( StateDataReporter('seg.nfo', 5000, step=True, potentialEnergy=True, kineticEnergy=True, temperature=True)) simulation.reporters.append(HDF5Reporter('seg.h5', 10000))
def _create_integrator(self, *args): from simtk.openmm import LangevinIntegrator return LangevinIntegrator(self.temperature, self.frictionCoeff, self.stepSize)
def test_reporter(tmpdir, get_fn): pdb = PDBFile(get_fn('native.pdb')) forcefield = ForceField('amber99sbildn.xml', 'amber99_obc.xml') # NO PERIODIC BOUNDARY CONDITIONS system = forcefield.createSystem(pdb.topology, nonbondedMethod=CutoffNonPeriodic, nonbondedCutoff=1.0 * nanometers, constraints=HBonds, rigidWater=True) integrator = LangevinIntegrator(300 * kelvin, 1.0 / picoseconds, 2.0 * femtoseconds) integrator.setConstraintTolerance(0.00001) platform = Platform.getPlatformByName('Reference') simulation = Simulation(pdb.topology, system, integrator, platform) simulation.context.setPositions(pdb.positions) simulation.context.setVelocitiesToTemperature(300 * kelvin) tmpdir = str(tmpdir) hdf5file = os.path.join(tmpdir, 'traj.h5') ncfile = os.path.join(tmpdir, 'traj.nc') dcdfile = os.path.join(tmpdir, 'traj.dcd') xtcfile = os.path.join(tmpdir, 'traj.xtc') reporter = HDF5Reporter(hdf5file, 2, coordinates=True, time=True, cell=True, potentialEnergy=True, kineticEnergy=True, temperature=True, velocities=True) reporter2 = NetCDFReporter(ncfile, 2, coordinates=True, time=True, cell=True) reporter3 = DCDReporter(dcdfile, 2) reporter4 = XTCReporter(xtcfile, 2) simulation.reporters.append(reporter) simulation.reporters.append(reporter2) simulation.reporters.append(reporter3) simulation.reporters.append(reporter4) simulation.step(100) reporter.close() reporter2.close() reporter3.close() reporter4.close() with HDF5TrajectoryFile(hdf5file) as f: got = f.read() eq(got.temperature.shape, (50,)) eq(got.potentialEnergy.shape, (50,)) eq(got.kineticEnergy.shape, (50,)) eq(got.coordinates.shape, (50, 22, 3)) eq(got.velocities.shape, (50, 22, 3)) eq(got.cell_lengths, None) eq(got.cell_angles, None) eq(got.time, 0.002 * 2 * (1 + np.arange(50))) assert f.topology == md.load(get_fn('native.pdb')).top with NetCDFTrajectoryFile(ncfile) as f: xyz, time, cell_lengths, cell_angles = f.read() eq(cell_lengths, None) eq(cell_angles, None) eq(time, 0.002 * 2 * (1 + np.arange(50))) hdf5_traj = md.load(hdf5file) dcd_traj = md.load(dcdfile, top=get_fn('native.pdb')) netcdf_traj = md.load(ncfile, top=get_fn('native.pdb')) xtc_traj = md.load(xtcfile, top=get_fn('native.pdb')) # we don't have to convert units here, because md.load already # handles that assert hdf5_traj.unitcell_vectors is None eq(hdf5_traj.xyz, netcdf_traj.xyz) eq(hdf5_traj.unitcell_vectors, netcdf_traj.unitcell_vectors) eq(hdf5_traj.time, netcdf_traj.time) eq(xtc_traj.time, netcdf_traj.time) eq(dcd_traj.xyz, hdf5_traj.xyz) eq(xtc_traj.xyz, dcd_traj.xyz, decimal=3)
def test_reporter_subset(tmpdir, get_fn): pdb = PDBFile(get_fn('native2.pdb')) pdb.topology.setUnitCellDimensions([2, 2, 2]) forcefield = ForceField('amber99sbildn.xml', 'amber99_obc.xml') system = forcefield.createSystem(pdb.topology, nonbondedMethod=CutoffPeriodic, nonbondedCutoff=1 * nanometers, constraints=HBonds, rigidWater=True) integrator = LangevinIntegrator(300 * kelvin, 1.0 / picoseconds, 2.0 * femtoseconds) integrator.setConstraintTolerance(0.00001) platform = Platform.getPlatformByName('Reference') simulation = Simulation(pdb.topology, system, integrator, platform) simulation.context.setPositions(pdb.positions) simulation.context.setVelocitiesToTemperature(300 * kelvin) tmpdir = str(tmpdir) hdf5file = os.path.join(tmpdir, 'traj.h5') ncfile = os.path.join(tmpdir, 'traj.nc') dcdfile = os.path.join(tmpdir, 'traj.dcd') xtcfile = os.path.join(tmpdir, 'traj.xtc') atomSubset = [0, 1, 2, 4, 5] reporter = HDF5Reporter(hdf5file, 2, coordinates=True, time=True, cell=True, potentialEnergy=True, kineticEnergy=True, temperature=True, velocities=True, atomSubset=atomSubset) reporter2 = NetCDFReporter(ncfile, 2, coordinates=True, time=True, cell=True, atomSubset=atomSubset) reporter3 = DCDReporter(dcdfile, 2, atomSubset=atomSubset) reporter4 = XTCReporter(xtcfile, 2, atomSubset=atomSubset) simulation.reporters.append(reporter) simulation.reporters.append(reporter2) simulation.reporters.append(reporter3) simulation.reporters.append(reporter4) simulation.step(100) reporter.close() reporter2.close() reporter3.close() reporter4.close() t = md.load(get_fn('native.pdb')) t.restrict_atoms(atomSubset) with HDF5TrajectoryFile(hdf5file) as f: got = f.read() eq(got.temperature.shape, (50, )) eq(got.potentialEnergy.shape, (50, )) eq(got.kineticEnergy.shape, (50, )) eq(got.coordinates.shape, (50, len(atomSubset), 3)) eq(got.velocities.shape, (50, len(atomSubset), 3)) eq(got.cell_lengths, 2 * np.ones((50, 3))) eq(got.cell_angles, 90 * np.ones((50, 3))) eq(got.time, 0.002 * 2 * (1 + np.arange(50))) assert f.topology == md.load(get_fn('native.pdb'), atom_indices=atomSubset).topology with NetCDFTrajectoryFile(ncfile) as f: xyz, time, cell_lengths, cell_angles = f.read() eq(cell_lengths, 20 * np.ones((50, 3))) eq(cell_angles, 90 * np.ones((50, 3))) eq(time, 0.002 * 2 * (1 + np.arange(50))) eq(xyz.shape, (50, len(atomSubset), 3)) hdf5_traj = md.load(hdf5file) dcd_traj = md.load(dcdfile, top=hdf5_traj) netcdf_traj = md.load(ncfile, top=hdf5_traj) xtc_traj = md.load(xtcfile, top=hdf5_traj) # we don't have to convert units here, because md.load already handles that eq(hdf5_traj.xyz, netcdf_traj.xyz) eq(hdf5_traj.unitcell_vectors, netcdf_traj.unitcell_vectors) eq(hdf5_traj.time, netcdf_traj.time) eq(xtc_traj.time, netcdf_traj.time) eq(dcd_traj.xyz, hdf5_traj.xyz) eq(xtc_traj.xyz, hdf5_traj.xyz) eq(dcd_traj.unitcell_vectors, hdf5_traj.unitcell_vectors)
pdb.topology, nonbondedMethod=app.NoCutoff, nonbondedCutoff=500.0 * unit.angstroms, switchDistance=496.0 * unit.angstroms, ) system = apply_opls_combo(system, switching_distance=496.0 * unit.angstroms) with open('QUBE_pro_out.xml', 'w') as outfile: serialized_system = XmlSerializer.serialize(system) outfile.write(serialized_system) # Create the integrator to do Langevin dynamics integrator = LangevinIntegrator( 298.15 * unit.kelvin, # Temperature of heat bath 1.0 / unit.picoseconds, # Friction coefficient 2.0 * unit.femtoseconds, # Time step ) platform = Platform.getPlatformByName('CPU') simulation = app.Simulation(pdb.topology, system, integrator, platform) simulation.context.setPositions(pdb.positions) print('energy from openmm library') print(simulation.context.getState(getEnergy=True).getPotentialEnergy()) # platform.setPropertyValue(simulation.context, property='Precision', value='double') # Minimize the energy # print('Minimizing energy') # Minimize(simulation, iters=0)
# atom_index_i atom_index_j r0 k with open(opt.bond_restraints) as input_file: for line in input_file: columns = line.split() atom_index_i = int(columns[0]) atom_index_j = int(columns[1]) r0 = float(columns[2]) k = float(columns[3]) flat_bottom_force.addBond(atom_index_i, atom_index_j, [r0, k]) print( 'Adding %sA distance restraints (k=%s kcal/mol/A^2) between %s and %s' % (r0, k, atom_index_i, atom_index_j)) sys.stdout.flush() system.addForce(flat_bottom_force) integrator = LangevinIntegrator(opt.temp * unit.kelvin, 1 / unit.picosecond, opt.timestep * unit.femtoseconds) #system.addForce(openmm.MonteCarloBarostat(1*unit.atmospheres, opt.temp * unit.kelvin, 25)) print('Default Periodic box:', system.getDefaultPeriodicBoxVectors()) simulation = Simulation(modeller.topology, system, integrator, platform=platform) context = simulation.context context.setPositions(modeller.positions) # # Save to Gromacs format File # # Save Protein-Ligand Complex # structure = parmed.openmm.load_topology(modeller.topology, system, xyz=modeller.positions) # structure.save('Cmp.pdb', overwrite=True) # #structure.save('Cmp.gro', format='gro', overwrite=True)