Exemplo n.º 1
0
    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)
Exemplo n.º 2
0
    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')
Exemplo n.º 3
0
    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'])
Exemplo n.º 4
0
    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)
Exemplo n.º 5
0
    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)
Exemplo n.º 6
0
    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
Exemplo n.º 7
0
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()
Exemplo n.º 8
0
    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
Exemplo n.º 9
0
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
Exemplo n.º 10
0
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