예제 #1
0
파일: util.py 프로젝트: giorginolab/miniomm
def add_reporters(simulation, trajectory_file, log_every, save_every,
                  total_steps, continuing, checkpoint_file):
    print(
        f"Reporting every {log_every} steps and checkpointing on {checkpoint_file} every {save_every} steps."
    )
    op = "append" if continuing else "write"
    print(f"Will {op} to trajectory file {trajectory_file}.\n")

    basename = "output"
    fp = open(f"{basename}.log", "a" if continuing else "w")
    simulation.reporters.append(
        app.DCDReporter(trajectory_file,
                        save_every,
                        append=continuing,
                        enforcePeriodicBox=False))
    simulation.reporters.append(
        app.CheckpointReporter(checkpoint_file, save_every))
    simulation.reporters.append(StdoutLogReporter(log_every, total_steps))
    simulation.reporters.append(
        app.StateDataReporter(fp,
                              log_every,
                              step=True,
                              time=True,
                              potentialEnergy=True,
                              kineticEnergy=True,
                              totalEnergy=True,
                              temperature=True,
                              volume=True,
                              progress=True,
                              remainingTime=True,
                              speed=True,
                              totalSteps=total_steps,
                              separator='\t'))
예제 #2
0
def build_openmm_simulation(structure,
                            temperature=300 * unyt.Kelvin,
                            pressure=1 * unyt.atm,
                            random_seed=42,
                            **kwargs):
    """ Build OpenMM simulation from a parmed.Structure 
    
    
    Notes
    -----
    OpenMM does not compute a virial, which prevents us from
    computing and reporting the pressure of a system. 
    However, the montecarlobarostat does allow for a robust method to sample
    under various pressures.
    """

    # First convert unyt units into something consistent for OpenMM
    temperature.convert_to_units(unyt.Kelvin)
    if pressure is not None:
        pressure.convert_to_units(unyt.bar)

    # hardcoded timestep - probably do not want to expose
    timestep = 2.0 * unyt.fs
    timestep.convert_to_units(unyt.ps)

    integrator = openmm.LangevinIntegrator(float(temperature.value),
                                           float((1.0 / unyt.ps).value),
                                           float(timestep.value))
    integrator.setRandomNumberSeed(random_seed)

    system = structure.createSystem(nonbondedMethod=app.PME,
                                    constraints=app.AllBonds,
                                    nonbondedCutoff=14.0 * unit.angstroms)
    if pressure is not None:
        barostat = openmm.MonteCarloBarostat(float(pressure.value),
                                             float(temperature.value), 25)
        system.addForce(barostat)

    sim = app.Simulation(structure.topology, system, integrator)
    sim.context.setPositions(structure.positions)

    sim.reporters.append(
        app.StateDataReporter(open('thermo.log', 'w'),
                              5000,
                              step=True,
                              time=True,
                              potentialEnergy=True,
                              temperature=True,
                              volume=True,
                              speed=True))
    sim.reporters.append(app.DCDReporter('trajectory.dcd', 5000))
    sim.reporters.append(app.CheckpointReporter('trajectory.chk', 5000))

    return sim
예제 #3
0
    def set_up_reporters(self, simulation):
        """
        Sets up reporters according to options 
        specified by arguments in md_param.
        See keywords in the Molecular Dynamics section of 
        the manual for more information.
        
        Parameters
        ----------
        simulation : OpenMM simulation object
            Adds reporters to simulation object
        """

        pot = False
        kin = False
        enrgy = False
        temp = False
        den = False

        if self.return_trajectory_interval != 0:
            if self.trajectory_format == 'NetCDF':
                simulation.reporters.append(
                    NetCDFReporter(self.return_trajectory_filename,
                                   self.return_trajectory_interval))

        if self.return_checkpoint_interval != 0:
            simulation.reporters.append(
                OM_app.CheckpointReporter(self.return_checkpoint_filename,
                                          self.return_checkpoint_interval))

        if self.return_info:

            if 'potentialEnergy' in self.return_info:
                pot = True
            if 'kineticEnergy' in self.return_info:
                kin = True
            if 'totalEnergy' in self.return_info:
                enrgy = True
            if 'temperature' in self.return_info:
                temp = True
            if 'density' in self.return_info:
                den = True

            simulation.reporters.append(
                OM_app.StateDataReporter(self.return_info_filename,
                                         self.return_info_interval,
                                         step=True,
                                         potentialEnergy=pot,
                                         kineticEnergy=kin,
                                         totalEnergy=enrgy,
                                         temperature=temp,
                                         density=den))
예제 #4
0
    def test_1(self):
        file = tempfile.NamedTemporaryFile()
        self.simulation.reporters.append(app.CheckpointReporter(file, 1))
        self.simulation.step(1)

        # get the current positions
        positions = self.simulation.context.getState(
            getPositions=True).getPositions(asNumpy=True)._value
        # now set the positions into junk...
        self.simulation.context.setPositions(np.random.random(positions.shape))
        # then reload the right positions from the checkpoint
        with open(file.name, 'rb') as f:
            self.simulation.context.loadCheckpoint(f.read())
        file.close()

        newPositions = self.simulation.context.getState(
            getPositions=True).getPositions(asNumpy=True)._value
        np.testing.assert_array_equal(positions, newPositions)
예제 #5
0
def simulation(filepath, outpath, nsteps, gpu=True):
    prmtop = app.AmberPrmtopFile(f'{filepath}.prmtop')
    inpcrd = app.AmberInpcrdFile(f'{filepath}.inpcrd')
    forcefield = app.ForceField('amber14-all.xml', 'amber14/tip3p.xml')
    modeller = app.Modeller(prmtop.topology, inpcrd.positions)
    modeller.addSolvent(forcefield, padding=1.4 * unit.nanometer)
    system = forcefield.createSystem(modeller.topology,
                                     nonbondedMethod=app.PME,
                                     nonbondedCutoff=1.0 * unit.nanometer,
                                     constraints=app.HBonds)
    integrator = mm.LangevinIntegrator(310.15 * unit.kelvin,
                                       1.0 / unit.picosecond,
                                       0.002 * unit.picosecond)
    if gpu:
        platform = 'CUDA'
    else:
        platform = 'CPU'
    platform = mm.Platform.getPlatformByName(platform)
    properties = {'Precision': 'double'}
    simulation = app.Simulation(modeller.topology, system, integrator,
                                platform, properties)
    simulation.context.setPositions(modeller.positions)
    simulation.minimizeEnergy()
    if nsteps != 0:
        simulation.reporters.append(
            app.DCDReporter(f'{outpath}/traj.dcd', 25000))
        simulation.reporters.append(
            app.StateDataReporter(f'{outpath}/sim.log',
                                  25000,
                                  step=True,
                                  potentialEnergy=True,
                                  temperature=True))
        simulation.reporters.append(
            app.CheckpointReporter(f'{outpath}/traj.chk', 250000))
        simulation.step(nsteps)
        positions = simulation.context.getState(
            getPositions=True).getPositions()
        app.PDBFile.writeFile(simulation.topology, positions,
                              open(f'{outpath}/output.pdb', 'w'))
    potential = simulation.context.getState(
        getEnergy=True).getPotentialEnergy().value_in_unit(unit.kilojoule /
                                                           unit.mole)
    return potential
