def set_thermo(system, args): ''' Takes care of thermostat if needed ''' if args.temperature <= 0.0: logger.info("This is a constant energy, constant volume (NVE) run.") integrator = mm.VerletIntegrator(2.0 * u.femtoseconds) else: logger.info("This is a constant temperature run at %.2f K" % args.temperature) logger.info( "The stochastic thermostat collision frequency is %.2f ps^-1" % args.collision_rate) if args.integrator == "langevin": logger.info( "Creating a Langevin integrator with %.2f fs timestep." % args.timestep) integrator = mm.LangevinIntegrator( args.temperature * u.kelvin, args.collision_rate / u.picoseconds, args.timestep * u.femtosecond) elif args.integrator == "verlet": integrator = mm.VerletIntegrator(2.0 * u.femtoseconds) thermostat = mm.AndersenThermostat( args.temperature * u.kelvin, args.collision_rate / u.picosecond) system.addForce(thermostat) else: logger.warning("Unknown integrator, will crash now") add_barostat(system, args) return integrator
def main(): print("Reading the PSF file"); # Read the PSF file psf = app.CharmmPsfFile('g1_25mm.psf'); boxsize = 5 # Boxsize in nm psf.setBox(boxsize*nanometer, boxsize*nanometer, boxsize*nanometer); print("Reading the pdb file") pdb = app.PDBFile('g1_25mm.pdb'); # Load the parameter set lib = 'toppar/' #params = app.CharmmParameterSet('toppar/top_all36_cgenff.rtf','toppar/par_all36_cgenff.prm','toppar/cgenff3.0.1/top_all36_cgenff.rtf','toppar/cgenff3.0.1/par_all36_cgenff.prm','g1_new.str','toppar_water_ions.str') params = app.CharmmParameterSet('toppar/cgenff3.0.1/top_all36_cgenff.rtf','toppar/cgenff3.0.1/par_all36_cgenff.prm','g1_new.str','toppar_water_ions.str') #platform = openmm.Platform.getPlatformByName('CUDA'); platform = openmm.Platform.getPlatformByName('Reference'); # Creating the system system = psf.createSystem(params, nonbondedMethod=app.PME, nonbondedCutoff=1.2*nanometer, switchDistance=1.0*nanometer, ewaldErrorTolerance= 0.0001, constraints=app.HBonds); # Thermostat @ 298 K system.addForce(openmm.AndersenThermostat(298*kelvin, 1/picosecond)) # adding the barostat for now system.addForce(openmm.MonteCarloBarostat(1*bar, 298*kelvin)); integrator = openmm.VerletIntegrator(0.001*picoseconds) simulation = app.Simulation(psf.topology, system, integrator, platform) simulation.context.setPositions(pdb.getPositions()) simulation.minimizeEnergy(maxIterations = 500) #nsavcrd = 10000 # save coordinates every 10 ps #nstep = 2000000 # write dcd files every 2 ps #nprint = 2000 # report every 2 ps nsavcrd = 10 # save coordinates every 10 ps nstep = 200 # write dcd files every 2 ps nprint = 20 # report every 2 ps firstDcdStep = nsavcrd ; # Reporters dcd = app.DCDReporter('g1_new.dcd', nsavcrd) dcd._dcd = app.DCDFile(dcd._out, simulation.topology, simulation.integrator.getStepSize(), firstDcdStep, nsavcrd) simulation.reporters.append(dcd) simulation.reporters.append(app.StateDataReporter('g1_new.out', nprint, step=True, kineticEnergy=True, potentialEnergy=True, totalEnergy=True, temperature=True, volume=True, speed=True)) simulation.step(nstep) simulation.reporters.pop() simulation.reporters.pop() dcd._out.close()
def testXTCreporter(self): output_PDB = "tests/data/test_xtcreporter.pdb" output_XTC = "tests/data/test_xtcreporter.xtc" top_PDB = "tests/data/top_xtcreporter.pdb" PLATFORM = mm.Platform_getPlatformByName(str('CPU')) prmtop = app.AmberPrmtopFile("tests/data/complex.prmtop") inpcrd = app.AmberInpcrdFile("tests/data/complex.inpcrd") system = prmtop.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=9 * unit.angstroms, constraints=app.HBonds) system.addForce( mm.AndersenThermostat(300 * unit.kelvin, 1 / unit.picosecond)) integrator = mm.VerletIntegrator(2 * unit.femtoseconds) force = mm.CustomExternalForce(str("k*((x-x0)^2+(y-y0)^2+(z-z0)^2)")) force.addGlobalParameter( str("k"), 5.0 * unit.kilocalories_per_mole / unit.angstroms**2) force.addPerParticleParameter(str("x0")) force.addPerParticleParameter(str("y0")) force.addPerParticleParameter(str("z0")) for j, atom in enumerate(prmtop.topology.atoms()): if (atom.name in ('CA', 'C', 'N', 'O') and atom.residue.name != "HOH") or (atom.residue.name == "BEN" and atom.element.symbol != "H"): force.addParticle( j, inpcrd.positions[j].value_in_unit(unit.nanometers)) system.addForce(force) simulation = app.Simulation(prmtop.topology, system, integrator, PLATFORM) if inpcrd.boxVectors is not None: simulation.context.setPeriodicBoxVectors(*inpcrd.boxVectors) simulation.context.setPositions(inpcrd.positions) simulation.minimizeEnergy(maxIterations=10) print("Minimization ended") xtcReporter = XTCReporter(output_XTC, 1) simulation.reporters.append(app.PDBReporter(output_PDB, 1)) simulation.reporters.append(xtcReporter) simulation.step(10) # the XTCReporter does not close the file, so opening the file again # without exiting the function causes problems to the mdtraj reader xtcReporter.close() t_xtc = md.load(str(output_XTC), top=top_PDB) t_pdb = md.load(output_PDB) self.assertEqual(t_pdb.top, t_xtc.top) self.assertEqual(np.sum(np.abs(t_pdb.xyz - t_xtc.xyz) > 1e-3), 0) os.remove(output_PDB) os.remove(output_XTC)
if sel[i]: force.addParticle(i, atom_crd.value_in_unit(u.nanometers)) system.addForce(force) if opt.ntp: if opt.aniso: print('Using anisotropic barostat'); sys.stdout.flush() baro = mm.MonteCarloAnisotropicBarostat(1*u.bar, opt.temp*u.kelvin) else: print('Using isotropic barostat'); sys.stdout.flush() baro = mm.MonteCarloBarostat(1*u.bar, opt.temp*u.kelvin) system.addForce(baro) if opt.gamma_ln == 0.0 and not opt.nve: print('Adding Anderson thermostat at %sK, 0.1 psec^-1' % opt.temp); sys.stdout.flush() thermo = mm.AndersenThermostat(opt.temp*u.kelvin, 0.1/u.picosecond) system.addForce(thermo) # Create the simulation if opt.gamma_ln > 0.0: if opt.nrespa > 1: integrator = MTSVVVRIntegrator(opt.temp*u.kelvin, opt.gamma_ln/u.picosecond, opt.timestep*u.femtoseconds, system, opt.nrespa) print('MTSVVVR: %8.2fK, %8.2f ps-1, %8.2f fs, %3d inner steps' % (opt.temp, opt.gamma_ln, opt.timestep, opt.nrespa) ); sys.stdout.flush() else: integrator = mm.LangevinIntegrator(opt.temp*u.kelvin, opt.gamma_ln/u.picosecond, opt.timestep*u.femtoseconds) print('Langevin: %8.2fK, %8.2f ps-1, %8.2f fs' % (opt.temp, opt.gamma_ln, opt.timestep) ); sys.stdout.flush()
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()
def NPTequilibration(topology, positions, PLATFORM, simulation_steps, constraints, parameters, reportName, platformProperties, velocities=None, dummy=None): """ Function that runs an equilibration at constant pressure conditions. It uses the AndersenThermostat, the VerletIntegrator, the MonteCarlo Barostat and apply's constrains to the backbone of the protein and to the heavy atoms of the ligand :param topology: OpenMM Topology object :param positions: OpenMM Positions object :param PLATFORM: platform in which the minimization will run :type PLATFORM: str :param simulation_steps: number of steps to run :type simulation_steps: int :param constraints: strength of the constrain (units: Kcal/mol) :type constraints: int :param parameters: Object with the parameters for the simulation :type parameters: :py:class:`/simulationrunner/SimulationParameters` -- SimulationParameters object :param platformProperties: Properties specific to the OpenMM platform :type platformProperties: dict :param velocities: OpenMM object with the velocities of the system. Optional, if velocities are not given, random velocities acording to the temperature will be used. :param dummy: List of indices of dummy atoms introduced for the box :type dummy: list :return: The equilibrated OpenMM simulation object """ system = topology.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=parameters.nonBondedCutoff * unit.angstroms, constraints=app.HBonds) 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, topology.topology, parameters.constraints) if parameters.boxCenter or parameters.cylinderBases: # the last parameter is only used to print a message, by passing a # value different than 0 we avoid having too many prints addDummyAtomToSystem(system, topology.topology, positions, parameters.ligandName, dummy, 3) if constraints: force = mm.CustomExternalForce( str("k*periodicdistance(x, y, z, x0, y0, z0)^2")) force.addGlobalParameter( str("k"), constraints * unit.kilocalories_per_mole / unit.angstroms**2) force.addPerParticleParameter(str("x0")) force.addPerParticleParameter(str("y0")) force.addPerParticleParameter(str("z0")) for j, atom in enumerate(topology.topology.atoms()): if atom.name == 'CA' or (atom.residue.name == parameters.ligandName and atom.element.symbol != "H"): force.addParticle(j, positions[j].value_in_unit(unit.nanometers)) system.addForce(force) simulation = app.Simulation(topology.topology, system, integrator, PLATFORM, platformProperties=platformProperties) simulation.context.setPositions(positions) if velocities: simulation.context.setVelocities(velocities) else: simulation.context.setVelocitiesToTemperature( parameters.Temperature * unit.kelvin, 1) root, _ = os.path.splitext(reportName) reportFile = "%s_report_NPT" % root report_freq = int(min(parameters.reporterFreq, simulation_steps / 4)) simulation.reporters.append( CustomStateDataReporter(reportFile, report_freq, step=True, potentialEnergy=True, temperature=True, time_sim=True, volume=True, remainingTime=True, speed=True, totalSteps=parameters.equilibrationLengthNPT, separator="\t")) simulation.step(simulation_steps) return simulation
# load in Amber input files prmtop = app.AmberPrmtopFile('wat_' + PDBid + '.prmtop') inpcrd = app.AmberInpcrdFile('wat_' + PDBid + '.inpcrd') # prepare system and integrator system = prmtop.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=1.0 * unit.nanometers, constraints=app.HBonds, rigidWater=True, ewaldErrorTolerance=0.0005) integrator = mm.LangevinIntegrator(TEMPid * unit.kelvin, 1.0 / unit.picoseconds, 2.0 * unit.femtoseconds) integrator.setConstraintTolerance(0.00001) thermostat = mm.AndersenThermostat(TEMPid * unit.kelvin, 1 / unit.picosecond) system.addForce(thermostat) barostat = mm.MonteCarloBarostat(1.0 * unit.bar, TEMPid * unit.kelvin, 25) system.addForce(barostat) # prepare simulation platform = mm.Platform.getPlatformByName('CUDA') properties = {'CudaPrecision': 'mixed', 'DeviceIndex': '0'} simulation = app.Simulation(prmtop.topology, system, integrator, platform, properties) simulation.context.setPositions(inpcrd.positions) # minimize print('Minimizing...') simulation.minimizeEnergy() # equilibrate for 100 steps
if not os.path.exists("lambda-%.2f" % lambdas[k]): os.makedirs("lambda-%.2f" % lambdas[k]) simfile = open("lambda-%.2f/simfile.csv" % lambdas[k], "w") if (k == 0): #at lambda 0.0 initialize the system #when we are at the very first iteration of lambda 0, create all the initial system #create an alchemical system alchemical_system = set_lambda_electrostatics(reference_system, [0], lambdas[k]) #add barostat alchemical_barostat = openmm.MonteCarloBarostat( pressure, temperature, 25) alchemical_system.addForce(alchemical_barostat) #add the thermostat alchemical_thermostat = openmm.AndersenThermostat( temperature, collision_rate) alchemical_system.addForce(alchemical_thermostat) #define the Verlet integrator alchemical_integrator = openmm.VerletIntegrator(timestep) #set the simulation alchemical_simulation = app.Simulation(base.topology, alchemical_system, alchemical_integrator, platform, properties) #set the positions based on the coordinate files alchemical_simulation.context.setPositions(base.positions) alchemical_simulation.context.setVelocitiesToTemperature(temperature) else: #if we are doing the other iterations or lambdas, recrate the system, based on the temporary/previous #alchemical system alchemical_system = set_lambda_electrostatics(reference_system, [0],
import lb_loader import pandas as pd import simtk.openmm.app as app import numpy as np import simtk.openmm as mm from simtk import unit as u from openmmtools import hmc_integrators, testsystems sysname = "ljbox" system, positions, groups, temperature, timestep = lb_loader.load(sysname) system.addForce(mm.AndersenThermostat(temperature, 1.0 / u.picoseconds)) integrator = mm.VerletIntegrator(timestep / 4.) context = lb_loader.build(system, integrator, positions, temperature) integrator.step(50000) positions = context.getState(getPositions=True).getPositions() collision_rate = 1.0 / u.picoseconds n_steps = 25 Neff_cutoff = 2000. grid = [] for itype in ["VerletIntegrator"]: for timestep_factor in [1.0, 2.0, 4.0]: d = dict(itype=itype, timestep=timestep / timestep_factor) grid.append(d) for settings in grid: itype = settings.pop("itype")
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()
def NVTequilibration(topology, positions, PLATFORM, simulation_steps, constraints, parameters, reportName, platformProperties, velocities=None): """ Function that runs an equilibration at constant volume conditions. It uses the AndersenThermostat, the VerletIntegrator and applys constrains to the heavy atoms of the protein and ligands :param topology: OpenMM Topology object :param positions: OpenMM Positions object :param PLATFORM: platform in which the minimization will run :type PLATFORM: str :param simulation_steps: number of steps to run :type simulation_steps: int :param constraints: strength of the constrain (units: Kcal/mol) :type constraints: int :param parameters: Object with the parameters for the simulation :type parameters: :py:class:`/simulationrunner/SimulationParameters` -- SimulationParameters object :param platformProperties: Properties specific to the OpenMM platform :type platformProperties: dict :param velocities: OpenMM object with the velocities of the system. Optional, if velocities are not given, random velocities acording to the temperature will be used. :return: The equilibrated OpenMM simulation object """ system = topology.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=parameters.nonBondedCutoff * unit.angstroms, constraints=app.HBonds) system.addForce( mm.AndersenThermostat(parameters.Temperature * unit.kelvin, 1 / unit.picosecond)) integrator = mm.VerletIntegrator(parameters.timeStep * unit.femtoseconds) if constraints: force = mm.CustomExternalForce(str("k*((x-x0)^2+(y-y0)^2+(z-z0)^2)")) force.addGlobalParameter( str("k"), constraints * unit.kilocalories_per_mole / unit.angstroms**2) force.addPerParticleParameter(str("x0")) force.addPerParticleParameter(str("y0")) force.addPerParticleParameter(str("z0")) for j, atom in enumerate(topology.topology.atoms()): if (atom.name in ('CA', 'C', 'N', 'O') and atom.residue.name != "HOH") or (atom.residue.name == parameters.ligandName and atom.element.symbol != "H"): force.addParticle(j, positions[j].value_in_unit(unit.nanometers)) system.addForce(force) simulation = app.Simulation(topology.topology, system, integrator, PLATFORM, platformProperties=platformProperties) simulation.context.setPositions(positions) if velocities: simulation.context.setVelocities(velocities) else: simulation.context.setVelocitiesToTemperature( parameters.Temperature * unit.kelvin, 1) reportFile = "%s_report_NVT" % reportName simulation.reporters.append( CustomStateDataReporter(reportFile, parameters.reporterFreq, step=True, potentialEnergy=True, temperature=True, time_sim=True, volume=True, remainingTime=True, speed=True, totalSteps=parameters.equilibrationLengthNVT, separator="\t")) simulation.step(simulation_steps) return simulation
lib = 'toppar/' # path of force field topology and parameter files params = app.CharmmParameterSet(lib + 'top_all36_prot.rtf', lib + 'par_all36m_prot.prm', lib + 'toppar_water_ions.str') # params = app.CharmmParameterSet(lib+'top_all36_prot.rtf', lib+'par_all36m_prot.prm', lib+'toppar_n010water_ions.str') # in case alternative water model is used to sample more extended states of IDPs platform = mm.Platform.getPlatformByName('CUDA') # make sure the GPU is used system = psf.createSystem(params, nonbondedMethod=app.PME, nonbondedCutoff=1.2 * nanometer, switchDistance=1.0 * nanometer, ewaldErrorTolerance=0.0001, constraints=app.HBonds) system.addForce(mm.AndersenThermostat(300 * kelvin, 1 / picosecond)) # thermostat system.addForce(mm.MonteCarloBarostat(1 * bar, 300 * kelvin)) # barostat integrator = mm.VerletIntegrator(0.002 * picoseconds) # 2 fs time step simulation = app.Simulation(psf.topology, system, integrator, platform) simulation.context.setPositions(crd.positions) # simulation.context.setPositions(pdb.getPositions()) # in case the pdb file is used # simulation.minimizeEnergy(maxIterations = 100) # minimization if start > 0: # restart from the positions and velocities restart = str(start - 1) #with open(jobname+'.'+restart+'.rst', 'r') as f: # the .rst file should only be used if .chk restart file cannot be loaded # simulation.context.setState(mm.XmlSerializer.deserialize(f.read())) with open(jobname + '.' + restart + '.chk', 'rb') as f:
psf.setBox(boxsize*nanometer,boxsize*nanometer,boxsize*nanometer) # Get the coordinates from the PDB crd = app.CharmmCrdFile('ubi_cubi.crd') # in case a crd file instead of pdb is used # Load the parameter set. lib = '/home/xuyou/toppar/' # FULL path of force field topology and parameter files params = app.CharmmParameterSet(lib+'top_all36_prot.rtf', lib+'par_all36m_prot.prm', lib+'toppar_water_ions.str') platform = mm.Platform.getPlatformByName('CUDA') # make sure the GPU is used. Others: Reference, CPU & OpenCL system = psf.createSystem(params, nonbondedMethod=app.LJPME, nonbondedCutoff=0.9*nanometer, ewaldErrorTolerance = 0.0001, constraints=app.HBonds) # The error tolerance is roughly equal to the fractional error in the forces due to truncating the Ewald summation. Default 0.0005. # The default vdwCutoff is as nonbondedCutof, so fswitch or fshift? system.addForce(mm.AndersenThermostat(temp*kelvin, 1/picosecond)) # thermostat: temperature and collision frequency system.addForce(mm.MonteCarloBarostat(pressure*bar, temp*kelvin)) # The barostat does not itself do anything to regulate the temperature integrator = mm.VerletIntegrator(0.002*picoseconds) # 2 fs time step simulation = app.Simulation(psf.topology, system, integrator, platform) # simulation.context.setPositions(pdb.getPositions()) # speicify the initial positions simulation.context.setPositions(crd.positions) # in case the crd file is used simulation.minimizeEnergy(maxIterations = 100) # default tolerance=10*kJ/mol, maxIterations: until converged if start > 0: # restart from the positions and velocities restart=str(start-1) with open(trjPath+jobname+'.'+restart+'.rst', 'r') as f: # the .rst file should only be used if .chk restart file cannot be loaded simulation.context.setState(mm.XmlSerializer.deserialize(f.read()))
#if verbose: print ("%i %i %s"%(atom_index_i, atom_index_j, str([epsilon,d,w]))) n_sbm_contacts = sbm_force.getNumBonds() if verbose: print("%i custom bonds" % (n_sbm_contacts)) system.addForce(sbm_force) sbm_force.setForceGroup(1) for i in xrange(system.getNumForces()): fi = system.getForce(i) if verbose: print(type(fi), fi.getForceGroup()) if verbose: print(system.getNumForces(), "energy terms") if solvent == 'explicit': system.addForce( mm.AndersenThermostat(temperature * unit.kelvin, 1 / unit.picosecond)) integrator = mm.VerletIntegrator(fsstep * unit.femtoseconds) print("Explicit solvent set up.") else: integrator = mm.LangevinIntegrator(temperature * unit.kelvin, 1.0 / unit.picoseconds, fsstep * unit.femtoseconds) integrator.setConstraintTolerance(0.00001) # ?? platform = mm.Platform.getPlatformByName(pform) simulation = app.Simulation(pdb.topology, system, integrator, platform) if pform == "OpenCL": platform.setPropertyValue(simulation.context, "OpenCLDeviceIndex", devices) elif pform == "CUDA":
### Perform Pressure coupling logger.info('Using isotropic barostat') baro = mm.MonteCarloBarostat(1*u.bar, opt.temp*u.kelvin) system.addForce(baro) ### Set integrator if opt.nrespa: if opt.mtsvvvr: logger.info("Use MTSVVVRIntegrator: a multiple timestep Langevin integrator with %.2f / %.2f fs outer/inner timestep." % (opt.timestep, opt.timestep/opt.nrespa ) ) logger.info("The stochastic thermostat collision frequency is %s ps^-1" % opt.gamma_ln ) integrator = MTSVVVRIntegrator(opt.temp*u.kelvin, opt.gamma_ln/u.picosecond, opt.timestep*u.femtosecond, system, opt.nrespa) else: logger.info("Use RESPA MTS Integrator with Anderson Thermostat. %.2f / %.2f fs outer/inner timestep." % (opt.timestep, opt.timestep/opt.nrespa ) ) logger.info('Adding Anderson thermostat at %s K, collison rate of %s psec^-1' % (opt.temp, opt.gamma_ln) ) thermo = mm.AndersenThermostat(opt.temp*u.kelvin, opt.gamma_ln/u.picosecond) system.addForce(thermo) slow = (mm.AmoebaMultipoleForce, mm.AmoebaVdwForce, mm.AmoebaGeneralizedKirkwoodForce, mm.AmoebaWcaDispersionForce, mm.NonbondedForce, mm.CustomNonbondedForce ) found_slow = False for force in system.getForces(): if isinstance(force, slow): found_slow = True force.setForceGroup(1) else: force.setForceGroup(0) if not found_slow: raise ValueError('No slow forces found for MTS integrator!') integrator = mm.MTSIntegrator(opt.timestep*u.femtoseconds, [(0, opt.nrespa), (1, 1)]) else: ### Temperature coupling with Langevin integrator