def __init__(self): self.positions = testsystems.AlanineDipeptideVacuum().positions.value_in_unit(nanometer) self.topology = testsystems.AlanineDipeptideVacuum().topology self.system = testsystems.AlanineDipeptideVacuum().system self.Bins = [] #only used for sampling, storing it here saves memory when calling pmap self.temperature = 300 #Kelvin self.stepsize = 0.002*picoseconds
def test_alchemical_elimination_peptide(): """ Test alchemical elimination for the alanine dipeptide. """ # Create an alanine dipeptide null transformation, where N-methyl group is deleted and then inserted. from openmmtools import testsystems testsystem = testsystems.AlanineDipeptideVacuum() from perses.rjmc.topology_proposal import TopologyProposal new_to_old_atom_map = { index: index for index in range(testsystem.system.getNumParticles()) if (index > 3) } # all atoms but N-methyl topology_proposal = TopologyProposal( old_system=testsystem.system, old_topology=testsystem.topology, old_chemical_state_key='AA', new_chemical_state_key='AA', new_system=testsystem.system, new_topology=testsystem.topology, logp_proposal=0.0, new_to_old_atom_map=new_to_old_atom_map, metadata=dict()) for ncmc_nsteps in [0, 1, 50]: f = partial(check_alchemical_null_elimination, topology_proposal, testsystem.positions, ncmc_nsteps=ncmc_nsteps) f.description = "Testing alchemical elimination using alanine dipeptide with %d NCMC steps" % ncmc_nsteps yield f
def test_simulationRun(self): """Tests the Simulation.runNCMC() function""" self.opt = { 'temperature' : 300.0, 'friction' : 1, 'dt' : 0.002, 'nIter' : 2, 'nstepsNC' : 100, 'nstepsMD' : 2, 'nprop' : 1, 'nonbondedMethod' : 'NoCutoff', 'constraints': 'HBonds', 'trajectory_interval' : 1, 'reporter_interval' : 1, 'outfname' : 'blues-test', 'platform' : None, 'write_move' : False} testsystem = testsystems.AlanineDipeptideVacuum(constraints=None) structure = parmed.openmm.topsystem.load_topology(topology=testsystem.topology, system=testsystem.system, xyz=testsystem.positions, ) self.model = RandomLigandRotationMove(structure, resname='ALA') self.model.atom_indices = range(22) self.model.topology = structure.topology self.model.positions = structure.positions self.model.calculateProperties() self.mover = MoveEngine(self.model) #Initialize the SimulationFactory object sims = SimulationFactory(structure, self.mover, **self.opt) #print(sims) system = sims.generateSystem(structure, **self.opt) simdict = sims.createSimulationSet() alch_system = sims.generateAlchSystem(system, self.model.atom_indices) self.nc_sim = sims.generateSimFromStruct(structure, self.mover, alch_system, ncmc=True, **self.opt) self.model.calculateProperties() self.initial_positions = self.nc_sim.context.getState(getPositions=True).getPositions(asNumpy=True) asim = Simulation(sims, self.mover, **self.opt) asim.run(self.opt['nIter'])
def test_metropolized_moves(): """Test Displacement and Rotation moves.""" testsystem = testsystems.AlanineDipeptideVacuum() original_sampler_state = SamplerState(testsystem.positions) thermodynamic_state = ThermodynamicState(testsystem.system, 300*unit.kelvin) all_metropolized_moves = MetropolizedMove.__subclasses__() for move_class in all_metropolized_moves: move = move_class(atom_subset=range(thermodynamic_state.n_particles)) sampler_state = copy.deepcopy(original_sampler_state) # Start applying the move and remove one at each iteration tyring # to generate both an accepted and rejected move. old_n_accepted, old_n_proposed = 0, 0 while len(move.atom_subset) > 0: initial_positions = copy.deepcopy(sampler_state.positions) move.apply(thermodynamic_state, sampler_state) final_positions = copy.deepcopy(sampler_state.positions) # If the move was accepted the positions should be different. if move.n_accepted > old_n_accepted: assert not np.allclose(initial_positions, final_positions) # If we have generated a rejection and an acceptance, test next move. if move.n_accepted > 0 and move.n_accepted != move.n_proposed: break # Try with a smaller subset. move.atom_subset = move.atom_subset[:-1] old_n_accepted, old_n_proposed = move.n_accepted, move.n_proposed # Check that we were able to generate both an accepted and a rejected move. assert len(move.atom_subset) != 0, ('Could not generate an accepted and rejected ' 'move for class {}'.format(move_class.__name__))
def generate_atp(phase='vacuum'): """ modify the AlanineDipeptideVacuum test system to be parametrized with amber14ffsb in vac or solvent (tip3p) """ import openmmtools.testsystems as ts atp = ts.AlanineDipeptideVacuum(constraints=app.HBonds, hydrogenMass=4 * unit.amus) forcefield_files = [ 'gaff.xml', 'amber14/protein.ff14SB.xml', 'amber14/tip3p.xml' ] if phase == 'vacuum': barostat = None system_generator = SystemGenerator(forcefield_files, barostat=barostat, forcefield_kwargs={ 'removeCMMotion': False, 'ewaldErrorTolerance': 1e-4, 'nonbondedMethod': app.NoCutoff, 'constraints': app.HBonds, 'hydrogenMass': 4 * unit.amus }) atp.system = system_generator.build_system( atp.topology) #update the parametrization scheme to amberff14sb elif phase == 'solvent': barostat = openmm.MonteCarloBarostat(1.0 * unit.atmosphere, 300 * unit.kelvin, 50) system_generator = SystemGenerator(forcefield_files, barostat=barostat, forcefield_kwargs={ 'removeCMMotion': False, 'ewaldErrorTolerance': 1e-4, 'nonbondedMethod': app.PME, 'constraints': app.HBonds, 'hydrogenMass': 4 * unit.amus }) if phase == 'solvent': modeller = app.Modeller(atp.topology, atp.positions) modeller.addSolvent(system_generator._forcefield, model='tip3p', padding=9 * unit.angstroms, ionicStrength=0.15 * unit.molar) solvated_topology = modeller.getTopology() solvated_positions = modeller.getPositions() # canonicalize the solvated positions: turn tuples into np.array atp.positions = unit.quantity.Quantity(value=np.array([ list(atom_pos) for atom_pos in solvated_positions.value_in_unit_system(unit.md_unit_system) ]), unit=unit.nanometers) atp.topology = solvated_topology atp.system = system_generator.build_system(atp.topology) return atp, system_generator
def test_move_restart(): """Test optional restart move if NaN is detected.""" n_restart_attempts = 5 # We define a Move that counts the times it is attempted. class MyMove(BaseIntegratorMove): def __init__(self, **kwargs): super(MyMove, self).__init__(n_steps=1, n_restart_attempts=n_restart_attempts, **kwargs) self.attempted_count = 0 def _get_integrator(self, thermodynamic_state): return integrators.GHMCIntegrator(temperature=300 * unit.kelvin) def _before_integration(self, context, thermodynamic_state): self.attempted_count += 1 # Create a system with an extra NaN particle. testsystem = testsystems.AlanineDipeptideVacuum() system = testsystem.system for force in system.getForces(): if isinstance(force, openmm.NonbondedForce): break # Add a non-interacting particle to the system at NaN position. system.addParticle(39.9 * unit.amu) force.addParticle(0.0, 1.0, 0.0) particle_position = np.array([np.nan, 0.2, 0.2]) positions = unit.Quantity(np.vstack( (testsystem.positions, particle_position)), unit=testsystem.positions.unit) # Create and run move. An IntegratoMoveError is raised. sampler_state = SamplerState(positions) thermodynamic_state = ThermodynamicState(system, 300 * unit.kelvin) # We use a local context cache with Reference platform since on the # CPU platform CustomIntegrators raises an error with NaN particles. reference_platform = openmm.Platform.getPlatformByName('Reference') move = MyMove(context_cache=cache.ContextCache( platform=reference_platform)) with nose.tools.assert_raises(IntegratorMoveError) as cm: move.apply(thermodynamic_state, sampler_state) # We have counted the correct number of restart attempts. assert move.attempted_count == n_restart_attempts + 1 # Test serialization of the error. with utils.temporary_directory() as tmp_dir: prefix = os.path.join(tmp_dir, 'prefix') cm.exception.serialize_error(prefix) assert os.path.exists(prefix + '-move.json') assert os.path.exists(prefix + '-system.xml') assert os.path.exists(prefix + '-integrator.xml') assert os.path.exists(prefix + '-state.xml')
def test_alchemical_elimination_mutation(): """ Test alchemical elimination for mutations. """ ff_filename = "amber99sbildn.xml" proposal_metadata = {'ffxmls': [ff_filename]} # Create peptide. from openmmtools import testsystems testsystem = testsystems.AlanineDipeptideVacuum() [topology, system, positions ] = [testsystem.topology, testsystem.system, testsystem.positions] # Create forcefield. ff = app.ForceField(ff_filename) chain_id = ' ' allowed_mutations = [[('2', 'GLY')]] from perses.rjmc.topology_proposal import SystemGenerator system_generator = SystemGenerator([ff_filename]) # Create a topology proposal fro mutating ALA -> GLY from perses.rjmc.topology_proposal import PointMutationEngine proposal_engine = PointMutationEngine(topology, system_generator, chain_id, proposal_metadata=proposal_metadata, allowed_mutations=allowed_mutations) topology_proposal = proposal_engine.propose(system, topology) # Modify atom mapping to get a null transformation. from perses.rjmc.topology_proposal import TopologyProposal new_to_old_atom_map = { atom1: atom1 for atom1 in topology_proposal.new_to_old_atom_map } topology_proposal = TopologyProposal( new_topology=topology_proposal.old_topology, new_system=topology_proposal.old_system, old_topology=topology_proposal.old_topology, old_system=topology_proposal.old_system, old_chemical_state_key='AA', new_chemical_state_key='AG', logp_proposal=0.0, new_to_old_atom_map=new_to_old_atom_map, metadata=topology_proposal.metadata) for ncmc_nsteps in [0, 1, 2, 50]: f = partial(check_alchemical_null_elimination, topology_proposal, positions, ncmc_nsteps=ncmc_nsteps) f.description = "Testing alchemical null transformation of ALA sidechain in alanine dipeptide with %d NCMC steps" % ncmc_nsteps yield f
def test_langevin_splitting_move(): """Test that the langevin splitting mcmc move works with different splittings""" splittings = ["V R O R V", "V R R R O R R R V", "O { V R V } O"] testsystem = testsystems.AlanineDipeptideVacuum() sampler_state = SamplerState(testsystem.positions) thermodynamic_state = ThermodynamicState(testsystem.system, 300*unit.kelvin) for splitting in splittings: move = LangevinSplittingDynamicsMove(splitting=splitting) # Create MCMC sampler sampler = MCMCSampler(thermodynamic_state, sampler_state, move=move) sampler.run(1)
def test_minimize(self): """Test AlchemicalPhase minimization of positions in reference state.""" # Ligand-receptor in implicit solvent. test_system = testsystems.AlanineDipeptideVacuum() thermodynamic_state = states.ThermodynamicState(test_system.system, temperature=300 * unit.kelvin) topography = Topography(test_system.topology) # We create 3 different sampler states that will be distributed over # replicas in a round-robin fashion. displacement_vector = np.ones(3) * unit.nanometer positions2 = test_system.positions + displacement_vector positions3 = positions2 + displacement_vector box_vectors = test_system.system.getDefaultPeriodicBoxVectors() sampler_state1 = states.SamplerState(positions=test_system.positions, box_vectors=box_vectors) sampler_state2 = states.SamplerState(positions=positions2, box_vectors=box_vectors) sampler_state3 = states.SamplerState(positions=positions3, box_vectors=box_vectors) sampler_states = [sampler_state1, sampler_state2, sampler_state3] with self.temporary_storage_path() as storage_path: # Create alchemical phase. alchemical_phase = AlchemicalPhase(ReplicaExchangeSampler()) alchemical_phase.create(thermodynamic_state, sampler_states, topography, self.protocol, storage_path) # Measure the average distance between positions. This should be # maintained after minimization. sampler_states = alchemical_phase._sampler.sampler_states original_diffs = [ np.average(sampler_states[i].positions - sampler_states[i + 1].positions) for i in range(len(sampler_states) - 1) ] # Minimize. alchemical_phase.minimize() # The minimized positions should be still more or less # one displacement vector from each other. sampler_states = alchemical_phase._sampler.sampler_states new_diffs = [ np.average(sampler_states[i].positions - sampler_states[i + 1].positions) for i in range(len(sampler_states) - 1) ] assert np.allclose( original_diffs, new_diffs, rtol=0.1 ), "original_diffs {} are not close to new_diffs {}".format( original_diffs, new_diffs)
def setUp(self): # Obtain topologies/positions prmtop = testsystems.get_data_filename( "data/alanine-dipeptide-gbsa/alanine-dipeptide.prmtop") inpcrd = testsystems.get_data_filename( "data/alanine-dipeptide-gbsa/alanine-dipeptide.crd") testsystem = testsystems.AlanineDipeptideVacuum(constraints=None) structure = parmed.openmm.topsystem.load_topology( topology=testsystem.topology, system=testsystem.system, xyz=testsystem.positions) #Initialize the Model object basis_particles = [0, 2, 7] self.move = SmartDartMove(structure, basis_particles=basis_particles, coord_files=[inpcrd, inpcrd], topology=prmtop, resname='ALA', self_dart=True) self.move.atom_indices = range(22) self.move.topology = structure.topology self.move.positions = structure.positions self.move_engine = MoveEngine(self.move) self.system_cfg = { 'nonbondedMethod': app.NoCutoff, 'constraints': app.HBonds } self.systems = SystemFactory(structure, self.move.atom_indices, self.system_cfg) #Initialize the SimulationFactory object self.cfg = { 'dt': 0.002 * unit.picoseconds, 'friction': 1 * 1 / unit.picoseconds, 'temperature': 300 * unit.kelvin, 'nIter': 10, 'nstepsMD': 50, 'nstepsNC': 10, 'alchemical_functions': { 'lambda_sterics': 'step(0.199999-lambda) + step(lambda-0.2)*step(0.8-lambda)*abs(lambda-0.5)*1/0.3 + step(lambda-0.800001)', 'lambda_electrostatics': 'step(0.2-lambda)- 1/0.2*lambda*step(0.2-lambda) + 1/0.2*(lambda-0.8)*step(lambda-0.8)' } } sims = SimulationFactory(self.systems, self.move_engine, self.cfg) self.ncmc_sim = sims.ncmc self.move.calculateProperties() self.initial_positions = self.ncmc_sim.context.getState( getPositions=True).getPositions(asNumpy=True)
def setUp(self): testsystem = testsystems.AlanineDipeptideVacuum(constraints=None) self.structure = parmed.openmm.topsystem.load_topology( topology=testsystem.topology, system=testsystem.system, xyz=testsystem.positions) self.move = RandomLigandRotationMove(self.structure, 'ALA') self.engine = MoveEngine(self.move) system_cfg = { 'nonbondedMethod': app.NoCutoff, 'constraints': app.HBonds } self.systems = SystemFactory(self.structure, self.move.atom_indices, system_cfg)
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
def setUp(self): # Obtain topologies/positions prmtop = testsystems.get_data_filename("data/alanine-dipeptide-gbsa/alanine-dipeptide.prmtop") inpcrd = testsystems.get_data_filename("data/alanine-dipeptide-gbsa/alanine-dipeptide.crd") testsystem = testsystems.AlanineDipeptideVacuum(constraints=None) structure = parmed.openmm.topsystem.load_topology(topology=testsystem.topology, system=testsystem.system, xyz=testsystem.positions, ) #self.atom_indices = utils.atomIndexfromTop('LIG', structure.topology) self.functions = { 'lambda_sterics' : 'step(0.199999-lambda) + step(lambda-0.2)*step(0.8-lambda)*abs(lambda-0.5)*1/0.3 + step(lambda-0.800001)', 'lambda_electrostatics' : 'step(0.2-lambda)- 1/0.2*lambda*step(0.2-lambda) + 1/0.2*(lambda-0.8)*step(lambda-0.8)' } self.opt = { 'temperature' : 300.0, 'friction' : 1, 'dt' : 0.002, 'nIter' : 10, 'nstepsNC' : 10, 'nstepsMD' : 50, 'nonbondedMethod' : 'NoCutoff', 'nonbondedCutoff': 10, 'constraints': 'HBonds', 'trajectory_interval' : 10, 'reporter_interval' : 10, 'outfname' : 'smartdart-test', 'platform' : None, 'verbose' : False } #Initialize the Model object basis_particles = [0,2,7] self.move = SmartDartMove(structure, basis_particles=basis_particles, coord_files=[inpcrd, inpcrd], topology=prmtop, resname='ALA', self_dart=True) self.move.atom_indices = range(22) self.move.topology = structure.topology self.move.positions = structure.positions self.move_engine = MoveEngine(self.move) #Initialize the SimulationFactory object sims = SimulationFactory(structure, self.move_engine, **self.opt) system = sims.generateSystem(structure, **self.opt) alch_system = sims.generateAlchSystem(system, self.move.atom_indices) self.nc_sim = sims.generateSimFromStruct(structure, self.move_engine, alch_system, ncmc=True, **self.opt) self.move.calculateProperties() self.initial_positions = self.nc_sim.context.getState(getPositions=True).getPositions(asNumpy=True)
} test_systems['TIP3P with reaction field, switch, dispersion correction'] = { 'test': testsystems.WaterBox(dispersion_correction=True, switch=True, nonbondedMethod=app.CutoffPeriodic), 'ligand_atoms': range(0, 3), 'receptor_atoms': range(3, 6) } #test_systems['TIP3P with PME, no switch, no dispersion correction'] = { # 'test' : testsystems.WaterBox(dispersion_correction=False, switch=False, nonbondedMethod=app.PME), # 'ligand_atoms' : range(0,3), 'receptor_atoms' : range(3,6) } test_systems['alanine dipeptide in vacuum'] = { 'test': testsystems.AlanineDipeptideVacuum(), 'ligand_atoms': range(0, 22), 'receptor_atoms': range(22, 22) } test_systems['alanine dipeptide in OBC GBSA'] = { 'test': testsystems.AlanineDipeptideImplicit(), 'ligand_atoms': range(0, 22), 'receptor_atoms': range(22, 22) } test_systems['alanine dipeptide in TIP3P with reaction field'] = { 'test': testsystems.AlanineDipeptideExplicit(nonbondedMethod=app.CutoffPeriodic), 'ligand_atoms': range(0, 22), 'receptor_atoms': range(22, 22)
def test_minimize(self): """Test AlchemicalPhase minimization of positions in reference state.""" # Ligand-receptor in implicit solvent. test_system = testsystems.AlanineDipeptideVacuum() thermodynamic_state = states.ThermodynamicState(test_system.system, temperature=300*unit.kelvin)
def RemoveTorsionForce(self, phi, psi): self.system = testsystems.AlanineDipeptideVacuum().system