예제 #6
0
def simulation_ESMACS(filepath, outpath, nsteps):
    prmtop = app.AmberPrmtopFile(f'{filepath}_sol.prmtop')
    inpcrd = app.AmberInpcrdFile(f'{filepath}_sol.inpcrd')
    system = prmtop.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=1.0*unit.nanometer,
            constraints=app.HBonds)
    integrator = mm.LangevinIntegrator(300*unit.kelvin, 1.0/unit.picosecond, 0.002*unit.picosecond)
    platform = mm.Platform.getPlatformByName('CUDA')
    properties = {'Precision': 'double'}
    simulation = app.Simulation(prmtop.topology, system, integrator, platform, properties)
    simulation.context.setPositions(inpcrd.positions)
    if inpcrd.boxVectors is not None:
        simulation.context.setPeriodicBoxVectors(*inpcrd.boxVectors)
    simulation.minimizeEnergy()
    simulation.reporters.append(app.DCDReporter(f'{outpath}/traj.dcd', 50000)) # snapshot at every 100 ps 
    simulation.reporters.append(app.StateDataReporter(f'{outpath}/sim.log', 5000, step=True,
    potentialEnergy=True, temperature=True)) # reporting at every 10 ps
    simulation.reporters.append(app.CheckpointReporter(f'{outpath}/traj.chk', 250000)) # checkpoint at every 0.5 ns
    simulation.step(nsteps)
    positions = simulation.context.getState(getPositions=True).getPositions()
    app.PDBFile.writeFile(simulation.topology, positions, open(f'{outpath}/output.pdb', 'w'))
    def test_1(self):
        file = tempfile.NamedTemporaryFile(delete=False)
        self.simulation.reporters.append(app.CheckpointReporter(file, 1))
        self.simulation.step(1)

        # get the current positions
        positions = self.simulation.context.getState(
            getPositions=True).getPositions()

        # now set the positions into junk...
        self.simulation.context.setPositions([mm.Vec3(0, 0, 0)] *
                                             len(positions))

        # then reload the right positions from the checkpoint
        file.close()
        with open(file.name, 'rb') as f:
            self.simulation.context.loadCheckpoint(f.read())
        os.unlink(file.name)

        newPositions = self.simulation.context.getState(
            getPositions=True).getPositions()
        self.assertSequenceEqual(positions, newPositions)
예제 #8
0
def simulation(filepath, outpath, nsteps):
    prmtop = app.AmberPrmtopFile(f'{filepath}.prmtop')
    inpcrd = app.AmberInpcrdFile(f'{filepath}.inpcrd')
    forcefield = app.ForceField('amber14-all.xml', 'amber14/tip3p.xml')  # gaff/gaff2/other ligand ff also required here or it may complain for 'com' or 'lig' 
    modeller = app.Modeller(prmtop.topology, inpcrd.positions)
    modeller.addSolvent(forcefield, padding=1.4*unit.nanometer)
    system = forcefield.createSystem(modeller.topology, nonbondedMethod=app.PME, nonbondedCutoff=1.0*unit.nanometer,
            constraints=app.HBonds)
    integrator = mm.LangevinIntegrator(300*unit.kelvin, 1.0/unit.picosecond, 0.002*unit.picosecond)
    platform = mm.Platform.getPlatformByName('CUDA')
    properties = {'Precision': 'double'}
    simulation = app.Simulation(modeller.topology, system, integrator, platform, properties)
    simulation.context.setPositions(modeller.positions)
    simulation.minimizeEnergy()
    if nsteps != 0:
        simulation.reporters.append(app.DCDReporter(f'{outpath}_traj.dcd', 25000)) # snapshot at every 50 ps 
        simulation.reporters.append(nosol.NewPDBReporter(f'{outpath}_system_nosol.pdb', 25000)) # snapshot at every 50 ps 
        simulation.reporters.append(app.StateDataReporter(f'{outpath}_sim.log', 25000, step=True,
        potentialEnergy=True, temperature=True)) # reporting at every 50 ps
        simulation.reporters.append(app.CheckpointReporter(f'{outpath}_traj.chk', 250000)) # checkpoint at every 0.5 ns
        simulation.step(nsteps)
        positions = simulation.context.getState(getPositions=True).getPositions()
        app.PDBFile.writeFile(simulation.topology, positions, open(f'{outpath}_output.pdb', 'w'))

# Return potential energy at the end of the simulation
#    potential = simulation.context.getState(getEnergy=True).getPotentialEnergy().value_in_unit(unit.kilojoule/unit.mole)
#    return potential

# Return mean potential energy during the simulation
    with open(f'{outpath}_sim.log','r') as log_file: 
        lines = log_file.readlines()
        mean = 0
    for i in range(1,len(lines)):
        potential = float(lines[i].split(',')[1])
        mean = mean + potential
    potential = mean/(len(lines)-1)
    return potential
예제 #9
0
sim.reporters.append(
        pmd.openmm.StateDataReporter(opt.output, reportInterval=opt.interval,
                        volume=True,density=True,separator='\t')
)
sim.reporters.append(
        pmd.openmm.ProgressReporter(opt.output + '.info', opt.interval, opt.num_steps)
)
sim.reporters.append(
        pmd.openmm.NetCDFReporter(opt.trajectory, opt.interval*10)
)
sim.reporters.append(
        pmd.openmm.RestartReporter(opt.restart, opt.interval*100, netcdf=True)
)
if opt.checkpoint is not None:
    sim.reporters.append(
            app.CheckpointReporter(opt.checkpoint, opt.interval*10)
    )

if opt.state is not None:
    print('Setting coordinates and velocities from restart file %s' %
        opt.state); sys.stdout.flush()

    if opt.state[-3:] == 'xml':
        with open(opt.state, 'r') as f:
            sim.context.setState(mm.XmlSerializer.deserialize(f.read()))
    elif opt.state[-3:] == 'chk':
        sim.loadCheckpoint(opt.state)
    else:
#       jason's code that is supposed to work for any restart file type:
        rst = pmd.load_file(opt.state)
        sim.context.setPositions(rst.coordinates[-1]*u.angstroms)
예제 #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
        app.StateDataReporter(stdout,
                              10000,
                              step=True,
                              potentialEnergy=True,
                              kineticEnergy=True,
                              temperature=True,
                              volume=True,
                              density=True,
                              progress=True,
                              remainingTime=True,
                              speed=True,
                              totalSteps=20000000,
                              separator=','))

simulation.reporters.append(
    app.CheckpointReporter(pdbname[:-4] + '_checkpnt%s.chk' % sim_string,
                           10000))

if verbose: print('Running Production...')

if do_sim_chunks:
    nsteps_chunks = nsteps / 10000
    chunk_size = nsteps / nsteps_chunks
else:
    nsteps_chunks = 1
    chunk_size = nsteps
#print (nsteps_chunks, chunk_size)

for i in xrange(nsteps_chunks):

    simulation.step(chunk_size)
예제 #12
0
    wfreq = cmd.wfreq if cmd.wfreq is not None else 2000
    pfreq = cmd.pfreq if cmd.pfreq is not None else 2000
else:
    # Time step is 2 fs
    # 500.000 steps give 1 ns
    wfreq = cmd.wfreq if cmd.wfreq is not None else 5000
    pfreq = cmd.pfreq if cmd.pfreq is not None else 5000

run_dcd = rootname + '.dcd'
run_dcd = get_part_filename(run_dcd)

run_log = rootname + '.log'
run_log = get_part_filename(run_log)

dcd = app.DCDReporter(run_dcd, wfreq)
cpt = app.CheckpointReporter(run_cpt, wfreq)

state = app.StateDataReporter(run_log,
                              pfreq,
                              step=True,
                              time=True,
                              progress=True,
                              potentialEnergy=True,
                              kineticEnergy=True,
                              temperature=True,
                              remainingTime=True,
                              speed=True,
                              totalSteps=n_steps,
                              separator='\t')

simulation.reporters.append(dcd)
예제 #13
0
    ##
    # Setup reporters: logger and checkpointing
    reporters.append(
        app.StateDataReporter(logfile,
                              5000,
                              step=True,
                              time=True,
                              potentialEnergy=True,
                              kineticEnergy=True,
                              totalEnergy=True,
                              temperature=True,
                              speed=True,
                              separator='\t'))

    reporters.append(app.CheckpointReporter(
        cpt_file, 5000))  # Save every 10 ps # noqa: E501

    ##
    # Equilibration
    nvt_state = '{}_NVT.xml'.format(rootname)
    if os.path.isfile(nvt_state):
        logging.info('Found saved NVT equilibrated state: {}'.format(
            nvt_state))  # noqa: E501
        simulation.loadState(nvt_state)
    else:
        time_in_ns = user_args.equilibration
        n_of_steps = time_in_ns / (0.002 / 1000)
        logging.info('NPT equilibration system at 300K for {} ns'.format(
            time_in_ns))  # noqa: E501
        simulation.integrator.setTemperature(md_temp)
        simulation.step(n_of_steps)
