コード例 #1
0
def configure_simulation(
    pdb_file: str,
    top_file: Optional[str],
    solvent_type: str,
    gpu_index: int,
    dt_ps: float,
    temperature_kelvin: float,
    heat_bath_friction_coef: float,
) -> simtk.openmm.app.Simulation:
    # Configure hardware
    try:
        platform = omm.Platform_getPlatformByName("CUDA")
        platform_properties = {"DeviceIndex": str(gpu_index), "CudaPrecision": "mixed"}
    except Exception:
        platform = omm.Platform_getPlatformByName("OpenCL")
        platform_properties = {"DeviceIndex": str(gpu_index)}

    # Select implicit or explicit solvent configuration
    if solvent_type == "implicit":
        sim, coords = configure_amber_implicit(
            pdb_file,
            top_file,
            dt_ps,
            temperature_kelvin,
            heat_bath_friction_coef,
            platform,
            platform_properties,
        )
    else:
        assert solvent_type == "explicit"
        assert top_file is not None
        sim, coords = configure_amber_explicit(
            pdb_file,
            top_file,
            dt_ps,
            temperature_kelvin,
            heat_bath_friction_coef,
            platform,
            platform_properties,
        )

    # Set simulation positions
    if coords.get_coordinates().shape[0] == 1:
        sim.context.setPositions(coords.positions)
    else:
        positions = random.choice(coords.get_coordinates())
        sim.context.setPositions(positions / 10)

    # Minimize energy and equilibrate
    sim.minimizeEnergy()
    sim.context.setVelocitiesToTemperature(
        temperature_kelvin * u.kelvin, random.randint(1, 10000)
    )

    return sim
コード例 #2
0
def configure_simulation(
    ctx,
    sim_type="implicit",
    gpu_index=0,
    dt_ps=0.002 * u.picoseconds,
    temperature_kelvin=300 * u.kelvin,
):
    logger.info(f"configure_simulation: {sim_type} {ctx.pdb_file}")
    # Configure hardware
    try:
        platform = omm.Platform_getPlatformByName("CUDA")
        platform_properties = {
            "DeviceIndex": str(gpu_index),
            "CudaPrecision": "mixed"
        }
    except Exception:
        platform = omm.Platform_getPlatformByName("OpenCL")
        platform_properties = {"DeviceIndex": str(gpu_index)}

    # Select implicit or explicit solvent
    args = (
        ctx.pdb_file,
        ctx.top_file,
        dt_ps,
        temperature_kelvin,
        platform,
        platform_properties,
    )
    if sim_type == "implicit":
        sim, coords = configure_amber_implicit(*args)
    else:
        assert sim_type == "explicit"
        sim, coords = configure_amber_explicit(*args)

    # Set simulation positions
    if coords.get_coordinates().shape[0] == 1:
        sim.context.setPositions(coords.positions)
    else:
        positions = random.choice(coords.get_coordinates())
        sim.context.setPositions(positions / 10)

    # Minimize energy and equilibrate
    sim.minimizeEnergy()
    sim.context.setVelocitiesToTemperature(300 * u.kelvin,
                                           random.randint(1, 10000))

    return sim
コード例 #3
0
def runEquilibration(equilibrationFiles, reportName, parameters, worker):
    """
    Function that runs the whole equilibration process and returns the final pdb

    :param equilibrationFiles: tuple with the topology (prmtop) in the first position and the coordinates
    in the second (inpcrd)
    :type equilibrationFiles: tuple
    :param outputPDB: string with the pdb to save
    :type outputPDB: str
    :param parameters: Object with the parameters for the simulation
    :type parameters: :py:class:`/simulationrunner/SimulationParameters` -- SimulationParameters object
    :param worker: Number of the subprocess
    :type worker: int

    :returns: str -- a string with the outputPDB
    """
    prmtop, inpcrd = equilibrationFiles
    prmtop = app.AmberPrmtopFile(prmtop)
    inpcrd = app.AmberInpcrdFile(inpcrd)
    PLATFORM = mm.Platform_getPlatformByName(str(parameters.runningPlatform))
    if parameters.runningPlatform == "CUDA":
        platformProperties = {"Precision": "mixed", "DeviceIndex": getDeviceIndexStr(worker, parameters.devicesPerTrajectory, devicesPerReplica=parameters.maxDevicesPerReplica), "UseCpuPme": "false"}
    else:
        platformProperties = {}
    if worker == 0:
        utilities.print_unbuffered("Running %d steps of minimization" % parameters.minimizationIterations)

    if parameters.boxCenter or parameters.cylinderBases:
        dummies = findDummyAtom(prmtop)
        assert dummies is not None
    else:
        dummies = None
    simulation = minimization(prmtop, inpcrd, PLATFORM, parameters.constraintsMin, parameters, platformProperties, dummies)
    # Retrieving the state is expensive (especially when running on GPUs) so we
    # only called it once and then separate positions and velocities
    state = simulation.context.getState(getPositions=True, getVelocities=True)
    positions = state.getPositions()
    velocities = state.getVelocities()
    if worker == 0:
        utilities.print_unbuffered("Running %d steps of NVT equilibration" % parameters.equilibrationLengthNVT)
    simulation = NVTequilibration(prmtop, positions, PLATFORM, parameters.equilibrationLengthNVT, parameters.constraintsNVT, parameters, reportName, platformProperties, velocities=velocities, dummy=dummies)
    state = simulation.context.getState(getPositions=True, getVelocities=True)
    positions = state.getPositions()
    velocities = state.getVelocities()
    if worker == 0:
        utilities.print_unbuffered("Running %d steps of NPT equilibration" % parameters.equilibrationLengthNPT)
    simulation = NPTequilibration(prmtop, positions, PLATFORM, parameters.equilibrationLengthNPT, parameters.constraintsNPT, parameters, reportName, platformProperties, velocities=velocities, dummy=dummies)
    state = simulation.context.getState(getPositions=True)
    root, _ = os.path.splitext(reportName)
    outputPDB = "%s_NPT.pdb" % root
    with open(outputPDB, 'w') as fw:
        app.PDBFile.writeFile(simulation.topology, state.getPositions(), fw)
    return outputPDB
コード例 #4
0
 def testXTCreporter(self):
     output_PDB = "tests/data/test_xtcreporter.pdb"
     output_XTC = "tests/data/test_xtcreporter.xtc"
     top_PDB = "tests/data/top_xtcreporter.pdb"
     PLATFORM = mm.Platform_getPlatformByName(str('CPU'))
     prmtop = app.AmberPrmtopFile("tests/data/complex.prmtop")
     inpcrd = app.AmberInpcrdFile("tests/data/complex.inpcrd")
     system = prmtop.createSystem(nonbondedMethod=app.PME,
                                  nonbondedCutoff=9 * unit.angstroms,
                                  constraints=app.HBonds)
     system.addForce(
         mm.AndersenThermostat(300 * unit.kelvin, 1 / unit.picosecond))
     integrator = mm.VerletIntegrator(2 * unit.femtoseconds)
     force = mm.CustomExternalForce(str("k*((x-x0)^2+(y-y0)^2+(z-z0)^2)"))
     force.addGlobalParameter(
         str("k"), 5.0 * unit.kilocalories_per_mole / unit.angstroms**2)
     force.addPerParticleParameter(str("x0"))
     force.addPerParticleParameter(str("y0"))
     force.addPerParticleParameter(str("z0"))
     for j, atom in enumerate(prmtop.topology.atoms()):
         if (atom.name in ('CA', 'C', 'N', 'O') and atom.residue.name !=
                 "HOH") or (atom.residue.name == "BEN"
                            and atom.element.symbol != "H"):
             force.addParticle(
                 j, inpcrd.positions[j].value_in_unit(unit.nanometers))
     system.addForce(force)
     simulation = app.Simulation(prmtop.topology, system, integrator,
                                 PLATFORM)
     if inpcrd.boxVectors is not None:
         simulation.context.setPeriodicBoxVectors(*inpcrd.boxVectors)
     simulation.context.setPositions(inpcrd.positions)
     simulation.minimizeEnergy(maxIterations=10)
     print("Minimization ended")
     xtcReporter = XTCReporter(output_XTC, 1)
     simulation.reporters.append(app.PDBReporter(output_PDB, 1))
     simulation.reporters.append(xtcReporter)
     simulation.step(10)
     # the XTCReporter does not close the file, so opening the file again
     # without exiting the function causes problems to the mdtraj reader
     xtcReporter.close()
     t_xtc = md.load(str(output_XTC), top=top_PDB)
     t_pdb = md.load(output_PDB)
     self.assertEqual(t_pdb.top, t_xtc.top)
     self.assertEqual(np.sum(np.abs(t_pdb.xyz - t_xtc.xyz) > 1e-3), 0)
     os.remove(output_PDB)
     os.remove(output_XTC)
