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_nonequilibrium_external_integrator(): """Moves the first atom during the third step of the integration and checks to see that the AlchemicalExternalLangevinIntegrator finds the correct energy change. """ testsystem = testsystems.AlanineDipeptideVacuum() functions = {'lambda_sterics': '1', 'lambda_electrostatics': '1'} factory = AbsoluteAlchemicalFactory(consistent_exceptions=False) alanine_vacuum = testsystem.system alchemical_region = AlchemicalRegion(alchemical_atoms=range(22), annihilate_electrostatics=True, annihilate_sterics=True) alanine_alchemical_system = factory.create_alchemical_system( reference_system=alanine_vacuum, alchemical_regions=alchemical_region) nsteps_neq = 6 integrator = AlchemicalExternalLangevinIntegrator( alchemical_functions=functions, timestep=0.05 * simtk.unit.femtoseconds, nsteps_neq=nsteps_neq, measure_shadow_work=False, steps_per_propagation=2) simulation = Simulation(testsystem.topology, alanine_alchemical_system, integrator) simulation.context.setPositions(testsystem.positions) for i in range(nsteps_neq): simulation.step(1) protocol_work = simulation.integrator.getGlobalVariableByName( "protocol_work") if i == 3: #perform the displacement of an atom state = simulation.context.getState(getPositions=True) pos = state.getPositions(asNumpy=True) pos[0, 1] = pos[0, 1] + 0.5 * simtk.unit.nanometers simulation.context.setPositions(pos) protocol_work = simulation.integrator.getLogAcceptanceProbability( simulation.context) print(protocol_work) #find the work done for that displacement #protocol work is around 221.0 (in kT units), so acceptance is around -221.0 assert -220.0 > protocol_work assert -223.0 < protocol_work
temperature=True, totalSteps=MD_steps, progress=True, remainingTime=True, speed=True, separator=",", )) # Run OpenMM widgets = [' [', Timer(), '] ', Bar(), ' (', ETA(), ')'] bar = ProgressBar(max=bar_freq, widgets=widgets).start() restr_potential = [] try: for i in progressbar(range(bar_freq), widgets=widgets): simulation.step(print_freq) static_restraint_energy = simulation.context.getState(getEnergy=True, groups={10}) static_restraint_energy = static_restraint_energy.getPotentialEnergy( ) / unit.kilocalorie_per_mole conformational_restraint_energy = simulation.context.getState( getEnergy=True, groups={11}) conformational_restraint_energy = conformational_restraint_energy.getPotentialEnergy( ) / unit.kilocalorie_per_mole guest_restraint_energy = simulation.context.getState(getEnergy=True, groups={12}) guest_restraint_energy = guest_restraint_energy.getPotentialEnergy( ) / unit.kilocalorie_per_mole
def main(argdict): """ Main function for entry point checking. Expects a dictionary of command line arguments. """ # are we continuing from logfile or starting from fresh PDB? if argdict["log"] is None: # keep track of restart number: argdict["restart_number"] = int(0) # write arguments to a file to keep a record: with open(argdict["outname"] + "_parameters.log", 'w') as f: print(json.dumps(argdict, sort_keys=True, indent=4), file=f) else: # load configuration from logfile: logfile = argdict["log"] with open(argdict["log"], 'r') as f: argdict = json.load(f) # make sure log file has appropriate entry: argdict["log"] = logfile # increment restart number: argdict["restart_number"] += 1 # write unnumbered parameters file (for easy restarts): with open(argdict["outname"] + "_parameters.log", 'w') as f: print(json.dumps(argdict, sort_keys=True, indent=4), file=f) # write numbered parameters file (for record keeping): with open( argdict["outname"] + "_" + str(argdict["restart_number"]) + "_parameters.log", 'w') as f: print(json.dumps(argdict, sort_keys=True, indent=4), file=f) # load system initial configuration: pdb = pdb_file_nonstandard_bonds(argdict["pdb"]) print("--> input topology: ", end="") print(pdb.topology) # get XML file from absolute path: xmlfile = os.path.abspath(argdict["xml"]) # set box size in topology to values from XML file: box_vectors = periodic_box_vectors_from_xml(xmlfile) pdb.topology.setPeriodicBoxVectors(box_vectors) # physical parameters of simulation: sim_temperature = argdict["temperature"] * kelvin sim_andersen_coupling = 1 / picosecond sim_pressure = ( (argdict["pressure"], argdict["pressure"], argdict["pressure"]) * bar) sim_scale_x = True sim_scale_y = True sim_scale_z = True # simulation control parameters: sim_timestep = argdict["timestep"] * femtoseconds sim_num_steps = argdict["num_steps"] sim_traj_rep_steps = argdict["report_freq"] sim_state_rep_steps = argdict["report_freq"] sim_checkpoint_steps = argdict["report_freq"] # restraints parameters: sim_restr_fc = argdict["restr_fc"] * kilojoule_per_mole / nanometer**2 # create force field object: ff = ForceField(*argdict["ff"]) # build a simulation system from topology and force field: # (note that AMOEBA is intended to be run without constraints) # (note that mutualInducedtargetEpsilon defaults to 0.01 unlike what is # specified in the documentation which claims 0.00001) sys = ff.createSystem( pdb.topology, nonbondedMethod=PME, nonbondedCutoff=argdict["nonbonded_cutoff"] * nanometer, vdwCutoff=argdict["vdw_cutoff"] * nanometer, ewaldErrorTolerance=argdict["ewald_error_tolerance"], polarisation=argdict["polarisation"], mutualInducedTargetEpsilon=argdict["mutual_induced_target_epsilon"], constraints=None, rigidWater=False, removeCMMotion=True # removes centre of mass motion ) # overwrite the polarisation method set at system creation; this is # necessary as openMM always sets polarisation method to "mutual" of the # target epsilon is specified at system creation; this way, target epsilon # is ignored for all but the mutual method multipole_force = sys.getForce(9) print("--> using polarisation method " + str(argdict["polarisation"])) if argdict["polarisation"] == "mutual": multipole_force.setPolarizationType(multipole_force.Mutual) elif argdict["polarisation"] == "extrapolated": multipole_force.setPolarizationType(multipole_force.Extrapolated) elif argdict["polarisation"] == "direct": multipole_force.setPolarizationType(multipole_force.Direct) else: raise Exception("Polarisation method " + str(argdict["polarisation"]) + " not supported!") # will use Andersen thermostat here: # (Inhibits particle dynamics somewhat, but little or no ergodicity # issues (from Gromacs documenation). However, only alternative is full # Langevin dynamics, which is even worse wrt dynamics. Bussi/v-rescale is # not available at the moment, it seems (it is available in tinker, but # without GPU acceleration)) sys.addForce(AndersenThermostat(sim_temperature, sim_andersen_coupling)) # use anisotropic barostat: # (note that this corresponds to semiisotropic pressure coupling in Gromacs # if the pressure is identical for the x- and y/axes) # (note that by default this attempts an update every 25 steps) sys.addForce( MonteCarloAnisotropicBarostat(sim_pressure, sim_temperature, sim_scale_x, sim_scale_y, sim_scale_z)) # prepare harmonic restraining potential: # (note that periodic distance is absolutely necessary here to prevent # system from blowing up, as otherwise periodic image position may be used # resulting in arbitrarily large forces) force = CustomExternalForce("k*periodicdistance(x, y, z, x0, y0, z0)^2") force.addGlobalParameter("k", sim_restr_fc) force.addPerParticleParameter("x0") force.addPerParticleParameter("y0") force.addPerParticleParameter("z0") # apply harmonic restraints to C-alphas: if argdict["restr"] == "capr": print("--> applying harmonic positional restraints to CA atoms") for atm in pdb.topology.atoms(): if atm.name == "CA": force.addParticle(atm.index, pdb.positions[atm.index]) elif argdict["restr"] == "hapr": sys.exit("Restraints mode " + str(argdict["restr"]) + "is not implemented.") elif argdict["restr"] == "none": print("--> applying no harmonic positional restraints to any atom") else: sys.exit("Restraints mode " + str(argdict["restr"]) + "is not implemented.") # add restraining force to system: sys.addForce(force) # make special group for nonbonded forces: for f in sys.getForces(): if (isinstance(f, AmoebaMultipoleForce) or isinstance(f, AmoebaVdwForce) or isinstance(f, AmoebaGeneralizedKirkwoodForce) or isinstance(f, AmoebaWcaDispersionForce)): f.setForceGroup(1) # read umbrella parameters from file: with open(argdict["umbrella_target"], "r") as f: umbrella_target = json.load(f) # obtain index from atom to be restrained: umbrella_index = umbrella_target["target_particle"]["index"] umbrella_fc = (umbrella_target["umbrella_params"]["fc"] * kilojoule_per_mole / nanometer**2) umbrella_cv = umbrella_target["umbrella_params"]["cv"] * nanometer # inform user: print("--> applying umbrella potential to " + str(list(pdb.topology.atoms())[umbrella_index]) + " at position " + str(pdb.positions[umbrella_index])) # additional restraining force applied to ion under umbrella restraints: umbrella_force = CustomExternalForce( "k*periodicdistance(0.0, 0.0, z, 0.0, 0.0, z0)^2") umbrella_force.addGlobalParameter("k", umbrella_fc) # z0 is set to value in JSON file rather than initial particle coordinate to # allow for a few steps of energy minimisation to avoid clashes between the # restrained umbrella target and surrounding atoms: umbrella_force.addGlobalParameter("z0", umbrella_cv) # select integrator: if argdict["integrator"] == "mts": # use multiple timestep RESPA integrator: print("--> using RESPA/MTS integrator") integrator = MTSIntegrator(sim_timestep, [(0, argdict["inner_ts_frac"]), (1, 1)]) elif argdict["integrator"] == "verlet": # use Leapfrog Verlet integrator here: print("--> using Verlet integrator") integrator = VerletIntegrator(sim_timestep) else: # no other integrators supported: raise Exception("Integrator " + str(argdict["integrator"]) + " is not supported.") # select a platform: platform = Platform.getPlatformByName(argdict["platform"]) properties = { "CudaPrecision": argdict["precision"], "CudaDeviceIndex": "0" } # prepare a simulation from topology, system, and integrator and set initial # positions as in PDB file: sim = Simulation(pdb.topology, sys, integrator, platform, properties) # is this initial simulation or restart from checkpoint? if argdict["log"] is None: # load positions and velocities from XML file: print("--> loading simulation state from XML file...") sim.loadState(xmlfile) # find all particles bonded to ion (i.e. Drude particles): idx_bonded = atom_idx_from_bonds(sim.topology, umbrella_index) idx_shift = idx_bonded + [umbrella_index] # shift target particle into position: pos = (sim.context.getState(getPositions=True).getPositions( asNumpy=True)) pos[idx_shift, :] = (umbrella_target["target_particle"]["init_pos"] * nanometer) print("--> target particle now placed at " + str(pos[idx_shift, :])) # set new particle positions in context: sim.context.setPositions(pos) e_pot = sim.context.getState(getEnergy=True).getPotentialEnergy() print("--> potential energy after target placement is: " + str(e_pot)) # minimise energy to remove clashes: # (too many steps might ruin everythin!) print("--> running energy minimisation...") sim.minimizeEnergy(maxIterations=argdict["minimisation_steps"]) e_pot = sim.context.getState(getEnergy=True).getPotentialEnergy() print( "--> " + str(argdict["minimisation_steps"]) + " steps of energy minimisation reduced the potential energy to " + str(e_pot)) # reduce time step for equilibration period: print("--> running equilibration at reduced time step...") sim.integrator.setStepSize(0.1 * sim.integrator.getStepSize()) sim.context.setTime(0.0 * picosecond) # will write report about equilibration phase: sim.reporters.append( StateDataReporter(stdout, int(argdict["equilibration_steps"] / 10), step=True, time=True, speed=True, progress=True, remainingTime=True, totalSteps=argdict["equilibration_steps"], separator="\t")) # run equilibration steps: sim.step(argdict["equilibration_steps"]) # reset step size to proper value: sim.integrator.setStepSize(10.0 * sim.integrator.getStepSize()) sim.context.setTime(0.0 * picosecond) sim.reporters.clear() else: # load checkpoint file: checkpoint_file = (str(argdict["outname"]) + "_" + str(argdict["restart_number"] - 1) + ".chk") print("--> loading checkpoint file " + checkpoint_file) sim.loadCheckpoint(checkpoint_file) # write collective variable value to file: sample_outname = (argdict["outname"] + "_" + str(argdict["restart_number"]) + str(".dat")) sim.reporters.append( CollectiveVariableReporter(sample_outname, argdict["umbrella_freq"], umbrella_index)) # write simulation trajectory to DCD file: dcd_outname = (argdict["outname"] + "_" + str(argdict["restart_number"]) + str(".dcd")) sim.reporters.append(DCDReporter(dcd_outname, sim_traj_rep_steps)) # write state data to tab-separated CSV file: state_outname = (argdict["outname"] + "_" + str(argdict["restart_number"]) + str(".csv")) sim.reporters.append( StateDataReporter(state_outname, sim_state_rep_steps, step=True, time=True, progress=False, remainingTime=True, potentialEnergy=True, kineticEnergy=True, totalEnergy=True, temperature=True, volume=True, density=False, speed=True, totalSteps=sim_num_steps, separator="\t")) # write limited state information to standard out: sim.reporters.append( StateDataReporter(stdout, sim_state_rep_steps, step=True, time=True, speed=True, progress=True, remainingTime=True, totalSteps=sim_num_steps, separator="\t")) # write checkpoint files regularly: checkpoint_outname = (argdict["outname"] + "_" + str(argdict["restart_number"]) + ".chk") sim.reporters.append( CheckpointReporter(checkpoint_outname, sim_checkpoint_steps)) # run simulation: sim.step(argdict["num_steps"]) # save final simulation state: sim.saveState(argdict["outname"] + "_" + str(argdict["restart_number"]) + ".xml") positions = sim.context.getState(getPositions=True).getPositions() PDBFile.writeFile( sim.topology, positions, open( argdict["outname"] + "_" + str(argdict["restart_number"]) + ".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') 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)
system.addForce(le_force) simulation = Simulation(pdb.topology, system, integrator) simulation.context.setPositions(pdb.positions) simulation.minimizeEnergy() simulation.reporters.append(DCDReporter('trj.dcd', 1)) simulation.reporters.append( StateDataReporter(stdout, 1000, step=True, potentialEnergy=True, temperature=True)) simulation.reporters.append( StateDataReporter(STATE_FNAME, 10, step=True, potentialEnergy=True)) simulation.step(STEPS_PER_CYCLE) for i in range(2, 35): p1, p2 = 49 - i, 49 + i for j in range(0, STEPS_PER_CYCLE): le_force.setBondParameters( i - 2, p1 + 1, p2 - 1, 1 * u.angstrom, LE_FORCE_MATRIX[1][j] * u.kilocalories_per_mole / u.angstroms**2) le_force.setBondParameters(i - 1, p1, p2, 1 * u.angstrom, LE_FORCE_MATRIX[2][j]) le_force.updateParametersInContext(simulation.context) simulation.step(1) # le_force.setBondParameters(i - 2, p1 + 1, p2 - 1, 1 * u.angstrom, # LE_FORCE_MATRIX[1][0] * u.kilocalories_per_mole / u.angstroms ** 2) # le_force.setBondParameters(i - 1, p1, p2, 1 * u.angstrom, LE_FORCE_MATRIX[2][0]) # simulation.minimizeEnergy()
print('(%d) %s' % (no_platform, Platform.getPlatform(no_platform).getName())) print(os.environ) print(Platform.getPluginLoadFailures()) print(Platform.getDefaultPluginsDirectory()) simulation.context.setPositions(pdb.positions) pbv = system.getDefaultPeriodicBoxVectors() simulation.context.setPeriodicBoxVectors(*pbv) # set velocities to temperature in integrator temperature = integrator.getTemperature() dt = integrator.getStepSize() simulation.context.setVelocitiesToTemperature(temperature) simulation.reporters.append(StateDataReporter(stdout, 1000, step=True, potentialEnergy=True, temperature=True)) if args.save_traj=='True': simulation.reporters.append(DCDReporter(args.path+'/iter'+str(args.iter)+'_traj'+str(i)+'.dcd', args.trajstride)) steps=args.md_steps #1000=2sec each, 10000=20sec start=datetime.now() simulation.step(steps) end = datetime.now() elapsed = end -start time=elapsed.seconds + elapsed.microseconds*1e-6 print('Integrated %d steps in %g seconds' % (steps, time)) print('%g ns/day' % (dt*steps*86400/time).value_in_unit(u.nanoseconds)) state = simulation.context.getState(getPositions=True, getVelocities=True,getEnergy=True) pbv = state.getPeriodicBoxVectors(asNumpy=True) vel = state.getVelocities(asNumpy=True) pos = state.getPositions(asNumpy=True) print(state.getPotentialEnergy(), state.getKineticEnergy()) PDBFile.writeFile(simulation.topology, pos, open(args.path+'/iter'+str(args.iter)+'_out'+str(i)+'.pdb', 'a')) del simulation, integrator, system
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)
platform.setPropertyDefaultValue('Precision', 'mixed') print("Done setting the precision to mixed.") minimize = Simulation(molecule.topology, system, integrator, platform) print("Done specifying simulation.") minimize.context.setPositions(molecule.positions) print("Done recording a context for positions.") minimize.context.setVelocitiesToTemperature(310.15*unit.kelvin) print("Done assigning velocities.") # start minimization tolerance = 0.1*unit.kilojoules_per_mole/unit.angstroms print("Done setting tolerance.") minimize.minimizeEnergy(tolerance=tolerance,maxIterations=1000) print("Done setting energy minimization.") minimize.reporters.append(StateDataReporter('relax-hydrogens.log', 1000, step=True, temperature=True, potentialEnergy=True, totalEnergy=True, speed=True)) minimize.step(min_steps) print("Done 100000 steps of minimization.") print("Potential energy after minimization:") #print(minimize.context.getState(getEnergy=True).getPotentialEnergy()) positions = minimize.context.getState(getPositions=True).getPositions() print("Done updating positions.") #velocities = minimize.context.getState(getVelocities=True).getVelocities() #print("Done updating velocities.") minimize.saveCheckpoint('state.chk') print("Done saving checkpoints.") # update the current context with changes in system # minimize.context.reinitialize(preserveState=True) # output the minimized protein as a shortcut PDBFile.writeFile(molecule.topology,positions,open(f'{pdbid}_chain{chain}_minimized.pdb', 'w'), keepIds=True) print("Done outputing minimized pdb.") # clean the context
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 simulate(self, header, content): """Main method that is "executed" by the receipt of the msg_type == 'simulate' message from the server. We run some OpenMM dynamics, and then send back the results. """ self.log.info('Setting up simulation...') state, topology = self.deserialize_input(content) starting_state_path = content.starting_state.path # set the GPU platform platform = Platform.getPlatformByName(str(self.platform)) if self.platform == 'CUDA': properties = { 'CudaPrecision': 'mixed', 'CudaDeviceIndex': str(self.device_index) } elif self.platform == 'OpenCL': properties = { 'OpenCLPrecision': 'mixed', 'OpenCLDeviceIndex': str(self.device_index) } else: properties = None simulation = Simulation(topology, self.system, self.integrator, platform, properties) # do the setup self.set_state(state, simulation) self.sanity_check(simulation) if self.minimize: self.log.info('minimizing...') simulation.minimizeEnergy() if self.random_initial_velocities: try: temp = simulation.integrator.getTemperature() simulation.context.setVelocitiesToTemperature(temp) except AttributeError: print "I don't know what temperature to use!!" # TODO: look through the system's forces to find an andersen # thermostate? raise pass assert content.output.protocol == 'localfs', "I'm currently only equiped for localfs output" self.log.info('adding reporters...') self.add_reporters(simulation, content.output.path) # run dynamics! self.log.info('Starting dynamics') simulation.step(self.number_of_steps) for reporter in simulation.reporters: # explicitly delete the reporters so that any open file handles # are closed. del reporter # tell the master that I'm done self.send_recv(msg_type='simulation_done', content={ 'status': 'success', 'starting_state': { 'protocol': 'localfs', 'path': starting_state_path }, 'output': { 'protocol': 'localfs', 'path': content.output.path } })
simulation.reporters.append( parmed.openmm.ProgressReporter( str(opt.output) + '.info', opt.interval, opt.num_steps)) simulation.reporters.append( #parmed.openmm.NetCDFReporter(opt.trajectory, opt.interval*10) DCDReporter(opt.trajectory, opt.interval * 10, enforcePeriodicBox=False)) #simulation.reporters.append( # parmed.openmm.RestartReporter(opt.restart, opt.interval*100, netcdf=True) #) print('Starting simulation with', opt.num_steps, 'steps ...') #simulation.context.setPositions(modeller.positions) #simulation.context.setVelocitiesToTemperature(opt.temp) t0 = time.time() simulation.step(opt.num_steps) t1 = time.time() print('Simulation complete in', t1 - t0, 'seconds at', opt.temp * unit.kelvin) import mdtraj as md mdtraj_topology = md.Topology.from_openmm(modeller.topology) trajectory = md.Trajectory( simulation.context.getState(getPositions=True).getPositions(asNumpy=True) / unit.nanometers, mdtraj_topology) trajectory[-1:].save('restart.nc') trajectory[-1:].save('restart.pdb') #atoms_to_keep = [r.index for r in trajectory.topology.residues if r.name == 'LIG'] if opt.ligand: atoms_to_keep = trajectory.topology.select('resname LIG') trajectory.restrict_atoms(
simulation.minimizeEnergy() # Write out the minimised PDB. The 'enforcePeriodicBox=False' bit is important otherwise the different # components can end up in different periodic boxes resulting in really strange looking output. with open(output_min, 'w') as outfile: PDBFile.writeFile( modeller.topology, context.getState(getPositions=True, enforcePeriodicBox=False).getPositions(), file=outfile, keepIds=True) # equilibrate simulation.context.setVelocitiesToTemperature(temperature) print('Equilibrating ...') simulation.step(equilibration_steps) # Run the simulation. # The enforcePeriodicBox arg to the reporters is important. # It's a bit counter-intuitive that the value needs to be False, but this is needed to ensure that # all parts of the simulation end up in the same periodic box when being output. # simulation.reporters.append(PDBReporter(output_traj_pdb, reporting_interval, enforcePeriodicBox=False)) simulation.reporters.append( DCDReporter(output_traj_dcd, reporting_interval, enforcePeriodicBox=False)) simulation.reporters.append( StateDataReporter(sys.stdout, reporting_interval * 5, step=True, potentialEnergy=True, temperature=True)) print('Starting simulation with', num_steps, 'steps ...')
def test_improper_recover(): from simtk import openmm, unit from simtk.openmm.app import Simulation from simtk.unit import Quantity TEMPERATURE = 500 * unit.kelvin STEP_SIZE = 1 * unit.femtosecond COLLISION_RATE = 1 / unit.picosecond system, topology, g = _create_impropers_only_system() # use langevin integrator, although it's not super useful here integrator = openmm.LangevinIntegrator( TEMPERATURE, COLLISION_RATE, STEP_SIZE ) # initialize simulation simulation = Simulation( topology=topology, system=system, integrator=integrator ) import openff.toolkit # get conformer g.mol.generate_conformers( toolkit_registry=openff.toolkit.utils.RDKitToolkitWrapper(), ) # put conformer in simulation simulation.context.setPositions(g.mol.conformers[0]) # minimize energy simulation.minimizeEnergy() # set velocities simulation.context.setVelocitiesToTemperature(TEMPERATURE) samples = [] us = [] # loop through number of samples for _ in range(10): # run MD for `self.n_steps_per_sample` steps simulation.step(10) # append samples to `samples` samples.append( simulation.context.getState(getPositions=True) .getPositions(asNumpy=True) .value_in_unit(esp.units.DISTANCE_UNIT) ) us.append( simulation.context.getState(getEnergy=True) .getPotentialEnergy() .value_in_unit(esp.units.ENERGY_UNIT) ) # put samples into an array samples = np.array(samples) us = np.array(us) # put samples into tensor samples = torch.tensor(samples, dtype=torch.float32) us = torch.tensor(us, dtype=torch.float32)[None, :, None] g.heterograph.nodes["n1"].data["xyz"] = samples.permute(1, 0, 2) # require gradient for force matching g.heterograph.nodes["n1"].data["xyz"].requires_grad = True g.heterograph.nodes["g"].data["u_ref"] = us # parametrize layer = esp.nn.dgl_legacy.gn() net = torch.nn.Sequential( esp.nn.Sequential(layer, [32, "tanh", 32, "tanh", 32, "tanh"]), esp.nn.readout.janossy.JanossyPoolingImproper( in_features=32, config=[32, "tanh"], out_features={ "k": 6, }, ), esp.mm.geometry.GeometryInGraph(), esp.mm.energy.EnergyInGraph(terms=["n4_improper"]), ) optimizer = torch.optim.Adam(net.parameters(), 1e-3) for _ in range(1500): optimizer.zero_grad() net(g.heterograph) u_ref = g.nodes["g"].data["u"] u = g.nodes["g"].data["u_ref"] loss = torch.nn.MSELoss()(u_ref, u) loss.backward() print(loss) optimizer.step() assert loss.detach().numpy().item() < 0.1
print("Done assigning velocities.") # start minimization tolerance = 0.1 * unit.kilojoules_per_mole / unit.angstroms print("Done setting tolerance.") minimize.minimizeEnergy(tolerance=tolerance, maxIterations=1000) print("Done setting energy minimization.") minimize.reporters.append( StateDataReporter('relax-hydrogens.log', 1000, step=True, temperature=True, potentialEnergy=True, totalEnergy=True, speed=True)) minimize.step(100000) print("Done 100000 steps of minimization.") print("Potential energy after minimization:") print(minimize.context.getState(getEnergy=True).getPotentialEnergy()) positions = minimize.context.getState(getPositions=True).getPositions() print("Done updating positions.") #velocities = minimize.context.getState(getVelocities=True).getVelocities() #print("Done updating velocities.") minimize.saveCheckpoint('state.chk') print("Done saving checkpoints.") # update the current context with changes in system # minimize.context.reinitialize(preserveState=True) # output the minimized protein as a shortcut PDBFile.writeFile(molecule.topology, positions, open("{}_minimized.pdb".format(pdbid), 'w')) print("Done outputing minimized pdb.")
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
'constraints': app.HBonds, 'rigidWater': True, 'removeCMMotion': False, 'hydrogenMass': 4 * unit.amu } # Initialize a SystemGenerator using GAFF system_generator = SystemGenerator( forcefields=['amber/ff14SB.xml', 'amber/tip3p_standard.xml'], small_molecule_forcefield='gaff-2.11', forcefield_kwargs=forcefield_kwargs) system = system_generator.create_system(complex_pdb.topology, molecules=ligand_mol) integrator = LangevinIntegrator(300 * unit.kelvin, 1 / unit.picosecond, 0.002 * unit.picoseconds) simulation = Simulation(complex_pdb.topology, system, integrator) simulation.context.setPositions(complex_pdb.positions) print('Minimising') simulation.minimizeEnergy() simulation.reporters.append(PDBReporter('output1.pdb', 1000)) simulation.reporters.append( StateDataReporter(sys.stdout, 1000, step=True, potentialEnergy=True, temperature=True)) print('Starting simulation') simulation.step(500000) print('Done')
atomSubset=prot_Select) else: remainingsteps = todosteps reporter = mdtraj.reporters.DCDReporter(savedcdfile, trajstride, atomSubset=prot_Select) # first frame adding reporter.report(simulation, state) simulation.reporters.append(reporter) start = datetime.now() while remainingsteps > 0: #print(remainingsteps) executesteps = min(trajstride, remainingsteps) simulation.step(executesteps) vel = state.getVelocities(asNumpy=True) pos = state.getPositions(asNumpy=True) remainingsteps = remainingsteps - executesteps np.savez(argsrestart, positions=pos, box_vectors=pbv, velocities=vel, remainingsteps=remainingsteps) end = datetime.now() elapsed = end - start time_el = elapsed.seconds + elapsed.microseconds * 1e-6 print('Integrated %d steps in %g seconds' % (todosteps, time_el)) print('%g ns/day' % (dt * todosteps * 86400 / time_el).value_in_unit(u.nanoseconds))
temperature=temperature, biasFactor=10.0, height=1.5 * unit.kilojoules_per_mole, frequency=250, saveFrequency=250, biasDir='./biases') integrator = mm.LangevinIntegrator(temperature, 1.0 / unit.picosecond, 0.004 * unit.picoseconds) print("Done specifying integrator.") simulation = Simulation(molecule.topology, system, integrator) simulation.context.setPositions(pdb.positions) print("Done specifying simulation.") # equilibration simulation.context.setVelocitiesToTemperature(temperature) simulation.step(100) print("Done 100 steps of equilibration.") # set simulation reporters simulation.reporters.append(DCDReporter('mtd_2JIU.dcd', reportInterval=250)) simulation.reporters.append( StateDataReporter('mtd_2JIU.out', reportInterval=5000, step=True, potentialEnergy=True, temperature=True, progress=True, remainingTime=True, speed=True, totalSteps=10000000, separator='\t'))
def distributeLipids(boxsize, resnames, sigmas, cutoff, mass=39.9 * unit.amu, # argon epsilon=0.238 * unit.kilocalories_per_mole, # argon, switch_width=3.4 * unit.angstrom, # argon ): nparticles = len(resnames) # Determine Lennard-Jones cutoff. cutoff = cutoff * unit.angstrom cutoff_type = openmm.NonbondedForce.CutoffPeriodic # Create an empty system object. system = openmm.System() # Periodic box vectors. a = unit.Quantity((boxsize[0] * unit.angstrom, 0 * unit.angstrom, 0 * unit.angstrom)) b = unit.Quantity((0 * unit.angstrom, boxsize[1] * unit.angstrom, 0 * unit.angstrom)) c = unit.Quantity((0 * unit.angstrom, 0 * unit.angstrom, boxsize[2] * unit.angstrom)) system.setDefaultPeriodicBoxVectors(a, b, c) # Set up periodic nonbonded interactions with a cutoff. nb = openmm.NonbondedForce() nb.setNonbondedMethod(cutoff_type) nb.setCutoffDistance(cutoff) nb.setUseDispersionCorrection(True) nb.setUseSwitchingFunction(False) if (switch_width is not None): nb.setUseSwitchingFunction(True) nb.setSwitchingDistance(cutoff - switch_width) for s in sigmas: system.addParticle(mass) nb.addParticle(0.0 * unit.elementary_charge, s * unit.angstrom, epsilon) positions = subrandom_particle_positions(nparticles, system.getDefaultPeriodicBoxVectors(), 2) # Add the nonbonded force. system.addForce(nb) # Add a restraining potential to keep atoms in z=0 energy_expression = 'k * (z^2)' force = openmm.CustomExternalForce(energy_expression) force.addGlobalParameter('k', 10) for particle_index in range(nparticles): force.addParticle(particle_index, []) system.addForce(force) # Create topology. topology = app.Topology() chain = topology.addChain() elems = ['Ar', 'Cl', 'Na'] _, idx = np.unique(resnames, return_inverse=True) for i in idx: element = app.Element.getBySymbol(elems[i]) residue = topology.addResidue(elems[i], chain) topology.addAtom(elems[i], element, residue) topology.setUnitCellDimensions(unit.Quantity(boxsize, unit.angstrom)) # Simulate it from simtk.openmm import LangevinIntegrator, VerletIntegrator from simtk.openmm.app import Simulation, PDBReporter, StateDataReporter, PDBFile from simtk.unit import kelvin, picoseconds, picosecond, angstrom from sys import stdout from mdtraj.reporters import DCDReporter nsteps = 10000 freq = 1 integrator = VerletIntegrator(0.002 * picoseconds) simulation = Simulation(topology, system, integrator) simulation.context.setPositions(positions) simulation.minimizeEnergy() # simulation.reporters.append(DCDReporter('output.dcd', 1)) # simulation.reporters.append(StateDataReporter(stdout, 1000, potentialEnergy=True, totalEnergy=True, step=True, separator=' ')) simulation.step(nsteps) state = simulation.context.getState(getPositions=True, enforcePeriodicBox=True) allfinalpos = state.getPositions(asNumpy=True).value_in_unit(angstrom) # with open('topology.pdb', 'w') as f: # PDBFile.writeFile(topology, positions, f) # from htmd.molecule.molecule import Molecule # mol = Molecule('topology.pdb') # mol.read('output.dcd') return allfinalpos
def loop_extrusion(STEPS, LE_FORCE_SCALE, MATRIX_LENGTH, STEPS_PER_CYCLE, STEPS_PER_IT): STATE_FNAME = '2sided-state.csv' #STEPS = 10000 #LE_FORCE_SCALE = 3 #MATRIX_LENGTH = 200 #STEPS_PER_CYCLE = 10 #STEPS_PER_IT = 1 #Macierz z parametrami sił wiązań #Dodano funkcje generacji macierzy o wartościach sinusoidalnych. Funkcja ta przyjmuje dwa argumenty. Pierwszy oznacza liczbę kroków które ma posiadać macierz a drugi #stanowi regulacje maksymalnej siły (tzn jeśli wstawimy 3 to maksymalna siła bedzie tyle wynosić) LE_FORCE_MATRIX = gen_sin_array(MATRIX_LENGTH,LE_FORCE_SCALE) LE_FORCE_MATRIX[1][0] = 0 LE_FORCE_MATRIX[2][-1] = 0 #print(LE_FORCE_MATRIX) pdb = PDBFile('initial_structure.pdb') forcefield = ForceField('polymer_ff.xml') system = forcefield.createSystem(pdb.topology, nonbondedCutoff=1 * u.nanometer) integrator = mm.LangevinIntegrator(100 * u.kelvin, 0.2, 1 * u.femtoseconds) # Distance constraint for i in range(system.getNumParticles() - 1): system.addConstraint(i, i + 1, 0.1 * u.nanometer) # Pinning ends with rubber pin_force = mm.CustomExternalForce("k*((x-x0)^2+(y-y0)^2+(z-z0)^2)") pin_force.addGlobalParameter("k", 50 * u.kilocalories_per_mole / u.angstroms ** 2) pin_force.addPerParticleParameter("x0") pin_force.addPerParticleParameter("y0") pin_force.addPerParticleParameter("z0") pin_force.addParticle(0, [15 * u.angstrom, 0 * u.angstrom, 0 * u.angstrom]) pin_force.addParticle(system.getNumParticles() - 1, [-15 * u.angstrom, 0 * u.angstrom, 0 * u.angstrom]) system.addForce(pin_force) # Loop extrusion force le_force = mm.HarmonicBondForce() le_force.addBond(48, 50, 1 * u.angstrom, LE_FORCE_SCALE * u.kilocalories_per_mole / u.angstroms ** 2) for i in range(2, 35): p1, p2 = 49 - i, 49 + i le_force.addBond(p1, p2, 1 * u.angstrom, 0.000001 * u.kilocalories_per_mole / u.angstroms ** 2) system.addForce(le_force) simulation = Simulation(pdb.topology, system, integrator) simulation.context.setPositions(pdb.positions) simulation.minimizeEnergy() simulation.reporters.append(DCDReporter('wyniki/2sided-trj.dcd', 1)) simulation.reporters.append(StateDataReporter(stdout, 1000, step=True, potentialEnergy=True, temperature=True)) simulation.reporters.append(StateDataReporter(STATE_FNAME, 10, step=True, potentialEnergy=True)) simulation.step(1) for i in range(2, 35): p1, p2 = 49 - i, 49 + i for j in range(MATRIX_LENGTH): le_force_one = LE_FORCE_MATRIX[1][j] * u.kilocalories_per_mole / u.angstroms ** 2 #ROSNĄCA le_force_two = LE_FORCE_MATRIX[2][j] * u.kilocalories_per_mole / u.angstroms ** 2 #MALEJĄCA le_force.setBondParameters(i - 2, p1 + 1, p2 - 1, 1 * u.angstrom, le_force_two) le_force.setBondParameters(i - 1, p1, p2, 1 * u.angstrom, le_force_one) le_force.updateParametersInContext(simulation.context) #print(le_force_one) #print(le_force_two) #simulation.minimizeEnergy() simulation.step(STEPS_PER_IT) # for i in range(STEPS_PER_CYCLE): # simulation.step(1) simulation.step(200) plot_data(STATE_FNAME, '2sided-energy.png') print('#1: repr stick; color white; color red :1,100; repr sphere :1,100; vdwdefine 0.5') print('#1: color green :49,51; repr sphere :49,51; color #ffffa2e8a2e8 :50;') for i in range(1, 35): p1, p2 = 50 - i - 1, 50 + i + 1 print( f'#{i*STEPS_PER_CYCLE+1}: color green :{p1},{p2}; repr sphere :{p1},{p2}; repr stick :{p1+1},{p2-1}; color #ffffa2e8a2e8 :{p1+1}-{p2-1};') print("Done")
def simulate(self, header, content): """Main method that is "executed" by the receipt of the msg_type == 'simulate' message from the server. We run some OpenMM dynamics, and then send back the results. """ self.log.info('Setting up simulation...') state, topology = self.deserialize_input(content) # set the GPU platform platform = Platform.getPlatformByName(str(self.platform)) if self.platform == 'CUDA': properties = {'CudaPrecision': 'mixed', 'CudaDeviceIndex': str(self.device_index) } elif self.platform == 'OpenCL': properties = {'OpenCLPrecision': 'mixed', 'OpenCLDeviceIndex': str(self.device_index) } else: properties = None simulation = Simulation(topology, self.system, self.integrator, platform, properties) # do the setup self.set_state(state, simulation) self.sanity_check(simulation) if self.minimize: self.log.info('minimizing...') simulation.minimizeEnergy() if self.random_initial_velocities: try: temp = simulation.integrator.getTemperature() simulation.context.setVelocitiesToTemperature(temp) except AttributeError: print "I don't know what temperature to use!!" # TODO: look through the system's forces to find an andersen # thermostate? raise pass assert content.output.protocol == 'localfs', "I'm currently only equiped for localfs output" self.log.info('adding reporters...') self.add_reporters(simulation, content.output.path) # run dynamics! self.log.info('Starting dynamics') simulation.step(self.number_of_steps) for reporter in simulation.reporters: # explicitly delete the reporters so that any open file handles # are closed. del reporter # tell the master that I'm done self.send_recv(msg_type='simulation_done', content={ 'status': 'success', 'output': { 'protocol': 'localfs', 'path': content.output.path } })
print("Done assigning velocities.") # start minimization tolerance = 0.1 * unit.kilojoules_per_mole / unit.angstroms print("Done setting tolerance.") minimize.minimizeEnergy(tolerance=tolerance, maxIterations=1000) print("Done setting energy minimization.") minimize.reporters.append( StateDataReporter('relax-hydrogens.log', 1000, step=True, temperature=True, potentialEnergy=True, totalEnergy=True, speed=True)) minimize.step(min_steps) print("Done 100000 steps of minimization.") print("Potential energy after minimization:") #print(minimize.context.getState(getEnergy=True).getPotentialEnergy()) positions = minimize.context.getState(getPositions=True).getPositions() print("Done updating positions.") #velocities = minimize.context.getState(getVelocities=True).getVelocities() #print("Done updating velocities.") minimize.saveCheckpoint('state.chk') print("Done saving checkpoints.") # update the current context with changes in system # minimize.context.reinitialize(preserveState=True) # output the minimized protein as a shortcut PDBFile.writeFile(molecule.topology, positions, open(f'{pdbid}_chain{chain}_minimized.pdb', 'w'),
simulation.reporters.append( StateDataReporter( stdout, output_stride, step=True, potentialEnergy=True, temperature=True, speed=True, separator=" || ", )) restart_file = os.path.join(output, 'restart.npz') print('START SIMULATION') simulation.step(args.length) print('DONE') state = simulation.context.getState(getPositions=True, getVelocities=True) pbv = state.getPeriodicBoxVectors(asNumpy=True) vel = state.getVelocities(asNumpy=True) pos = state.getPositions(asNumpy=True) np.savez(restart_file, positions=pos, box_vectors=pbv, velocities=vel, index=args.length) print('Written to directory `%s`' % args.output)
def distributeAtoms(boxsize=[34, 34, 34], nparticles=1000, reduced_density=0.05, mass=39.9 * unit.amu, # argon sigma=3.4 * unit.angstrom, # argon, epsilon=0.238 * unit.kilocalories_per_mole, # argon, cutoff=None, switch_width=3.4 * unit.angstrom, # argon dispersion_correction=True, lattice=False, charge=None, **kwargs): # Determine Lennard-Jones cutoff. if cutoff is None: cutoff = 3.0 * sigma charge = 0.0 * unit.elementary_charge cutoff_type = openmm.NonbondedForce.CutoffPeriodic # Create an empty system object. system = openmm.System() # Periodic box vectors. a = unit.Quantity((boxsize[0] * unit.angstrom, 0 * unit.angstrom, 0 * unit.angstrom)) b = unit.Quantity((0 * unit.angstrom, boxsize[1] * unit.angstrom, 0 * unit.angstrom)) c = unit.Quantity((0 * unit.angstrom, 0 * unit.angstrom, boxsize[2] * unit.angstrom)) system.setDefaultPeriodicBoxVectors(a, b, c) # Set up periodic nonbonded interactions with a cutoff. nb = openmm.NonbondedForce() nb.setNonbondedMethod(cutoff_type) nb.setCutoffDistance(cutoff) nb.setUseDispersionCorrection(dispersion_correction) nb.setUseSwitchingFunction(False) if (switch_width is not None): nb.setUseSwitchingFunction(True) nb.setSwitchingDistance(cutoff - switch_width) for particle_index in range(nparticles): system.addParticle(mass) nb.addParticle(charge, sigma, epsilon) positions = subrandom_particle_positions(nparticles, system.getDefaultPeriodicBoxVectors(), 2) # Add the nonbonded force. system.addForce(nb) # Add a restrining potential to keep atoms in z=0 energy_expression = 'k * (z^2)' force = openmm.CustomExternalForce(energy_expression) force.addGlobalParameter('k', 100) for particle_index in range(nparticles): force.addParticle(particle_index, []) system.addForce(force) # Create topology. topology = app.Topology() element = app.Element.getBySymbol('Ar') chain = topology.addChain() for particle in range(system.getNumParticles()): residue = topology.addResidue('Ar', chain) topology.addAtom('Ar', element, residue) topology.setUnitCellDimensions(unit.Quantity(boxsize, unit.angstrom)) # Simulate it from simtk.openmm import LangevinIntegrator, VerletIntegrator from simtk.openmm.app import Simulation, PDBReporter, StateDataReporter, PDBFile from simtk.unit import kelvin, picoseconds, picosecond, angstrom from sys import stdout from mdtraj.reporters import DCDReporter #from dcdreporter import DCDReporter nsteps = 10000 freq = 1 #integrator = LangevinIntegrator(300 * kelvin, 1 / picosecond, 0.002 * picoseconds) integrator = VerletIntegrator(0.002 * picoseconds) simulation = Simulation(topology, system, integrator) simulation.context.setPositions(positions) simulation.minimizeEnergy() simulation.reporters.append(DCDReporter('output.dcd', 1)) simulation.reporters.append(StateDataReporter(stdout, 1000, potentialEnergy=True, totalEnergy=True, step=True, separator=' ')) simulation.step(nsteps) state = simulation.context.getState(getPositions=True) finalpos = state.getPositions(asNumpy=True).value_in_unit(angstrom) with open('topology.pdb', 'w') as f: PDBFile.writeFile(topology, positions, f) from htmd.molecule.molecule import Molecule mol = Molecule('topology.pdb') mol.read('output.dcd') return finalpos, mol, system, simulation