예제 #14
0
def main(
    paramfile='params.in',
    overrides={},
    quiktest=False,
    deviceid=None,
    progressreport=True,
    soluteRes=[0],
    lambdaLJ=1.0,
    lambdaQ=1.0
):  #simtime=2.0, T=298.0, NPT=True, LJcut=10.0, tail=True, useLJPME=False, rigidH2O=True, device=0, quiktest=False):
    # === PARSE === #
    args = mdparse.SimulationOptions(paramfile, overrides)

    # Files
    gromacs.GROMACS_TOPDIR = args.topdir
    top_file = args.topfile
    box_file = args.grofile
    defines = {}
    cont = args.cont

    args.force_active('chkxml',
                      val='chk_{:02n}.xml'.format(cont),
                      msg='first one')
    args.force_active('chkpdb',
                      val='chk_{:02n}.pdb'.format(cont),
                      msg='first one')
    if cont > 0:
        args.force_active('incoord',
                          val='chk_{:02n}.xml'.format(cont - 1),
                          msg='continuing')
        args.force_active('outpdb',
                          val='output_{:02n}.pdb'.format(cont),
                          msg='continuing')
        args.force_active('outnetcdf',
                          val='output_{:02n}.nc'.format(cont),
                          msg='continuing')
        args.force_active('logfile',
                          val='thermo.log_{:02n}'.format(cont),
                          msg='continuing')
        args.force_active('outdcd',
                          val='output_{:02n}.dcd'.format(cont),
                          msg='continuing')

    incoord = args.incoord
    out_pdb = args.outpdb
    out_netcdf = args.outnetcdf
    out_dcd = args.outdcd
    molecTopology = 'topology.pdb'
    out_nowater = 'output_nowater.nc'
    out_nowater_dcd = 'output_nowater.dcd'
    logfile = args.logfile
    checkpointxml = args.chkxml
    checkpointpdb = args.chkpdb
    checkpointchk = 'chk_{:02n}.chk'.format(cont)

    # Parameters
    #Temp            = args.temperature        #K
    #Pressure = 1      #bar
    #barostatfreq    = 25 #time steps
    #fric            = args.collision_rate     #1/ps

    dt = args.timestep  #fs
    if args.use_fs_interval:
        reportfreq = int(args.report_interval / dt)
        netcdffreq = int(args.netcdf_report_interval / dt)  #5e4
        dcdfreq = int(args.dcd_report_interval / dt)
        pdbfreq = int(args.pdb_report_interval / dt)
        checkfreq = int(args.checkpoint_interval / dt)
        #simtime    = int( simtime ) #nanoseconds; make sure division is whole... no remainders...
        blocksteps = int(args.block_interval /
                         dt)  #1e6, steps per block of simulation
        nblocks = args.nblocks  #aiming for 1 block is 1ns
    else:
        reportfreq = args.report_interval
        netcdffreq = args.netcdf_report_interval
        dcdfreq = args.dcd_report_interval
        pdbfreq = args.pdb_report_interval
        checkfreq = args.checkpoint_interval
        blocksteps = args.block_interval
        nblocks = args.nblocks

    if quiktest == True:
        reportfreq = 1
        blocksteps = 10
        nblocks = 2

    # === Start Making System === #
    start = time.time()
    top = gromacs.GromacsTopologyFile(top_file, defines=defines)
    gro = gromacs.GromacsGroFile.parse(box_file)
    top.box = gro.box
    logger.info("Took {}s to create topology".format(time.time() - start))
    print(top)

    constr = {
        None: None,
        "None": None,
        "HBonds": app.HBonds,
        "HAngles": app.HAngles,
        "AllBonds": app.AllBonds
    }[args.constraints]
    start = time.time()
    system = top.createSystem(nonbondedMethod=app.PME,
                              ewaldErrorTolerance=args.ewald_error_tolerance,
                              nonbondedCutoff=args.nonbonded_cutoff *
                              u.nanometers,
                              rigidWater=args.rigid_water,
                              constraints=constr)
    logger.info("Took {}s to create system".format(time.time() - start))

    nbm = {
        "NoCutoff": mm.NonbondedForce.NoCutoff,
        "CutoffNonPeriodic": mm.NonbondedForce.CutoffNonPeriodic,
        "Ewald": mm.NonbondedForce.Ewald,
        "PME": mm.NonbondedForce.PME,
        "LJPME": mm.NonbondedForce.LJPME
    }[args.nonbonded_method]

    ftmp = [
        f for ii, f in enumerate(system.getForces())
        if isinstance(f, mm.NonbondedForce)
    ]
    fnb = ftmp[0]
    fnb.setNonbondedMethod(nbm)
    logger.info("Nonbonded method ({},{})".format(args.nonbonded_method,
                                                  fnb.getNonbondedMethod()))
    if (not args.dispersion_correction) or (args.nonbonded_method == "LJPME"):
        logger.info("Turning off tail correction...")
        fnb.setUseDispersionCorrection(False)

    logger.info("Check dispersion correction flag: {}".format(
        fnb.getUseDispersionCorrection()))

    # --- execute custom forcefield code ---
    """
    if customff:
        logger.info("Using customff: [{}]".format(customff))
        with open(customff,'r') as f:
            ffcode = f.read()
        exec(ffcode,globals(),locals()) #python 3, need to pass in globals to allow exec to modify them (i.e. the system object)
        #print(sys.path)
        #sys.path.insert(1,'.')
        #exec("import {}".format(".".join(customff.split(".")[:-1])))
    else:
        logger.info("--- No custom ff code provided ---")

    fExts=[f for f in system.getForces() if isinstance(f,mm.CustomExternalForce)]
    logger.info("External forces added: {}".format(fExts))
    """
    soluteIndices = []
    soluteResidues = soluteRes  #list of residues to alchemify. modified s.t. soluteRes is already a list
    #parmed gromacs topology
    for ir, res in enumerate(top.residues):
        if ir in soluteResidues:
            for atom in res.atoms:
                soluteIndices.append(atom.idx)
    print("Solute residue: {}".format(
        [top.residues[ir].atoms for ir in soluteResidues]))
    print("Solute Indices: {}".format(soluteIndices))
    #if using openmm topology. unfortunately don't know how to convert from parmed to openmm#:
    #topology = parmed.openmm.load_topology(top.topology)
    #print(type(topology))
    #for ir,res in topology.residues():
    #    if ir in soluteResidues:
    #        for atom in res.atoms:
    #            soluteIndices.append(atom.index)

    alch = alchemifyIons.alchemist(system, lambdaLJ, lambdaQ)
    alch.setupSolute(soluteIndices)
    print(system.getForces())

    # === Integrator, Barostat, Additional Constraints === #
    integrator = set_thermo(system, args)

    if not hasattr(args, 'constraints') or (str(args.constraints) == "None"
                                            and args.rigidwater == False):
        args.deactivate('constraint_tolerance',
                        "There are no constraints in this system")
    else:
        logger.info("Setting constraint tolerance to %.3e" %
                    args.constraint_tolerance)
        integrator.setConstraintTolerance(args.constraint_tolerance)

    # === Make Platform === #
    logger.info("Setting Platform to %s" % str(args.platform))
    try:
        platform = mm.Platform.getPlatformByName(args.platform)
    except:
        logger.info(
            "Warning: %s platform not found, going to Reference platform \x1b[91m(slow)\x1b[0m"
            % args.platform)
        args.force_active('platform', "Reference",
                          "The %s platform was not found." % args.platform)
        platform = mm.Platform.getPlatformByName("Reference")

    if deviceid is not None or deviceid >= 0:
        args.force_active('device',
                          deviceid,
                          msg="Using cmdline-input deviceid")
    if 'device' in args.ActiveOptions and (platform.getName() == "OpenCL"
                                           or platform.getName() == "CUDA"):
        device = str(args.device)
        # The device may be set using an environment variable or the input file.
        #if 'CUDA_DEVICE' in os.environ.keys(): #os.environ.has_key('CUDA_DEVICE'):
        #    device = os.environ.get('CUDA_DEVICE',str(args.device))
        #elif 'CUDA_DEVICE_INDEX' in os.environ.keys(): #os.environ.has_key('CUDA_DEVICE_INDEX'):
        #    device = os.environ.get('CUDA_DEVICE_INDEX',str(args.device))
        #else:
        #    device = str(args.device)
        if device != None:
            logger.info("Setting Device to %s" % str(device))
            #platform.setPropertyDefaultValue("CudaDevice", device)
            if platform.getName() == "CUDA":
                platform.setPropertyDefaultValue("CudaDeviceIndex", device)
            elif platform.getName() == "OpenCL":
                print("set OpenCL device to {}".format(device))
                platform.setPropertyDefaultValue("OpenCLDeviceIndex", device)
        else:
            logger.info("Using the default (fastest) device")
    else:
        logger.info(
            "Using the default (fastest) device, or not using CUDA nor OpenCL")

    if "Precision" in platform.getPropertyNames() and (
            platform.getName() == "OpenCL" or platform.getName() == "CUDA"):
        platform.setPropertyDefaultValue("Precision", args.cuda_precision)
    else:
        logger.info("Not setting precision")
        args.deactivate(
            "cuda_precision",
            msg="Platform does not support setting cuda_precision.")

    # === Create Simulation === #
    logger.info("Creating the Simulation object")
    start = time.time()
    # Get the number of forces and set each force to a different force group number.
    nfrc = system.getNumForces()
    if args.integrator != 'mtsvvvr':
        for i in range(nfrc):
            system.getForce(i).setForceGroup(i)
    ''' 
    for i in range(nfrc):
        # Set vdW switching function manually.
        f = system.getForce(i)
        if f.__class__.__name__ == 'NonbondedForce':
            #f.setUseSwitchingFunction(False)
            #f.setSwitchingDistance(1.0*u.nanometers)
            if 'vdw_switch' in args.ActiveOptions and args.vdw_switch:
                f.setUseSwitchingFunction(True)
                f.setSwitchingDistance(args.switch_distance)
    '''

    #create simulation object
    if args.platform != None:
        simulation = app.Simulation(top.topology, system, integrator, platform)
    else:
        simulation = app.Simulation(top.topology, system, integrator)
    topomm = mdtraj.Topology.from_openmm(simulation.topology)
    logger.info("System topology: {}".format(topomm))

    #print platform we're using
    mdparse.printcool_dictionary(
        {
            i: simulation.context.getPlatform().getPropertyValue(
                simulation.context, i)
            for i in simulation.context.getPlatform().getPropertyNames()
        },
        title="Platform %s has properties:" %
        simulation.context.getPlatform().getName())

    logger.info("--== PME parameters ==--")
    ftmp = [
        f for ii, f in enumerate(simulation.system.getForces())
        if isinstance(f, mm.NonbondedForce)
    ]
    fnb = ftmp[0]
    if fnb.getNonbondedMethod() == 4:  #check for PME
        PMEparam = fnb.getPMEParametersInContext(simulation.context)
        logger.info(fnb.getPMEParametersInContext(simulation.context))
    if fnb.getNonbondedMethod() == 5:  #check for LJPME
        PMEparam = fnb.getLJPMEParametersInContext(simulation.context)
        logger.info(fnb.getLJPMEParametersInContext(simulation.context))
    #nmeshx = int(PMEparam[1]*1.5)
    #nmeshy = int(PMEparam[2]*1.5)
    #nmeshz = int(PMEparam[3]*1.5)
    #fnb.setPMEParameters(PMEparam[0],nmeshx,nmeshy,nmeshz)
    #logger.info(fnb.getPMEParametersInContext(simulation.context))

    # Print out some more information about the system
    logger.info("--== System Information ==--")
    logger.info("Number of particles   : %i" %
                simulation.context.getSystem().getNumParticles())
    logger.info("Number of constraints : %i" %
                simulation.context.getSystem().getNumConstraints())
    for f in simulation.context.getSystem().getForces():
        if f.__class__.__name__ == 'NonbondedForce':
            method_names = [
                "NoCutoff", "CutoffNonPeriodic", "CutoffPeriodic", "Ewald",
                "PME", "LJPME"
            ]
            logger.info("Nonbonded method      : %s" %
                        method_names[f.getNonbondedMethod()])
            logger.info("Number of particles   : %i" % f.getNumParticles())
            logger.info("Number of exceptions  : %i" % f.getNumExceptions())
            if f.getNonbondedMethod() > 0:
                logger.info("Nonbonded cutoff      : %.3f nm" %
                            (f.getCutoffDistance() / u.nanometer))
                if f.getNonbondedMethod() >= 3:
                    logger.info("Ewald error tolerance : %.3e" %
                                (f.getEwaldErrorTolerance()))
                logger.info("LJ switching function : %i" %
                            f.getUseSwitchingFunction())
                if f.getUseSwitchingFunction():
                    logger.info("LJ switching distance : %.3f nm" %
                                (f.getSwitchingDistance() / u.nanometer))

    # Print the sample input file here.
    for line in args.record():
        print(line)

    print("Took {}s to make and setup simulation object".format(time.time() -
                                                                start))

    #============================#
    #| Initialize & Eq/Warm-Up  |#
    #============================#

    p = simulation.context.getPlatform()
    if p.getName() == "CUDA" or p.getName() == "OpenCL":
        print("simulation platform: {}".format(p.getName()))
        print(p.getPropertyNames())
        print(p.getPropertyValue(simulation.context, 'DeviceName'))
        print("Device Index: {}".format(
            p.getPropertyValue(simulation.context, 'DeviceIndex')))

    if os.path.exists(args.restart_filename) and args.read_restart:
        print("Restarting simulation from the restart file.")
        print("Currently is filler")
    else:
        # Set initial positions.
        if incoord.split(".")[-1] == "pdb":
            pdb = app.PDBFile(incoord)  #pmd.load_file(incoord)
            simulation.context.setPositions(pdb.positions)
            print('Set positions from pdb, {}'.format(incoord))
            molecTopology = incoord
        elif incoord.split(".")[-1] == "xyz":
            traj = mdtraj.load(incoord,
                               top=mdtraj.Topology.from_openmm(
                                   simulation.topology))
            simulation.context.setPositions(traj.openmm_positions(0))
        elif incoord.split(".")[-1] == "xml":
            simulation.loadState(incoord)
            print('Set positions from xml, {}'.format(incoord))
        else:
            logger.info("Error, can't handle input coordinate filetype")

        if args.constraint_tolerance > 0.0:
            simulation.context.applyConstraints(
                args.constraint_tolerance
            )  #applies constraints in current frame.
        logger.info("Initial potential energy is: {}".format(
            simulation.context.getState(getEnergy=True).getPotentialEnergy()))

        if args.integrator != 'mtsvvvr':
            eda = mdparse.EnergyDecomposition(simulation)
            eda_kcal = OrderedDict([(i, "%10.4f" % (j / 4.184))
                                    for i, j in eda.items()])
            mdparse.printcool_dictionary(
                eda_kcal, title="Energy Decomposition (kcal/mol)")

        # Minimize the energy.
        if args.minimize:
            logger.info("Minimization start, the energy is: {}".format(
                simulation.context.getState(
                    getEnergy=True).getPotentialEnergy()))
            simulation.minimizeEnergy()
            logger.info("Minimization done, the energy is {}".format(
                simulation.context.getState(
                    getEnergy=True).getPotentialEnergy()))
            positions = simulation.context.getState(
                getPositions=True).getPositions()
            logger.info("Minimized geometry is written to 'minimized.pdb'")
            app.PDBFile.writeModel(simulation.topology, positions,
                                   open('minimized.pdb', 'w'))
        # Assign velocities.
        if args.gentemp > 0.0:
            logger.info(
                "Generating velocities corresponding to Maxwell distribution at %.2f K"
                % args.gentemp)
            simulation.context.setVelocitiesToTemperature(args.gentemp *
                                                          u.kelvin)
        # Equilibrate.
        logger.info("--== Equilibrating (%i steps, %.2f ps) ==--" %
                    (args.equilibrate, args.equilibrate * args.timestep *
                     u.femtosecond / u.picosecond))
        if args.report_interval > 0:
            # Append the ProgressReport for equilibration run.
            simulation.reporters.append(
                mdparse.ProgressReport(args, sys.stdout, args.report_interval,
                                       simulation, args.equilibrate))
            simulation.reporters[-1].t00 = time.time()
            logger.info("Progress will be reported every %i steps" %
                        args.report_interval)
        # This command actually does all of the computation.
        simulation.step(args.equilibrate)
        if args.report_interval > 0:
            # Get rid of the ProgressReport because we'll make a new one.
            simulation.reporters.pop()
        first = args.equilibrate

    #============================#
    #| Production MD simulation |#
    #============================#
    logger.info(
        "--== Production (%i blocks, %i steps total, %.2f ps total) ==--" %
        (nblocks, nblocks * blocksteps,
         nblocks * blocksteps * args.timestep * u.femtosecond / u.picosecond))

    #===========================================#
    #| Add reporters for production simulation |#
    #===========================================#
    print("===== registering reporters and runnning =====")

    if args.report_interval > 0:
        logger.info("Thermo and Progress will be reported every %i steps" %
                    args.report_interval)
        #simulation.reporters.append(ProgressReport(sys.stdout, args.report_interval, simulation, args.production, first))
        mdparse.bak(logfile)
        simulation.reporters.append(
            app.StateDataReporter(logfile,
                                  reportfreq,
                                  step=True,
                                  potentialEnergy=True,
                                  kineticEnergy=True,
                                  temperature=True,
                                  volume=True,
                                  density=True,
                                  speed=True))
        #simulation.reporters.append(app.StateDataReporter(stdout, reportfreq, step=True,
        #        potentialEnergy=True, kineticEnergy=True, temperature=True, volume=True, density=True, speed=True))
        if progressreport:
            simulation.reporters.append(
                mdparse.ProgressReport(args,
                                       sys.stdout,
                                       reportfreq,
                                       simulation,
                                       nblocks * blocksteps,
                                       first=args.equilibrate))
            Prog = simulation.reporters[-1]

    if args.pdb_report_interval > 0:
        mdparse.bak(out_pdb)
        logger.info("PDB Reporter will write to %s every %i steps" %
                    (out_pdb, pdbfreq))
        simulation.reporters.append(app.PDBReporter(out_pdb, pdbfreq))

    if args.netcdf_report_interval > 0:
        mdparse.bak(out_netcdf)
        logger.info("netcdf Reporter will write to %s every %i steps" %
                    (out_netcdf, netcdffreq))
        simulation.reporters.append(
            NetCDFReporter(out_netcdf,
                           netcdffreq,
                           crds=True,
                           vels=args.netcdf_vels,
                           frcs=args.netcdf_frcs))
        '''
        mdparse.bak(out_nowater)
        logger.info("netcdf Reporter will write a no-water coordinate file %s every %i steps" %(out_nowater,netcdffreq))
        #toptraj = mdtraj.load(molecTopology)
        #top = toptraj.top
        top = mdtraj.Topology.from_openmm(simulation.topology)
        sel = [atom.index for residue in top.residues for atom in residue.atoms if (residue.name!="SOL") and (residue.name!="HOH")]
        simulation.reporters.append(mdtraj.reporters.NetCDFReporter(out_nowater, netcdffreq, atomSubset = sel))
        '''
    if args.dcd_report_interval > 0:
        mdparse.bak(out_dcd)
        logger.info("dcd Reporter will write to %s every %i steps" %
                    (out_dcd, dcdfreq))
        simulation.reporters.append(
            mdtraj.reporters.DCDReporter(out_dcd, dcdfreq))
        '''
        mdparse.bak(out_nowater_dcd)
        logger.info("dcd Reporter will write a no-water coordinate file %s every %i steps" %(out_nowater_dcd, dcdfreq))
        #toptraj = mdtraj.load(molecTopology)
        #top = toptraj.top
        top = mdtraj.Topology.from_openmm(simulation.topology)
        sel = [atom.index for residue in top.residues for atom in residue.atoms if (residue.name!="SOL") and (residue.name!="HOH")]
        simulation.reporters.append(mdtraj.reporters.DCDReporter(out_nowater_dcd, dcdfreq, atomSubset = sel))

        #write out a nowater.pdb as topology input
        top2 = top.subset(sel)
        xyz0 = np.zeros([len(sel),3])
        traj2 = mdtraj.Trajectory(xyz0,topology=top2)
        traj2.save('output_nowater_top.pdb')
        top2omm = top2.to_openmm()
        '''
    if args.checkpoint_interval > 0:
        simulation.reporters.append(
            app.CheckpointReporter(checkpointchk, checkfreq))
    #simulation.reporters.append(app.DCDReporter(out_dcd, writefreq))
    #simulation.reporters.append(mdtraj.reporters.HDF5Reporter(out_hdf5, writefreq, velocities=True))

    #============================#
    #| Finally Run!             |#
    #============================#
    t1 = time.time()
    if progressreport:
        Prog.t00 = t1
    #simulation.step(args.production)

    for iblock in range(0, nblocks):
        logger.info("Starting block {}".format(iblock))
        start = time.time()
        simulation.step(blocksteps)
        end = time.time()
        logger.info('Took {} seconds for block {}'.format(end - start, iblock))

        simulation.saveState(checkpointxml)
        positions = simulation.context.getState(
            getPositions=True, enforcePeriodicBox=True).getPositions()
        app.PDBFile.writeFile(simulation.topology, positions,
                              open(checkpointpdb, 'w'))