コード例 #5
0
ファイル: steered_md.py プロジェクト: simonbray/duck
def run_steered_md(
    temperature,
    checkpoint_in_file,
    csv_out_file,
    dat_out_file,
    pdb_out_file,
    traj_out_file,
    startdist,
    spring_constant=50,
    force_constant_chunk=0.1,
    init_velocity=0.00001,
    gpu_id=0,
):
    if os.path.isfile(pdb_out_file):
        return
    spring_k = spring_constant * u.kilocalorie / (u.mole * u.angstrom *
                                                  u.angstrom)
    dist_in = startdist * u.angstrom  # in angstrom
    dist_fin = (startdist + 2.5) * u.angstrom  # in angstrom
    steps_per_move = 200
    velocity = init_velocity * u.angstrom
    # Platform definition
    platform = mm.Platform_getPlatformByName("OpenCL")
    platformProperties = {}
    platformProperties["OpenCLPrecision"] = "mixed"
    platformProperties["OpenCLDeviceIndex"] = gpu_id
    print("loading pickle")
    pickle_in = open("complex_system.pickle", "rb")
    combined_pmd = pickle.load(pickle_in)[0]
    print(combined_pmd)
    pickle_in.close()
    keyInteraction = cal_ints.find_interaction()
    print(keyInteraction)
    # Get indexes of heavy atoms in chunk
    Chunk_Heavy_Atoms = duck_stuff.getHeavyAtomsInSystem(combined_pmd)
    # Setting System
    system = combined_pmd.createSystem(
        nonbondedMethod=app.PME,
        nonbondedCutoff=9 * u.angstrom,
        constraints=app.HBonds,
        hydrogenMass=None,
    )
    # Apply force on all havy atoms of chunk
    duck_stuff.applyHarmonicPositionalRestraints(system, force_constant_chunk,
                                                 combined_pmd.positions,
                                                 Chunk_Heavy_Atoms)
    # Integrator
    integrator = mm.LangevinIntegrator(temperature, 4 / u.picosecond,
                                       0.002 * u.picosecond)
    # Setting Simulation object and loading the checkpoint
    simulation = app.Simulation(combined_pmd.topology, system, integrator,
                                platform, platformProperties)
    simulation.loadCheckpoint(checkpoint_in_file)
    # SMD force definition
    pullforce = mm.CustomExternalForce("k_sp*0.5*(R-R0)^2; \
                                       R = periodicdistance(x, y, z, x0, y0, z0);"
                                       )
    pullforce.addPerParticleParameter("k_sp")
    pullforce.addGlobalParameter("x0", 0.0 * u.nanometer)
    pullforce.addGlobalParameter("y0", 0.0 * u.nanometer)
    pullforce.addGlobalParameter("z0", 0.0 * u.nanometer)
    pullforce.addGlobalParameter("R0", 0.0 * u.nanometer)
    pullforce.addParticle(keyInteraction[1], [spring_k])
    system.addForce(pullforce)
    # Redefine integrator and simulation, and load checkpoint with new-updated system
    integrator = mm.LangevinIntegrator(temperature, 4 / u.picosecond,
                                       0.002 * u.picosecond)
    simulation = app.Simulation(combined_pmd.topology, system, integrator,
                                platform, platformProperties)
    simulation.loadCheckpoint(checkpoint_in_file)
    # Initializing energy
    work_val_old = u.Quantity(value=0, unit=u.kilocalorie / u.mole)
    # Number of big steps and pull distance
    steps = int(round((dist_fin - dist_in) / velocity) / steps_per_move)
    pull_distance = velocity * steps_per_move
    # Reporters and duck.dat file
    simulation.reporters.append(
        app.StateDataReporter(
            csv_out_file,
            steps_per_move,
            step=True,
            time=True,
            totalEnergy=True,
            kineticEnergy=True,
            potentialEnergy=True,
            temperature=True,
            density=True,
            progress=True,
            totalSteps=steps_per_move * steps,
            speed=True,
        ))
    simulation.reporters.append(app.DCDReporter(traj_out_file, 100000))
    f = open(dat_out_file, "w")
    # Production in N steps with the update every 200 steps (2 pm)
    for i in range(steps):
        # Get current state tu update the system
        state = simulation.context.getState(getPositions=True)
        pos_keyInt = state.getPositions()
        keyInteraction_pos = [
            pos_keyInt[keyInteraction[0]],
            pos_keyInt[keyInteraction[1]],
        ]
        # Get radius of starting point and end point
        R_val = dist_in + float(i + 1) * pull_distance
        R_val_start = dist_in + float(i) * pull_distance
        # Get distance of main interaction
        keyInteraction_dist = np.linalg.norm(keyInteraction_pos[0] -
                                             keyInteraction_pos[1])
        print(keyInteraction_dist)
        # Updated system
        simulation.context.setParameter("x0", keyInteraction_pos[0][0])
        simulation.context.setParameter("y0", keyInteraction_pos[0][1])
        simulation.context.setParameter("z0", keyInteraction_pos[0][2])
        simulation.context.setParameter("R0", R_val)
        # Calculate force F = -k * x
        force_val = -spring_k * (keyInteraction_dist - R_val)
        # Make step
        simulation.step(steps_per_move)
        # Calculate work for difference in potential energy in tranzition
        # W = EK_end - EK_start
        # EK = 0.5 * k * x^2
        spr_energy_end = 0.5 * spring_k * (keyInteraction_dist - R_val)**2
        spr_energy_start = 0.5 * spring_k * (keyInteraction_dist -
                                             R_val_start)**2
        work_val = work_val_old + spr_energy_end - spr_energy_start
        work_val_old = work_val
        # Write duck.dat file
        f.write(
            str(i) + " " + str(R_val) + " " + str(keyInteraction_dist) + " " +
            str(force_val) + " " + str(work_val) + "\n")
    f.close()
    # Save state in PDB file
    positions = simulation.context.getState(getPositions=True).getPositions()
    app.PDBFile.writeFile(simulation.topology, positions,
                          open(pdb_out_file, "w"))
