示例#1
0
    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)
示例#2
0
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)
示例#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'])
示例#4
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()
示例#5
0
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])
示例#6
0
文件: test_mc.py 项目: zuzanaj/blues
    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
示例#7
0
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'])
示例#8
0
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)

    #Define some options
    opt = {
        'temperature': 300.0,
        'friction': 1,
        'dt': 0.002,
        'nIter': 100,
        'nstepsNC': 10000,
        'nstepsMD': 10000,
        'nprop': 1,
        'nonbondedMethod': 'PME',
        'nonbondedCutoff': 10,
        'constraints': 'HBonds',
        'freeze_distance': 5.0,
        'trajectory_interval': 2000,
        'reporter_interval': 1000,
        'write_move': False,
        'platform': platform_name,
        'outfname': 't4-toluene'
    }

    logger = init_logger(logging.getLogger(),
                         level=logging.INFO,
                         outfname=opt['outfname'])
    opt['Logger'] = logger

    #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(
        opt['outfname'] + '-nc{}.dcd'.format(nstepsNC),
        opt['trajectory_interval'])
    md_progress_reporter = BLUESStateDataReporter(
        logger,
        separator="\t",
        title='md',
        reportInterval=opt['reporter_interval'],
        step=True,
        totalSteps=opt['nIter'] * opt['nstepsMD'],
        time=False,
        speed=True,
        progress=True,
        remainingTime=True)
    simulations.md.reporters.append(traj_reporter)
    simulations.md.reporters.append(md_progress_reporter)

    # Add reporters to NCMC simulation.
    ncmc_reporter = BLUESHDF5Reporter(file=opt['outfname'] + '-pmoves.h5',
                                      reportInterval=1,
                                      coordinates=True,
                                      frame_indices=[1, opt['nstepsNC']],
                                      time=False,
                                      cell=True,
                                      temperature=False,
                                      potentialEnergy=False,
                                      kineticEnergy=False,
                                      velocities=False,
                                      atomSubset=None,
                                      protocolWork=True,
                                      alchemicalLambda=True,
                                      parameters=opt,
                                      environment=True)
    ncmc_progress_reporter = BLUESStateDataReporter(
        logger,
        separator="\t",
        title='ncmc',
        reportInterval=opt['reporter_interval'],
        step=True,
        totalSteps=opt['nstepsNC'],
        time=False,
        speed=True,
        progress=True,
        remainingTime=True)
    simulations.nc.reporters.append(ncmc_reporter)
    simulations.nc.reporters.append(ncmc_progress_reporter)

    # Run BLUES Simulation
    blues = Simulation(simulations, ligand_mover, **opt)
    blues.run(opt['nIter'])