예제 #15
0
# Default: 0.01 ns
if cmd.hmr:
    # Time step is 5 fs vs 2fs
    cmd.xyz_freq = int(cmd.xyz_freq // 2.5)
    cmd.log_freq = int(cmd.log_freq // 2.5)

# Calculate total simulation length in steps
n_steps = int(math.ceil(cmd.runtime / md_step.in_units_of(units.nanoseconds)))
# n_steps is dimensionless (ns/ns)

# Setup Reporters
dcd_fname = _utils.make_fname_serial(rootname + '.dcd')
cpt_fname = _utils.make_fname_serial(rootname + '.cpt')
log_fname = _utils.make_fname_serial(rootname + '.log')
dcd = app.DCDReporter(dcd_fname, cmd.xyz_freq)
cpt = app.CheckpointReporter(cpt_fname, cmd.xyz_freq)
state = app.StateDataReporter(log_fname,
                              cmd.log_freq,
                              step=True,
                              time=True,
                              potentialEnergy=True,
                              kineticEnergy=True,
                              temperature=True,
                              progress=True,
                              remainingTime=True,
                              volume=True,
                              totalSteps=n_steps,
                              speed=True,
                              separator='\t')

simulation.reporters.append(dcd)
예제 #16
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)
예제 #17
0
prmtop = app.AmberPrmtopFile('../equib/ade_D_ala.prmtop')
inpcrd = app.AmberInpcrdFile('../equib/ade_D_ala.inpcrd')

system = prmtop.createSystem(nonbondedMethod=app.PME, 
    nonbondedCutoff=1.0*unit.nanometers, constraints=app.HBonds, rigidWater=True, 
    ewaldErrorTolerance=0.0005)
integrator = mm.LangevinIntegrator(300*unit.kelvin, 1.0/unit.picoseconds, 
    2.0*unit.femtoseconds)
integrator.setConstraintTolerance(0.00001)
system.addForce(mm.MonteCarloBarostat(1*unit.atmospheres, 300*unit.kelvin, 25))

platform = mm.Platform.getPlatformByName('CUDA')
properties = {'CudaPrecision': 'mixed', 'CudaDeviceIndex': '1'}
simulation = app.Simulation(prmtop.topology, system, integrator, platform, 
    properties)
simulation.loadState('../equib/equilibrated.xml')
simulation.context.setVelocitiesToTemperature(300*unit.kelvin)

total_steps = 500000000
simulation.reporters.append(app.DCDReporter('trajectory002.dcd', 5000))
simulation.reporters.append(app.StateDataReporter('prod002.dat', 50000, step=True,
    time=True, potentialEnergy=True, kineticEnergy=True, totalEnergy=True, 
    temperature=True, volume=True, density=True, progress=True, 
    remainingTime=True, speed=True, totalSteps=total_steps, separator=','))
simulation.reporters.append(app.CheckpointReporter('checkpnt002.chk', 50000))

print('Running Production...')
simulation.step(total_steps)
simulation.saveState('prod002.xml')
print('Done!')
예제 #18
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
예제 #19
0
def main(targetVol, tol=1e-4, paramfile='params.in', overrides={}, quiktest=False, deviceid=None, progressreport=True): #simtime=2.0, T=298.0, NPT=True, LJcut=10.0, tail=True, useLJPME=False, rigidH2O=True, device=0, quiktest=False):
    logger.info("This protocol runs NPT until a target volume is achieved, with given tolerance.")
    logger.info("Make sure you prescribe pressure and barsostat freq!")  
 
    # === PARSE === #
    args = mdparse.SimulationOptions(paramfile, overrides)

    # === forced parameters special to this protocol === #
    args.force_active('cont', val=-1, msg="targetVolume protocol, don't use continue flag")
    args.force_active('equilibrate', val=args.nbarostat*5, msg="targetVolume protocol, just minor warmup")
    args.force_active('grofile', val="targetVolume.gro", msg="default input gro file with box size for targetVolumeProtocol")
    if 'incoord' in overrides:
        args.force_active('incoord', val=overrides['incoord'], msg="user-supplied incoord overrides that in parameter file") 
    if 'pressure' in overrides:
        args.force_active('pressure', val=overrides['pressure'], msg="user-supplied pressure overrides that in parameter file")    
    if 'nbarostat' in overrides:
        args.force_active('nbarostat', val=overrides['nbarostat'], msg="user-supplied nbarostat overrides that in parameter file")
    if args.pressure <= 0.0:
        logger.info("WARNING: parameter file did not have valid pressure, using default 1.0 bar and nbarostat=25")
        args.force_active('pressure', val=1.0, msg="Parameter file did not have valid pressure, using default 1.0bar")
        args.force_active('nbarostat', val=25, msg="Parameter file did not have valid nbarostat, using default 25")
    elif args.nbarostat <= 0:
        logger.info("WARNING: parameter file has invalid nbarostat, using default 25")
        args.force_active('nbarostat', val=25, msg="Parameter file did not have valid nbarostat, using default 25")
    if args.temperature <= 0.0:
        logger.info("NPT must have valid thermostat, but temperature not supplied, using default 298K")
        args.force_active('nbarostat', val=298.0, msg="NPT needs thermostat, but temperature invalid. using default 298.0K")    
    
    args.force_active('use_fs_interval', val=False, msg="target Vol protocol based on nbarostat time step intervals")
    args.force_active('report_interval', val=10*args.nbarostat, msg="target Vol protocol based on nbarostat time step intervals")
    args.force_active('pdb_report_interval', val=0, msg="don't keep track of pdb")
    args.force_active('netcdf_report_interval', val=0, msg="don't keep trajectory")
    args.force_active('checkpoint_interval', val=0, msg="don't write .chk files")
    args.force_active('block_interval', val=10*args.nbarostat, msg="target Vol protocol based on nbarostat intervals")
    args.force_active('nblocks', val = 5e4, msg="cap the number of barostat moves to try")

    args.deactivate('outpdb', "not writing pdb trajectory")
    args.deactivate('outnetcdf', "not writing netcdf trajectory")
    #args.force_active('outnetcdf', val="targetVolume.nc", "target Volume trajectory writes")
    args.force_active('logfile', val="targetVolume.log", msg="target Volume protocol log")
    args.force_active('chkxml', val="targetVolume.xml", msg="target Volume protocol xml")
    args.force_active('chkpdb', val="targetVolume.pdb", msg="target Volume protocol pdb")


    # === Files === #
    gromacs.GROMACS_TOPDIR = args.topdir
    top_file        = args.topfile
    box_file        = args.grofile
    defines         = {}
    cont            = args.cont
    '''
    args.force_active('chkxml',val='chk_{:02n}.xml'.format(cont),msg='first one')
    args.force_active('chkpdb',val='chk_{:02n}.pdb'.format(cont),msg='first one')
    
    if cont > 0:
        args.force_active('incoord',val='chk_{:02n}.xml'.format(cont-1),msg='continuing')
        args.force_active('outpdb',val='output_{:02n}.pdb'.format(cont),msg='continuing')
        args.force_active('outnetcdf',val='output_{:02n}.nc'.format(cont),msg='continuing')
        args.force_active('logfile',val='thermo.log_{:02n}'.format(cont),msg='continuing')
    '''

    incoord         = args.incoord
    out_pdb         = args.outpdb
    out_netcdf      = args.outnetcdf
    logfile         = args.logfile
    checkpointxml   = args.chkxml
    checkpointpdb   = args.chkpdb
    checkpointchk   = 'chk_{:02n}.chk'.format(cont)

    # Parameters
    #Temp            = args.temperature        #K
    #Pressure = 1      #bar
    #barostatfreq    = 25 #time steps
    #fric            = args.collision_rate     #1/ps

    dt              = args.timestep 	      #fs
    if args.use_fs_interval:
        reportfreq = int(args.report_interval/dt)
        netcdffreq = int(args.netcdf_report_interval/dt) #5e4
        pdbfreq    = int(args.pdb_report_interval/dt)
        checkfreq  = int(args.checkpoint_interval/dt)
        #simtime    = int( simtime ) #nanoseconds; make sure division is whole... no remainders...
        blocksteps = int(args.block_interval/dt)   #1e6, steps per block of simulation 
        nblocks    = args.nblocks #aiming for 1 block is 1ns
    else:
        reportfreq = args.report_interval
        netcdffreq = args.netcdf_report_interval
        pdbfreq    = args.pdb_report_interval
        checkfreq  = args.checkpoint_interval
        blocksteps = args.block_interval
        nblocks    = args.nblocks 

    if quiktest==True:
        reportfreq = 1
        blocksteps = 10
        nblocks = 2

    # === Start Making System === #
    top = gromacs.GromacsTopologyFile(top_file, defines=defines)
    gro = gromacs.GromacsGroFile.parse(box_file)
    top.box = gro.box

    constr = {None: None, "None":None,"HBonds":app.HBonds,"HAngles":app.HAngles,"AllBonds":app.AllBonds}[args.constraints]   
    system = top.createSystem(nonbondedMethod=app.PME, ewaldErrorTolerance = args.ewald_error_tolerance,
                        nonbondedCutoff=args.nonbonded_cutoff*u.nanometers,
                        rigidWater = args.rigid_water, constraints = constr)
                        
    nbm = {"NoCutoff":mm.NonbondedForce.NoCutoff, "CutoffNonPeriodic":mm.NonbondedForce.CutoffNonPeriodic,
                "Ewald":mm.NonbondedForce.Ewald, "PME":mm.NonbondedForce.PME, "LJPME":mm.NonbondedForce.LJPME}[args.nonbonded_method]

    ftmp = [f for ii, f in enumerate(system.getForces()) if isinstance(f,mm.NonbondedForce)]
    fnb = ftmp[0]
    fnb.setNonbondedMethod(nbm)
    logger.info("Nonbonded method ({},{})".format(args.nonbonded_method, fnb.getNonbondedMethod()) )
    if (not args.dispersion_correction) or (args.nonbonded_method=="LJPME"):
        logger.info("Turning off tail correction...")
        fnb.setUseDispersionCorrection(False)
        logger.info("Check dispersion flag: {}".format(fnb.getUseDispersionCorrection()) )


    # === Integrator, Barostat, Additional Constraints === #
    integrator = set_thermo(system,args)

    if not hasattr(args,'constraints') or (str(args.constraints) == "None" and args.rigidwater == False):
        args.deactivate('constraint_tolerance',"There are no constraints in this system")
    else:
        logger.info("Setting constraint tolerance to %.3e" % args.constraint_tolerance)
        integrator.setConstraintTolerance(args.constraint_tolerance)

    # === Make Platform === #
    logger.info("Setting Platform to %s" % str(args.platform))
    try:
        platform = mm.Platform.getPlatformByName(args.platform)
    except:
        logger.info("Warning: %s platform not found, going to Reference platform \x1b[91m(slow)\x1b[0m" % args.platform)
        args.force_active('platform',"Reference","The %s platform was not found." % args.platform)
        platform = mm.Platform.getPlatformByName("Reference")

    if deviceid is not None or deviceid>=0:
        args.force_active('device',deviceid,msg="Using cmdline-input deviceid")
    if 'device' in args.ActiveOptions and (platform.getName()=="OpenCL" or platform.getName()=="CUDA"):
        device = str(args.device)
        # The device may be set using an environment variable or the input file.
        #if 'CUDA_DEVICE' in os.environ.keys(): #os.environ.has_key('CUDA_DEVICE'):
        #    device = os.environ.get('CUDA_DEVICE',str(args.device))
        #elif 'CUDA_DEVICE_INDEX' in os.environ.keys(): #os.environ.has_key('CUDA_DEVICE_INDEX'):
        #    device = os.environ.get('CUDA_DEVICE_INDEX',str(args.device))
        #else:
        #    device = str(args.device)
        if device != None:
            logger.info("Setting Device to %s" % str(device))
            #platform.setPropertyDefaultValue("CudaDevice", device)
            platform.setPropertyDefaultValue("CudaDeviceIndex", device)
            #platform.setPropertyDefaultValue("OpenCLDeviceIndex", device)
        else:
            logger.info("Using the default (fastest) device")
    else:
        logger.info("Using the default (fastest) device, or not using CUDA nor OpenCL")

    if "CudaPrecision" in platform.getPropertyNames() and (platform.getName()=="OpenCL" or platform.getName()=="CUDA"):
        platform.setPropertyDefaultValue("CudaPrecision", args.cuda_precision)
    else:
        logger.info("Not setting precision")
        args.deactivate("cuda_precision",msg="Platform does not support setting cuda_precision.")

    # === Create Simulation === #
    logger.info("Creating the Simulation object")
    # Get the number of forces and set each force to a different force group number.
    nfrc = system.getNumForces()
    if args.integrator != 'mtsvvvr':
        for i in range(nfrc):
            system.getForce(i).setForceGroup(i)
    '''
    for i in range(nfrc):
        # Set vdW switching function manually.
        f = system.getForce(i)
        if f.__class__.__name__ == 'NonbondedForce':
            if 'vdw_switch' in args.ActiveOptions and args.vdw_switch:
                f.setUseSwitchingFunction(True)
                f.setSwitchingDistance(args.switch_distance)
    '''

    #create simulation object
    if args.platform != None:
        simulation = app.Simulation(top.topology, system, integrator, platform)
    else:
        simulation = app.Simulation(top.topology, system, integrator)


    #print platform we're using
    mdparse.printcool_dictionary({i:simulation.context.getPlatform().getPropertyValue(simulation.context,i) for i in simulation.context.getPlatform().getPropertyNames()},title="Platform %s has properties:" % simulation.context.getPlatform().getName())

    # Print out some more information about the system
    logger.info("--== System Information ==--")
    logger.info("Number of particles   : %i" % simulation.context.getSystem().getNumParticles())
    logger.info("Number of constraints : %i" % simulation.context.getSystem().getNumConstraints())
    for f in simulation.context.getSystem().getForces():
        if f.__class__.__name__ == 'NonbondedForce':
            method_names = ["NoCutoff", "CutoffNonPeriodic", "CutoffPeriodic", "Ewald", "PME", "LJPME"]
            logger.info("Nonbonded method      : %s" % method_names[f.getNonbondedMethod()])
            logger.info("Number of particles   : %i" % f.getNumParticles())
            logger.info("Number of exceptions  : %i" % f.getNumExceptions())
            if f.getNonbondedMethod() > 0:
                logger.info("Nonbonded cutoff      : %.3f nm" % (f.getCutoffDistance() / u.nanometer))
                if f.getNonbondedMethod() >= 3:
                    logger.info("Ewald error tolerance : %.3e" % (f.getEwaldErrorTolerance()))
                logger.info("LJ switching function : %i" % f.getUseSwitchingFunction())
                if f.getUseSwitchingFunction():
                    logger.info("LJ switching distance : %.3f nm" % (f.getSwitchingDistance() / u.nanometer))

    # Print the sample input file here.
    for line in args.record():
        print(line)


    #============================#
    #| Initialize & Eq/Warm-Up  |#
    #============================#

    p = simulation.context.getPlatform()
    if p.getName()=="CUDA" or p.getName()=="OpenCL":
        print("simulation platform: {}".format(p.getName()) )
        print(p.getPropertyNames())
        print(p.getPropertyValue(simulation.context,'DeviceName'))
        print("Device Index: {}".format(p.getPropertyValue(simulation.context,'DeviceIndex')))

    
    if os.path.exists(args.restart_filename) and args.read_restart:
        print("Restarting simulation from the restart file.")
        print("Currently is filler")
    else:
        # Set initial positions.
        if incoord.split(".")[1]=="pdb":
            pdb = pmd.load_file(incoord)
            simulation.context.setPositions(pdb.positions)
        elif incoord.split(".")[1]=="xml":
            simulation.loadState(incoord)
        else:
            logger.info("Error, can't handle input coordinate filetype")
            
        simulation.context.applyConstraints(args.constraint_tolerance) #applies constraints in current frame.
        logger.info("Initial potential energy is: {}".format(simulation.context.getState(getEnergy=True).getPotentialEnergy()) )

        if args.integrator != 'mtsvvvr':
            eda = mdparse.EnergyDecomposition(simulation)
            eda_kcal = OrderedDict([(i, "%10.4f" % (j/4.184)) for i, j in eda.items()])
            mdparse.printcool_dictionary(eda_kcal, title="Energy Decomposition (kcal/mol)")

        # Minimize the energy.
        if args.minimize:
            logger.info("Minimization start, the energy is:", simulation.context.getState(getEnergy=True).getPotentialEnergy())
            simulation.minimizeEnergy()
            logger.info("Minimization done, the energy is", simulation.context.getState(getEnergy=True).getPotentialEnergy())
            positions = simulation.context.getState(getPositions=True).getPositions()
            logger.info("Minimized geometry is written to 'minimized.pdb'")
            app.PDBFile.writeModel(simulation.topology, positions, open('minimized.pdb','w'))
        # Assign velocities.
        if args.gentemp > 0.0:
            logger.info("Generating velocities corresponding to Maxwell distribution at %.2f K" % args.gentemp)
            simulation.context.setVelocitiesToTemperature(args.gentemp * u.kelvin)
        # Equilibrate.
        logger.info("--== Equilibrating (%i steps, %.2f ps) ==--" % (args.equilibrate, args.equilibrate * args.timestep * u.femtosecond / u.picosecond))
        if args.report_interval > 0:
            # Append the ProgressReport for equilibration run.
            simulation.reporters.append(mdparse.ProgressReport(args, sys.stdout, args.report_interval, simulation, args.equilibrate))
            simulation.reporters[-1].t00 = time.time()
            logger.info("Progress will be reported every %i steps" % args.report_interval)
        # This command actually does all of the computation.
        simulation.step(args.equilibrate)
        if args.report_interval > 0:
            # Get rid of the ProgressReport because we'll make a new one.
            simulation.reporters.pop()
        first = args.equilibrate
    

    #============================#
    #| Production MD simulation |#
    #============================#
    logger.info("--== Production (%i blocks, %i steps total, %.2f ps total) ==--" % (nblocks, nblocks*blocksteps, nblocks*blocksteps * args.timestep * u.femtosecond / u.picosecond))

    #===========================================#
    #| Add reporters for production simulation |#
    #===========================================#   
    print("===== registering reporters and runnning =====")

    if args.report_interval > 0:
        logger.info("Thermo and Progress will be reported every %i steps" % args.report_interval)
        #simulation.reporters.append(ProgressReport(sys.stdout, args.report_interval, simulation, args.production, first))
        mdparse.bak(logfile)
        simulation.reporters.append(app.StateDataReporter(logfile, reportfreq, step=True,
                potentialEnergy=True, kineticEnergy=True, temperature=True, volume=True, density=True, speed=True))
        #simulation.reporters.append(app.StateDataReporter(stdout, reportfreq, step=True,
        #        potentialEnergy=True, kineticEnergy=True, temperature=True, volume=True, density=True, speed=True))
        if progressreport:
            simulation.reporters.append(mdparse.ProgressReport(args, sys.stdout, reportfreq, simulation, nblocks*blocksteps, first=args.equilibrate))
            Prog = simulation.reporters[-1]
        

    if args.pdb_report_interval > 0:
        mdparse.bak(out_pdb)
        logger.info("PDB Reporter will write to %s every %i steps" % (out_pdb, pdbfreq))
        simulation.reporters.append(app.PDBReporter(out_pdb, pdbfreq))

    if args.netcdf_report_interval > 0:
        mdparse.bak(out_netcdf)
        logger.info("netcdf Reporter will write to %s every %i steps" %(out_netcdf, netcdffreq))
        simulation.reporters.append(NetCDFReporter(out_netcdf, netcdffreq, crds=True, vels=args.netcdf_vels, frcs=args.netcdf_frcs))

    if args.checkpoint_interval > 0: 
       simulation.reporters.append(app.CheckpointReporter(checkpointchk, checkfreq))
    #simulation.reporters.append(app.DCDReporter(out_dcd, writefreq))
    #simulation.reporters.append(mdtraj.reporters.HDF5Reporter(out_hdf5, writefreq, velocities=True))
    

    #============================#
    #| Finally Run!             |#
    #============================#
    t1 = time.time()
    if progressreport:
        Prog.t00 = t1
    #simulation.step(args.production)


    if simulation.topology.getUnitCellDimensions() != None :
        box_vectors = simulation.context.getState().getPeriodicBoxVectors()
        volume = mdparse.compute_volume(box_vectors) / u.nanometer**3
    iblock = 0
    err = abs(volume - targetVol)/targetVol 
    while err > tol and iblock < nblocks:
        logger.info("Starting block {}".format(iblock))
        start = time.time()
        simulation.step(blocksteps)
        end = time.time()
        logger.info('Took {} seconds for block {}'.format(end-start,iblock))

        if simulation.topology.getUnitCellDimensions() != None :
            box_vectors = simulation.context.getState().getPeriodicBoxVectors()
            volume = mdparse.compute_volume(box_vectors) / u.nanometer**3
            print("Volume is {}, targeting {}".format(volume, targetVol))
            with open("finalL.txt",'w') as f:
                f.write("{}".format(volume**(1.0/3.0)))
        err = abs(volume - targetVol)/targetVol
        iblock = iblock+1
    
    #avoid frequent writes, only write at the end
    simulation.saveState(checkpointxml)
    positions = simulation.context.getState(getPositions=True, enforcePeriodicBox=True).getPositions()
    app.PDBFile.writeFile(simulation.topology, positions, open(checkpointpdb, 'w'))    
예제 #20
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)
예제 #21
0
파일: production.py 프로젝트: uibcdf/HIF1
# Observables