コード例 #6
0
def runProductionSimulation(equilibrationFiles,
                            workerNumber,
                            outputDir,
                            seed,
                            parameters,
                            reportFileName,
                            checkpoint,
                            ligandName,
                            replica_id,
                            trajsPerReplica,
                            epoch_number,
                            restart=False):
    """
    Functions that runs the production run at NPT conditions.
    If a boxRadius is defined in the parameters section, a Flat-bottom harmonic restrains will be applied between
    the protein and the ligand

    :param equilibrationFiles: Tuple with the paths for the Amber topology file (prmtop) and the pdb for the system
    :type equilibrationFiles: Tuple
    :param workerNumber: Number of the subprocess
    :type workerNumber: int
    :param outputDir: path to the directory where the output will be written
    :type outputDir: str
    :param seed: Seed to use to generate the random numbers
    :type seed: int
    :param parameters: Object with the parameters for the simulation
    :type parameters: :py:class:`/simulationrunner/SimulationParameters` -- SimulationParameters object
    :param reportFileName: Name for the file where the energy report will be written
    :type reportFileName: str
    :param checkpoint: Path to the checkpoint from where the production run will be restarted (Optional)
    :type checkpoint: str
    :param ligandName: Code Name for the ligand
    :type ligandName: str
    :param replica_id: Id of the replica running
    :type replica_id: int
    :param trajsPerReplica: Number of trajectories per replica
    :type trajsPerReplica: int
    :param restart: Whether the simulation run has to be restarted or not
    :type restart: bool
    :param epoch_number: Number of the epoch
    :type epoch_number: int

    """
    # this number gives the number of the subprocess in the given node
    deviceIndex = workerNumber
    # this one gives the number of the subprocess in the overall simulation (i.e
    # the trajectory file number)
    workerNumber += replica_id * trajsPerReplica + 1
    prmtop, pdb = equilibrationFiles
    prmtop = app.AmberPrmtopFile(prmtop)
    trajName = os.path.join(
        outputDir, constants.AmberTemplates.trajectoryTemplate %
        (workerNumber, parameters.format))
    stateReporter = os.path.join(outputDir,
                                 "%s_%s" % (reportFileName, workerNumber))
    checkpointReporter = os.path.join(
        outputDir,
        constants.AmberTemplates.CheckPointReporterTemplate % workerNumber)
    lastStep = getLastStep(stateReporter)
    simulation_length = parameters.productionLength - lastStep
    # if the string is unicode the PDBReaders fails to read the file (this is
    # probably due to the fact that openmm was built with python2 in my
    # computer, will need to test thoroughly with python3)
    pdb = app.PDBFile(str(pdb))
    PLATFORM = mm.Platform_getPlatformByName(str(parameters.runningPlatform))
    if parameters.runningPlatform == "CUDA":
        platformProperties = {
            "Precision":
            "mixed",
            "DeviceIndex":
            getDeviceIndexStr(
                deviceIndex,
                parameters.devicesPerTrajectory,
                devicesPerReplica=parameters.maxDevicesPerReplica),
            "UseCpuPme":
            "false"
        }
    else:
        platformProperties = {}

    dummies = None
    if parameters.boxCenter or parameters.cylinderBases:
        dummies = findDummyAtom(prmtop)

    if epoch_number > 0:
        min_sim = minimization(prmtop,
                               pdb,
                               PLATFORM,
                               parameters.constraintsMin,
                               parameters,
                               platformProperties,
                               dummy=dummies)
        positions = min_sim.context.getState(getPositions=True).getPositions()
    else:
        positions = pdb.positions
    system = prmtop.createSystem(nonbondedMethod=app.PME,
                                 nonbondedCutoff=parameters.nonBondedCutoff *
                                 unit.angstroms,
                                 constraints=app.HBonds,
                                 removeCMMotion=True)
    if parameters.boxCenter or parameters.cylinderBases:
        addDummyAtomToSystem(system, prmtop.topology, positions,
                             parameters.ligandName, dummies, deviceIndex)

    system.addForce(
        mm.AndersenThermostat(parameters.Temperature * unit.kelvin,
                              1 / unit.picosecond))
    integrator = mm.VerletIntegrator(parameters.timeStep * unit.femtoseconds)
    system.addForce(
        mm.MonteCarloBarostat(1 * unit.bar,
                              parameters.Temperature * unit.kelvin))
    if parameters.constraints is not None:
        # Add the specified constraints to the system
        addConstraints(system, prmtop.topology, parameters.constraints)

    if parameters.boxCenter or parameters.cylinderBases:
        if parameters.boxType == blockNames.SimulationParams.sphere:
            if deviceIndex == 0:
                utilities.print_unbuffered("Adding spherical ligand box")
            assert len(dummies) == 1
            addLigandBox(prmtop.topology, positions, system,
                         parameters.ligandName, dummies[0],
                         parameters.boxRadius, deviceIndex)
        elif parameters.boxType == blockNames.SimulationParams.cylinder:
            if deviceIndex == 0:
                utilities.print_unbuffered("Adding cylinder ligand box")
            addLigandCylinderBox(prmtop.topology, positions, system,
                                 parameters.ligandName, dummies,
                                 parameters.boxRadius, deviceIndex)
    simulation = app.Simulation(prmtop.topology,
                                system,
                                integrator,
                                PLATFORM,
                                platformProperties=platformProperties)
    utilities.print_unbuffered(workerNumber, equilibrationFiles, dummies,
                               len(positions), prmtop.topology.getNumAtoms(),
                               system.getNumParticles())
    simulation.context.setPositions(positions)
    if restart:
        with open(str(checkpoint), 'rb') as check:
            simulation.context.loadCheckpoint(check.read())
        stateData = open(str(stateReporter), "a")
    else:
        simulation.context.setVelocitiesToTemperature(
            parameters.Temperature * unit.kelvin, seed)
        stateData = open(str(stateReporter), "w")
    if parameters.format == "xtc":
        simulation.reporters.append(
            XTCReporter(str(trajName),
                        parameters.reporterFreq,
                        append=restart,
                        enforcePeriodicBox=parameters.postprocessing))
    elif parameters.format == "dcd":
        simulation.reporters.append(
            app.DCDReporter(str(trajName),
                            parameters.reporterFreq,
                            append=restart,
                            enforcePeriodicBox=parameters.postprocessing))

    simulation.reporters.append(
        app.CheckpointReporter(str(checkpointReporter),
                               parameters.reporterFreq))
    simulation.reporters.append(
        CustomStateDataReporter(stateData,
                                parameters.reporterFreq,
                                step=True,
                                potentialEnergy=True,
                                temperature=True,
                                time_sim=True,
                                volume=True,
                                remainingTime=True,
                                speed=True,
                                totalSteps=simulation_length,
                                separator="\t",
                                append=restart,
                                initialStep=lastStep))

    if workerNumber == 1:
        frequency = min(10 * parameters.reporterFreq,
                        parameters.productionLength)
        simulation.reporters.append(
            app.StateDataReporter(sys.stdout, frequency, step=True))
    simulation.step(simulation_length)
    stateData.close()
コード例 #7
0
def openmm_simulate_amber_fs_pep(pdb_file, top_file=None, checkpnt_fname='checkpnt.chk', 
                                 checkpnt=None, GPU_index=0,
                                 output_traj='output.dcd', output_log='output.log', output_cm=None,
                                 report_time=10*u.picoseconds,sim_time=10*u.nanoseconds, 
                                 platform='CUDA'):
    """
    Start and run an OpenMM NVT simulation with Langevin integrator at 2 fs 
    time step and 300 K. The cutoff distance for nonbonded interactions were 
    set at 1.2 nm and LJ switch distance at 1.0 nm, which commonly used with
    Charmm force field. Long-range nonbonded interactions were handled with PME.  

    Parameters
    ----------
    pdb_file : coordinates file (.gro, .pdb, ...)
        This is the molecule configuration file contains all the atom position
        and PBC (periodic boundary condition) box in the system. 
   
    checkpnt : None or check point file to load 
        
    GPU_index : Int or Str 
        The device # of GPU to use for running the simulation. Use Strings, '0,1'
        for example, to use more than 1 GPU
  
    output_traj : the trajectory file (.dcd)
        This is the file stores all the coordinates information of the MD 
        simulation results. 
  
    output_log : the log file (.log) 
        This file stores the MD simulation status, such as steps, time, potential
        energy, temperature, speed, etc.
 
    output_cm : the h5 file contains contact map information

    report_time : 10 ps
        The program writes its information to the output every 10 ps by default 

    sim_time : 10 ns
        The timespan of the simulation trajectory

    platform : str
        Name of platform. Options: 'CUDA', 'OpenCL', or 'CPU'

    """

    if top_file: 
        pdb = pmd.load_file(top_file, xyz=pdb_file)
        system = pdb.createSystem(nonbondedMethod=app.CutoffNonPeriodic, 
                nonbondedCutoff=1.0*u.nanometer, constraints=app.HBonds, 
                implicitSolvent=app.OBC1)
    else: 
        pdb = pmd.load_file(pdb_file)
        forcefield = app.ForceField('amber99sbildn.xml', 'amber99_obc.xml')
        system = forcefield.createSystem(pdb.topology, nonbondedMethod=app.CutoffNonPeriodic, 
                nonbondedCutoff=1.0*u.nanometer, constraints=app.HBonds)

    dt = 0.002*u.picoseconds
    integrator = omm.LangevinIntegrator(300*u.kelvin, 91.0/u.picosecond, dt)
    integrator.setConstraintTolerance(0.00001)

    # Select platform
    if platform is 'CUDA':
        platform = omm.Platform_getPlatformByName('CUDA')
        properties = {'DeviceIndex': str(GPU_index), 'CudaPrecision': 'mixed'}
    elif platform is 'OpenCL':
        platform = omm.Platform_getPlatformByName('OpenCL')
        properties = {'DeviceIndex': str(GPU_index)}
    elif platform is 'CPU':
        platform, properties = None, None
    else:
        raise ValueError(f'Invalid platform name: {platform}')

    simulation = app.Simulation(pdb.topology, system, integrator, platform, properties)

    simulation.context.setPositions(random.choice(pdb.get_coordinates())/10) #parmed \AA to OpenMM nm

    # equilibrate
    simulation.minimizeEnergy() 
    simulation.context.setVelocitiesToTemperature(300*u.kelvin, random.randint(1, 10000))
    simulation.step(int(100*u.picoseconds / (2*u.femtoseconds)))

    report_freq = int(report_time/dt)
    simulation.reporters.append(app.DCDReporter(output_traj, report_freq))
    if output_cm:
        simulation.reporters.append(sim.ContactMapReporter(output_cm, report_freq))

    simulation.reporters.append(app.StateDataReporter(output_log,
            report_freq, step=True, time=True, speed=True,
            potentialEnergy=True, temperature=True, totalEnergy=True))
    simulation.reporters.append(app.CheckpointReporter(checkpnt_fname, report_freq))

    if checkpnt:
        simulation.loadCheckpoint(checkpnt)
    nsteps = int(sim_time/dt)
    simulation.step(nsteps)
