def propagator(timestep=1.0 * unit.femtoseconds, n_steps=1000, platform='CUDA'): """Return a openmmtools mcmc move.""" cache.global_context_cache.platform = mm.Platform.getPlatformByName( platform) # ['Reference', 'CPU', 'CUDA', 'OpenCL'] # platforms return mcmc.LangevinDynamicsMove( timestep=timestep, collision_rate=5.0 / unit.picoseconds, n_steps=n_steps, # steps between multistate moves reassign_velocities=True, n_restart_attempts=6)
def main(): parser = argparse.ArgumentParser( description= 'Compute a potential of mean force (PMF) for porin permeation.') parser.add_argument('--index', dest='index', action='store', type=int, help='Index of ') parser.add_argument('--output', dest='output_filename', action='store', default='output.nc', help='output netcdf filename (default: output.nc)') args = parser.parse_args() index = args.index output_filename = args.output_filename logger = logging.getLogger(__name__) logging.root.setLevel(logging.DEBUG) logging.basicConfig(level=logging.DEBUG) yank.utils.config_root_logger(verbose=True, log_file_path=None) # Configure ContextCache, platform and precision from yank.experiment import ExperimentBuilder platform = ExperimentBuilder._configure_platform('CUDA', 'mixed') try: openmmtools.cache.global_context_cache.platform = platform except RuntimeError: # The cache has been already used. Empty it before switching platform. openmmtools.cache.global_context_cache.empty() openmmtools.cache.global_context_cache.platform = platform # Topology pdbx = app.PDBxFile('mem_prot_md_system.pdbx') # This system contains the CVforce with parameters different than zero with open('openmm_system.xml', 'r') as infile: openmm_system = XmlSerializer.deserialize(infile.read()) ####### Indexes of configurations in trajectory ############################ configs = [ 39, 141, 276, 406, 562, 668, 833, 1109, 1272, 1417, 1456, 1471, 1537, 1645, 1777, 1882 ] ####### Indexes of states for series of replica exchange simulations ####### limits = [(0, 9), (10, 19), (20, 29), (30, 39), (40, 49), (50, 59), (60, 69), (70, 79), (80, 89), (90, 99), (100, 109), (110, 119), (120, 129), (130, 139), (140, 149), (150, 159)] ####### Reading positions from mdtraj trajectory ########################### topology = md.Topology.from_openmm(pdbx.topology) t = md.load('../../steered_md/comp7/forward/seed_0/steered_forward.nc', top=topology) positions = t.openmm_positions(configs[index]) thermodynamic_state_deserialized = states.ThermodynamicState( system=openmm_system, temperature=310 * unit.kelvin, pressure=1.0 * unit.atmospheres) sampler_state = states.SamplerState( positions=positions, box_vectors=t.unitcell_vectors[configs[index], :, :] * unit.nanometer) logger.debug(type(sampler_state)) move = mcmc.LangevinDynamicsMove(timestep=2 * unit.femtosecond, collision_rate=1.0 / unit.picoseconds, n_steps=500, reassign_velocities=False) simulation = ReplicaExchangeSampler(mcmc_moves=move, number_of_iterations=1) analysis_particle_indices = topology.select( '(protein and mass > 3.0) or (resname MER and mass > 3.0)') reporter = MultiStateReporter( output_filename, checkpoint_interval=2000, analysis_particle_indices=analysis_particle_indices) first, last = limits[index] # Initialize compound thermodynamic states protocol = { 'lambda_restraints': [i / 159 for i in range(first, last + 1)], 'K_parallel': [ 1250 * unit.kilojoules_per_mole / unit.nanometer**2 for i in range(first, last + 1) ], 'Kmax': [ 500 * unit.kilojoules_per_mole / unit.nanometer**2 for i in range(first, last + 1) ], 'Kmin': [ 500 * unit.kilojoules_per_mole / unit.nanometer**2 for i in range(first, last + 1) ] } my_composable_state = MyComposableState.from_system(openmm_system) compound_states = states.create_thermodynamic_state_protocol( thermodynamic_state_deserialized, protocol=protocol, composable_states=[my_composable_state]) simulation.create(thermodynamic_states=compound_states, sampler_states=[sampler_state], storage=reporter) simulation.equilibrate(50, mcmc_moves=move) simulation.run() ts = simulation._thermodynamic_states[0] context, _ = openmmtools.cache.global_context_cache.get_context(ts) files_names = [ 'state_{}_{}.log'.format(index, i) for i in range(first, last + 1) ] files = [] for i, file in enumerate(files_names): files.append(open(file, 'w')) mpi.distribute(write_cv, range(simulation.n_replicas), context, simulation, files, send_results_to=None) for i in range(10000): simulation.extend(n_iterations=2) mpi.distribute(write_cv, range(simulation.n_replicas), context, simulation, files, send_results_to=None)
def run_hybrid_endpoint_overlap(topology_proposal, current_positions, new_positions): """ Test that the variance of the perturbation from lambda={0,1} to the corresponding nonalchemical endpoint is not too large. Parameters ---------- topology_proposal : perses.rjmc.TopologyProposal TopologyProposal object describing the transformation current_positions : np.array, unit-bearing Positions of the initial system new_positions : np.array, unit-bearing Positions of the new system Returns ------- hybrid_endpoint_results : list list of [df, ddf, N_eff] for 1 and 0 """ #create the hybrid system: #hybrid_factory = HybridTopologyFactory(topology_proposal, current_positions, new_positions, use_dispersion_correction=True) hybrid_factory = HybridTopologyFactory( topology_proposal, current_positions, new_positions, use_dispersion_correction=False) # DEBUG #get the relevant thermodynamic states: nonalchemical_zero_thermodynamic_state, nonalchemical_one_thermodynamic_state, lambda_zero_thermodynamic_state, lambda_one_thermodynamic_state = utils.generate_endpoint_thermodynamic_states( hybrid_factory.hybrid_system, topology_proposal) nonalchemical_thermodynamic_states = [ nonalchemical_zero_thermodynamic_state, nonalchemical_one_thermodynamic_state ] alchemical_thermodynamic_states = [ lambda_zero_thermodynamic_state, lambda_one_thermodynamic_state ] #create an MCMCMove, BAOAB with default parameters (but don't restart if we encounter a NaN) mc_move = mcmc.LangevinDynamicsMove(n_restart_attempts=0, n_steps=100) initial_sampler_state = SamplerState( hybrid_factory.hybrid_positions, box_vectors=hybrid_factory.hybrid_system.getDefaultPeriodicBoxVectors( )) hybrid_endpoint_results = [] all_results = [] for lambda_state in (0, 1): result, non, hybrid = run_endpoint_perturbation( alchemical_thermodynamic_states[lambda_state], nonalchemical_thermodynamic_states[lambda_state], initial_sampler_state, mc_move, 100, hybrid_factory, lambda_index=lambda_state) all_results.append(non) all_results.append(hybrid) print('lambda {} : {}'.format(lambda_state, result)) hybrid_endpoint_results.append(result) calculate_cross_variance(all_results) return hybrid_endpoint_results
def _setup(self): """ Set up calculation. """ # Signal that system has now been set up if self._setup_complete: raise Exception( "System has already been set up---cannot run again.") self._setup_complete = True # Compute thermal energy and inverse temperature self.kT = kB * self.temperature self.beta = 1.0 / self.kT # Create the system self.system = self._create_system() # Add a barostat # TODO: Is this necessary, sicne ThermodynamicState handles this automatically? It may not correctly handle MonteCarloAnisotropicBarostat. self._add_barostat() # Restrain protein atoms in space # TODO: Allow protein atom selection to be configured selection = '((residue 342 and resname GLY) or (residue 97 and resname ASP) or (residue 184 and resname SER)) and (name CA)' protein_atoms_to_restrain = self.mdtraj_topology.select(selection) #self._restrain_protein(protein_atoms_to_restrain) # Create SamplerState for initial conditions self.sampler_state = states.SamplerState( positions=self.grofile.positions, box_vectors=self.grofile.getPeriodicBoxVectors()) # Create reference thermodynamic state self.reference_thermodynamic_state = states.ThermodynamicState( system=self.system, temperature=self.temperature, pressure=self.pressure) # Anneal ligand into binding site if self.anneal_ligand: self._anneal_ligand() # Create ThermodynamicStates for umbrella sampling along pore self.thermodynamic_states = self._create_thermodynamic_states( self.reference_thermodynamic_state) # Minimize initial thermodynamic state # TODO: Select initial thermodynamic state based on which state has minimum energy initial_state_index = 0 self.sampler_state = self._minimize_sampler_state( self.thermodynamic_states[initial_state_index], self.sampler_state) # Set up simulation from yank.multistate import SAMSSampler, MultiStateReporter # TODO: Change this to LangevinSplittingDynamicsMove move = mcmc.LangevinDynamicsMove(timestep=self.timestep, collision_rate=self.collision_rate, n_steps=self.n_steps_per_iteration, reassign_velocities=False) self.simulation = SAMSSampler( mcmc_moves=move, number_of_iterations=self.n_iterations, online_analysis_interval=None, gamma0=self.gamma0, flatness_threshold=self.flatness_threshold) self.reporter = MultiStateReporter( self.output_filename, checkpoint_interval=self.checkpoint_interval, analysis_particle_indices=self.analysis_particle_indices) self.simulation.create( thermodynamic_states=self.thermodynamic_states, unsampled_thermodynamic_states=[ self.reference_thermodynamic_state ], sampler_states=[self.sampler_state], initial_thermodynamic_states=[initial_state_index], storage=self.reporter)
composable_state = MyComposableState.from_system(system) thermo_states = states.create_thermodynamic_state_protocol( system=system, protocol=protocol, constants=constants, composable_states=[composable_state]) # assign sampler_state sampler_state = states.SamplerState( positions=pdb.positions, box_vectors=system.getDefaultPeriodicBoxVectors()) # Set up the context for mtd simulation # at this step the CV and the system are separately passed to Metadynamics from yank.multistate import SAMSSampler, MultiStateReporter # TODO: You can use heavy hydrogens and 4 fs timesteps move = mcmc.LangevinDynamicsMove(timestep=2.0 * unit.femtoseconds, collision_rate=1.0 / unit.picosecond, n_steps=1000, reassign_velocities=False) print("Done specifying integrator for simulation.") simulation = SAMSSampler(mcmc_moves=move, number_of_iterations=iteration, online_analysis_interval=None, gamma0=1.0, flatness_threshold=0.2) storage_path = os.path.join(work_dir, 'traj.nc') reporter = MultiStateReporter(storage_path, checkpoint_interval=500) # We should also add unsampled_states with the fully-interacting system simulation.create(thermodynamic_states=thermo_states, sampler_states=[sampler_state], storage=reporter) print("Done specifying simulation.") simulation.run()
def _setup(self, topology, positions, box): """ Set up calculation. """ # Signal that system has now been set up if self._setup_complete: raise Exception( "System has already been set up---cannot run again.") self._setup_complete = True # Compute thermal energy and inverse temperature self.kT = kB * self.temperature self.beta = 1.0 / self.kT # Add a barostat # TODO: Is this necessary, since ThermodynamicState handles this automatically? It may not correctly handle MonteCarloAnisotropicBarostat. self._add_barostat() # Create SamplerState for initial conditions self.sampler_state = states.SamplerState(positions=positions, box_vectors=self.box) # Create reference thermodynamic state self.reference_thermodynamic_state = states.ThermodynamicState( system=self.system, temperature=self.temperature, pressure=self.pressure) # Anneal ligand into binding site if self.anneal_ligand: self._anneal_ligand() positions = self.sampler_state.positions structure = pmd.openmm.load_topology(topology, system=self.system, xyz=positions) # Create ThermodynamicStates for umbrella sampling along pore self.thermodynamic_states = self._auto_create_thermodynamic_states( structure, topology, self.reference_thermodynamic_state) # Minimize initial thermodynamic state # TODO: Select initial thermodynamic state based on which state has minimum energy initial_state_index = 0 #self.sampler_state = self._minimize_sampler_state(self.thermodynamic_states[initial_state_index], self.sampler_state) #pickle.dump(self.sampler_state, open('sampler_state.obj', 'wb')) #pickle.dump(self.reference_thermodynamic_state, open('reference_thermodynamic_state.obj', 'wb')) #pickle.dump(self.thermodynamic_states, open('thermodynamic_states.obj', 'wb')) #pickle.dump(self.system, open('system.obj', 'wb')) # Set up simulation from yank.multistate import SAMSSampler, MultiStateReporter # TODO: Change this to LangevinSplittingDynamicsMove move = mcmc.LangevinDynamicsMove(timestep=self.timestep, collision_rate=self.collision_rate, n_steps=self.n_steps_per_iteration, reassign_velocities=False) self.simulation = SAMSSampler( mcmc_moves=move, number_of_iterations=self.n_iterations, online_analysis_interval=None, gamma0=self.gamma0, flatness_threshold=self.flatness_threshold) self.reporter = MultiStateReporter( self.output_filename, checkpoint_interval=self.checkpoint_interval, analysis_particle_indices=self.analysis_particle_indices) self.simulation.create( thermodynamic_states=self.thermodynamic_states, unsampled_thermodynamic_states=[ self.reference_thermodynamic_state ], sampler_states=[self.sampler_state], initial_thermodynamic_states=[initial_state_index], storage=self.reporter)
import numpy as np from simtk import unit from openmmtools import mcmc from perses.dispersed.relative_setup import HybridTopologyFactory, HybridSAMSSampler import logging logging.basicConfig(level=logging.DEBUG) if __name__ == '__main__': mcl1tp = np.load( '/home/ballen/PycharmProjects/perses/examples/cdk2-example/cdk2_sams_hbonds/cdk2topology_proposals.npy' ).item() factory = HybridTopologyFactory(mcl1tp['complex_topology_proposal'], mcl1tp['complex_old_positions'], mcl1tp['complex_new_positions']) chss = HybridSAMSSampler(mcmc_moves=mcmc.LangevinDynamicsMove( timestep=2.0 * unit.femtosecond, collision_rate=5.0 / unit.picosecond, n_steps=1000, reassign_velocities=False, n_restart_attempts=6), hybrid_factory=factory) chss.setup( n_states=100, temperature=300.0 * unit.kelvin, storage_file='/media/ballen/overflow/perses/complex_test_100.nc', checkpoint_interval=1) chss.minimize() chss.equilibrate(10) chss.extend(10000) print("DONE FINALLY!!!")