simulation.reporters.append(
    HDF5Reporter(trajectory_file,
                 reportInterval=steps_interval_saving,
                 coordinates=True,
                 time=True,
                 cell=True,
                 potentialEnergy=True,
                 kineticEnergy=True,
                 temperature=True))

# Checkpoints

simulation.reporters.append(
    app.CheckpointReporter(checkpoint_file, steps_interval_checkpoint))

#### Running Simulation

start_simulation_realtime = realtime()

simulation.step(steps_simulation)

end_simulation_realtime = realtime()

#### Saving Finnal State

simulation.saveState(final_state_file)
simulation.saveCheckpoint(final_checkpoint_file)
m3t.convert(simulation, final_pdb_file)
예제 #22
0
# Observables

simulation.reporters.append(
    HDF5Reporter('trajectory.h5',
                 reportInterval=steps_interval_saving,
                 coordinates=True,
                 time=True,
                 cell=True,
                 potentialEnergy=True,
                 kineticEnergy=True,
                 temperature=True))

# Checkpoints

simulation.reporters.append(
    app.CheckpointReporter('checkpnt.chk', steps_interval_checkpoint))

#### Running Simulation

start_simulation_realtime = realtime()

simulation.step(steps_simulation)

end_simulation_realtime = realtime()

#### Saving Finnal State

