def openmm_system(self): """Initialise the OpenMM system we will use to evaluate the energies.""" # load the initial coords into the system and initialise pdb = app.PDBFile(self.pdb) # count the amount of atoms in the structure for atom in pdb.topology.atoms(): self.natoms += 1 # must use a custom version of the tip3p water moddel forcefield = app.ForceField(self.xml, 'tip3p_opls.xml') self.modeller = app.Modeller( pdb.topology, pdb.positions) # set the intial positions from the pdb # Now we need to solvate the system self.modeller.addSolvent(forcefield, model='tip3p', padding=1 * unit.nanometer) # write out the solvated system coords app.PDBFile.writeFile(self.modeller.topology, self.modeller.positions, open('output.pdb', 'w')) # now we create the system and add the lj correction self.system = forcefield.createSystem(self.modeller.topology, nonbondedMethod=app.PME, constraints=None, nonbondedCutoff=1.1 * unit.nanometer) if self.opls: self.opls_lj() # set control parameters temperature = 298.15 * unit.kelvin integrator = mm.LangevinIntegrator(temperature, 5 / unit.picoseconds, 0.001 * unit.picoseconds) # add preasure to the system self.system.addForce( mm.MonteCarloBarostat(1 * unit.bar, 300 * unit.kelvin)) # create the simulation context self.simulation = app.Simulation(self.modeller.topology, self.system, integrator) # set the positions to the solvated system self.simulation.context.setPositions(self.modeller.positions) # get the energy of the sytem print( self.simulation.context.getState( getEnergy=True).getPotentialEnergy()) # check the energy break down struct = pmd.load_file('output.pdb') ecomps = (pmd.openmm.energy_decomposition_system(struct, self.system)) tot_ene = 0.0 for i in range(0, len(ecomps)): tot_ene += ecomps[i][1] print(ecomps[i][0], ecomps[i][1]) print('Total-energy %6.6f' % tot_ene) # serialize the system serialized_system = mm.XmlSerializer.serialize(self.system) outfile = open('test.xml', 'w') outfile.write(serialized_system) outfile.close() # now minimize the system self.simulation.minimizeEnergy(maxIterations=100) # now run the simulation self.simulation.reporters.append(app.PDBReporter('run.pdb', 1000)) self.simulation.reporters.append( app.StateDataReporter('run.txt', 1000, step=True, potentialEnergy=True, temperature=True)) self.simulation.step(100000)
TEMPid = int(TEMPid) print("my Production Run Temperature is", TEMPid) # load in Amber input files prmtop = app.AmberPrmtopFile('wat_' + PDBid + '.prmtop') inpcrd = app.AmberInpcrdFile('wat_' + PDBid + '.inpcrd') for x in range(RUNSid): # prepare system and integrator system = prmtop.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=1.0 * unit.nanometers, constraints=app.HBonds, rigidWater=True, ewaldErrorTolerance=0.0005) integrator = mm.LangevinIntegrator(TEMPid * unit.kelvin, 1.0 / unit.picoseconds, 2.0 * unit.femtoseconds) integrator.setConstraintTolerance(0.00001) thermostat = mm.AndersenThermostat(TEMPid * unit.kelvin, 1 / unit.picosecond) system.addForce(thermostat) barostat = mm.MonteCarloBarostat(1.0 * unit.bar, TEMPid * unit.kelvin, 25) system.addForce(barostat) # prepare simulation platform = mm.Platform.getPlatformByName('CUDA') properties = {'CudaPrecision': 'mixed', 'DeviceIndex': '0'} simulation = app.Simulation(prmtop.topology, system, integrator, platform, properties) simulation.context.setPositions(inpcrd.positions)
def generate_simulation_data(database, parameters): """ Regenerate simulation data for given parameters. ARGUMENTS database (dict) - database of molecules parameters (dict) - dictionary of GBSA parameters keyed on GBSA atom types """ platform = openmm.Platform.getPlatformByName("Reference") from pymbar import timeseries for cid in database.keys(): entry = database[cid] molecule = entry['molecule'] iupac_name = entry['iupac'] # Retrieve vacuum system. vacuum_system = copy.deepcopy(entry['system']) # Retrieve OpenMM System. solvent_system = copy.deepcopy(entry['system']) # Get nonbonded force. forces = { solvent_system.getForce(index).__class__.__name__: solvent_system.getForce(index) for index in range(solvent_system.getNumForces()) } nonbonded_force = forces['NonbondedForce'] # Add GBSA term gbsa_force = openmm.GBSAOBCForce() gbsa_force.setNonbondedMethod( openmm.GBSAOBCForce.NoCutoff) # set no cutoff gbsa_force.setSoluteDielectric(1) gbsa_force.setSolventDielectric(78) # Build indexable list of atoms. atoms = [atom for atom in molecule.GetAtoms()] natoms = len(atoms) # Assign GBSA parameters. for (atom_index, atom) in enumerate(atoms): [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(atom_index) atomtype = atom.GetStringData("gbsa_type") # GBSA atomtype radius = parameters['%s_%s' % (atomtype, 'radius')] * units.angstroms scalingFactor = parameters['%s_%s' % (atomtype, 'scalingFactor')] gbsa_force.addParticle(charge, radius, scalingFactor) # Add the force to the system. solvent_system.addForce(gbsa_force) # Create context for solvent system. timestep = 2.0 * units.femtosecond collision_rate = 20.0 / units.picoseconds temperature = entry['temperature'] integrator = openmm.LangevinIntegrator(temperature, collision_rate, timestep) context = openmm.Context(vacuum_system, integrator, platform) # Set the coordinates. positions = entry['positions'] context.setPositions(positions) # Minimize. openmm.LocalEnergyMinimizer.minimize(context) # Simulate, saving periodic snapshots of configurations. kT = kB * temperature beta = 1.0 / kT initial_time = time.time() nsteps_per_iteration = 2500 niterations = 200 x_n = numpy.zeros([niterations, natoms, 3], numpy.float32) # positions, in nm u_n = numpy.zeros([niterations], numpy.float64) # energy differences, in kT for iteration in range(niterations): integrator.step(nsteps_per_iteration) state = context.getState(getEnergy=True, getPositions=True) x_n[iteration, :, :] = state.getPositions( asNumpy=True) / units.nanometers u_n[iteration] = beta * state.getPotentialEnergy() if numpy.any(numpy.isnan(u_n)): raise Exception("Encountered NaN for molecule %s | %s" % (cid, iupac_name)) final_time = time.time() elapsed_time = final_time - initial_time # Clean up. del context, integrator # Discard initial transient to equilibration. [t0, g, Neff_max] = timeseries.detectEquilibration(u_n) x_n = x_n[t0:, :, :] u_n = u_n[t0:] # Subsample to remove correlation. indices = timeseries.subsampleCorrelatedData(u_n, g=g) x_n = x_n[indices, :, :] u_n = u_n[indices] # Store data. entry['x_n'] = x_n entry['u_n'] = u_n print "%48s | %64s | simulation %12.3f s | %5d samples discarded | %5d independent samples remain" % ( cid, iupac_name, elapsed_time, t0, len(indices)) return
# Create the system print('Creating OpenMM System...') system = forcefield.createSystem(modeller.topology, nonbondedMethod=app.PME, constraints=app.HBonds, removeCMMotion=False, hydrogenMass=hydrogen_mass) # Add a barostat print('Adding barostat...') barostat = openmm.MonteCarloBarostat(pressure, temperature) system.addForce(barostat) # Serialize integrator print('Serializing integrator to %s' % integrator_xml_filename) integrator = openmm.LangevinIntegrator(temperature, collision_rate, timestep) with open(output_prefix + integrator_xml_filename, 'w') as outfile: xml = openmm.XmlSerializer.serialize(integrator) outfile.write(xml) # Minimize print('Minimizing energy...') context = openmm.Context(system, integrator) context.setPositions(modeller.positions) print(' initial : %8.3f kcal/mol' % (context.getState(getEnergy=True).getPotentialEnergy() / unit.kilocalories_per_mole)) openmm.LocalEnergyMinimizer.minimize(context) print(' final : %8.3f kcal/mol' % (context.getState(getEnergy=True).getPotentialEnergy() / unit.kilocalories_per_mole))
def openmm_simulate_charmm_nvt(top_file, pdb_file, check_point=None, GPU_index=0, output_traj="output.dcd", output_log="output.log", output_cm=None, report_time=10 * u.picoseconds, sim_time=10 * u.nanoseconds): """ Start and run an OpenMM NVT simulation with Langevin integrator at 2 fs time step and 300 K. The cutoff distance for nonbonded interactions were set at 1.2 nm and LJ switch distance at 1.0 nm, which commonly used with Charmm force field. Long-range nonbonded interactions were handled with PME. Parameters ---------- top_file : topology file (.top, .prmtop, ...) This is the topology file discribe all the interactions within the MD system. pdb_file : coordinates file (.gro, .pdb, ...) This is the molecule configuration file contains all the atom position and PBC (periodic boundary condition) box in the system. check_point : None or check point file to load GPU_index : Int or Str The device # of GPU to use for running the simulation. Use Strings, '0,1' for example, to use more than 1 GPU output_traj : the trajectory file (.dcd) This is the file stores all the coordinates information of the MD simulation results. output_log : the log file (.log) This file stores the MD simulation status, such as steps, time, potential energy, temperature, speed, etc. output_cm : the h5 file contains contact map information report_time : 10 ps The program writes its information to the output every 10 ps by default sim_time : 10 ns The timespan of the simulation trajectory """ top = pmd.load_file(top_file, xyz=pdb_file) system = top.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=1.2 * u.nanometer, switchDistance=1.0 * u.nanometer, constraints=app.HBonds) dt = 0.002 * u.picoseconds integrator = omm.LangevinIntegrator(300 * u.kelvin, 1 / u.picosecond, dt) try: platform = omm.Platform_getPlatformByName("CUDA") properties = {'DeviceIndex': str(GPU_index), 'CudaPrecision': 'mixed'} except Exception: platform = omm.Platform_getPlatformByName("OpenCL") properties = {'DeviceIndex': str(GPU_index)} simulation = app.Simulation(top.topology, system, integrator, platform, properties) simulation.context.setPositions(top.positions) simulation.minimizeEnergy() report_freq = int(report_time / dt) simulation.context.setVelocitiesToTemperature(10 * u.kelvin, random.randint(1, 10000)) simulation.reporters.append(app.DCDReporter(output_traj, report_freq)) if output_cm: simulation.reporters.append(ContactMapReporter(output_cm, report_freq)) simulation.reporters.append( app.StateDataReporter(output_log, report_freq, step=True, time=True, speed=True, potentialEnergy=True, temperature=True, totalEnergy=True)) simulation.reporters.append( app.CheckpointReporter('checkpnt.chk', report_freq)) if check_point: simulation.loadCheckpoint(check_point) nsteps = int(sim_time / dt) simulation.step(nsteps)
def langevin_integrator(): integrator = omm.LangevinIntegrator( *OpenMMSimMaker.DEFAULT_INTEGRATOR_PARAMS['LangevinIntegrator']) return integrator
# Load the Amber files print('Loading AMBER files...') ala5_gas = load_file('ala5_gas.parm7', 'ala5_gas.rst7') # Create the OpenMM system print('Creating OpenMM System') system = ala5_gas.createSystem(nonbondedMethod=app.NoCutoff, constraints=app.HBonds, implicitSolvent=app.GBn2, implicitSolventSaltConc=0.1*u.moles/u.liter, ) # Create the integrator to do Langevin dynamics integrator = mm.LangevinIntegrator( 300*u.kelvin, # Temperature of heat bath 1.0/u.picoseconds, # Friction coefficient 2.0*u.femtoseconds, # Time step ) # Define the platform to use; CUDA, OpenCL, CPU, or Reference. Or do not specify # the platform to use the default (fastest) platform platform = mm.Platform.getPlatformByName('CUDA') prop = dict(CudaPrecision='mixed') # Use mixed single/double precision # Create the Simulation object sim = app.Simulation(ala5_gas.topology, system, integrator, platform, prop) # Set the particle positions sim.context.setPositions(ala5_gas.positions) # Minimize the energy
glob.glob1(netDir, "train[1-9][0-9]")) if nEnsambles <= 0: warn("No train* directories found in " + netDir) sys.exit(1) temperature = 298.15 * u.kelvin pdb = app.PDBFile(inFile) modeller = app.Modeller(pdb.topology, pdb.positions) topo = modeller.topology system = createSystem(modeller.topology) atomSym = [] for atom in topo.atoms(): atomSym.append(atom.element.symbol) print(atomSym) saveANIInfo("aniInfo.txt", netDir, paramFile, atFitFile, nEnsambles) ################################################# # add ANI force to system f = ANIForce("aniInfo.txt", atomSym) system.addForce(f) ################################################# integrator = mm.LangevinIntegrator(temperature, 1 / u.picosecond, 0.0005 * u.picoseconds) simulation = app.Simulation(modeller.topology, system, integrator) simulation.context.setPositions(modeller.positions) simulation = Minimize(simulation, outFile, 1000)
def test_ffxml_simulation(): """Test converting toluene and benzene smiles to oemol to ffxml to openmm simulation.""" with utils.enter_temp_directory(): m0 = openmoltools.openeye.smiles_to_oemol("Cc1ccccc1") charged0 = openmoltools.openeye.get_charges(m0) m1 = openmoltools.openeye.smiles_to_oemol("c1ccccc1") charged1 = openmoltools.openeye.get_charges(m1) ligands = [charged0, charged1] n_atoms = [15, 12] trajectories, ffxml = openmoltools.openeye.oemols_to_ffxml(ligands) eq(len(trajectories), len(ligands)) pdb_filename = utils.get_data_filename("chemicals/proteins/1vii.pdb") temperature = 300 * u.kelvin friction = 0.3 / u.picosecond timestep = 0.01 * u.femtosecond protein_traj = md.load(pdb_filename) protein_traj.center_coordinates() protein_top = protein_traj.top.to_openmm() protein_xyz = protein_traj.openmm_positions(0) for k, ligand in enumerate(ligands): ligand_traj = trajectories[k] ligand_traj.center_coordinates() eq(ligand_traj.n_atoms, n_atoms[k]) eq(ligand_traj.n_frames, 1) #Move the pre-centered ligand sufficiently far away from the protein to avoid a clash. min_atom_pair_distance = ( (ligand_traj.xyz[0]**2.).sum(1)**0.5).max() + ( (protein_traj.xyz[0]**2.).sum(1)**0.5).max() + 0.3 ligand_traj.xyz += np.array([1.0, 0.0, 0.0 ]) * min_atom_pair_distance ligand_xyz = ligand_traj.openmm_positions(0) ligand_top = ligand_traj.top.to_openmm() ffxml.seek(0) forcefield = app.ForceField("amber10.xml", ffxml, "tip3p.xml") model = app.modeller.Modeller(protein_top, protein_xyz) model.add(ligand_top, ligand_xyz) model.addSolvent(forcefield, padding=0.4 * u.nanometer) system = forcefield.createSystem(model.topology, nonbondedMethod=app.PME, nonbondedCutoff=1.0 * u.nanometers, constraints=app.HAngles) integrator = mm.LangevinIntegrator(temperature, friction, timestep) simulation = app.Simulation(model.topology, system, integrator) simulation.context.setPositions(model.positions) print("running") simulation.step(1)
print "frictionCoeffEq =", frictionCoeffEq print "stepSizeEq =", stepSizeEq print "variableIntegrator =", variableIntegrator print "checks =", checks print "timeBetweenChecks =", timeBetweenChecks if variableIntegrator: print "errorTolerance =", errorTolerance else: stepsBetweenChecks = int(timeBetweenChecks / stepSize) print "stepSize =", stepSize print "stepsBetweenChecks =", stepsBetweenChecks print "constraintTolerance =", constraintTolerance #print "energyTolerance =", energyTolerance # create the equilibration integrator and context equilibrationIntegrator = mm.LangevinIntegrator(temperatureEq, frictionCoeffEq, stepSizeEq) equilibrationIntegrator.setConstraintTolerance(constraintTolerance) platform = mm.Platform.getPlatformByName(platformName) equilibrationContext = mm.Context(system, equilibrationIntegrator, platform) # set the positions according to the .pos file equilibrationContext.setPositions(positions) # equilibrate the system equilibrationContext.setVelocitiesToTemperature(temperatureEq) equilibrationContext.getIntegrator().step(equilibrationSteps) # get the positions and velocities in the equilibrium state equilibriumState = equilibrationContext.getState(getPositions=True,
def run(self, production_steps=200, start='ala2_1stFrame.pdb', production='ala2_production.pdb'): #### ?!!!!!!!!!!!!!!!! #from __future__ import print_function from simtk.openmm import app import simtk.openmm as mm from simtk import unit from sys import stdout nonbondedCutoff = 1.0 * unit.nanometers timestep = 2.0 * unit.femtoseconds temperature = 300 * unit.kelvin #save_frequency = 100 #Every 100 steps, save the trajectory save_frequency = 10 #Every 1 steps, save the trajectory pdb = app.PDBFile(start) forcefield = app.ForceField('amber99sb.xml', 'tip3p.xml') ala2_model = app.Modeller(pdb.topology, pdb.positions) #Hydrogens will be constrained after equilibrating system = forcefield.createSystem(ala2_model.topology, nonbondedMethod=app.PME, nonbondedCutoff=nonbondedCutoff, constraints=app.HBonds, rigidWater=True, ewaldErrorTolerance=0.0005) system.addForce(mm.MonteCarloBarostat( 1 * unit.bar, temperature, 100)) #Apply Monte Carlo Pressure changes in 100 timesteps integrator = mm.LangevinIntegrator(temperature, 1.0 / unit.picoseconds, timestep) integrator.setConstraintTolerance(0.00001) platform = mm.Platform.getPlatformByName('CPU') simulation = app.Simulation(ala2_model.topology, system, integrator, platform) simulation.context.setPositions(ala2_model.positions) simulation.context.setVelocitiesToTemperature(temperature) simulation.reporters.append(app.PDBReporter(production, save_frequency)) simulation.reporters.append( app.StateDataReporter('stateReporter_constantPressure.txt', 1000, step=True, totalEnergy=True, temperature=True, volume=True, progress=True, remainingTime=True, speed=True, totalSteps=production_steps, separator='\t')) print('Running Production...') simulation.step(production_steps) print('Done!') import mdtraj as md trj = md.load(production) return trj
"clamp": 2 }, name=f"glow_{i}", )) nodes.append(Ff.OutputNode(nodes[-1], name="output")) net = Ff.ReversibleGraphNet(nodes, verbose=False) net = net.to(device=device) print("Building OpenMM context") pdb = app.PDBFile("5ura_start.pdb") forcefield = app.ForceField('amber99sbildn.xml', 'amber99_obc.xml') system = forcefield.createSystem(pdb.topology, nonbondedMethod=app.CutoffNonPeriodic, nonbondedCutoff=1.0 * nanometer, constraints=None) integrator = openmm.LangevinIntegrator(298, 1.0, 0.002) simulation = app.Simulation(pdb.topology, system, integrator) context = simulation.context print("Training") # # Training # losses = [] val_losses = [] epochs = args.iterations n_batch = args.batch_size writer = SummaryWriter() # n = training_data_npy.shape[0]
def apply(self, thermodynamic_state, sampler_state, platform=None): """ Apply the Langevin dynamics MCMC move. Parameters ---------- thermodynamic_state : ThermodynamicState The thermodynamic state to use when applying the MCMC move sampler_state : SamplerState The sampler state to apply the move to platform : simtk.openmm.Platform, optional, default = None If not None, the specified platform will be used. Returns ------- updated_sampler_state : SamplerState The updated sampler state Examples -------- Alanine dipeptide in vacuum. >>> # Create a test system >>> from openmmtools import testsystems >>> test = testsystems.AlanineDipeptideVacuum() >>> # Create a sampler state. >>> sampler_state = SamplerState(system=test.system, positions=test.positions) >>> # Create a thermodynamic state. >>> from openmmmcmc.thermodynamics import ThermodynamicState >>> thermodynamic_state = ThermodynamicState(system=test.system, temperature=298*u.kelvin) >>> # Create a LangevinDynamicsMove >>> move = LangevinDynamicsMove(nsteps=10, timestep=0.5*u.femtoseconds, collision_rate=20.0/u.picoseconds) >>> # Perform one update of the sampler state. >>> updated_sampler_state = move.apply(thermodynamic_state, sampler_state) Ideal gas. >>> # Create a test system >>> from openmmtools import testsystems >>> test = testsystems.IdealGas() >>> # Add a MonteCarloBarostat. >>> barostat = mm.MonteCarloBarostat(1*u.atmospheres, 298*u.kelvin, 25) >>> force_index = test.system.addForce(barostat) >>> # Create a sampler state. >>> sampler_state = SamplerState(system=test.system, positions=test.positions) >>> # Create a thermodynamic state. >>> from openmmmcmc.thermodynamics import ThermodynamicState >>> thermodynamic_state = ThermodynamicState(system=test.system, temperature=298*u.kelvin, pressure=1.0*u.atmospheres) >>> # Create a LangevinDynamicsMove >>> move = LangevinDynamicsMove(nsteps=500, timestep=0.5*u.femtoseconds, collision_rate=20.0/u.picoseconds) >>> # Perform one update of the sampler state. >>> updated_sampler_state = move.apply(thermodynamic_state, sampler_state) """ timer = Timer() # Check if the system contains a barostat. system = sampler_state.system forces = { system.getForce(index).__class__.__name__: system.getForce(index) for index in range(system.getNumForces()) } barostat = None if 'MonteCarloBarostat' in forces: barostat = forces['MonteCarloBarostat'] barostat.setTemperature(thermodynamic_state.temperature) parameter_name = barostat.Pressure() if thermodynamic_state.pressure == None: raise Exception( 'MonteCarloBarostat is present but no pressure specified in thermodynamic state.' ) # Create integrator. integrator = mm.LangevinIntegrator(thermodynamic_state.temperature, self.collision_rate, self.timestep) # Random number seed. seed = np.random.randint(_RANDOM_SEED_MAX) integrator.setRandomNumberSeed(seed) # Create context. timer.start("Context Creation") context = sampler_state.createContext(integrator, platform=platform) timer.stop("Context Creation") logger.debug("LangevinDynamicMove: Context created, platform is %s" % context.getPlatform().getName()) # Set pressure, if barostat is included. if barostat is not None: context.setParameter( parameter_name, thermodynamic_state.pressure.value_in_unit_system( u.md_unit_system)) if self.reassign_velocities: # Assign Maxwell-Boltzmann velocities. context.setVelocitiesToTemperature(thermodynamic_state.temperature) # Run dynamics. timer.start("step()") integrator.step(self.nsteps) timer.stop("step()") # Get updated sampler state. timer.start("update_sampler_state") updated_sampler_state = SamplerState.createFromContext(context) timer.start("update_sampler_state") # Clean up. del context timer.report_timing() return updated_sampler_state
def enumerate_experiments(): experiments = OrderedDict() ############################################################################ sysname = "switchedljbox" system, positions, groups, temperature, timestep, langevin_timestep, testsystem, equil_steps, steps_per_hmc = lb_loader.load( sysname) ############################################################################ for timestep in [2.5 * u.femtoseconds, 5.0 * u.femtoseconds]: collision_rate = 1.0 / u.picoseconds integrator = mm.LangevinIntegrator(temperature, collision_rate, timestep) prms = dict(sysname=sysname, timestep=timestep / u.femtoseconds, collision=lb_loader.fixunits(collision_rate)) expt = Experiment(integrator=integrator, sysname=sysname, prms=prms) collision_rate = None for timestep in [20.0 * u.femtoseconds]: integrator = hmc_integrators.GHMCIntegrator( temperature=temperature, steps_per_hmc=steps_per_hmc, timestep=timestep, collision_rate=collision_rate) prms = dict(sysname=sysname, timestep=timestep / u.femtoseconds, collision=lb_loader.fixunits(collision_rate)) expt = Experiment(integrator=integrator, sysname=sysname, prms=prms) timestep = 35.0 * u.femtoseconds extra_chances = 2 collision_rate = 1.0 / u.picoseconds integrator = hmc_integrators.XCGHMCIntegrator( temperature=temperature, steps_per_hmc=steps_per_hmc, timestep=timestep, extra_chances=extra_chances, collision_rate=collision_rate) itype = type(integrator).__name__ prms = dict(sysname=sysname, itype=itype, timestep=timestep / u.femtoseconds, collision=lb_loader.fixunits(collision_rate)) expt = Experiment(integrator=integrator, sysname=sysname, prms=prms) return collision_rate = None for timestep in []: # [2.0 * u.femtoseconds]: integrator = hmc_integrators.XCGHMCIntegrator( temperature=temperature, steps_per_hmc=steps_per_hmc, timestep=timestep, extra_chances=extra_chances, collision_rate=collision_rate) itype = type(integrator).__name__ prms = dict(sysname=sysname, itype=itype, timestep=timestep / u.femtoseconds, collision=lb_loader.fixunits(collision_rate)) int_string = lb_loader.format_int_name(prms) key = (sysname, int_string) experiments[key] = integrator ############################################################################ sysname = "switchedaccurateflexiblewater" system, positions, groups, temperature, timestep, langevin_timestep, testsystem, equil_steps, steps_per_hmc = lb_loader.load( sysname) ############################################################################ for timestep in [ 0.10 * u.femtoseconds, 0.15 * u.femtoseconds, 0.5 * u.femtoseconds ]: collision_rate = 1.0 / u.picoseconds integrator = mm.LangevinIntegrator(temperature, collision_rate, timestep) itype = type(integrator).__name__ prms = dict(sysname=sysname, itype=itype, timestep=timestep / u.femtoseconds, collision=lb_loader.fixunits(collision_rate)) int_string = lb_loader.format_int_name(prms) key = (sysname, int_string) experiments[key] = integrator xcghmc_parms = dict(timestep=0.668 * u.femtoseconds, steps_per_hmc=10, extra_chances=1, collision_rate=None) integrator = hmc_integrators.XCGHMCIntegrator(temperature=temperature, **xcghmc_parms) itype = type(integrator).__name__ prms = dict(sysname=sysname, itype=itype, timestep=integrator.timestep / u.femtoseconds, collision=lb_loader.fixunits(None)) int_string = lb_loader.format_int_name(prms) key = (sysname, int_string) experiments[key] = integrator # hyperopt determined optimal settings obtain ~113 effective ns / day xcghmc_parms = dict(timestep=1.1868 * u.femtoseconds, steps_per_hmc=23, collision_rate=None, groups=((0, 1), (1, 4))) integrator = hmc_integrators.GHMCRESPAIntegrator(temperature=temperature, **xcghmc_parms) itype = type(integrator).__name__ prms = dict(sysname=sysname, itype=itype, timestep=integrator.timestep / u.femtoseconds, collision=lb_loader.fixunits(None)) int_string = lb_loader.format_int_name(prms) key = (sysname, int_string) experiments[key] = integrator # Obtained by taking hyperopt optimal GHMCRespa parameters and adding 2 extra chances xcghmc_parms = dict(timestep=1.1868 * u.femtoseconds, steps_per_hmc=23, collision_rate=None, extra_chances=2, groups=((0, 1), (1, 4))) integrator = hmc_integrators.XCGHMCRESPAIntegrator(temperature=temperature, **xcghmc_parms) itype = type(integrator).__name__ prms = dict(sysname=sysname, itype=itype, timestep=integrator.timestep / u.femtoseconds, collision=lb_loader.fixunits(None)) int_string = lb_loader.format_int_name(prms) key = (sysname, int_string) experiments[key] = integrator # hyperopt determined optimal settings obtain ~79.8 effective ns/day xcghmc_parms = dict(timestep=0.6791 * u.femtoseconds, steps_per_hmc=20, collision_rate=None) integrator = hmc_integrators.GHMCIntegrator(temperature=temperature, **xcghmc_parms) itype = type(integrator).__name__ prms = dict(sysname=sysname, itype=itype, timestep=integrator.timestep / u.femtoseconds, collision=lb_loader.fixunits(None)) int_string = lb_loader.format_int_name(prms) key = (sysname, int_string) experiments[key] = integrator xcghmc_parms = dict(timestep=0.6791 * u.femtoseconds, steps_per_hmc=20, collision_rate=None) xcghmc_parms.update(dict()) integrator = hmc_integrators.XCGHMCIntegrator(temperature=temperature, **xcghmc_parms) itype = type(integrator).__name__ prms = dict(sysname=sysname, itype=itype, timestep=timestep / u.femtoseconds, collision=lb_loader.fixunits(collision_rate)) int_string = lb_loader.format_int_name(prms) key = (sysname, int_string) experiments[key] = integrator ############################################################################ sysname = "switchedaccuratebigflexiblewater" system, positions, groups, temperature, timestep, langevin_timestep, testsystem, equil_steps, steps_per_hmc = lb_loader.load( sysname) ############################################################################ experiments = OrderedDict() # hyperopt determined optimal settings obtain ~113 effective ns / day xcghmc_parms = dict(timestep=0.256927 * u.femtoseconds, steps_per_hmc=24, collision_rate=None, groups=((0, 4), (1, 1))) integrator = hmc_integrators.GHMCRESPAIntegrator(temperature=temperature, **xcghmc_parms) itype = type(integrator).__name__ prms = dict(sysname=sysname, itype=itype, timestep=integrator.timestep / u.femtoseconds, collision=lb_loader.fixunits(None)) int_string = lb_loader.format_int_name(prms) key = (sysname, int_string) experiments[key] = integrator
def calculate_VT(self, oe_mol): # Extract starting MD data from OEMol mdData = utils.MDData(oe_mol) structure = mdData.structure topology = mdData.topology positions = mdData.positions velocities = mdData.velocities box = mdData.box volume = box[0][0] * box[1][1] * box[2][2] # OpenMM system system = structure.createSystem( nonbondedMethod=eval("app.%s" % self.cube.args.nonbondedMethod), nonbondedCutoff=self.cube.args.nonbondedCutoff * unit.angstroms, constraints=eval("app.%s" % self.cube.args.constraints)) # OpenMM Integrator integrator = openmm.LangevinIntegrator( self.cube.args.temperature * unit.kelvin, 1.0 / unit.picoseconds, 0.002 * unit.picoseconds) # Add Force Barostat to the system system.addForce( openmm.MonteCarloBarostat( self.cube.args.pressure * unit.atmospheres, self.cube.args.temperature * unit.kelvin, 25)) # Set Simulation simulation = app.Simulation(topology, system, integrator) # Set Positions simulation.context.setPositions(positions) # Set Velocities simulation.context.setVelocities(velocities) # Set Box dimensions simulation.context.setPeriodicBoxVectors(box[0], box[1], box[2]) # Collect the OpenMM state energy info state = simulation.context.getState(getEnergy=True) # Kinetic Energy keng = state.getKineticEnergy() # Calculate system degrees of freedom: dof = 0 for i in range(system.getNumParticles()): if system.getParticleMass(i) > 0 * unit.dalton: dof += 3 dof -= system.getNumConstraints() if any( type(system.getForce(i)) == openmm.CMMotionRemover for i in range(system.getNumForces())): dof -= 3 # Calculate the temperature from the equipartition theorem temperature = ((2 * keng) / (dof * unit.MOLAR_GAS_CONSTANT_R)) return volume, temperature
mol = oechem.OEGraphMol() ifs = oechem.oemolistream(mol_filename) # LPW: I don't understand the meaning of these lines. # flavor = oechem.OEIFlavor_Generic_Default | oechem.OEIFlavor_MOL2_Default | oechem.OEIFlavor_MOL2_Forcefield # ifs.SetFlavor( oechem.OEFormat_MOL2, flavor) oechem.OEReadMolecule(ifs, mol) oechem.OETriposAtomNames(mol) # Create the OpenMM system system = forcefield.createSystem(pdb.topology, [mol], nonbondedMethod=PME, nonbondedCutoff=1.0 * unit.nanometers, rigidWater=True) # Set up an OpenMM simulation integrator = openmm.LangevinIntegrator(temperature, friction, time_step) platform = openmm.Platform.getPlatformByName('CUDA') simulation = Simulation(pdb.topology, system, integrator) simulation.context.setPositions(pdb.positions) simulation.context.setVelocitiesToTemperature(temperature) netcdf_reporter = NetCDFReporter('water_traj.nc', trj_freq) simulation.reporters.append(netcdf_reporter) simulation.reporters.append( StateDataReporter('water_data.csv', data_freq, step=True, potentialEnergy=True, temperature=True, density=True)) print(simulation.context.getState(getEnergy=True).getPotentialEnergy())
## read the OpenMM system of butane with open("./output/system.xml", 'r') as file_handle: xml = file_handle.read() system = omm.XmlSerializer.deserialize(xml) ## read psf and pdb file of butane psf = omm_app.CharmmPsfFile("./data/butane.psf") pdb = omm_app.PDBFile('./data/butane.pdb') ## setup an OpenMM context platform = omm.Platform.getPlatformByName('Reference') T = 298.15 * unit.kelvin fricCoef = 10 / unit.picoseconds stepsize = 1 * unit.femtoseconds integrator = omm.LangevinIntegrator(T, fricCoef, stepsize) context = omm.Context(system, integrator, platform) ## set equilibrium theta0 for the biasing potential K = 50 context.setParameter("K", K) ## M centers of dihedral windows are used in umbrella sampling M = 30 theta0 = np.linspace(-math.pi, math.pi, M, endpoint=False) np.savetxt("./output/theta0.csv", theta0, delimiter=",") ## the main loop to run umbrella sampling window by window for theta0_index in range(M): print(f"sampling at theta0 index: {theta0_index} out of {M}")
def prepare_RL_system(): RL_complex_structure = ligand_structure + receptor_structure barostat = openmm.MonteCarloBarostat(pressure, temperature) parmed_forcefield_kwargs = { 'removeCMMotion': False, 'ewaldErrorTolerance': 5e-04, 'nonbondedMethod': app.PME, 'constraints': False, 'rigidWater': False, 'hydrogenMass': 3.0 * unit.amu } parmed_system_generator = SystemGenerator( forcefields=[protein_forcefield, solvation_forcefield], barostat=barostat, forcefield_kwargs=parmed_forcefield_kwargs, molecules=[ligand], small_molecule_forcefield=small_molecule_forcefield, cache=f'{RL_output_prefix}/LIG{ligand_ndx}.json') openmm_forcefield_kwargs = { 'removeCMMotion': False, 'ewaldErrorTolerance': 5e-04, 'nonbondedMethod': app.PME, 'constraints': True, 'rigidWater': True, 'hydrogenMass': 3.0 * unit.amu } openmm_system_generator = SystemGenerator( forcefields=[protein_forcefield, solvation_forcefield], barostat=barostat, forcefield_kwargs=openmm_forcefield_kwargs, molecules=[ligand], small_molecule_forcefield=small_molecule_forcefield, cache=f'{RL_output_prefix}/LIG{ligand_ndx}.json') modeller = app.Modeller(RL_complex_structure.topology, RL_complex_structure.positions) modeller.addSolvent( openmm_system_generator.forcefield, model='tip3p', padding=solvent_padding, ionicStrength=ionic_strength ) # padding=solvent_padding for RL, boxSize=box_size for L parmed_system = parmed_system_generator.create_system(modeller.topology) openmm_system = openmm_system_generator.create_system(modeller.topology) integrator = openmm.LangevinIntegrator(temperature, collision_rate, timestep) # minimize and equilibrate print('Minimizing...') platform = openmm.Platform.getPlatformByName('CUDA') platform.setPropertyDefaultValue('Precision', 'mixed') platform.setPropertyDefaultValue('CudaDeviceIndex', sys.argv[3]) context = openmm.Context(openmm_system, integrator, platform) context.setPositions(modeller.positions) openmm.LocalEnergyMinimizer.minimize(context) print('Equilibrating...') integrator.step(nsteps_equil) print('Saving RL GMX files...') state = context.getState(getPositions=True, getVelocities=True, getEnergy=True, getForces=True) parmed_system.setDefaultPeriodicBoxVectors(*state.getPeriodicBoxVectors()) parmed_system = parmed.openmm.load_topology( modeller.topology, parmed_system, xyz=state.getPositions(asNumpy=True)) parmed_system.save(f'{RL_output_prefix}/conf.gro', overwrite=True) parmed_system.save(f'{RL_output_prefix}/topol.top', overwrite=True) if ligand_ndx <= openmm_write_cutoff: with open(f'{RL_output_prefix}/integrator.xml', 'w') as f: f.write(openmm.XmlSerializer.serialize(integrator)) with open(f'{RL_output_prefix}/state.xml', 'w') as f: f.write(openmm.XmlSerializer.serialize(state)) with open(f'{RL_output_prefix}/system.xml', 'w') as f: f.write(openmm.XmlSerializer.serialize(parmed_system))
traj = mdtraj.load(pdb_filename) top, bonds = traj.top.to_dataframe() atom_indices = top.index[top.chainID == 0].values pdb = app.PDBFile(pdb_filename) topology = pdb.topology positions = pdb.positions ff = app.ForceField(which_forcefield, which_water) platform = mm.Platform.getPlatformByName(platform_name) system = ff.createSystem(topology, nonbondedMethod=app.PME, nonbondedCutoff=cutoff, constraints=app.HBonds) integrator = mm.LangevinIntegrator(temperature, 1.0 / u.picoseconds, timestep) system.addForce(mm.MonteCarloBarostat(pressure, temperature, 25)) simulation = app.Simulation(topology, system, integrator, platform=platform) simulation.context.setPositions(positions) simulation.context.setVelocitiesToTemperature(temperature) print("Using platform %s" % simulation.context.getPlatform().getName()) if os.path.exists(dcd_filename): sys.exit() simulation.reporters.append(mdtraj.reporters.DCDReporter(dcd_filename, output_frequency, atomSubset=atom_indices)) simulation.reporters.append(app.StateDataReporter(open(log_filename, 'w'), output_frequency, step=True, time=True, speed=True)) simulation.step(n_steps)