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)
reportInterval=report_freq, step=True, time=True, potentialEnergy=True, kineticEnergy=True, temperature=True, speed=True, progress=True, remainingTime=True, totalSteps=nsteps, separator="\t", )) # Write to checkpoint files regularly: sim.reporters.append( CheckpointReporter(file=output_prefix + checkpoint_filename, reportInterval=chk_freq)) # Write out the trajectory sim.reporters.append( md.reporters.DCDReporter(file=output_prefix + traj_output_filename, reportInterval=traj_freq)) # Run NPT dynamics print("Running dynamics in the NPT ensemble...") initial_time = time.time() sim.step(nsteps) elapsed_time = (time.time() - initial_time) * unit.seconds simulation_time = nsteps * timestep print(' Equilibration took %.3f s for %.3f ns (%8.3f ns/day)' % (elapsed_time / unit.seconds, simulation_time / unit.nanoseconds, simulation_time / elapsed_time * unit.day / unit.nanoseconds))
reportInterval=report_freq, step=True, time=True, potentialEnergy=True, kineticEnergy=True, temperature=True, speed=True, progress=True, remainingTime=True, totalSteps=nsteps, separator="\t", )) # Write to checkpoint files regularly: sim.reporters.append( CheckpointReporter(file=os.path.join(output_prefix, checkpoint_filename), reportInterval=chk_freq)) # Write out the trajectory sim.reporters.append( md.reporters.XTCReporter(file=os.path.join(output_prefix, traj_output_filename), reportInterval=traj_freq)) # Run NPT dynamics print("--> Running dynamics in the NPT ensemble for the 4AT3:" + chosen_ligand + " complex") sim.step(nsteps) # Save and serialize the final state print("--> Serializing state to %s" % os.path.join(output_prefix, state_xml_filename))
simulation.reporters.append( StateDataReporter(stdout, 1000, step=True, potentialEnergy=True, temperature=True)) if args.save_traj == 'True': simulation.reporters.append( mdtraj.reporters.HDF5Reporter(args.path + '/iter' + str(args.iter) + '_traj' + str(i) + '.h5', args.trajstride, atomSubset=prot_Select)) simulation.reporters.append( CheckpointReporter( args.path + '/iter' + str(args.iter) + '_traj' + str(i) + '.chk', args.trajstride)) steps = args.md_steps #1000=2sec each, 10000=20sec start = datetime.now() simulation.step(steps) end = datetime.now() elapsed = end - start time_el = elapsed.seconds + elapsed.microseconds * 1e-6 print('Integrated %d steps in %g seconds' % (steps, time_el)) print('%g ns/day' % (dt * steps * 86400 / time_el).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)
def reporter(self): from simtk.openmm.app import CheckpointReporter return CheckpointReporter(self.file, self.reportInterval)
step=True, time=True, potentialEnergy=True, kineticEnergy=True, temperature=True, speed=True, progress=True, remainingTime=True, totalSteps=production_steps, separator="\t", ) ) simulation.reporters.append( CheckpointReporter( file=str(output_directory / "checkpoint.chk"), reportInterval=production_checkpoint_frequency, ) ) simulation.reporters.append( md.reporters.XTCReporter( file=str(output_directory / "trajectory.xtc"), reportInterval=production_trajectory_frequency, ) ) print("Running production simulation ...") simulation.step(production_steps) if production_steps / production_trajectory_frequency >= 1:
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"))