simulation.saveState('finnal_state.xml')
simulation.saveCheckpoint('finnal_state.chk')
m3t.convert(simulation, 'finnal_positions.pdb')
예제 #23
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)
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()
예제 #25
0
파일: my_openmm.py 프로젝트: ahy3nz/setup
print("Creating integrator")
integrator = mm.LangevinIntegrator(temp, 1.0 / u.picoseconds, timestep)

print("Creating Simulation")
sim = app.Simulation(top.topology, system, integrator, platform, properties)

print("Setting context")
sim.context.setPositions(top.positions)
sim.reporters.append(
    app.StateDataReporter(open('thermo.log', 'a'),
                          1000,
                          step=True,
                          time=True,
                          potentialEnergy=True,
                          temperature=True,
                          volume=True,
                          speed=True))
sim.reporters.append(app.DCDReporter('trajectory.dcd', 2500))
sim.reporters.append(app.CheckpointReporter('trajectory.chk', 2500))
# Load the checkpoint
#with open('my_checkpoint.chk', 'rb') as f:
#        sim.context.loadCheckpoint(f.read())
print("Running MD")
remaining_time = sim_time - sim.context.getState(-1).getTime()
remaining_steps = int(round(remaining_time / timestep))

sim.step(remaining_steps)

pdbreporter = app.PDBReporter('trajectory.pdb', 5000)
pdbreporter.report(sim, sim.context.getState(-1))
예제 #26
0
else:
    # Time step is 2 fs
    # 500.000 steps give 1 ns
    wfreq = cmd.wfreq if cmd.wfreq is not None else 5000
    pfreq = cmd.pfreq if cmd.pfreq is not None else 5000

