def simulate_system(self, equilibrate=100, production=100, dcd_frequency=10): context, integrator = self.get_context() # integrator.step(num_steps) dummy_integrator = mm.VerletIntegrator(1 * u.femtosecond) simulation = app.Simulation(self.topology, context.getSystem(), dummy_integrator) simulation.context = context simulation.integrator = integrator simulation.reporters.append( app.DCDReporter('equilibration.dcd', dcd_frequency)) simulation.step(equilibrate) simulation.reporters.clear() simulation.reporters.append( app.DCDReporter('production.dcd', dcd_frequency)) simulation.step(production) self.sampler_state.update_from_context(context) del context
def add_reporters(simulation, trajectory_file, log_every, save_every, total_steps, continuing, checkpoint_file): print( f"Reporting every {log_every} steps and checkpointing on {checkpoint_file} every {save_every} steps." ) op = "append" if continuing else "write" print(f"Will {op} to trajectory file {trajectory_file}.\n") basename = "output" fp = open(f"{basename}.log", "a" if continuing else "w") simulation.reporters.append( app.DCDReporter(trajectory_file, save_every, append=continuing, enforcePeriodicBox=False)) simulation.reporters.append( app.CheckpointReporter(checkpoint_file, save_every)) simulation.reporters.append(StdoutLogReporter(log_every, total_steps)) simulation.reporters.append( app.StateDataReporter(fp, log_every, step=True, time=True, potentialEnergy=True, kineticEnergy=True, totalEnergy=True, temperature=True, volume=True, progress=True, remainingTime=True, speed=True, totalSteps=total_steps, separator='\t'))
def configure_reporters(sim, ctx, report_interval_ps, dt_ps, frames_per_h5, wrap): report_freq = int(report_interval_ps / dt_ps) # Configure DCD file reporter sim.reporters.append(app.DCDReporter(ctx.traj_file, report_freq)) # Configure contact map reporter sim.reporters.append( OfflineReporter( ctx.h5_prefix, report_freq, wrap_pdb_file=ctx.pdb_file if wrap else None, reference_pdb_file=ctx.reference_pdb_file, frames_per_h5=frames_per_h5, )) # Configure simulation output log sim.reporters.append( app.StateDataReporter( ctx.log_file, report_freq, step=True, time=True, speed=True, potentialEnergy=True, temperature=True, totalEnergy=True, ))
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
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)
def run(self, number_of_steps=15000, report_interval=500, filename_output_dcd="traj.dcd", filename_output_log="openmm_equilibration.log"): print("Running MD...") self.simulation.reporters.append( app.DCDReporter(filename_output_dcd, report_interval)) self.simulation.reporters.append( app.StateDataReporter(filename_output_log, report_interval, step=True, time=True, potentialEnergy=True, kineticEnergy=True, totalEnergy=True, temperature=True, volume=True, density=True, progress=True, remainingTime=True, speed=True, totalSteps=number_of_steps, separator='\t')) self.simulation.step(number_of_steps) print("done")
def main(): print("Reading the PSF file"); # Read the PSF file psf = app.CharmmPsfFile('g1_25mm.psf'); boxsize = 5 # Boxsize in nm psf.setBox(boxsize*nanometer, boxsize*nanometer, boxsize*nanometer); print("Reading the pdb file") pdb = app.PDBFile('g1_25mm.pdb'); # Load the parameter set lib = 'toppar/' #params = app.CharmmParameterSet('toppar/top_all36_cgenff.rtf','toppar/par_all36_cgenff.prm','toppar/cgenff3.0.1/top_all36_cgenff.rtf','toppar/cgenff3.0.1/par_all36_cgenff.prm','g1_new.str','toppar_water_ions.str') params = app.CharmmParameterSet('toppar/cgenff3.0.1/top_all36_cgenff.rtf','toppar/cgenff3.0.1/par_all36_cgenff.prm','g1_new.str','toppar_water_ions.str') #platform = openmm.Platform.getPlatformByName('CUDA'); platform = openmm.Platform.getPlatformByName('Reference'); # Creating the system system = psf.createSystem(params, nonbondedMethod=app.PME, nonbondedCutoff=1.2*nanometer, switchDistance=1.0*nanometer, ewaldErrorTolerance= 0.0001, constraints=app.HBonds); # Thermostat @ 298 K system.addForce(openmm.AndersenThermostat(298*kelvin, 1/picosecond)) # adding the barostat for now system.addForce(openmm.MonteCarloBarostat(1*bar, 298*kelvin)); integrator = openmm.VerletIntegrator(0.001*picoseconds) simulation = app.Simulation(psf.topology, system, integrator, platform) simulation.context.setPositions(pdb.getPositions()) simulation.minimizeEnergy(maxIterations = 500) #nsavcrd = 10000 # save coordinates every 10 ps #nstep = 2000000 # write dcd files every 2 ps #nprint = 2000 # report every 2 ps nsavcrd = 10 # save coordinates every 10 ps nstep = 200 # write dcd files every 2 ps nprint = 20 # report every 2 ps firstDcdStep = nsavcrd ; # Reporters dcd = app.DCDReporter('g1_new.dcd', nsavcrd) dcd._dcd = app.DCDFile(dcd._out, simulation.topology, simulation.integrator.getStepSize(), firstDcdStep, nsavcrd) simulation.reporters.append(dcd) simulation.reporters.append(app.StateDataReporter('g1_new.out', nprint, step=True, kineticEnergy=True, potentialEnergy=True, totalEnergy=True, temperature=True, volume=True, speed=True)) simulation.step(nstep) simulation.reporters.pop() simulation.reporters.pop() dcd._out.close()
def run_dynamics(dcd_name, system, sim, equi, n_steps): """ Given an OpenMM Context object and options, perform molecular dynamics calculations. Parameters ---------- context : an OpenMM context instance n_steps : the number of iterations for the sim Returns ------- """ pdb = sim.extended_pdb temperature = sim.temperature friction = sim.friction timestep = sim.timestep integrator = mm.LangevinIntegrator(temperature, friction, timestep) integrator.setConstraintTolerance(0.00001) platform = mm.Platform.getPlatformByName('CUDA') device = dcd_name[1] dcd_name = dcd_name[0][0] properties = {'CudaPrecision': 'mixed', 'CudaDeviceIndex': device} simulation = app.Simulation(pdb.topology, system, integrator, platform, properties) simulation.context.setPositions(pdb.positions) #zero ghost exceptions if not sim.opt: nonbonded_force = FSim.zero_ghost_exceptions(sim, system) nonbonded_force.updateParametersInContext(simulation.context) else: nonbonded_force = system.getForce(sim.nonbonded_index) logger.debug('Minimizing...') simulation.minimizeEnergy() simulation.context.setVelocitiesToTemperature(temperature) logger.debug('Equilibrating...') simulation.step(equi) simulation.reporters.append(app.DCDReporter(dcd_name, 2500)) simulation.reporters.append( app.StateDataReporter(stdout, 2500, step=True, potentialEnergy=True, temperature=True, progress=True, remainingTime=True, speed=True, totalSteps=equi + n_steps, separator='\t')) logger.debug('Running Production...') simulation.step(n_steps) logger.debug('Done!')
def equilibrate(self, ff_name, water_name): input_pdb_filename = self.get_initial_pdb_filename(ff_name, water_name) equil_pdb_filename = self.get_equil_pdb_filename(ff_name, water_name) equil_dcd_filename = self.get_equil_dcd_filename(ff_name, water_name) equil_protein_pdb_filename = self.get_equil_protein_pdb_filename( ff_name, water_name) utils.make_path(equil_pdb_filename) if os.path.exists(equil_pdb_filename): return ff = app.ForceField('%s.xml' % ff_name, '%s.xml' % water_name) pdb = app.PDBFile(input_pdb_filename) modeller = app.Modeller(pdb.topology, pdb.positions) modeller.addSolvent(ff, model=water_mapping[water_name], padding=self.padding, ionicStrength=self.ionic_strength) topology = modeller.getTopology() positions = modeller.getPositions() system = ff.createSystem(topology, nonbondedMethod=app.PME, nonbondedCutoff=self.cutoff, constraints=app.HBonds) integrator = mm.LangevinIntegrator(self.temperature, self.equil_friction, self.equil_timestep) system.addForce( mm.MonteCarloBarostat(self.pressure, self.temperature, self.barostat_frequency)) simulation = app.Simulation(topology, system, integrator) simulation.context.setPositions(positions) print('Minimizing.') simulation.minimizeEnergy() simulation.context.setVelocitiesToTemperature(self.temperature) print('Equilibrating.') simulation.reporters.append( app.PDBReporter(equil_pdb_filename, self.n_equil_steps - 1)) simulation.reporters.append( app.DCDReporter(equil_dcd_filename, self.equil_output_frequency)) simulation.step(self.n_equil_steps) del simulation del system traj = md.load(equil_dcd_filename, top=equil_pdb_filename)[-1] traj.save(equil_pdb_filename) top, bonds = traj.top.to_dataframe() atom_indices = top.index[top.chainID == 0].values traj.restrict_atoms(atom_indices) traj.save(equil_protein_pdb_filename)
def nvt(coords): # Load OpenMM System file = open(xml_filename, 'r') serialized_system = file.read() system = XmlSerializer.deserialize(serialized_system) # Select Integrator integrator = mm.LangevinIntegrator(TEMPERATURE, NVT_FRICTION, NVT_TIME_STEP) # Set Simulation simulation = app.Simulation(pdb.topology, system, integrator, NVT_PLATFORM, NVT_PROPERTIES) #DEBUG STUFF properties = NVT_PLATFORM.getPropertyValue(simulation.context, 'DeviceIndex') print(properties) print(NVT_PLATFORM.getPropertyNames()) print(NVT_PLATFORM.getSpeed()) #DEBUG STUFF # Set Position and velocities simulation.context.setPositions(coords) simulation.context.setVelocitiesToTemperature(TEMPERATURE) # Set Reporter simulation.reporters.append( app.DCDReporter(nvt_dcd_filename, NVT_OUTPUT_FREQ)) simulation.reporters.append( app.StateDataReporter(nvt_data_filename, NVT_DATA_FREQ, step=True, potentialEnergy=True, temperature=True, density=True)) state = simulation.context.getState(getEnergy=True) if np.isnan(state.getPotentialEnergy() / kilojoule_per_mole): raise ValueError("The Potential Energy before NVT is NaN") print('NVT...\n') simulation.step(NVT_STEPS) state = simulation.context.getState(getPositions=True, getVelocities=True, getEnergy=True) if np.isnan(state.getPotentialEnergy() / kilojoule_per_mole): raise ValueError("The Potential Energy after NVT is NaN") coords = state.getPositions() velocities = state.getVelocities() return coords, velocities
def build_openmm_simulation(structure, temperature=300 * unyt.Kelvin, pressure=1 * unyt.atm, random_seed=42, **kwargs): """ Build OpenMM simulation from a parmed.Structure Notes ----- OpenMM does not compute a virial, which prevents us from computing and reporting the pressure of a system. However, the montecarlobarostat does allow for a robust method to sample under various pressures. """ # First convert unyt units into something consistent for OpenMM temperature.convert_to_units(unyt.Kelvin) if pressure is not None: pressure.convert_to_units(unyt.bar) # hardcoded timestep - probably do not want to expose timestep = 2.0 * unyt.fs timestep.convert_to_units(unyt.ps) integrator = openmm.LangevinIntegrator(float(temperature.value), float((1.0 / unyt.ps).value), float(timestep.value)) integrator.setRandomNumberSeed(random_seed) system = structure.createSystem(nonbondedMethod=app.PME, constraints=app.AllBonds, nonbondedCutoff=14.0 * unit.angstroms) if pressure is not None: barostat = openmm.MonteCarloBarostat(float(pressure.value), float(temperature.value), 25) system.addForce(barostat) sim = app.Simulation(structure.topology, system, integrator) sim.context.setPositions(structure.positions) sim.reporters.append( app.StateDataReporter(open('thermo.log', 'w'), 5000, step=True, time=True, potentialEnergy=True, temperature=True, volume=True, speed=True)) sim.reporters.append(app.DCDReporter('trajectory.dcd', 5000)) sim.reporters.append(app.CheckpointReporter('trajectory.chk', 5000)) return sim
def npt(coords, velocities): # Create OpenMM System file = open(xml_filename, 'r') serialized_system = file.read() system = XmlSerializer.deserialize(serialized_system) # Select Integrator integrator = mm.LangevinIntegrator(TEMPERATURE, NPT_FRICTION, NPT_TIME_STEP) # Set Barostat system.addForce( mm.MonteCarloBarostat(PRESSURE, TEMPERATURE, BAROSTAT_FREQUENCY)) # Set Simulation simulation = app.Simulation(prmtop.topology, system, integrator, NPT_PLATFORM, NPT_PROPERTIES) # Set Position and velocities simulation.context.setPositions(coords) simulation.context.setVelocities(velocities) # Set Reporter simulation.reporters.append( app.DCDReporter(npt_dcd_filename, NPT_OUTPUT_FREQ)) simulation.reporters.append( app.StateDataReporter(npt_data_filename, NPT_DATA_FREQ, step=True, potentialEnergy=True, temperature=True, density=True)) state = simulation.context.getState(getEnergy=True) if np.isnan(state.getPotentialEnergy() / kilojoule_per_mole): raise ValueError("The Potential Energy before NPT is NaN") print('NPT...\n') simulation.step(NPT_STEPS) state = simulation.context.getState(getPositions=True, getVelocities=True, getEnergy=True) if np.isnan(state.getPotentialEnergy() / kilojoule_per_mole): raise ValueError("The Potential Energy after NPT is NaN") coords = state.getPositions() velocities = state.getVelocities() box = state.getPeriodicBoxVectors() return coords, velocities, box
def testAppend(self): """Test appending to an existing trajectory.""" fname = tempfile.mktemp(suffix='.dcd') pdb = app.PDBFile('systems/alanine-dipeptide-implicit.pdb') ff = app.ForceField('amber99sb.xml', 'tip3p.xml') system = ff.createSystem(pdb.topology) # Create a simulation and write some frames to a DCD file. integrator = mm.VerletIntegrator(0.001 * unit.picoseconds) simulation = app.Simulation(pdb.topology, system, integrator, mm.Platform.getPlatformByName('Reference')) dcd = app.DCDReporter(fname, 2) simulation.reporters.append(dcd) simulation.context.setPositions(pdb.positions) simulation.context.setVelocitiesToTemperature(300 * unit.kelvin) simulation.step(10) self.assertEqual(5, dcd._dcd._modelCount) del simulation del dcd len1 = os.stat(fname).st_size # Create a new simulation and have it append some more frames. integrator = mm.VerletIntegrator(0.001 * unit.picoseconds) simulation = app.Simulation(pdb.topology, system, integrator, mm.Platform.getPlatformByName('Reference')) dcd = app.DCDReporter(fname, 2, append=True) simulation.reporters.append(dcd) simulation.context.setPositions(pdb.positions) simulation.context.setVelocitiesToTemperature(300 * unit.kelvin) simulation.step(10) self.assertEqual(10, dcd._dcd._modelCount) len2 = os.stat(fname).st_size self.assertTrue(len2 - len1 > 3 * 4 * 5 * system.getNumParticles()) del simulation del dcd os.remove(fname)
def production(self, ff_name, water_name): equil_pdb_filename = self.get_equil_pdb_filename(ff_name, water_name) production_dcd_filename = self.get_production_dcd_filename( ff_name, water_name) production_protein_dcd_filename = self.get_production_protein_dcd_filename( ff_name, water_name) utils.make_path(production_dcd_filename) if os.path.exists(production_protein_dcd_filename): return ff = app.ForceField('%s.xml' % ff_name, '%s.xml' % water_name) traj = md.load(equil_pdb_filename) top, bonds = traj.top.to_dataframe() atom_indices = top.index[top.chainID == 0].values pdb = app.PDBFile(equil_pdb_filename) system = ff.createSystem(pdb.topology, nonbondedMethod=app.PME, nonbondedCutoff=self.cutoff, constraints=app.HBonds) integrator = mm.LangevinIntegrator(self.temperature, self.friction, self.timestep) system.addForce( mm.MonteCarloBarostat(self.pressure, self.temperature, self.barostat_frequency)) platform = mm.Platform.getPlatformByName("CUDA") platform.setPropertyDefaultValue("CudaDeviceIndex", os.environ["CUDA_VISIBLE_DEVICES"]) simulation = app.Simulation(pdb.topology, system, integrator, platform=platform) simulation.context.setPositions(pdb.positions) simulation.context.setVelocitiesToTemperature(self.temperature) print('Production.') simulation.reporters.append( md.reporters.DCDReporter(production_protein_dcd_filename, self.protein_output_frequency, atomSubset=atom_indices)) simulation.reporters.append( app.DCDReporter(production_dcd_filename, self.output_frequency)) simulation.step(self.n_steps)
def scr(input_coor_name, temperature, time_step_number, user_rand): dir_path = 'media/files/' + user_rand + '/' simulation_status_path = dir_path + 'simulation_status.txt' simulation_status_during_run_path = dir_path + 'simulation_status_during_run.txt' trajectory_path = dir_path traj_dcd = 'trajectory.dcd' pdb = app.PDBFile(input_coor_name) forcefield = app.ForceField('amber99sbildn.xml', 'tip3p.xml') system = forcefield.createSystem(pdb.topology, nonbondedMethod=app.NoCutoff, constraints=app.HBonds, rigidWater=True) integrator = mm.LangevinIntegrator(temperature * unit.kelvin, 1.0 / unit.picoseconds, 2.0 * unit.femtoseconds) integrator.setConstraintTolerance(0.00001) # platform = mm.Platform.getPlatformByName('CPU') # simulation = app.Simulation(pdb.topology, system, integrator, platform) platform = mm.Platform.getPlatformByName('OpenCL') properties = {'OpenCLPrecision': 'mixed'} simulation = app.Simulation(pdb.topology, system, integrator, platform, properties) simulation.context.setPositions(pdb.positions) update_simulation_status('Minimizing energy...', user_rand) simulation.minimizeEnergy() simulation.context.setVelocitiesToTemperature(temperature * unit.kelvin) update_simulation_status('Equilibrating...', user_rand) simulation.step(100) simulation.reporters.append( app.DCDReporter(trajectory_path + traj_dcd, 1000)) simulation.reporters.append( app.StateDataReporter(simulation_status_during_run_path, 1000, progress=True, remainingTime=True, totalSteps=time_step_number, separator=',')) update_simulation_status('Running simulation...', user_rand) simulation.step(time_step_number)
def liquid_analysis(mol_name, switch_dist=1.25, temp=298.15): pdb = app.PDBFile('new.pdb') modeller = app.Modeller(pdb.topology, pdb.positions) forcefield = app.ForceField(f'{mol_name}.xml') try: system = forcefield.createSystem(modeller.topology, nonbondedMethod=app.PME, ewaldErrorTolerance=0.0005, nonbondedCutoff=(switch_dist + 0.05) * unit.nanometer) except ValueError: modeller.addExtraParticles(forcefield) system = forcefield.createSystem(modeller.topology, nonbondedMethod=app.PME, ewaldErrorTolerance=0.0005, nonbondedCutoff=(switch_dist + 0.05) * unit.nanometer) system = opls_lj(system, switch_dist) # FOR NPT temp *= unit.kelvin system.addForce(mm.MonteCarloBarostat(1 * unit.bar, temp)) integrator = mm.LangevinIntegrator(temp, 5 / unit.picosecond, 0.001 * unit.picosecond) platform = mm.Platform.getPlatformByName('CUDA') properties = {'CudaPrecision': 'mixed', 'CudaDeviceIndex': '0'} simulation = app.Simulation(modeller.topology, system, integrator, platform, properties) simulation.context.setPositions(modeller.positions) print('MINIMISATION STARTED') simulation.minimizeEnergy() print('MINIMISATION DONE') simulation.reporters.append(app.DCDReporter('output.dcd', 1000)) simulation.reporters.append( app.StateDataReporter('liquid.txt', 1000, step=True, potentialEnergy=True, temperature=True, density=True)) simulation.step(3000000) np_equ_pos = simulation.context.getState(getPositions=True).getPositions() app.PDBFile.writeFile(simulation.topology, np_equ_pos, open('NPT_EQ_FINAL.pdb', 'w'))
def production(in_top, in_pdb, out_dcd, out_csv, temperature): temperature = temperature * u.kelvin # TODO: recycle John's simtk.unit parser pdb = app.PDBFile(in_pdb) top = app.GromacsTopFile(in_top) top.topology.setPeriodicBoxVectors(pdb.topology.getPeriodicBoxVectors()) system = top.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=CUTOFF, constraints=app.HBonds) integrator = mm.LangevinIntegrator(temperature, FRICTION, TIMESTEP) system.addForce( mm.MonteCarloBarostat(PRESSURE, temperature, BAROSTAT_FREQUENCY)) simulation = app.Simulation(top.topology, system, integrator) simulation.context.setPositions(pdb.positions) simulation.context.setPeriodicBoxVectors( *pdb.topology.getPeriodicBoxVectors()) simulation.context.setVelocitiesToTemperature(temperature) print('Production.') simulation.reporters.append(app.DCDReporter(out_dcd, OUTPUT_FREQUENCY)) simulation.reporters.append( app.StateDataReporter(out_csv, OUTPUT_DATA_FREQUENCY, step=True, potentialEnergy=True, temperature=True, density=True)) converged = False while not converged: simulation.step(N_STEPS) d = pd.read_csv(out_csv, 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
def equilibrate(self): self.ran_equilibrate = True utils.make_path('equil/') self.equil_dcd_filename = "equil/" + self.identifier + "_equil.dcd" self.equil_pdb_filename = "equil/" + self.identifier + "_equil.pdb" utils.make_path(self.equil_pdb_filename) if os.path.exists(self.equil_pdb_filename): return positions = self.packed_trj.openmm_positions(0) topology = self.packed_trj.top.to_openmm() topology.setUnitCellDimensions( mm.Vec3(*self.packed_trj.unitcell_lengths[0]) * u.nanometer) ff = self.ffxml system = ff.createSystem(topology, nonbondedMethod=app.PME, nonbondedCutoff=self.cutoff, constraints=app.HBonds) integrator = mm.LangevinIntegrator(self.temperature, self.equil_friction, self.equil_timestep) system.addForce( mm.MonteCarloBarostat(self.pressure, self.temperature, self.barostat_frequency)) simulation = app.Simulation(topology, system, integrator) simulation.context.setPositions(positions) print('Minimizing.') simulation.minimizeEnergy() simulation.context.setVelocitiesToTemperature(self.temperature) print('Equilibrating.') simulation.reporters.append( app.DCDReporter(self.equil_dcd_filename, self.equil_output_frequency)) simulation.step(self.n_equil_steps) # Re-write a better PDB with correct box sizes. traj = md.load(self.equil_dcd_filename, top=self.box_pdb_filename)[-1] traj.save(self.equil_pdb_filename)
def simulation(filepath, outpath, nsteps, gpu=True): prmtop = app.AmberPrmtopFile(f'{filepath}.prmtop') inpcrd = app.AmberInpcrdFile(f'{filepath}.inpcrd') forcefield = app.ForceField('amber14-all.xml', 'amber14/tip3p.xml') modeller = app.Modeller(prmtop.topology, inpcrd.positions) modeller.addSolvent(forcefield, padding=1.4 * unit.nanometer) system = forcefield.createSystem(modeller.topology, nonbondedMethod=app.PME, nonbondedCutoff=1.0 * unit.nanometer, constraints=app.HBonds) integrator = mm.LangevinIntegrator(310.15 * unit.kelvin, 1.0 / unit.picosecond, 0.002 * unit.picosecond) if gpu: platform = 'CUDA' else: platform = 'CPU' platform = mm.Platform.getPlatformByName(platform) properties = {'Precision': 'double'} simulation = app.Simulation(modeller.topology, system, integrator, platform, properties) simulation.context.setPositions(modeller.positions) simulation.minimizeEnergy() if nsteps != 0: simulation.reporters.append( app.DCDReporter(f'{outpath}/traj.dcd', 25000)) simulation.reporters.append( app.StateDataReporter(f'{outpath}/sim.log', 25000, step=True, potentialEnergy=True, temperature=True)) simulation.reporters.append( app.CheckpointReporter(f'{outpath}/traj.chk', 250000)) simulation.step(nsteps) positions = simulation.context.getState( getPositions=True).getPositions() app.PDBFile.writeFile(simulation.topology, positions, open(f'{outpath}/output.pdb', 'w')) potential = simulation.context.getState( getEnergy=True).getPotentialEnergy().value_in_unit(unit.kilojoule / unit.mole) return potential
def simulation_ESMACS(filepath, outpath, nsteps): prmtop = app.AmberPrmtopFile(f'{filepath}_sol.prmtop') inpcrd = app.AmberInpcrdFile(f'{filepath}_sol.inpcrd') system = prmtop.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=1.0*unit.nanometer, constraints=app.HBonds) integrator = mm.LangevinIntegrator(300*unit.kelvin, 1.0/unit.picosecond, 0.002*unit.picosecond) platform = mm.Platform.getPlatformByName('CUDA') properties = {'Precision': 'double'} simulation = app.Simulation(prmtop.topology, system, integrator, platform, properties) simulation.context.setPositions(inpcrd.positions) if inpcrd.boxVectors is not None: simulation.context.setPeriodicBoxVectors(*inpcrd.boxVectors) simulation.minimizeEnergy() simulation.reporters.append(app.DCDReporter(f'{outpath}/traj.dcd', 50000)) # snapshot at every 100 ps simulation.reporters.append(app.StateDataReporter(f'{outpath}/sim.log', 5000, step=True, potentialEnergy=True, temperature=True)) # reporting at every 10 ps simulation.reporters.append(app.CheckpointReporter(f'{outpath}/traj.chk', 250000)) # checkpoint at every 0.5 ns simulation.step(nsteps) positions = simulation.context.getState(getPositions=True).getPositions() app.PDBFile.writeFile(simulation.topology, positions, open(f'{outpath}/output.pdb', 'w'))
def scr_for_checks(input_coor_name, user_rand, full_check=False): pdb = app.PDBFile(input_coor_name) forcefield = app.ForceField('amber99sbildn.xml', 'tip3p.xml') # The following line causes an error (when we do not perform "fix pdb") system = forcefield.createSystem(pdb.topology, nonbondedMethod=app.NoCutoff, constraints=app.HBonds, rigidWater=True) if full_check: integrator = mm.LangevinIntegrator(300 * unit.kelvin, 1.0 / unit.picoseconds, 2.0 * unit.femtoseconds) integrator.setConstraintTolerance(0.00001) # platform = mm.Platform.getPlatformByName('CPU') # simulation = app.Simulation(pdb.topology, system, integrator, platform) platform = mm.Platform.getPlatformByName('OpenCL') properties = {'OpenCLPrecision': 'mixed'} simulation = app.Simulation(pdb.topology, system, integrator, platform, properties) simulation.context.setPositions(pdb.positions) # Minimizing simulation.minimizeEnergy() simulation.context.setVelocitiesToTemperature(300 * unit.kelvin) # Equilibrating simulation.step(100) simulation.reporters.append( app.DCDReporter( 'media/files/' + user_rand + '/' + 'scr_for_checks.dcd', 1000)) # Running Production simulation.step(1000)
def configure_reporters( sim: omm.app.Simulation, ctx: SimulationContext, cfg: OpenMMConfig, report_steps: int, frames_per_h5: int, ): # Configure DCD file reporter sim.reporters.append(app.DCDReporter(ctx.traj_file, report_steps)) # Configure contact map reporter sim.reporters.append( OfflineReporter( ctx.h5_prefix, report_steps, frames_per_h5=frames_per_h5, wrap_pdb_file=ctx.pdb_file if cfg.wrap else None, reference_pdb_file=ctx.reference_pdb_file, openmm_selection=cfg.openmm_selection, mda_selection=cfg.mda_selection, threshold=cfg.threshold, contact_map=cfg.contact_map, point_cloud=cfg.point_cloud, fraction_of_contacts=cfg.fraction_of_contacts, )) # Configure simulation output log sim.reporters.append( app.StateDataReporter( ctx.log_file, report_steps, step=True, time=True, speed=True, potentialEnergy=True, temperature=True, totalEnergy=True, ))
def simulation(filepath, outpath, nsteps): prmtop = app.AmberPrmtopFile(f'{filepath}.prmtop') inpcrd = app.AmberInpcrdFile(f'{filepath}.inpcrd') forcefield = app.ForceField('amber14-all.xml', 'amber14/tip3p.xml') # gaff/gaff2/other ligand ff also required here or it may complain for 'com' or 'lig' modeller = app.Modeller(prmtop.topology, inpcrd.positions) modeller.addSolvent(forcefield, padding=1.4*unit.nanometer) system = forcefield.createSystem(modeller.topology, nonbondedMethod=app.PME, nonbondedCutoff=1.0*unit.nanometer, constraints=app.HBonds) integrator = mm.LangevinIntegrator(300*unit.kelvin, 1.0/unit.picosecond, 0.002*unit.picosecond) platform = mm.Platform.getPlatformByName('CUDA') properties = {'Precision': 'double'} simulation = app.Simulation(modeller.topology, system, integrator, platform, properties) simulation.context.setPositions(modeller.positions) simulation.minimizeEnergy() if nsteps != 0: simulation.reporters.append(app.DCDReporter(f'{outpath}_traj.dcd', 25000)) # snapshot at every 50 ps simulation.reporters.append(nosol.NewPDBReporter(f'{outpath}_system_nosol.pdb', 25000)) # snapshot at every 50 ps simulation.reporters.append(app.StateDataReporter(f'{outpath}_sim.log', 25000, step=True, potentialEnergy=True, temperature=True)) # reporting at every 50 ps simulation.reporters.append(app.CheckpointReporter(f'{outpath}_traj.chk', 250000)) # checkpoint at every 0.5 ns simulation.step(nsteps) positions = simulation.context.getState(getPositions=True).getPositions() app.PDBFile.writeFile(simulation.topology, positions, open(f'{outpath}_output.pdb', 'w')) # Return potential energy at the end of the simulation # potential = simulation.context.getState(getEnergy=True).getPotentialEnergy().value_in_unit(unit.kilojoule/unit.mole) # return potential # Return mean potential energy during the simulation with open(f'{outpath}_sim.log','r') as log_file: lines = log_file.readlines() mean = 0 for i in range(1,len(lines)): potential = float(lines[i].split(',')[1]) mean = mean + potential potential = mean/(len(lines)-1) return potential
def equilibrate(in_top, in_gro, out_dcd, out_pdb, temperature): temperature = temperature * u.kelvin # TODO: recycle John's simtk.unit parser gro = app.GromacsGroFile(in_gro) top = app.GromacsTopFile(in_top, unitCellDimensions=gro.getUnitCellDimensions()) system = top.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=CUTOFF, constraints=app.HBonds) integrator = mm.LangevinIntegrator(temperature, EQUIL_FRICTION, EQUIL_TIMESTEP) system.addForce( mm.MonteCarloBarostat(PRESSURE, temperature, BAROSTAT_FREQUENCY)) simulation = app.Simulation(top.topology, system, integrator) simulation.context.setPositions(gro.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(temperature) print('Equilibrating.') simulation.reporters.append( app.DCDReporter(out_dcd, OUTPUT_FREQUENCY_EQUIL)) simulation.step(N_EQUIL_STEPS) # Re-write a better PDB with correct box sizes. traj = md.load(out_dcd, top=in_gro)[-1] traj.save(out_pdb)
def gas_analysis(mol_name, temp=298.15): temp *= unit.kelvin pdb = app.PDBFile(mol_name + '.pdb') modeller = app.Modeller(pdb.topology, pdb.positions) forcefield = app.ForceField(mol_name + '.xml') try: system = forcefield.createSystem(modeller.topology, nonbondedMethod=app.NoCutoff, constraints=None) except ValueError: modeller.addExtraParticles(forcefield) system = forcefield.createSystem(modeller.topology, nonbondedMethod=app.NoCutoff, constraints=None) system = opls_lj(system) integrator = mm.LangevinIntegrator(temp, 5 / unit.picosecond, 0.0005 * unit.picosecond) simulation = app.Simulation(modeller.topology, system, integrator) simulation.context.setPositions(modeller.positions) print(f'Results for: {mol_name}.') simulation = minimise(simulation, 100) simulation.reporters.append(app.DCDReporter('gas_output.dcd', 1000)) simulation.reporters.append( app.StateDataReporter('gas.txt', 1000, step=True, temperature=True, potentialEnergy=True, density=True, totalSteps=10000, totalEnergy=True)) simulation.step(6000000)
def configure_reporters(sim, ctx, report_interval_ps, dt_ps, frames_per_h5, wrap): # Configure reporters report_freq = int(report_interval_ps / dt_ps) # Overwriting sim.reporters: we're writing new report files but with same # simulation state sim.reporters = [] # Configure DCD file reporter sim.reporters.append(app.DCDReporter(ctx.traj_file, report_freq)) # Configure contact map reporter senders = [ctx.scp_sender] if ctx.scp_sender is not None else [] sim.reporters.append( SparseContactMapReporter( ctx.h5_prefix, report_freq, wrap_pdb_file=ctx.pdb_file if wrap else None, reference_pdb_file=ctx.reference_pdb_file, senders=senders, batch_size=frames_per_h5, )) # Configure simulation output log sim.reporters.append( app.StateDataReporter( ctx.log_file, report_freq, step=True, time=True, speed=True, potentialEnergy=True, temperature=True, totalEnergy=True, ))
def run_steered_md( temperature, checkpoint_in_file, csv_out_file, dat_out_file, pdb_out_file, traj_out_file, startdist, spring_constant=50, force_constant_chunk=0.1, init_velocity=0.00001, gpu_id=0, ): if os.path.isfile(pdb_out_file): return spring_k = spring_constant * u.kilocalorie / (u.mole * u.angstrom * u.angstrom) dist_in = startdist * u.angstrom # in angstrom dist_fin = (startdist + 2.5) * u.angstrom # in angstrom steps_per_move = 200 velocity = init_velocity * u.angstrom # Platform definition platform = mm.Platform_getPlatformByName("OpenCL") platformProperties = {} platformProperties["OpenCLPrecision"] = "mixed" platformProperties["OpenCLDeviceIndex"] = gpu_id print("loading pickle") pickle_in = open("complex_system.pickle", "rb") combined_pmd = pickle.load(pickle_in)[0] print(combined_pmd) pickle_in.close() keyInteraction = cal_ints.find_interaction() print(keyInteraction) # Get indexes of heavy atoms in chunk Chunk_Heavy_Atoms = duck_stuff.getHeavyAtomsInSystem(combined_pmd) # Setting System system = combined_pmd.createSystem( nonbondedMethod=app.PME, nonbondedCutoff=9 * u.angstrom, constraints=app.HBonds, hydrogenMass=None, ) # Apply force on all havy atoms of chunk duck_stuff.applyHarmonicPositionalRestraints(system, force_constant_chunk, combined_pmd.positions, Chunk_Heavy_Atoms) # Integrator integrator = mm.LangevinIntegrator(temperature, 4 / u.picosecond, 0.002 * u.picosecond) # Setting Simulation object and loading the checkpoint simulation = app.Simulation(combined_pmd.topology, system, integrator, platform, platformProperties) simulation.loadCheckpoint(checkpoint_in_file) # SMD force definition pullforce = mm.CustomExternalForce("k_sp*0.5*(R-R0)^2; \ R = periodicdistance(x, y, z, x0, y0, z0);" ) pullforce.addPerParticleParameter("k_sp") pullforce.addGlobalParameter("x0", 0.0 * u.nanometer) pullforce.addGlobalParameter("y0", 0.0 * u.nanometer) pullforce.addGlobalParameter("z0", 0.0 * u.nanometer) pullforce.addGlobalParameter("R0", 0.0 * u.nanometer) pullforce.addParticle(keyInteraction[1], [spring_k]) system.addForce(pullforce) # Redefine integrator and simulation, and load checkpoint with new-updated system integrator = mm.LangevinIntegrator(temperature, 4 / u.picosecond, 0.002 * u.picosecond) simulation = app.Simulation(combined_pmd.topology, system, integrator, platform, platformProperties) simulation.loadCheckpoint(checkpoint_in_file) # Initializing energy work_val_old = u.Quantity(value=0, unit=u.kilocalorie / u.mole) # Number of big steps and pull distance steps = int(round((dist_fin - dist_in) / velocity) / steps_per_move) pull_distance = velocity * steps_per_move # Reporters and duck.dat file simulation.reporters.append( app.StateDataReporter( csv_out_file, steps_per_move, step=True, time=True, totalEnergy=True, kineticEnergy=True, potentialEnergy=True, temperature=True, density=True, progress=True, totalSteps=steps_per_move * steps, speed=True, )) simulation.reporters.append(app.DCDReporter(traj_out_file, 100000)) f = open(dat_out_file, "w") # Production in N steps with the update every 200 steps (2 pm) for i in range(steps): # Get current state tu update the system state = simulation.context.getState(getPositions=True) pos_keyInt = state.getPositions() keyInteraction_pos = [ pos_keyInt[keyInteraction[0]], pos_keyInt[keyInteraction[1]], ] # Get radius of starting point and end point R_val = dist_in + float(i + 1) * pull_distance R_val_start = dist_in + float(i) * pull_distance # Get distance of main interaction keyInteraction_dist = np.linalg.norm(keyInteraction_pos[0] - keyInteraction_pos[1]) print(keyInteraction_dist) # Updated system simulation.context.setParameter("x0", keyInteraction_pos[0][0]) simulation.context.setParameter("y0", keyInteraction_pos[0][1]) simulation.context.setParameter("z0", keyInteraction_pos[0][2]) simulation.context.setParameter("R0", R_val) # Calculate force F = -k * x force_val = -spring_k * (keyInteraction_dist - R_val) # Make step simulation.step(steps_per_move) # Calculate work for difference in potential energy in tranzition # W = EK_end - EK_start # EK = 0.5 * k * x^2 spr_energy_end = 0.5 * spring_k * (keyInteraction_dist - R_val)**2 spr_energy_start = 0.5 * spring_k * (keyInteraction_dist - R_val_start)**2 work_val = work_val_old + spr_energy_end - spr_energy_start work_val_old = work_val # Write duck.dat file f.write( str(i) + " " + str(R_val) + " " + str(keyInteraction_dist) + " " + str(force_val) + " " + str(work_val) + "\n") f.close() # Save state in PDB file positions = simulation.context.getState(getPositions=True).getPositions() app.PDBFile.writeFile(simulation.topology, positions, open(pdb_out_file, "w"))
# 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_crds.positions) # Minimize the energy print('Minimizing energy') sim.minimizeEnergy(maxIterations=500) # Set up the reporters to report energies and coordinates every 100 steps sim.reporters.append( StateDataReporter(sys.stdout, 100, step=True, potentialEnergy=True, kineticEnergy=True, temperature=True, volume=True, density=True)) sim.reporters.append(app.DCDReporter('ala5_gb.dcd', 100)) # Run dynamics print('Running dynamics') sim.step(10000)
forcefield = app.ForceField(ff_filename) system = forcefield.createSystem(topology, nonbondedMethod=app.CutoffPeriodic, nonbondedCutoff=cutoff, switchDistance=r_switch, ignoreExternalBonds=True, residueTemplates=templates) #for i in range(system.getNumForces()): # force = system.getForce(i) # force.setForceGroup(i) integrator = omm.LangevinIntegrator(temperature, collision_rate, timestep) simulation = app.Simulation(topology, system, integrator) simulation.context.setPositions(positions) simulation.reporters.append(app.DCDReporter(traj_name, nsteps_out)) simulation.reporters.append(app.StateDataReporter(log_name, nsteps_out, step=True, potentialEnergy=True)) simulation.reporters.append(sop.additional_reporters.ForceReporter(name + "_forces_{}.dat".format(traj_idx), nsteps_out)) simulation.step(100*nsteps_out + 5) sigma_ply, eps_ply, mass_ply, bonded_params = sop.build_ff.toy_polymer_params() r0, kb, theta0, ka = bonded_params sigma_ply_nm = sigma_ply/unit.nanometer r0_wca_nm = sigma_ply_nm*(2**(1./6)) eps_ply_kj = eps_ply/unit.kilojoule_per_mole kb_kj = kb/(unit.kilojoule_per_mole/(unit.nanometer**2)) ka_kj = (ka/(unit.kilojoule_per_mole/(unit.radian**2)))
pfreq = cmd.pfreq if cmd.pfreq is not None else 2000 else: # Time step is 2 fs # 500.000 steps give 1 ns wfreq = cmd.wfreq if cmd.wfreq is not None else 5000 pfreq = cmd.pfreq if cmd.pfreq is not None else 5000 eq_dcd = rootname + '.dcd' if cmd.continuation: eq_dcd = get_part_filename(eq_dcd) eq_log = rootname + '.log' if cmd.continuation: eq_log = get_part_filename(eq_log) dcd = app.DCDReporter(eq_dcd, wfreq) cpt = app.CheckpointReporter(eq_cpt, wfreq) state = app.StateDataReporter(eq_log, pfreq, step=True, time=True, progress=True, potentialEnergy=True, kineticEnergy=True, temperature=True, remainingTime=True, speed=True, totalSteps=n_steps, separator='\t')