コード例 #8
0
def openmm_simulate_charmm_nvt(top_file,
                               pdb_file,
                               check_point=None,
                               GPU_index=0,
                               output_traj="output.dcd",
                               output_log="output.log",
                               output_cm=None,
                               report_time=10 * u.picoseconds,
                               sim_time=10 * u.nanoseconds):
    """
    Start and run an OpenMM NVT simulation with Langevin integrator at 2 fs 
    time step and 300 K. The cutoff distance for nonbonded interactions were 
    set at 1.2 nm and LJ switch distance at 1.0 nm, which commonly used with
    Charmm force field. Long-range nonbonded interactions were handled with PME.  

    Parameters
    ----------
    top_file : topology file (.top, .prmtop, ...)
        This is the topology file discribe all the interactions within the MD 
        system. 

    pdb_file : coordinates file (.gro, .pdb, ...)
        This is the molecule configuration file contains all the atom position
        and PBC (periodic boundary condition) box in the system. 
   
    check_point : None or check point file to load 
        
    GPU_index : Int or Str 
        The device # of GPU to use for running the simulation. Use Strings, '0,1'
        for example, to use more than 1 GPU
  
    output_traj : the trajectory file (.dcd)
        This is the file stores all the coordinates information of the MD 
        simulation results. 
  
    output_log : the log file (.log) 
        This file stores the MD simulation status, such as steps, time, potential
        energy, temperature, speed, etc.
 
    output_cm : the h5 file contains contact map information

    report_time : 10 ps
        The program writes its information to the output every 10 ps by default 

    sim_time : 10 ns
        The timespan of the simulation trajectory
    """

    top = pmd.load_file(top_file, xyz=pdb_file)

    system = top.createSystem(nonbondedMethod=app.PME,
                              nonbondedCutoff=1.2 * u.nanometer,
                              switchDistance=1.0 * u.nanometer,
                              constraints=app.HBonds)
    dt = 0.002 * u.picoseconds
    integrator = omm.LangevinIntegrator(300 * u.kelvin, 1 / u.picosecond, dt)

    try:
        platform = omm.Platform_getPlatformByName("CUDA")
        properties = {'DeviceIndex': str(GPU_index), 'CudaPrecision': 'mixed'}
    except Exception:
        platform = omm.Platform_getPlatformByName("OpenCL")
        properties = {'DeviceIndex': str(GPU_index)}

    simulation = app.Simulation(top.topology, system, integrator, platform,
                                properties)

    simulation.context.setPositions(top.positions)

    simulation.minimizeEnergy()

    report_freq = int(report_time / dt)
    simulation.context.setVelocitiesToTemperature(10 * u.kelvin,
                                                  random.randint(1, 10000))
    simulation.reporters.append(app.DCDReporter(output_traj, report_freq))
    if output_cm:
        simulation.reporters.append(ContactMapReporter(output_cm, report_freq))
    simulation.reporters.append(
        app.StateDataReporter(output_log,
                              report_freq,
                              step=True,
                              time=True,
                              speed=True,
                              potentialEnergy=True,
                              temperature=True,
                              totalEnergy=True))
    simulation.reporters.append(
        app.CheckpointReporter('checkpnt.chk', report_freq))

    if check_point:
        simulation.loadCheckpoint(check_point)
    nsteps = int(sim_time / dt)
    simulation.step(nsteps)