eq_dcd = rootname + '.dcd'
if cmd.continuation:
    eq_dcd = get_part_filename(eq_dcd)

eq_log = rootname + '.log'
if cmd.continuation:
    eq_log = get_part_filename(eq_log)

dcd = app.DCDReporter(eq_dcd, wfreq)
cpt = app.CheckpointReporter(eq_cpt, wfreq)

state = app.StateDataReporter(eq_log,
                              pfreq,
                              step=True,
                              time=True,
                              progress=True,
                              potentialEnergy=True,
                              kineticEnergy=True,
                              temperature=True,
                              remainingTime=True,
                              speed=True,
                              totalSteps=n_steps,
                              separator='\t')

simulation.reporters.append(dcd)
예제 #27
0
       u.kilocalories_per_mole))

# Equilibrate

print('Benchmarking...')
print('Equilibrate...')
initial_time = time.time()

simulation.system.addForce(barostat)
simulation.step(int(total_steps * 1 / 3))
simulation.saveState('equilibrated.xml')

# Production
print('Production...')
simulation.reporters.append(
    app.CheckpointReporter('checkpnt.chk', int(total_steps / 10)))
simulation.reporters.append(
    app.DCDReporter('simulation.dcd', int(total_steps / 400)))
simulation.reporters.append(
    app.StateDataReporter('simulation.log',
                          int(total_steps / 200),
                          step=True,
                          time=True,
                          totalEnergy=True))
simulation.step(int(total_steps * 2 / 3))

final_time = time.time()
elapsed_time = (final_time - initial_time) * u.seconds
simulated_time = total_steps * integrator.getStepSize()
performance = (simulated_time / elapsed_time)
print('Completed %8d steps in %8.3f s : performance is %8.3f ns/day' %