def test_sidechain_move(self): simulations = SimulationFactory(self.struct, self.mover, **self.opt) simulations.createSimulationSet() nc_context = simulations.nc.context self.sidechain.move(nc_context, verbose=False)
def setUp(self): # Obtain topologies/positions prmtop = utils.get_data_filename('blues', 'tests/data/TOL-parm.prmtop') inpcrd = utils.get_data_filename('blues', 'tests/data/TOL-parm.inpcrd') structure = parmed.load_file(prmtop, xyz=inpcrd) 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' : 'PME', 'nonbondedCutoff': 10, 'constraints': 'HBonds', 'trajectory_interval' : 10, 'reporter_interval' : 10, 'platform' : None, 'outfname' : 'smartdart-test', 'verbose' : False } #Initialize the SmartDartMove object self.move = SmartDartMove(structure, basis_particles=[100, 110, 150], coord_files = [inpcrd, inpcrd], topology=prmtop, self_dart=False, resname='LIG', ) self.engine = MoveEngine(self.move) self.engine.selectMove() #Initialize the SimulationFactory object sims = SimulationFactory(structure, self.engine, **self.opt) system = sims.generateSystem(structure, **self.opt) alch_system = sims.generateAlchSystem(system, self.atom_indices) self.nc_sim = sims.generateSimFromStruct(structure, self.engine, alch_system, ncmc=True, **self.opt) self.initial_positions = self.nc_sim.context.getState(getPositions=True).getPositions(asNumpy=True)
def test_generateSimFromStruct(self): print('Generating Simulation from parmed.Structure') integrator = openmm.LangevinIntegrator(100 * unit.kelvin, 1, 0.002 * unit.picoseconds) simulation = SimulationFactory.generateSimFromStruct( self.structure, self.system, integrator) #Check that we've made a Simulation object self.assertIsInstance(simulation, app.Simulation) state = simulation.context.getState(getPositions=True) positions = state.getPositions(asNumpy=True) / unit.nanometers box_vectors = state.getPeriodicBoxVectors( asNumpy=True) / unit.nanometers struct_box = np.array( self.structure.box_vectors.value_in_unit(unit.nanometers)) struct_pos = np.array( self.structure.positions.value_in_unit(unit.nanometers)) #Check that the box_vectors/positions in the Simulation # have been set from the parmed.Structure np.testing.assert_array_almost_equal(positions, struct_pos) np.testing.assert_array_equal(box_vectors, struct_box) print('Attaching Reporter') reporters = [app.StateDataReporter('test.log', 5)] self.assertEqual(len(simulation.reporters), 0) simulation = SimulationFactory.attachReporters(simulation, reporters) self.assertEqual(len(simulation.reporters), 1) os.remove('test.log')
def runNCMC(platform_name, nstepsNC, nprop, outfname): #Generate the ParmEd Structure prmtop = '../../complex_wat.prmtop' inpcrd = '../../ligand1.equi.rst' struct = parmed.load_file(prmtop, xyz=inpcrd) print('Structure: %s' % struct.topology) nstepsNC = 1000 #Define some options opt = { 'temperature' : 300.0, 'friction' : 1, 'dt' : 0.002, 'nIter' : 5000, 'nstepsNC' : nstepsNC, 'nstepsMD' : 1000, 'nprop' : nprop, 'nonbondedMethod' : 'PME', 'nonbondedCutoff': 10, 'constraints': 'HBonds', 'freeze_distance' : 5.0, 'trajectory_interval' : 1000, 'reporter_interval' : 1000, 'ncmc_traj' : False, 'write_move' : False, 'platform' : platform_name, 'outfname' : 'gmx', 'NPT' : False, 'verbose' : False} #Define the 'model' object we are perturbing here. # Calculate particle masses of object to be moved resname = "LIG" dihedral_atoms = ["C10", "C9", "C3", "C2" ] alch_list = ['C9', 'H92', 'H93', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'H1', 'H2', 'H4', 'H5', 'H6'] ligand = RotatableBondNoMove(struct, prmtop, inpcrd, dihedral_atoms, alch_list, resname) # Initialize object that proposes moves. ligand_mover = MoveEngine(ligand) # Generate the MD, NCMC, ALCHEMICAL Simulation objects simulations = SimulationFactory(struct, ligand_mover, **opt) simulations.createSimulationSet() # Add reporters to MD simulation. #traj_reporter = openmm.app.DCDReporter(outfname+'-nc{}.dcd'.format(nstepsNC), opt['trajectory_interval']) progress_reporter = openmm.app.StateDataReporter(sys.stdout, separator="\t", reportInterval=opt['reporter_interval'], step=True, totalSteps=opt['nIter']*opt['nstepsMD'], time=True, speed=True, progress=True, remainingTime=True) #simulations.md.reporters.append(traj_reporter) simulations.md.reporters.append(progress_reporter) netcdf_reporter = NetCDFReporter('gmx.nc', 500, crds=True) simulations.md.reporters.append(netcdf_reporter) # Run BLUES Simulation blues = Simulation(simulations, ligand_mover, **opt) blues.run(opt['nIter']) # saving last restart restrt = RestartReporter('blues.rst', 1, struct.ptr('natom') ); state = simulations.md.context.getState(getPositions=True, getEnergy=True, getVelocities=True, enforcePeriodicBox=True) restrt.report(simulations.md, state)
def test_generateSimulationSet(self, structure, systems, engine, sim_cfg): print('Testing generateSimulationSet') simulations = SimulationFactory(systems, engine) simulations.generateSimulationSet(sim_cfg) #Check that we've made the MD/ALCH/NCMC simulation set assert hasattr(simulations, 'md') assert hasattr(simulations, 'alch') assert hasattr(simulations, 'ncmc') #Check that the physical parameters are equivalent assert simulations.ncmc_integrator.getStepSize() == sim_cfg['dt'] assert simulations.integrator.getStepSize() == sim_cfg['dt'] assert round(abs(simulations.ncmc_integrator.getTemperature()._value - sim_cfg['temperature']._value), 7) == 0 assert round(abs(simulations.integrator.getTemperature()._value - sim_cfg['temperature']._value), 7) == 0
def test_initSimulationFactory(self): print('Testing initialization of SimulationFactory') cfg = { 'nprop': 1, 'prop_lambda': 0.3, 'dt': 0.001 * unit.picoseconds, 'friction': 1 * 1 / unit.picoseconds, 'temperature': 100 * unit.kelvin, 'nIter': 1, 'nstepsMD': 10, 'nstepsNC': 10, } simulations = SimulationFactory(self.systems, self.engine, cfg) #Check that we've made the MD/ALCH/NCMC simulation set self.assertTrue(hasattr(simulations, 'md')) self.assertTrue(hasattr(simulations, 'alch')) self.assertTrue(hasattr(simulations, 'ncmc')) #Check that the physical parameters are equivalent self.assertEqual(simulations.ncmc_integrator.getStepSize(), cfg['dt']) self.assertEqual(simulations.integrator.getStepSize(), cfg['dt']) self.assertAlmostEqual( simulations.ncmc_integrator.getTemperature()._value, cfg['temperature']._value) self.assertAlmostEqual(simulations.integrator.getTemperature()._value, cfg['temperature']._value)
def test_generateNCMCIntegrator(self): print('Testing AlchemicalExternalLangevinIntegrator') cfg = { 'nstepsNC': 100, 'temperature': 100 * unit.kelvin, 'dt': 0.001 * unit.picoseconds, 'nprop': 2, 'propLambda': 0.1, 'splitting': 'V H R O R H V', 'alchemical_functions': { 'lambda_sterics': '1', 'lambda_electrostatics': '1' } } ncmc_integrator = SimulationFactory.generateNCMCIntegrator(**cfg) #Check we made the right integrator assert isinstance(ncmc_integrator, AlchemicalExternalLangevinIntegrator) #Check that the integrator has taken our Parameters assert round(abs(ncmc_integrator.getTemperature()._value - cfg['temperature']._value), 7) == 0 assert ncmc_integrator.getStepSize() == cfg['dt'] assert ncmc_integrator._n_steps_neq == cfg['nstepsNC'] assert ncmc_integrator._n_lambda_steps == \ cfg['nstepsNC'] * cfg['nprop'] assert ncmc_integrator._alchemical_functions == \ cfg['alchemical_functions'] assert ncmc_integrator._splitting == cfg['splitting'] prop_range = (0.5 - cfg['propLambda'], 0.5 + cfg['propLambda']) assert ncmc_integrator._prop_lambda == prop_range
def test_generateNCMCIntegrator(self): print('Testing AlchemicalExternalLangevinIntegrator') cfg = { 'nstepsNC': 100, 'temperature': 100 * unit.kelvin, 'dt': 0.001 * unit.picoseconds, 'nprop': 2, 'propLambda': 0.1, 'splitting': 'V H R O R H V', 'alchemical_functions': { 'lambda_sterics': '1', 'lambda_electrostatics': '1' } } ncmc_integrator = SimulationFactory.generateNCMCIntegrator(**cfg) #Check we made the right integrator self.assertIsInstance(ncmc_integrator, AlchemicalExternalLangevinIntegrator) #Check that the integrator has taken our Parameters self.assertAlmostEqual(ncmc_integrator.getTemperature()._value, cfg['temperature']._value) self.assertEqual(ncmc_integrator.getStepSize(), cfg['dt']) self.assertEqual(ncmc_integrator._n_steps_neq, cfg['nstepsNC']) self.assertEqual(ncmc_integrator._n_lambda_steps, cfg['nstepsNC'] * cfg['nprop']) self.assertEqual(ncmc_integrator._alchemical_functions, cfg['alchemical_functions']) self.assertEqual(ncmc_integrator._splitting, cfg['splitting']) prop_range = (0.5 - cfg['propLambda'], 0.5 + cfg['propLambda']) self.assertEqual(ncmc_integrator._prop_lambda, prop_range)
def test_generateSimulationSet(self, structure, systems, engine, sim_cfg): print('Testing generateSimulationSet') simulations = SimulationFactory(systems, engine) simulations.generateSimulationSet(sim_cfg) #Check that we've made the MD/ALCH/NCMC simulation set assert hasattr(simulations, 'md') assert hasattr(simulations, 'alch') assert hasattr(simulations, 'ncmc') #Check that the physical parameters are equivalent assert simulations.ncmc_integrator.getStepSize() == sim_cfg['dt'] assert simulations.integrator.getStepSize() == sim_cfg['dt'] assert round( abs(simulations.ncmc_integrator.getTemperature()._value - sim_cfg['temperature']._value), 7) == 0 assert round( abs(simulations.integrator.getTemperature()._value - sim_cfg['temperature']._value), 7) == 0
def runNCMC(platform_name, relaxstepsNC, themdsteps): #Define some options opt = { 'temperature': 300.0, 'friction': 1, 'dt': 0.002, 'nIter': 50000, 'nstepsNC': relaxstepsNC, 'nstepsMD': themdsteps, 'nonbondedMethod': 'PME', 'nonbondedCutoff': 10, 'constraints': 'HBonds', 'trajectory_interval': 1000, 'reporter_interval': 1000, 'platform': platform_name, 'verbose': False, 'write_ncmc': False } #Generate the ParmEd Structure #prmtop = utils.get_data_filename('blues', 'tests/data/eqToluene.prmtop')# #inpcrd = utils.get_data_filename('blues', 'tests/data/eqToluene.inpcrd') prmtop = '/home/burleyk/projects/sidechain/inputs/watDivaline.prmtop' inpcrd = '/home/burleyk/projects/sidechain/inputs/watDivaline.inpcrd' struct = parmed.load_file(prmtop, xyz=inpcrd) #Define the 'model' object we are perturbing here. # Calculate particle masses of object to be moved ligand = SideChainMove(struct, [1]) ligand.atom_indices = ligand.rot_bond_atoms # Initialize object that proposes moves. ligand_mover = MoveEngine(ligand) # Generate the MD, NCMC, ALCHEMICAL Simulation objects simulations = SimulationFactory(struct, ligand_mover, **opt) simulations.createSimulationSet() blues = Simulation(simulations, ligand_mover, **opt) #add the reporter here blues.md_sim.reporters.append( openmm.app.dcdreporter.DCDReporter('accept.dcd', 1000)) blues.runNCMC()
def test_blues_simulationRunPure(self): print('Testing BLUESSimulation.run() from pure python') md_rep_cfg = { 'stream': { 'title': 'md', 'reportInterval': 1, 'totalSteps': 4, 'step': True, 'speed': True, 'progress': True, 'remainingTime': True, 'currentIter': True } } ncmc_rep_cfg = { 'stream': { 'title': 'ncmc', 'reportInterval': 1, 'totalSteps': 4, 'step': True, 'speed': True, 'progress': True, 'remainingTime': True, 'currentIter': True } } md_reporters = ReporterConfig('ala-dipep-vac', md_rep_cfg).makeReporters() ncmc_reporters = ReporterConfig('ala-dipep-vac-ncmc', ncmc_rep_cfg).makeReporters() cfg = { 'nprop': 1, 'prop_lambda': 0.3, 'dt': 0.001 * unit.picoseconds, 'friction': 1 * 1 / unit.picoseconds, 'temperature': 100 * unit.kelvin, 'nIter': 1, 'nstepsMD': 4, 'nstepsNC': 4, } simulations = SimulationFactory(self.systems, self.engine, cfg, md_reporters=md_reporters, ncmc_reporters=ncmc_reporters) blues = BLUESSimulation(simulations) before_iter = blues._md_sim.context.getState( getPositions=True).getPositions(asNumpy=True) blues.run() after_iter = blues._md_sim.context.getState( getPositions=True).getPositions(asNumpy=True) #Check that our system has run dynamics pos_compare = np.not_equal(before_iter, after_iter).all() self.assertTrue(pos_compare)
def test_generateIntegrator(self): print('Testing LangevinIntegrator') cfg = {'temperature': 500 * unit.kelvin, 'dt': 0.004 * unit.picoseconds} integrator = SimulationFactory.generateIntegrator(**cfg) #Check we made the right integrator assert isinstance(integrator, openmm.LangevinIntegrator) #Check that the integrator has taken our Parameters assert integrator.getTemperature() == cfg['temperature'] assert integrator.getStepSize() == cfg['dt']
def test_addBarostat(self): print('Testing MonteCarloBarostat') forces = self.system.getForces() npt_system = SimulationFactory.addBarostat(self.system) npt_forces = npt_system.getForces() #Check that forces have been added to the system. self.assertNotEqual(len(forces), len(npt_forces)) #Check that it has added the MonteCarloBarostat self.assertIsInstance(npt_forces[-1], openmm.MonteCarloBarostat)
def test_addBarostat(self, system): print('Testing MonteCarloBarostat') forces = system.getForces() npt_system = SimulationFactory.addBarostat(system) npt_forces = npt_system.getForces() #Check that forces have been added to the system. assert len(forces) != len(npt_forces) #Check that it has added the MonteCarloBarostat assert isinstance(npt_forces[-1], openmm.MonteCarloBarostat)
def test_addBarostat(self, system): print('Testing MonteCarloBarostat') forces = system.getForces() npt_system = SimulationFactory.addBarostat(system) npt_forces = npt_system.getForces() #Check that forces have been added to the system. assert len(forces) != len(npt_forces) #Check that it has added the MonteCarloBarostat assert isinstance(npt_forces[-1], openmm.MonteCarloBarostat)
def test_generateIntegrator(self): print('Testing LangevinIntegrator') cfg = { 'temperature': 500 * unit.kelvin, 'dt': 0.004 * unit.picoseconds } integrator = SimulationFactory.generateIntegrator(**cfg) #Check we made the right integrator self.assertIsInstance(integrator, openmm.LangevinIntegrator) #Check that the integrator has taken our Parameters self.assertEqual(integrator.getTemperature(), cfg['temperature']) self.assertEqual(integrator.getStepSize(), cfg['dt'])
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 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): # 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)
def test_blues_simulationRunPython(self, systems, simulations, engine, tmpdir, sim_cfg): print('Testing BLUESSimulation.run() from pure python') md_rep_cfg = { 'stream': { 'title': 'md', 'reportInterval': 1, 'totalSteps': 2, 'step': True, 'speed': True, 'progress': True, 'remainingTime': True, 'currentIter': True } } ncmc_rep_cfg = { 'stream': { 'title': 'ncmc', 'reportInterval': 1, 'totalSteps': 2, 'step': True, 'speed': True, 'progress': True, 'remainingTime': True, 'currentIter': True } } md_reporters = ReporterConfig(tmpdir.join('tol-test'), md_rep_cfg).makeReporters() ncmc_reporters = ReporterConfig(tmpdir.join('tol-test-ncmc'), ncmc_rep_cfg).makeReporters() simulations = SimulationFactory(systems, engine, sim_cfg, md_reporters=md_reporters, ncmc_reporters=ncmc_reporters) blues = BLUESSimulation(simulations) blues._md_sim.minimizeEnergy() blues._alch_sim.minimizeEnergy() blues._ncmc_sim.minimizeEnergy() before_iter = blues._md_sim.context.getState( getPositions=True).getPositions(asNumpy=True) blues.run() after_iter = blues._md_sim.context.getState( getPositions=True).getPositions(asNumpy=True) #Check that our system has run dynamics pos_compare = np.not_equal(before_iter, after_iter).all() assert pos_compare
def test_generateSimFromStruct(self, structure, system, tmpdir): print('Generating Simulation from parmed.Structure') integrator = openmm.LangevinIntegrator(100 * unit.kelvin, 1, 0.002 * unit.picoseconds) simulation = SimulationFactory.generateSimFromStruct(structure, system, integrator) #Check that we've made a Simulation object assert isinstance(simulation, app.Simulation) state = simulation.context.getState(getPositions=True) positions = state.getPositions(asNumpy=True) / unit.nanometers box_vectors = state.getPeriodicBoxVectors(asNumpy=True) / unit.nanometers struct_box = np.array(structure.box_vectors.value_in_unit(unit.nanometers)) struct_pos = np.array(structure.positions.value_in_unit(unit.nanometers)) #Check that the box_vectors/positions in the Simulation # have been set from the parmed.Structure np.testing.assert_array_almost_equal(positions, struct_pos) np.testing.assert_array_equal(box_vectors, struct_box) print('Attaching Reporter') reporters = [app.StateDataReporter(tmpdir.join('test.log'), 5)] assert len(simulation.reporters) == 0 simulation = SimulationFactory.attachReporters(simulation, reporters) assert len(simulation.reporters) == 1
def ncmc_integrator(structure, system): cfg = { 'nstepsNC': 10, 'temperature': 100 * unit.kelvin, 'dt': 0.001 * unit.picoseconds, 'nprop': 1, 'propLambda': 0.3, 'splitting': 'V H R O R H V', 'alchemical_functions': { 'lambda_sterics': '1', 'lambda_electrostatics': '1' } } ncmc_integrator = SimulationFactory.generateNCMCIntegrator(**cfg) return ncmc_integrator
def ncmc_integrator(structure, system): cfg = { 'nstepsNC': 10, 'temperature': 100 * unit.kelvin, 'dt': 0.001 * unit.picoseconds, 'nprop': 1, 'propLambda': 0.3, 'splitting': 'V H R O R H V', 'alchemical_functions': { 'lambda_sterics': '1', 'lambda_electrostatics': '1' } } ncmc_integrator = SimulationFactory.generateNCMCIntegrator(**cfg) return ncmc_integrator
def setUp(self): # Obtain topologies/positions prmtop = utils.get_data_filename('blues', 'tests/data/TOL-parm.prmtop') inpcrd = utils.get_data_filename('blues', 'tests/data/TOL-parm.inpcrd') structure = parmed.load_file(prmtop, xyz=inpcrd) self.atom_indices = utils.atomIndexfromTop('LIG', structure.topology) #Initialize the SmartDartMove object self.move = SmartDartMove( structure, basis_particles=[100, 110, 150], coord_files=[inpcrd, inpcrd], topology=prmtop, self_dart=False, resname='LIG', ) self.engine = MoveEngine(self.move) self.engine.selectMove() self.system_cfg = { 'nonbondedMethod': app.NoCutoff, 'constraints': app.HBonds } 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(systems, self.engine, self.cfg) self.ncmc_sim = sims.ncmc self.initial_positions = self.ncmc_sim.context.getState( getPositions=True).getPositions(asNumpy=True)
def setUp(self): # Obtain topologies/positions prmtop = utils.get_data_filename('blues', 'tests/data/eqToluene.prmtop') inpcrd = utils.get_data_filename('blues', 'tests/data/eqToluene.pdb') structure = parmed.load_file(prmtop, xyz=inpcrd) #Initialize the Move object self.move = WaterTranslationMove( structure, protein_selection='(index 1656) or (index 1657)', radius=0.9 * unit.nanometer) self.atom_indices = self.move.atom_indices self.engine = MoveEngine(self.move) self.engine.selectMove() self.system_cfg = { 'nonbondedMethod': app.NoCutoff, 'constraints': app.HBonds } 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, 'nprop': 1, 'nIter': 1, 'nstepsMD': 1, 'nstepsNC': 100, '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)' } } self.simulations = SimulationFactory(systems, self.engine, self.cfg) self.ncmc_sim = self.simulations.ncmc self.initial_positions = self.ncmc_sim.context.getState( getPositions=True).getPositions(asNumpy=True)
def test_simulationfactory(self): #Initialize the SimulationFactory object move = RandomLigandRotationMove(self.full_struct, 'LIG') engine = MoveEngine(move) sims = SimulationFactory(self.full_struct, engine, **self.opt) system = sims.generateSystem(self.full_struct, **self.opt) self.assertIsInstance(system, openmm.System) alch_system = sims.generateAlchSystem(system, move.atom_indices) self.assertIsInstance(alch_system, openmm.System) md_sim = sims.generateSimFromStruct(self.full_struct, engine, system, **self.opt) self.assertIsInstance(md_sim, openmm.app.simulation.Simulation) nc_sim = sims.generateSimFromStruct(self.full_struct, engine, alch_system, ncmc=True, **self.opt) self.assertIsInstance(nc_sim, openmm.app.simulation.Simulation)
def setUp(self): # Load the waterbox with toluene into a structure. self.prmtop = utils.get_data_filename('blues', 'tests/data/TOL-parm.prmtop') self.inpcrd = utils.get_data_filename('blues', 'tests/data/TOL-parm.inpcrd') self.structure = parmed.load_file(self.prmtop, xyz=self.inpcrd) self.atom_indices = utils.atomIndexfromTop('LIG', self.structure.topology) system_cfg = { 'nonbondedMethod': app.PME, 'nonbondedCutoff': 8.0 * unit.angstroms, 'constraints': app.HBonds } self.systems = SystemFactory(self.structure, self.atom_indices, system_cfg) move = RandomLigandRotationMove(self.structure, 'LIG') self.engine = MoveEngine(move) self.simulations = SimulationFactory(self.systems, self.engine) self.system = self.simulations._system
def setUp(self): # Obtain topologies/positions prmtop = utils.get_data_filename('blues', 'tests/data/vacDivaline.prmtop') inpcrd = utils.get_data_filename('blues', 'tests/data/vacDivaline.inpcrd') self.struct = parmed.load_file(prmtop, xyz=inpcrd) self.sidechain = SideChainMove(self.struct, [1]) self.engine = MoveEngine(self.sidechain) self.engine.selectMove() self.system_cfg = { 'nonbondedMethod': app.NoCutoff, 'constraints': app.HBonds } self.systems = SystemFactory(self.struct, self.sidechain.atom_indices, self.system_cfg) self.cfg = { 'dt': 0.002 * unit.picoseconds, 'friction': 1 * 1 / unit.picoseconds, 'temperature': 300 * unit.kelvin, 'nIter': 1, 'nstepsMD': 1, 'nstepsNC': 4, '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)' } } self.simulations = SimulationFactory(self.systems, self.engine, self.cfg)
def simulations(systems, engine, sim_cfg): simulations = SimulationFactory(systems, engine, sim_cfg) return simulations
def test_blues_simulationRunYAML(self): yaml_cfg = """ output_dir: . outfname: ala-dipep-vac logger: level: info stream: True system: nonbonded: NoCutoff constraints: HBonds simulation: dt: 0.002 * picoseconds friction: 1 * 1/picoseconds temperature: 400 * kelvin nIter: 1 nstepsMD: 4 nstepsNC: 4 md_reporters: stream: title: md reportInterval: 1 totalSteps: 4 # nIter * nstepsMD step: True speed: True progress: True remainingTime: True currentIter : True ncmc_reporters: stream: title: ncmc reportInterval: 1 totalSteps: 4 # Use nstepsNC step: True speed: True progress: True remainingTime: True protocolWork : True alchemicalLambda : True currentIter : True """ print('Testing Simulation.run() from YAML') yaml_cfg = Settings(yaml_cfg) cfg = yaml_cfg.asDict() simulations = SimulationFactory(self.systems, self.engine, cfg['simulation'], cfg['md_reporters'], cfg['ncmc_reporters']) blues = BLUESSimulation(simulations) before_iter = blues._md_sim.context.getState( getPositions=True).getPositions(asNumpy=True) blues.run() after_iter = blues._md_sim.context.getState( getPositions=True).getPositions(asNumpy=True) #Check that our system has run dynamics pos_compare = np.not_equal(before_iter, after_iter).all() self.assertTrue(pos_compare) os.remove('ala-dipep-vac.log')
def md_sim(structure, system): integrator = openmm.LangevinIntegrator(100 * unit.kelvin, 1, 0.002 * unit.picoseconds) md_sim = SimulationFactory.generateSimFromStruct(structure, system, integrator) return md_sim
def runNCMC(platform_name, nstepsNC, nprop, outfname): #Generate the ParmEd Structure prmtop = utils.get_data_filename('blues', 'tests/data/vacDivaline.prmtop') inpcrd = utils.get_data_filename('blues', 'tests/data/vacDivaline.inpcrd') struct = parmed.load_file(prmtop, xyz=inpcrd) print('Structure: %s' % struct.topology) #Define some options opt = { 'temperature': 300.0, 'friction': 1, 'dt': 0.004, 'hydrogenMass': 3.024, 'nIter': 100, 'nstepsNC': nstepsNC, 'nstepsMD': 1000, 'nprop': nprop, 'nonbondedMethod': 'PME', 'nonbondedCutoff': 10, 'constraints': 'HBonds', 'trajectory_interval': 100, 'reporter_interval': 250, 'ncmc_traj': None, 'write_move': False, 'platform': platform_name, 'outfname': 'vacDivaline', 'verbose': False } #Define the 'model' object we are perturbing here. # Calculate particle masses of object to be moved ligand = SideChainMove(struct, [1]) # Initialize object that proposes moves. ligand_mover = MoveEngine(ligand) # Generate the MD, NCMC, ALCHEMICAL Simulation objects simulations = SimulationFactory(struct, ligand_mover, **opt) simulations.createSimulationSet() # Add reporters to MD simulation. trajfile = outfname + '-nc{}.dcd'.format(nstepsNC) traj_reporter = openmm.app.DCDReporter(trajfile, opt['trajectory_interval']) progress_reporter = openmm.app.StateDataReporter( sys.stdout, separator="\t", reportInterval=opt['reporter_interval'], step=True, totalSteps=opt['nIter'] * opt['nstepsMD'], time=True, speed=True, progress=True, elapsedTime=True, remainingTime=True) simulations.md.reporters.append(traj_reporter) simulations.md.reporters.append(progress_reporter) # Run BLUES Simulation blues = Simulation(simulations, ligand_mover, **opt) blues.run(opt['nIter']) #Analysis import mdtraj as md import numpy as np traj = md.load_dcd(trajfile, top='protein.pdb') indicies = np.array([[0, 4, 6, 8]]) dihedraldata = md.compute_dihedrals(traj, indicies) with open("dihedrals-%iNC.txt" % (nstepsNC), 'w') as output: for value in dihedraldata: output.write("%s\n" % str(value)[1:-1])
def test_simulationRun(self): """Tests the Simulation.runMC() function""" self.opt = { 'temperature': 300.0, 'friction': 1, 'dt': 0.00002, 'nIter': 2, 'nstepsNC': 2, 'nstepsMD': 1, 'nprop': 1, 'nonbondedMethod': 'NoCutoff', 'constraints': 'HBonds', 'trajectory_interval': 1, 'reporter_interval': 1, 'outfname': 'mc-test', 'platform': None, 'constraints': 'HBonds', 'mc_per_iter': 2 } structure = self.full_struct class SetRotationMove(RandomLigandRotationMove): def __init__(self, structure, resname='LIG'): super(SetRotationMove, self).__init__(structure, resname) def move(self, context): """Function that performs a random rotation about the center of mass of the ligand. """ #TODO: check if we need to deepcopy positions = context.getState(getPositions=True).getPositions( asNumpy=True) self.positions = positions[self.atom_indices] self.center_of_mass = self.getCenterOfMass( self.positions, self.masses) reduced_pos = self.positions - self.center_of_mass # Define random rotational move on the ligand #set rotation so that test is reproducible set_rotation_matrix = np.array( [[-0.62297988, -0.17349253, 0.7627558], [0.55082352, -0.78964857, 0.27027502], [0.55541834, 0.58851973, 0.58749893]]) #set_rotation_matrix = np.array([[1, 0, 0], # [0, 1, 0], # [0, 0, 1]]) #multiply lig coordinates by rot matrix and add back COM translation from origin rot_move = np.dot(reduced_pos, set_rotation_matrix ) * positions.unit + self.center_of_mass # Update ligand positions in nc_sim for index, atomidx in enumerate(self.atom_indices): positions[atomidx] = rot_move[index] context.setPositions(positions) positions = context.getState(getPositions=True).getPositions( asNumpy=True) self.positions = positions[self.atom_indices] return context self.model = SetRotationMove(structure, resname='ALA') #self.model = RandomLigandRotationMove(structure, resname='ALA') self.model.atom_indices = range(22) self.model.topology = structure[self.model.atom_indices].topology self.model.positions = structure[self.model.atom_indices].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) mc_sim = Simulation(sims, self.mover, **self.opt) #monkeypatch to access acceptance value def nacceptRejectMC(self, temperature=300, **opt): """Function that chooses to accept or reject the proposed move. """ md_state0 = self.current_state['md']['state0'] md_state1 = self.current_state['md']['state1'] log_mc = (md_state1['potential_energy'] - md_state0['potential_energy']) * ( -1.0 / self.nc_sim.context._integrator.kT) randnum = math.log(np.random.random()) if log_mc > randnum: self.accept += 1 print('MC MOVE ACCEPTED: log_mc {} > randnum {}'.format( log_mc, randnum)) self.md_sim.context.setPositions(md_state1['positions']) else: self.reject += 1 print('MC MOVE REJECTED: log_mc {} < {}'.format( log_mc, randnum)) self.md_sim.context.setPositions(md_state0['positions']) self.log_mc = log_mc self.md_sim.context.setVelocitiesToTemperature( self.opt['temperature']) mc_sim.acceptRejectMC = nacceptRejectMC nacceptRejectMC.__get__(mc_sim) mc_sim.acceptRejectMC = types.MethodType(nacceptRejectMC, mc_sim) mc_sim.runMC(self.opt['nIter']) #get log acceptance print(mc_sim.log_mc) #if mc is working, should be around -24.1 assert mc_sim.log_mc <= -23.8 and mc_sim.log_mc >= -24.3
def runNCMC(platform_name, nstepsNC, nprop, outfname): #Generate the ParmEd Structure prmtop = utils.get_data_filename('blues', 'tests/data/eqToluene.prmtop') # inpcrd = utils.get_data_filename('blues', 'tests/data/eqToluene.inpcrd') struct = parmed.load_file(prmtop, xyz=inpcrd) print('Structure: %s' % struct.topology) #Define some options opt = { 'temperature': 300.0, 'friction': 1, 'dt': 0.002, 'nIter': 100, 'nstepsNC': nstepsNC, 'nstepsMD': 5000, 'nprop': nprop, 'nonbondedMethod': 'PME', 'nonbondedCutoff': 10, 'constraints': 'HBonds', 'freeze_distance': 5.0, 'trajectory_interval': 1000, 'reporter_interval': 1000, 'ncmc_traj': None, 'write_move': True, 'platform': platform_name, 'outfname': 't4-tol', 'verbose': False } #Define the 'model' object we are perturbing here. # Calculate particle masses of object to be moved ligand = RandomLigandRotationMove(struct, 'LIG') ligand.calculateProperties() # Initialize object that proposes moves. ligand_mover = MoveEngine(ligand) # Generate the MD, NCMC, ALCHEMICAL Simulation objects simulations = SimulationFactory(struct, ligand_mover, **opt) simulations.createSimulationSet() # Add reporters to MD simulation. traj_reporter = openmm.app.DCDReporter( outfname + '-nc{}.dcd'.format(nstepsNC), opt['trajectory_interval']) progress_reporter = openmm.app.StateDataReporter( sys.stdout, separator="\t", reportInterval=opt['reporter_interval'], step=True, totalSteps=opt['nIter'] * opt['nstepsMD'], time=True, speed=True, progress=True, remainingTime=True) simulations.md.reporters.append(traj_reporter) simulations.md.reporters.append(progress_reporter) # Run BLUES Simulation blues = Simulation(simulations, ligand_mover, **opt) blues.run(opt['nIter'])
def test_blues_simulationRunYAML(self, tmpdir, structure, tol_atom_indices, system_cfg, engine): yaml_cfg = """ output_dir: . outfname: tol-test logger: level: info stream: True system: nonbondedMethod: PME nonbondedCutoff: 8.0 * angstroms constraints: HBonds simulation: dt: 0.002 * picoseconds friction: 1 * 1/picoseconds temperature: 300 * kelvin nIter: 1 nstepsMD: 2 nstepsNC: 2 platform: CPU md_reporters: stream: title: md reportInterval: 1 totalSteps: 2 # nIter * nstepsMD step: True speed: True progress: True remainingTime: True currentIter : True ncmc_reporters: stream: title: ncmc reportInterval: 1 totalSteps: 2 # Use nstepsNC step: True speed: True progress: True remainingTime: True protocolWork : True alchemicalLambda : True currentIter : True """ print('Testing Simulation.run() from YAML') yaml_cfg = Settings(yaml_cfg) cfg = yaml_cfg.asDict() cfg['output_dir'] = tmpdir # os.getenv is equivalent, and can also give a default value instead of `None` PLATFORM = os.getenv('OMM_PLATFORM', 'CPU') cfg['simulation']['platform'] = PLATFORM systems = SystemFactory(structure, tol_atom_indices, cfg['system']) simulations = SimulationFactory(systems, engine, cfg['simulation'], cfg['md_reporters'], cfg['ncmc_reporters']) blues = BLUESSimulation(simulations) blues._md_sim.minimizeEnergy() blues._alch_sim.minimizeEnergy() blues._ncmc_sim.minimizeEnergy() before_iter = blues._md_sim.context.getState( getPositions=True).getPositions(asNumpy=True) blues.run() after_iter = blues._md_sim.context.getState( getPositions=True).getPositions(asNumpy=True) #Check that our system has run dynamics pos_compare = np.not_equal(before_iter, after_iter).all() assert pos_compare
def runEthyleneTest(N): filename = 'ethylene-test_%s' % N print('Running %s...' % filename) seed = np.random.randint(low=1, high=5000) #print('Seed', seed) # filename = 'ethylene-test_%s' % N # print(filename) # Set Simulation parameters sim_cfg = { 'platform': 'CPU', 'nprop': 1, 'propLambda': 0.3, 'dt': 1 * unit.femtoseconds, 'friction': 1 / unit.picoseconds, 'temperature': 200 * unit.kelvin, 'nIter': 100, 'nstepsMD': 20, 'nstepsNC': 20, 'propSteps': 20, 'moveStep': 10 } totalSteps = int(sim_cfg['nIter'] * sim_cfg['nstepsMD']) reportInterval = 5 alchemical_atoms = [2, 3, 4, 5, 6, 7] alchemical_functions = { 'lambda_sterics': 'min(1, (1/0.3)*abs(lambda-0.5))', 'lambda_electrostatics': 'step(0.2-lambda) - 1/0.2*lambda*step(0.2-lambda) + 1/0.2*(lambda-0.8)*step(lambda-0.8)' } md_reporters = {'traj_netcdf': {'reportInterval': reportInterval}} # Load a Parmed Structure for the Topology and create our openmm.Simulation structure_pdb = utils.get_data_filename( 'blues', 'tests/data/ethylene_structure.pdb') structure = parmed.load_file(structure_pdb) # Initialize our move proposal class rot_move = RandomLigandRotationMove(structure, 'LIG') mover = MoveEngine(rot_move) # Load our OpenMM System and create Integrator system_xml = utils.get_data_filename('blues', 'tests/data/ethylene_system.xml') with open(system_xml, 'r') as infile: xml = infile.read() system = openmm.XmlSerializer.deserialize(xml) integrator = openmm.LangevinIntegrator(sim_cfg['temperature'], sim_cfg['friction'], sim_cfg['dt']) integrator.setRandomNumberSeed(seed) alch_integrator = openmm.LangevinIntegrator(sim_cfg['temperature'], sim_cfg['friction'], sim_cfg['dt']) alch_integrator.setRandomNumberSeed(seed) alch_system = SystemFactory.generateAlchSystem(system, alchemical_atoms) ncmc_integrator = AlchemicalExternalLangevinIntegrator( nsteps_neq=sim_cfg['nstepsNC'], alchemical_functions=alchemical_functions, splitting="H V R O R V H", temperature=sim_cfg['temperature'], timestep=sim_cfg['dt']) # ncmc_integrator.setRandomNumberSeed(seed) # Pack our systems into a single object systems = SystemFactory(structure, alchemical_atoms) systems.md = system systems.alch = alch_system # Make our reporters md_reporter_cfg = ReporterConfig(filename, md_reporters) md_reporters_list = md_reporter_cfg.makeReporters() # Pack our simulations into a single object simulations = SimulationFactory(systems, mover) simulations.md = SimulationFactory.generateSimFromStruct( structure, system, integrator, 'CPU') simulations.md = SimulationFactory.attachReporters(simulations.md, md_reporters_list) simulations.alch = SimulationFactory.generateSimFromStruct( structure, system, alch_integrator, 'CPU') simulations.ncmc = SimulationFactory.generateSimFromStruct( structure, alch_system, ncmc_integrator, 'CPU') ethylene_sim = BLUESSimulation(simulations, sim_cfg) ethylene_sim.run()
def md_sim(structure, system): integrator = openmm.LangevinIntegrator(100 * unit.kelvin, 1, 0.002 * unit.picoseconds) md_sim = SimulationFactory.generateSimFromStruct(structure, system, integrator) return md_sim