コード例 #9
0
ファイル: simtools.py プロジェクト: oess/openmm_orion
    def __init__(self, mdstate, parmed_structure, opt):
        super().__init__(mdstate, parmed_structure, opt)

        opt['platform'] = 'Auto'
        opt['cuda_opencl_precision'] = 'mixed'

        topology = parmed_structure.topology
        positions = mdstate.get_positions()
        velocities = mdstate.get_velocities()
        box = mdstate.get_box_vectors()

        opt['omm_log_fn'] = os.path.join(opt['out_directory'], 'trajectory.log')
        opt['omm_trj_fn'] = os.path.join(opt['out_directory'], 'trajectory.h5')

        # Time step in ps
        if opt['hmr']:
            self.stepLen = 0.004 * unit.picoseconds
            opt['Logger'].info("Hydrogen Mass repartitioning is On")
        else:
            self.stepLen = 0.002 * unit.picoseconds

        opt['timestep'] = self.stepLen

        # Centering the system to the OpenMM Unit Cell
        if opt['center'] and box is not None:
            opt['Logger'].info("[{}] Centering is On".format(opt['CubeTitle']))
            # Numpy array in A
            coords = parmed_structure.coordinates
            # System Center of Geometry
            cog = np.mean(coords, axis=0)
            # System box vectors
            box_v = parmed_structure.box_vectors.in_units_of(unit.angstrom) / unit.angstrom
            box_v = np.array([box_v[0][0], box_v[1][1], box_v[2][2]])
            # Translation vector
            delta = box_v / 2 - cog
            # New Coordinates
            new_coords = coords + delta
            parmed_structure.coordinates = new_coords
            positions = parmed_structure.positions
            mdstate.set_positions(positions)

        # Constraint type
        constraints = md_keys_converter[MDEngines.OpenMM]['constraints'][opt['constraints']]

        # OpenMM system
        if box is not None:
            box_v = parmed_structure.box_vectors.value_in_unit(unit.angstrom)
            box_v = np.array([box_v[0][0], box_v[1][1], box_v[2][2]])

            min_box = np.min(box_v)

            threshold = (min_box / 2.0) * 0.85

            if opt['nonbondedCutoff'] < threshold:
                cutoff_distance = opt['nonbondedCutoff'] * unit.angstroms
            else:
                opt['Logger'].warn("[{}] Cutoff Distance too large for the box size. Set the cutoff distance "
                                   "to {} A".format(opt['CubeTitle'], threshold))

                cutoff_distance = threshold * unit.angstroms

            self.system = parmed_structure.createSystem(nonbondedMethod=app.PME,
                                                        nonbondedCutoff=cutoff_distance,
                                                        constraints=eval("app.%s" % constraints),
                                                        removeCMMotion=False,
                                                        hydrogenMass=4.0 * unit.amu if opt['hmr'] else None)
        else:  # Vacuum
            self.system = parmed_structure.createSystem(nonbondedMethod=app.NoCutoff,
                                                        constraints=eval("app.%s" % constraints),
                                                        removeCMMotion=False,
                                                        hydrogenMass=4.0 * unit.amu if opt['hmr'] else None)
        # Add Implicit Solvent Force
        if opt['implicit_solvent'] != 'None':
            opt['Logger'].info("[{}] Implicit Solvent Selected".format(opt['CubeTitle']))

            implicit_force = parmed_structure.omm_gbsa_force(eval("app.%s" % opt['implicit_solvent']),
                                                             temperature=opt['temperature'] * unit.kelvin,
                                                             nonbondedMethod=app.PME,
                                                             nonbondedCutoff=opt['nonbondedCutoff'] * unit.angstroms)
            self.system.addForce(implicit_force)

        # OpenMM Integrator
        integrator = openmm.LangevinIntegrator(opt['temperature'] * unit.kelvin, 1 / unit.picoseconds, self.stepLen)

        if opt['SimType'] == 'npt':
            if box is None:
                raise ValueError("NPT simulation without box vector")

            # Add Force Barostat to the system
            self.system.addForce(
                openmm.MonteCarloBarostat(opt['pressure'] * unit.atmospheres, opt['temperature'] * unit.kelvin, 25))

        # Apply restraints
        if opt['restraints']:
            opt['Logger'].info("[{}] RESTRAINT mask applied to: {}"
                               "\tRestraint weight: {}".format(opt['CubeTitle'],
                                                               opt['restraints'],
                                                               opt['restraintWt'] *
                                                               unit.kilocalories_per_mole / unit.angstroms ** 2))
            # Select atom to restraint
            res_atom_set = oeommutils.select_oemol_atom_idx_by_language(opt['molecule'], mask=opt['restraints'])
            opt['Logger'].info("[{}] Number of restraint atoms: {}".format(opt['CubeTitle'],
                                                                           len(res_atom_set)))
            # define the custom force to restrain atoms to their starting positions
            force_restr = openmm.CustomExternalForce('k_restr*periodicdistance(x, y, z, x0, y0, z0)^2')
            # Add the restraint weight as a global parameter in kcal/mol/A^2
            force_restr.addGlobalParameter("k_restr",
                                           opt['restraintWt'] * unit.kilocalories_per_mole / unit.angstroms ** 2)
            # Define the target xyz coords for the restraint as per-atom (per-particle) parameters
            force_restr.addPerParticleParameter("x0")
            force_restr.addPerParticleParameter("y0")
            force_restr.addPerParticleParameter("z0")

            if opt['restraint_to_reference'] and box is not None:
                opt['Logger'].info("[{}] Restraint to the Reference State Enabled".format(opt['CubeTitle']))
                reference_positions = opt['reference_state'].get_positions()
                coords = np.array(reference_positions.value_in_unit(unit.nanometers))
                # System Center of Geometry
                cog = np.mean(coords, axis=0)

                # System box vectors
                box_v = opt['reference_state'].get_box_vectors().value_in_unit(unit.nanometers)
                box_v = np.array([box_v[0][0], box_v[1][1], box_v[2][2]])

                # Translation vector
                delta = box_v / 2 - cog
                # New Coordinates
                corrected_reference_positions = coords + delta

            for idx in range(0, len(positions)):
                if idx in res_atom_set:
                    if opt['restraint_to_reference']:
                        xyz = corrected_reference_positions[idx]  # nanometers unit
                    else:
                        xyz = positions[idx].in_units_of(unit.nanometers) / unit.nanometers
                    force_restr.addParticle(idx, xyz)

            self.system.addForce(force_restr)

        # Freeze atoms
        if opt['freeze']:
            opt['Logger'].info("[{}] FREEZE mask applied to: {}".format(opt['CubeTitle'],
                                                                        opt['freeze']))

            freeze_atom_set = oeommutils.select_oemol_atom_idx_by_language(opt['molecule'], mask=opt['freeze'])
            opt['Logger'].info("[{}] Number of frozen atoms: {}".format(opt['CubeTitle'],
                                                                        len(freeze_atom_set)))
            # Set atom masses to zero
            for idx in range(0, len(positions)):
                if idx in freeze_atom_set:
                    self.system.setParticleMass(idx, 0.0)

        # Platform Selection
        if opt['platform'] == 'Auto':
            # Select the platform
            for plt_name in ['CUDA', 'OpenCL', 'CPU', 'Reference']:
                try:
                    platform = openmm.Platform_getPlatformByName(plt_name)
                    break
                except:
                    if plt_name == 'Reference':
                        raise ValueError('It was not possible to select any OpenMM Platform')
                    else:
                        pass
            if platform.getName() in ['CUDA', 'OpenCL']:
                for precision in ['mixed', 'single', 'double']:
                    try:
                        # Set platform precision for CUDA or OpenCL
                        properties = {'Precision': precision}

                        if 'gpu_id' in opt and 'OE_VISIBLE_DEVICES' in os.environ and not in_orion():
                            properties['DeviceIndex'] = opt['gpu_id']

                        simulation = app.Simulation(topology, self.system, integrator,
                                                    platform=platform,
                                                    platformProperties=properties)
                        break
                    except:
                        if precision == 'double':
                            raise ValueError('It was not possible to select any Precision '
                                             'for the selected Platform: {}'.format(platform.getName()))
                        else:
                            pass
            else:  # CPU or Reference
                simulation = app.Simulation(topology, self.system, integrator, platform=platform)
        else:  # Not Auto Platform selection
            try:
                platform = openmm.Platform.getPlatformByName(opt['platform'])
            except Exception as e:
                raise ValueError('The selected platform is not supported: {}'.format(str(e)))

            if opt['platform'] in ['CUDA', 'OpenCL']:
                try:
                    # Set platform CUDA or OpenCL precision
                    properties = {'Precision': opt['cuda_opencl_precision']}

                    simulation = app.Simulation(topology, self.system, integrator,
                                                platform=platform,
                                                platformProperties=properties)
                except Exception:
                    raise ValueError('It was not possible to set the {} precision for the {} platform'
                                     .format(opt['cuda_opencl_precision'], opt['platform']))
            else:  # CPU or Reference Platform
                simulation = app.Simulation(topology, self.system, integrator, platform=platform)

        # Set starting positions and velocities
        simulation.context.setPositions(positions)

        # Set Box dimensions
        if box is not None:
            simulation.context.setPeriodicBoxVectors(box[0], box[1], box[2])

        # If the velocities are not present in the Parmed structure
        # new velocity vectors are generated otherwise the system is
        # restarted from the previous State
        if opt['SimType'] in ['nvt', 'npt']:

            if velocities is not None:
                opt['Logger'].info('[{}] RESTARTING simulation from a previous State'.format(opt['CubeTitle']))
                simulation.context.setVelocities(velocities)
            else:
                # Set the velocities drawing from the Boltzmann distribution at the selected temperature
                opt['Logger'].info('[{}] GENERATING a new starting State'.format(opt['CubeTitle']))
                simulation.context.setVelocitiesToTemperature(opt['temperature'] * unit.kelvin)

            # Convert simulation time in steps
            opt['steps'] = int(round(opt['time'] / (self.stepLen.in_units_of(unit.nanoseconds) / unit.nanoseconds)))

            # Set Reporters
            for rep in getReporters(**opt):
                simulation.reporters.append(rep)

        # OpenMM platform information
        mmver = openmm.version.version
        mmplat = simulation.context.getPlatform()

        str_logger = '\n' + '-' * 32 + ' SIMULATION ' + '-' * 32
        str_logger += '\n' + '{:<25} = {:<10}'.format('time step', str(opt['timestep']))

        # Host information
        for k, v in uname()._asdict().items():
            str_logger += "\n{:<25} = {:<10}".format(k, v)
            opt['Logger'].info("[{}] {} : {}".format(opt['CubeTitle'],
                                                     k, v))

        # Platform properties
        for prop in mmplat.getPropertyNames():
            val = mmplat.getPropertyValue(simulation.context, prop)
            str_logger += "\n{:<25} = {:<10}".format(prop, val)
            opt['Logger'].info("[{}] {} : {}".format(opt['CubeTitle'],
                                                     prop, val))

        info = "{:<25} = {:<10}".format("OpenMM Version", mmver)
        opt['Logger'].info("[{}] OpenMM Version : {}".format(opt['CubeTitle'], mmver))
        str_logger += '\n' + info

        info = "{:<25} = {:<10}".format("Platform in use", mmplat.getName())
        opt['Logger'].info("[{}] Platform in use : {}".format(opt['CubeTitle'], mmplat.getName()))
        str_logger += '\n' + info

        self.mdstate = mdstate
        self.parmed_structure = parmed_structure
        self.opt = opt
        self.str_logger = str_logger
        self.omm_simulation = simulation

        return
コード例 #10
0
def runProductionSimulation(equilibrationFiles,
                            workerNumber,
                            outputDir,
                            seed,
                            parameters,
                            reportFileName,
                            checkpoint,
                            ligandName,
                            replica_id,
                            trajsPerReplica,
                            restart=False):
    """
    Functions that runs the production run at NVT conditions.
    If a boxRadius is defined in the parameters section, a Flat-bottom harmonic restrains will be applied between
    the protein and the ligand

    :param equilibrationFiles: Tuple with the paths for the Amber topology file (prmtop) and the pdb for the system
    :type equilibrationFiles: Tuple
    :param workerNumber: Number of the subprocess
    :type workerNumber: int
    :param outputDir: path to the directory where the output will be written
    :type outputDir: str
    :param seed: Seed to use to generate the random numbers
    :type seed: int
    :param parameters: Object with the parameters for the simulation
    :type parameters: :py:class:`/simulationrunner/SimulationParameters` -- SimulationParameters object
    :param reportFileName: Name for the file where the energy report will be written
    :type reportFileName: str
    :param checkpoint: Path to the checkpoint from where the production run will be restarted (Optional)
    :type checkpoint: str
    :param ligandName: Code Name for the ligand
    :type ligandName: str
    :param replica_id: Id of the replica running
    :type replica_id: int
    :param trajsPerReplica: Number of trajectories per replica
    :type trajsPerReplica: int
    :param restart: Whether the simulation run has to be restarted or not
    :type restart: bool

    """
    deviceIndex = workerNumber
    workerNumber += replica_id * trajsPerReplica + 1
    prmtop, pdb = equilibrationFiles
    prmtop = app.AmberPrmtopFile(prmtop)
    trajName = os.path.join(
        outputDir, constants.AmberTemplates.trajectoryTemplate %
        (workerNumber, parameters.format))
    stateReporter = os.path.join(outputDir,
                                 "%s_%s" % (reportFileName, workerNumber))
    checkpointReporter = os.path.join(
        outputDir,
        constants.AmberTemplates.CheckPointReporterTemplate % workerNumber)
    lastStep = getLastStep(stateReporter)
    simulation_length = parameters.productionLength - lastStep
    # if the string is unicode the PDBReaders fails to read the file (this is
    # probably due to the fact that openmm was built with python2 in my
    # computer, will need to test thoroughly with python3)
    pdb = app.PDBFile(str(pdb))
    PLATFORM = mm.Platform_getPlatformByName(str(parameters.runningPlatform))
    if parameters.runningPlatform == "CUDA":
        platformProperties = {
            "Precision":
            "mixed",
            "DeviceIndex":
            getDeviceIndexStr(
                deviceIndex,
                parameters.devicesPerTrajectory,
                devicesPerReplica=parameters.maxDevicesPerReplica),
            "UseCpuPme":
            "false"
        }
    else:
        platformProperties = {}
    system = prmtop.createSystem(nonbondedMethod=app.PME,
                                 nonbondedCutoff=parameters.nonBondedCutoff *
                                 unit.angstroms,
                                 constraints=app.HBonds,
                                 removeCMMotion=True)
    system.addForce(
        mm.AndersenThermostat(parameters.Temperature * unit.kelvin,
                              1 / unit.picosecond))
    integrator = mm.VerletIntegrator(parameters.timeStep * unit.femtoseconds)
    system.addForce(
        mm.MonteCarloBarostat(1 * unit.bar,
                              parameters.Temperature * unit.kelvin))
    if parameters.boxRadius:
        group_ligand = []
        group_protein = []
        for atom in prmtop.topology.atoms():
            if atom.residue.name == ligandName:
                group_ligand.append(atom.index)
            elif atom.residue.name not in ("HOH", "Cl-", "Na+"):
                group_protein.append(atom.index)
        # Harmonic flat-bottom restrain for the ligand
        group_ligand = np.array(group_ligand)
        group_protein = np.array(group_protein)
        force = mm.CustomCentroidBondForce(
            2, 'step(distance(g1,g2)-r) * (k/2) * (distance(g1,g2)-r)^2')
        force.addGlobalParameter(
            "k", 5.0 * unit.kilocalories_per_mole / unit.angstroms**2)
        force.addGlobalParameter("r", parameters.boxRadius * unit.angstroms)
        force.addGroup(group_protein)
        force.addGroup(group_ligand)
        force.addBond(
            [0, 1], []
        )  # the first parameter is the list of indexes of the groups, the second is the list of perbondparameters
        system.addForce(force)
    simulation = app.Simulation(prmtop.topology,
                                system,
                                integrator,
                                PLATFORM,
                                platformProperties=platformProperties)
    simulation.context.setPositions(pdb.positions)

    if restart:
        with open(str(checkpoint), 'rb') as check:
            simulation.context.loadCheckpoint(check.read())
            stateData = open(str(stateReporter), "a")
    else:
        simulation.context.setVelocitiesToTemperature(
            parameters.Temperature * unit.kelvin, seed)
        stateData = open(str(stateReporter), "w")

    if parameters.format == "xtc":
        simulation.reporters.append(
            XTCReporter(str(trajName), parameters.reporterFreq,
                        append=restart))
    elif parameters.format == "dcd":
        simulation.reporters.append(
            app.DCDReporter(str(trajName),
                            parameters.reporterFreq,
                            append=restart,
                            enforcePeriodicBox=True))

    simulation.reporters.append(
        app.CheckpointReporter(str(checkpointReporter),
                               parameters.reporterFreq))
    simulation.reporters.append(
        CustomStateDataReporter(stateData,
                                parameters.reporterFreq,
                                step=True,
                                potentialEnergy=True,
                                temperature=True,
                                time_sim=True,
                                volume=True,
                                remainingTime=True,
                                speed=True,
                                totalSteps=parameters.productionLength,
                                separator="\t",
                                append=restart,
                                initialStep=lastStep))
    if workerNumber == 1:
        frequency = min(10 * parameters.reporterFreq,
                        parameters.productionLength)
        simulation.reporters.append(
            app.StateDataReporter(sys.stdout, frequency, step=True))
    simulation.step(simulation_length)
    stateData.close()
コード例 #11
0
def perform_md(
    checkpoint_in_file,
    checkpoint_out_file,
    csv_out_file,
    pdb_out_file,
    force_constant_ligand=1.0,
    md_len=1.0,
    force_constant_chunk=0.1,
    gpu_id=0,
):

    if os.path.isfile(checkpoint_out_file):
        return
    print("loading pickle")
    pickle_in = open("complex_system.pickle", "rb")
    pkl = pickle.load(pickle_in)
    combined_pmd = pkl[0]
    print(dir(combined_pmd))
    key_interaction = pkl[1:]
    pickle_in.close()
    MD_len = md_len * u.nanosecond
    sim_steps = round(MD_len / (0.002 * u.picosecond))
    # Platform definition

    platformProperties = {}
    if gpu_id != None:
        platform = mm.Platform_getPlatformByName("CUDA")
        platformProperties["CudaPrecision"] = "double"
    else:
        platform = mm.Platform_getPlatformByName("CPU")
    platformProperties["DeterministicForces"] = 'true'
    # Get indexes of heavy atoms in chunk
    Chunk_Heavy_Atoms = duck_stuff.getHeavyAtomsInSystem(combined_pmd)
    # Setting System
    system = combined_pmd.createSystem(
        nonbondedMethod=app.PME,
        nonbondedCutoff=9 * u.angstrom,
        constraints=app.HBonds,
        hydrogenMass=None,
    )
    # Apply force on all havy atoms of chunk and apply restraint for the ligand-chunk distance
    duck_stuff.applyHarmonicPositionalRestraints(system, force_constant_chunk,
                                                 combined_pmd.positions,
                                                 Chunk_Heavy_Atoms)
    duck_stuff.applyLigandChunkRestraint(
        system,
        force_constant_ligand,
        10.0,
        2 * u.angstrom,
        3 * u.angstrom,
        4 * u.angstrom,
        key_interaction,
    )
    # Integrator
    integrator = mm.LangevinIntegrator(300 * u.kelvin, 4 / u.picosecond,
                                       0.002 * u.picosecond)
    # Setting Simulation object and loading the checkpoint
    simulation = app.Simulation(combined_pmd.topology, system, integrator,
                                platform, platformProperties)
    simulation.loadCheckpoint(checkpoint_in_file)
    # Simulation reporters
    simulation.reporters.append(
        app.StateDataReporter(
            csv_out_file,
            2000,
            step=True,
            time=True,
            totalEnergy=True,
            kineticEnergy=True,
            potentialEnergy=True,
            temperature=True,
            density=True,
            progress=True,
            totalSteps=sim_steps,
            speed=True,
        ))
    simulation.reporters.append(app.DCDReporter("md.dcd", 100000))
    # Production
    simulation.step(sim_steps)
    # Save state in checkpoint file and save coordinates in PDB file
    state = simulation.context.getState(getPositions=True, getVelocities=True)
    positions = state.getPositions()
    app.PDBFile.writeFile(simulation.topology, positions,
                          open(pdb_out_file, "w"))
    simulation.saveCheckpoint(checkpoint_out_file)
コード例 #12
0
ファイル: duck_vernalis.py プロジェクト: MaciejMajew/OpenDUck
Plot = False


###############################################################################    

######Conditional Import####
#the 

if Plot == True:
    import matplotlib.pyplot as plt 
    import seaborn as sns
    sns.set_style('ticks')

#Platform definition

platform = mm.Platform_getPlatformByName("CUDA")
platformProperties = {}
platformProperties['CudaPrecision'] = 'mixed'
platformProperties['CudaDeviceIndex'] = '0'

#Read files

prmtopName = 'system_solv.prmtop'
inpcrdName = 'system_solv.inpcrd'

prmtop = app.AmberPrmtopFile(prmtopName)
inpcrd = app.AmberInpcrdFile(inpcrdName)

#Minimization

logging.info('Minimising...')
コード例 #13
0
def simulate_explicit(
        pdb_file,
        top_file,
        check_point=None,
        GPU_index=0,
        output_traj="output.dcd",
        output_log="output.log",
        output_cm=None,
        temperature=300.,
        # ion_strength=0.,
        report_time=10,
        sim_time=10):
    """
    Start and run an OpenMM NPT simulation with Langevin integrator at 2 fs 
    time step and 300 K. The cutoff distance for nonbonded interactions were 
    set at 1.0 nm, which commonly used along with Amber force field. Long-range
    nonbonded interactions were handled with PME. 
    Water molecules and ions will be added to the system. 
    Parameters
    ----------
    top_file : topology file (.top, .prmtop, ...)
        This is the topology file discribe all the interactions within the MD 
        system. 
    pdb_file : coordinates file (.gro, .pdb, ...)
        This is the molecule configuration file contains all the atom position
        and PBC (periodic boundary condition) box in the system. 
    GPU_index : Int or Str 
        The device # of GPU to use for running the simulation. 
        Use Strings, '0,1' for example, to use more than 1 GPU
    output_traj : the trajectory file (.dcd)
        This is the file stores all the coordinates information of the MD 
        simulation results. 
    output_log : the log file (.log) 
        This file stores the MD simulation status, such as steps, time, 
        potential energy, temperature, speed, etc. 
    temperature : float, unit K 
        The temperature the simulation will be running under 
    ion_strength : float
        The ion concentration in the system, (to be implemented)
    report_time : 10 ps
        The frequency that program writes its information to the output in 
        picoseconds, 10^(-12) s
    sim_time : 10 ns
        The timespan of the simulation trajectory in nanoseconds, 10^(-9) s
    """

    top = pmd.load_file(top_file, xyz=pdb_file)

    system = top.createSystem(nonbondedMethod=app.PME,
                              nonbondedCutoff=1 * u.nanometer,
                              constraints=app.HBonds)
    dt = 0.002 * u.picoseconds
    integrator = omm.LangevinIntegrator(temperature * u.kelvin,
                                        1 / u.picosecond, dt)
    system.addForce(omm.MonteCarloBarostat(1 * u.bar, temperature * u.kelvin))

    try:
        platform = omm.Platform_getPlatformByName("CUDA")
        properties = {'DeviceIndex': str(GPU_index), 'CudaPrecision': 'mixed'}
    except Exception:
        platform = omm.Platform_getPlatformByName("OpenCL")
        properties = {'DeviceIndex': str(GPU_index)}

    simulation = app.Simulation(top.topology, system, integrator, platform,
                                properties)

    simulation.context.setPositions(top.positions)

    simulation.minimizeEnergy()

    report_time = report_time * u.picoseconds
    report_freq = int(report_time / dt)
    simulation.context.setVelocitiesToTemperature(temperature * u.kelvin,
                                                  np.random.randint(1, 10000))
    simulation.reporters.append(app.DCDReporter(output_traj, report_freq))
    if output_cm:
        simulation.reporters.append(ContactMapReporter(output_cm, report_freq))
    simulation.reporters.append(
        app.StateDataReporter(output_log,
                              report_freq,
                              step=True,
                              time=True,
                              speed=True,
                              potentialEnergy=True,
                              temperature=True,
                              totalEnergy=True))
    simulation.reporters.append(
        app.CheckpointReporter('checkpnt.chk', report_freq))

    if check_point:
        simulation.loadCheckpoint(check_point)
    sim_time = sim_time * u.nanoseconds
    nsteps = int(sim_time / dt)
    simulation.step(nsteps)
コード例 #14
0
def openmm_simulate_amber_explicit(
    pdb_file,
    top_file=None,
    check_point=None,
    GPU_index=0,
    output_traj="output.dcd",
    output_log="output.log",
    output_cm=None,
    report_time=10 * u.picoseconds,
    sim_time=10 * u.nanoseconds,
    reeval_time=None,
):
    """
    Start and run an OpenMM NPT simulation with Langevin integrator at 2 fs 
    time step and 300 K. The cutoff distance for nonbonded interactions were 
    set at 1.0 nm, which commonly used along with Amber force field. Long-range
    nonbonded interactions were handled with PME. 

    Parameters
    ----------
    top_file : topology file (.top, .prmtop, ...)
        This is the topology file discribe all the interactions within the MD 
        system. 

    pdb_file : coordinates file (.gro, .pdb, ...)
        This is the molecule configuration file contains all the atom position
        and PBC (periodic boundary condition) box in the system. 

    GPU_index : Int or Str 
        The device # of GPU to use for running the simulation. Use Strings, '0,1'
        for example, to use more than 1 GPU

    output_traj : the trajectory file (.dcd)
        This is the file stores all the coordinates information of the MD 
        simulation results. 

    output_log : the log file (.log) 
        This file stores the MD simulation status, such as steps, time, potential
        energy, temperature, speed, etc.

    report_time : 10 ps
        The program writes its information to the output every 10 ps by default 

    sim_time : 10 ns
        The timespan of the simulation trajectory
    """

    # set up save dir for simulation results
    work_dir = os.getcwd()
    time_label = int(time.time())
    omm_path = create_md_path(time_label)
    print(f"Running simulation at {omm_path}")

    # setting up running path
    os.chdir(omm_path)

    top = pmd.load_file(top_file, xyz=pdb_file)

    system = top.createSystem(nonbondedMethod=app.PME,
                              nonbondedCutoff=1 * u.nanometer,
                              constraints=app.HBonds)
    dt = 0.002 * u.picoseconds
    integrator = omm.LangevinIntegrator(300 * u.kelvin, 1 / u.picosecond, dt)
    system.addForce(omm.MonteCarloBarostat(1 * u.bar, 300 * u.kelvin))

    try:
        platform = omm.Platform_getPlatformByName("CUDA")
        properties = {'DeviceIndex': str(GPU_index), 'CudaPrecision': 'mixed'}
    except Exception:
        platform = omm.Platform_getPlatformByName("OpenCL")
        properties = {'DeviceIndex': str(GPU_index)}

    simulation = app.Simulation(top.topology, system, integrator, platform,
                                properties)

    # simulation.context.setPositions(top.positions)
    if pdb.get_coordinates().shape[0] == 1:
        simulation.context.setPositions(pdb.positions)
        shutil.copy2(pdb_file, './')
    else:
        positions = random.choice(pdb.get_coordinates())
        simulation.context.setPositions(positions / 10)
        #parmed \AA to OpenMM nm
        pdb.write_pdb('start.pdb', coordinates=positions)

    simulation.minimizeEnergy()
    simulation.context.setVelocitiesToTemperature(300 * u.kelvin,
                                                  random.randint(1, 10000))
    simulation.step(int(100 * u.picoseconds / (2 * u.femtoseconds)))

    report_freq = int(report_time / dt)
    simulation.reporters.append(app.DCDReporter(output_traj, report_freq))
    if output_cm:
        simulation.reporters.append(ContactMapReporter(output_cm, report_freq))
    simulation.reporters.append(
        app.StateDataReporter(output_log,
                              report_freq,
                              step=True,
                              time=True,
                              speed=True,
                              potentialEnergy=True,
                              temperature=True,
                              totalEnergy=True))
    simulation.reporters.append(
        app.CheckpointReporter('checkpnt.chk', report_freq))

    if check_point:
        simulation.loadCheckpoint(check_point)
    nsteps = int(sim_time / dt)
    simulation.step(nsteps)

    if reeval_time:
        nsteps = int(reeval_time / dt)
        niter = int(sim_time / reeval_time)
        for i in range(niter):
            if os.path.exists('../halt'):
                return
            elif os.path.exists('new_pdb'):
                print("Found new.pdb, starting new sim...")

                # cleaning up old runs
                del simulation
                # starting new simulation with new pdb
                with open('new_pdb', 'r') as fp:
                    new_pdb = fp.read().split()[0]
                os.chdir(work_dir)
                openmm_simulate_amber_explicit(
                    new_pdb,
                    top_file=top_file,
                    check_point=None,
                    GPU_index=GPU_index,
                    output_traj=output_traj,
                    output_log=output_log,
                    output_cm=output_cm,
                    report_time=report_time,
                    sim_time=sim_time,
                    reeval_time=reeval_time,
                )
            else:
                simulation.step(nsteps)
    else:
        nsteps = int(sim_time / dt)
        simulation.step(nsteps)

    os.chdir(work_dir)
    if not os.path.exists('../halt'):
        openmm_simulate_amber_explicit(
            pdb_file,
            top_file=top_file,
            check_point=None,
            GPU_index=GPU_index,
            output_traj=output_traj,
            output_log=output_log,
            output_cm=output_cm,
            report_time=report_time,
            sim_time=sim_time,
            reeval_time=reeval_time,
        )
    else:
        return
コード例 #15
0
ファイル: equlibrate.py プロジェクト: simonbray/duck
def do_equlibrate(force_constant_equilibrate=1.0, gpu_id=0):
    # Find the interations
    keyInteraction = cal_ints.find_interaction()
    # Platform definition
    platform = mm.Platform_getPlatformByName("OpenCL")
    platformProperties = {}
    platformProperties['OpenCLPrecision'] = 'mixed'
    platformProperties["OpenCLDeviceIndex"] = gpu_id
    print("loading pickle")
    pickle_in = open('complex_system.pickle', 'rb')
    combined_pmd = pickle.load(pickle_in)[0]
    combined_pmd.symmetry = None
    pickle_in.close()
    ##################
    ##################
    #  Minimisation  #
    ##################
    ##################
    print('Minimising...')
    # Define system
    system = combined_pmd.createSystem(nonbondedMethod=app.PME,
                                       nonbondedCutoff=9 * u.angstrom)
    # Get indexes of heavy atoms in chunk
    Chunk_Heavy_Atoms = duck_stuff.getHeavyAtomsInSystem(combined_pmd)
    # Apply force on all havy atoms of chunk
    duck_stuff.applyHarmonicPositionalRestraints(system,
                                                 force_constant_equilibrate,
                                                 combined_pmd.positions,
                                                 Chunk_Heavy_Atoms)
    # Integrator
    integrator = mm.VerletIntegrator(1 * u.femtosecond)
    # Define Simulation
    simulation = app.Simulation(combined_pmd.topology, system, integrator,
                                platform, platformProperties)
    simulation.context.setPositions(combined_pmd.positions)
    print(simulation.context.getPlatform().getName())
    for key in simulation.context.getPlatform().getPropertyNames():
        print(
            key,
            simulation.context.getPlatform().getPropertyValue(
                simulation.context, key))
    # Minimizing energy
    simulation.minimizeEnergy(maxIterations=1000)
    # Saving minimised positions
    positions = simulation.context.getState(getPositions=True).getPositions()
    app.PDBFile.writeFile(simulation.topology, positions,
                          open('minimisation.pdb', 'w'))
    ##########################
    ##########################
    # Equlibration - heating #
    ##########################
    ##########################
    #new minimised positions, however using old restraints
    # Define new system
    system = combined_pmd.createSystem(nonbondedMethod=app.PME,
                                       nonbondedCutoff=9 * u.angstrom,
                                       constraints=app.HBonds,
                                       hydrogenMass=None)
    # Apply force on all havy atoms of chunk and apply restraint for the ligand-chunk distance
    duck_stuff.applyHarmonicPositionalRestraints(system,
                                                 force_constant_equilibrate,
                                                 combined_pmd.positions,
                                                 Chunk_Heavy_Atoms)
    duck_stuff.applyLigandChunkRestraint(system, force_constant_equilibrate,
                                         10.0, 2 * u.angstrom, 3 * u.angstrom,
                                         4 * u.angstrom, keyInteraction)
    # Intergator
    integrator = mm.LangevinIntegrator(300 * u.kelvin, 4 / u.picosecond,
                                       0.002 * u.picosecond)
    # Define Simulation
    simulation = app.Simulation(combined_pmd.topology, system, integrator,
                                platform, platformProperties)
    simulation.context.setPositions(
        positions)  #changing coordintes to minimized
    # Reporters
    simulation.reporters.append(
        app.StateDataReporter("heating.csv",
                              1000,
                              time=True,
                              potentialEnergy=True,
                              temperature=True,
                              density=True,
                              remainingTime=True,
                              speed=True,
                              totalSteps=50000))
    simulation.reporters.append(app.DCDReporter("heating.dcd", 1000))
    # Heating the system
    print("Heating ... ")
    simulation.step(50000)  # 0.01 ns
    # Save the positions and velocities
    positions = simulation.context.getState(getPositions=True).getPositions()
    velocities = simulation.context.getState(
        getVelocities=True).getVelocities()
    app.PDBFile.writeFile(simulation.topology, positions,
                          open('heating_final.pdb', 'w'))
    #clear reporters
    simulation.reporters = []
    ##########################
    ##########################
    # Equlibration - density #
    ##########################
    ##########################
    simulation = duck_stuff.setUpNPTEquilibration(system, combined_pmd,
                                                  platform, platformProperties,
                                                  positions, velocities)
    # Reporters
    simulation.reporters.append(
        app.StateDataReporter("density.csv",
                              1000,
                              time=True,
                              potentialEnergy=True,
                              temperature=True,
                              density=True,
                              remainingTime=True,
                              speed=True,
                              totalSteps=50000))
    # Correcting the density
    print("Correcting density")
    simulation.step(50000)  # 0.01 ns
    # Save the positions and velocities
    positions = simulation.context.getState(getPositions=True).getPositions()
    velocities = simulation.context.getState(
        getVelocities=True).getVelocities()
    app.PDBFile.writeFile(simulation.topology, positions,
                          open('density_final.pdb', 'w'))
    #saving simulation stage
    checkpoint = 'equil.chk'
    simulation.saveCheckpoint(checkpoint)
    return [checkpoint]
コード例 #16
0
import numpy as np
import pandas as pd
import simtk.openmm as mm
from simtk import unit as u
from openmmtools import hmc_integrators, testsystems

opencl = mm.Platform_getPlatformByName("OpenCL")
cuda = mm.Platform_getPlatformByName("CUDA")
cpu = mm.Platform_getPlatformByName("CPU")

#platform = cpu
#platform = opencl
platform = cuda


n_steps = 5000
temperature = 300. * u.kelvin

#testsystem = testsystems.WaterBox(box_edge=3.18 * u.nanometers)  # Around 1060 molecules of water
testsystem = testsystems.FlexibleWaterBox(box_edge=3.18 * u.nanometers)  # Around 1060 molecules of water
#testsystem = testsystems.AlanineDipeptideExplicit()
system = testsystem.system

integrator = mm.LangevinIntegrator(temperature, 0.25 / u.picoseconds, 0.25 * u.femtoseconds)
#integrator = hmc_integrators.RandomTimestepGHMC(temperature, 12, 0.25 * u.femtoseconds)
context = mm.Context(testsystem.system, integrator, platform)
context.setPositions(testsystem.positions)
context.setVelocitiesToTemperature(temperature)
integrator.step(5000)
positions = context.getState(getPositions=True).getPositions()