def create_system_from_amber(prmtop_filename, crd_filename, verbose=False): """Utility function. Create and return an OpenMM System given a prmtop and crd, AMBER format files. Parameters ---------- prmtop_filename : str (filename) Filename of input AMBER format prmtop file crd_filename : str (filename) Filename of input AMBER format crd file Returns _______ topology : OpenMM Topology system : OpenMM System positions : initial atomic positions (OpenMM) """ # Create System object prmtop = app.AmberPrmtopFile(prmtop_filename) topology = prmtop.topology system = prmtop.createSystem(nonbondedMethod=app.NoCutoff, constraints=None, implicitSolvent=None) # Read coordinates crd = app.AmberInpcrdFile(crd_filename) positions = crd.getPositions() return (topology, system, positions)
def build(self, target_path="", file_name="out"): build_string = self.build_string if self.chains: for chain in self.chains: self.build_string += chain.structure.init_string for index, chain in enumerate(self.chains): if chain.sequence: self.build_string +=""" CHAIN%s = sequence {%s} """%(index, chain.sequence) else: raise ValueError("Empty Chain Index: %s"%index) chain_string = " ".join(["CHAIN%s"%index for index in range(len(self.chains))]) self.build_string +=""" UNION = combine {%s} saveamberparm UNION %s.prmtop %s.inpcrd quit """%(chain_string, target_path+file_name, target_path+file_name) infile = open("%s%s.in"%(target_path, file_name),"w") infile.write(self.build_string) infile.close() self.build_string = build_string #os.remove("%s%s.in"%(target_path, file_name)) result = subprocess.call("tleap -f %s%s.in"%(target_path,file_name),shell=True) self.prmtop = app.AmberPrmtopFile(target_path+file_name+".prmtop") self.inpcrd = app.AmberInpcrdFile(target_path+file_name+".inpcrd") self.topology = self.prmtop.topology self.positions = self.inpcrd.positions self.system = self.prmtop.createSystem(nonbondedMethod=app.NoCutoff, constraints=None, implicitSolvent=app.OBC1) self.integrator = mm.LangevinIntegrator(300.*unit.kelvin, 1./unit.picosecond, 0.002*unit.picoseconds) self.simulation = app.Simulation(self.topology, self.system, self.integrator) else: raise ValueError('Empty Complex! CANNOT build!')
def MinimizedEnergy(filepath): prmtop = app.AmberPrmtopFile(f'{filepath}.prmtop') inpcrd = app.AmberInpcrdFile(f'{filepath}.inpcrd') system = prmtop.createSystem(implicitSolvent=app.GBn2, nonbondedMethod=app.CutoffNonPeriodic, 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) # TODO: This should just recognize whatever the computer is capable of, not force CUDA. platform = mm.Platform.getPlatformByName('CUDA') # TODO: I am not sure if mixed precision is necessary. It dramatically changes the results. properties = {'CudaPrecision': 'mixed'} simulation = app.Simulation(prmtop.topology, system, integrator, platform) simulation.context.setPositions(inpcrd.positions) simulation.minimizeEnergy() energy = simulation.context.getState(getEnergy=True).getPotentialEnergy().value_in_unit(unit.kilojoule/unit.mole) return energy
def test_amber_implicit(prmtop_filename, inpcrd_filename): logger.info("====================================================================") logger.info("Creating system...") from simtk.openmm import app prmtop = app.AmberPrmtopFile(prmtop_filename) reference_system = prmtop.createSystem(constraints=app.HBonds, nonbondedMethod=app.NoCutoff, implicitSolvent=app.OBC1) # Read positions. inpcrd = app.AmberInpcrdFile(inpcrd_filename, loadBoxVectors=False) positions = inpcrd.getPositions(asNumpy=True) # Set box vectors. #box_vectors = inpcrd.getBoxVectors(asNumpy=True) #system.setDefaultPeriodicBoxVectors(box_vectors[0], box_vectors[1], box_vectors[2]) receptor_atoms = range(0,1326) ligand_atoms = range(1326, 1356) # Minimize. logger.info("Minimizing...") timestep = 1.0 * units.femtoseconds integrator = openmm.VerletIntegrator(timestep) context = openmm.Context(reference_system, integrator) context.setPositions(positions) openmm.LocalEnergyMinimizer.minimize(context, 1.0, 100) state = context.getState(getEnergy=True, getPositions=True) positions = state.getPositions(asNumpy=True) del context, integrator logger.info("Done.") alchemical_factory_check(reference_system, positions, receptor_atoms, ligand_atoms) #benchmark(reference_system, positions, receptor_atoms, ligand_atoms) logger.info("====================================================================") logger.info("")
def _setup_OpenMM(self, moiety, phase): if not hasattr(self, '_OpenMM_sims'): self._OpenMM_sims = {} key = moiety + phase if not key in self._OpenMM_sims.keys(): import simtk.openmm import simtk.openmm.app as OpenMM_app prmtop = OpenMM_app.AmberPrmtopFile( self.args.FNs['prmtop'][moiety]) inpcrd = OpenMM_app.AmberInpcrdFile( self.args.FNs['inpcrd'][moiety]) OMM_system = prmtop.createSystem(nonbondedMethod=OpenMM_app.NoCutoff, \ constraints=None, implicitSolvent={ 'OpenMM_Gas':None, 'OpenMM_GBn':OpenMM_app.GBn, 'OpenMM_GBn2':OpenMM_app.GBn2, 'OpenMM_HCT':OpenMM_app.HCT, 'OpenMM_OBC1':OpenMM_app.OBC1, 'OpenMM_OBC2':OpenMM_app.OBC2}[phase]) # Set receptor atom mass to zero to facilitate future minimization if moiety == 'R': for i in range(OMM_system.getNumParticles()): OMM_system.setParticleMass(i, 0) elif moiety == 'RL': for i in range(self.top_RL.L_first_atom) + \ range(self.top_RL.L_first_atom + self.top.universe.numberOfAtoms(), \ OMM_system.getNumParticles()): OMM_system.setParticleMass(i, 0) dummy_integrator = simtk.openmm.LangevinIntegrator(300*simtk.unit.kelvin, \ 1/simtk.unit.picosecond, 0.002*simtk.unit.picoseconds) self._OpenMM_sims[key] = OpenMM_app.Simulation(prmtop.topology, \ OMM_system, dummy_integrator)
def oemol_to_openmm_system(oemol, molecule_name): """ Create an openmm system out of an oemol Returns ------- system : openmm.System object the system from the molecule positions : [n,3] np.array of floats """ _, tripos_mol2_filename = openmoltools.openeye.molecule_to_mol2( oemol, tripos_mol2_filename=molecule_name + '.tripos.mol2', conformer=0, residue_name='MOL') gaff_mol2, frcmod = openmoltools.openeye.run_antechamber( molecule_name, tripos_mol2_filename) prmtop_file, inpcrd_file = openmoltools.utils.run_tleap( molecule_name, gaff_mol2, frcmod) prmtop = app.AmberPrmtopFile(prmtop_file) # NOTE implicit solvent not supported by this SystemGenerator #system = prmtop.createSystem(implicitSolvent=app.OBC1) system = prmtop.createSystem(implicitSolvent=None) crd = app.AmberInpcrdFile(inpcrd_file) return system, crd.getPositions(asNumpy=True), prmtop.topology
def MinimizedEnergy(filepath, gpu=False): prmtop = app.AmberPrmtopFile(f'{filepath}.prmtop') inpcrd = app.AmberInpcrdFile(f'{filepath}.inpcrd') print(f'{filepath}.prmtop') system = prmtop.createSystem(implicitSolvent=app.GBn2, nonbondedMethod=app.CutoffNonPeriodic, nonbondedCutoff=1.0 * unit.nanometers, constraints=app.HBonds, rigidWater=True, ewaldErrorTolerance=0.0005) integrator = mm.LangevinIntegrator(310.15 * unit.kelvin, 1.0 / unit.picoseconds, 2.0 * unit.femtoseconds) integrator.setConstraintTolerance(0.00001) # TODO: This should just recognize whatever the computer is capable of, not force CUDA. if gpu: platform = 'CUDA' else: platform = 'CPU' platform = mm.Platform.getPlatformByName(platform) simulation = app.Simulation(prmtop.topology, system, integrator, platform) simulation.context.setPositions(inpcrd.positions) simulation.minimizeEnergy() energy = simulation.context.getState( getEnergy=True).getPotentialEnergy().value_in_unit(unit.kilojoule / unit.mole) return energy
def _create_implicit_solvent_openmm(self, mol): """ Take a list of oemols, and generate openmm systems and positions for each. Parameters ---------- mol : oemol oemol to be turned into system, positions Returns ------- system : simtk.openmm.System openmm system corresponding to molecule positions : np.array, Quantity nm array of atomic positions """ molecule_name = oeiupac.OECreateIUPACName(mol) openmoltools.openeye.enter_temp_directory() _, tripos_mol2_filename = openmoltools.openeye.molecule_to_mol2( mol, tripos_mol2_filename=molecule_name + '.tripos.mol2', conformer=0, residue_name='MOL') gaff_mol2, frcmod = openmoltools.amber.run_antechamber( molecule_name, tripos_mol2_filename) prmtop_file, inpcrd_file = openmoltools.amber.run_tleap( molecule_name, gaff_mol2, frcmod) prmtop = app.AmberPrmtopFile(prmtop_file) crd = app.AmberInpcrdFile(inpcrd_file) system = prmtop.createSystem(implicitSolvent=self.implicit_solvent, constraints=self.constraints, removeCMMotion=False) positions = crd.getPositions(asNumpy=True) return system, positions
def equilibrate(self): if os.path.exists(self.equil_pdb_filename): return prmtop = app.AmberPrmtopFile(self.prmtop_filename) inpcrd = app.AmberInpcrdFile(self.inpcrd_filename) system = prmtop.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=CUTOFF, constraints=app.HBonds) integrator = mm.LangevinIntegrator(self.temperature, EQUIL_FRICTION, EQUIL_TIMESTEP) system.addForce(mm.MonteCarloBarostat(PRESSURE, self.temperature, BAROSTAT_FREQUENCY)) simulation = app.Simulation(prmtop.topology, system, integrator) simulation.context.setPositions(inpcrd.positions) state = simulation.context.getState(getEnergy=True) print(state.getPotentialEnergy()) print('Minimizing.') simulation.minimizeEnergy() state = simulation.context.getState(getEnergy=True) print(state.getPotentialEnergy()) simulation.context.setVelocitiesToTemperature(self.temperature) print('Equilibrating.') simulation.reporters.append(app.DCDReporter(self.equil_dcd_filename, OUTPUT_FREQUENCY_EQUIL)) simulation.step(N_EQUIL_STEPS) # Re-write a better PDB with correct box sizes. traj = md.load(self.equil_dcd_filename, top=self.prmtop_filename)[-1] traj.save(self.equil_pdb_filename)
def _system_from_prmtop(self, prmtop_path, impcrd_path): # load in Amber input files prmtop = app.AmberPrmtopFile(prmtop_path) inpcrd = app.AmberInpcrdFile(incrd_path) from numpy import array, float64 from simtk import unit positions = 10 * array(inpcrd.positions.value_in_unit(unit.nanometers), float64) # Angstroms self._particle_positions = positions # Ordered atoms to match inpcrd order. # PDB can have atoms for a chain not contiguous, e.g. chain A hetatm at end of file. # But inpcrd has reordered so all chain atoms are contiguous. atom_pos = atoms.scene_coords from chimerax.geometry import find_closest_points i1, i2, near = find_closest_points(positions, atom_pos, 1.0) from numpy import empty, int32 ai = empty((len(i1), ), int32) ai[i1] = near self.atoms = oatoms = atoms[ai] # diff = oatoms.scene_coords - positions # print ('diff', diff.max(), diff.min()) # p2a = {tuple(int(x) for x in a.scene_coord):a for a in atoms} # oatoms = [p2a[tuple(int(x) for x in p)] for p in positions] # print('\n'.join('%s %s' %(str(a1), str(a2)) for a1,a2 in zip(atoms, oatoms))) # print ('inpcrd', positions[:10]) # print ('atoms', atom_pos[:10]) # prepare system and integrator system = prmtop.createSystem(nonbondedMethod=app.CutoffNonPeriodic, nonbondedCutoff=1.0 * unit.nanometers, constraints=app.HBonds, rigidWater=True, ewaldErrorTolerance=0.0005) self._system = system
def parameterize_molecule(molecule, implicitSolvent=app.OBC1, constraints=None, cleanup=True, verbose=False): """ Parameterize the specified molecule for AMBER. Parameters ---------- molecule : openeye.oechem.OEMol The molecule to be parameterized. implicitSolvent : default=app.OBC1 The implicit solvent model to use; one of [None, HCT, OBC1, OBC2, GBn, GBn2] constraints : default=None Constraints to use; one of [None, HBonds, AllBonds, HAngles] cleanup : bool, optional, default=False If True, work done in a temporary working directory will be deleted. Returns ------- system : simtk.openmm.System The OpenMM System of the molecule. topology : simtk.openmm.app.Topology The OpenMM topology of the molecule. positions : The positions of the molecule. gaff_molecule : oechem.OEMol The OEMol molecule with GAFF atom and bond types. """ # Create molecule and geometry. molecule = gaff2xml.openeye.iupac_to_oemol(iupac_name) # Create a a temporary directory. working_directory = tempfile.mkdtemp() old_directory = os.getcwd() os.chdir(working_directory) # Parameterize molecule for AMBER (currently using old machinery for convenience) # TODO: Replace this with gaff2xml stuff amber_prmtop_filename = 'molecule.prmtop' amber_inpcrd_filename = 'molecule.inpcrd' amber_off_filename = 'molecule.off' oldmmtools.parameterizeForAmber(molecule, amber_prmtop_filename, amber_inpcrd_filename, charge_model=None, offfile=amber_off_filename) # Read in the molecule with GAFF atom and bond types print "Overwriting OEMol with GAFF atom and bond types..." gaff_molecule = oldmmtools.loadGAFFMolecule(molecule, amber_off_filename) # Load positions. inpcrd = app.AmberInpcrdFile(amber_inpcrd_filename) positions = inpcrd.getPositions() # Load system (with GB parameters). prmtop = app.AmberPrmtopFile(amber_prmtop_filename) system = prmtop.createSystem(implicitSolvent=implicitSolvent, constraints=constraints) # Clean up temporary files. os.chdir(old_directory) if cleanup: commands.getoutput('rm -r %s' % working_directory) else: print "Work done in %s..." % working_directory return [system, topology, positions, gaff_molecule]
def setup_simulation(self, system, settings): inpcrd = app.AmberInpcrdFile(settings['coordinates']) prmtop = app.AmberPrmtopFile(self.topology) platform, prop = self.setup_platform(settings) simulation = app.Simulation(prmtop.topology, system, self.integrator, platform, prop) simulation.context.setPositions(inpcrd.positions) return simulation
def build_simulation_from_dictionary(self): d = {} d = json.load(open(self.lot_inp_file)) print(d) # crystal use_crystal = d.get('use_crystal', 'no') # PME use_pme = d.get('use_pme', 'no') cutoff = d.get('cutoff', 1.0) # prmtop, inpcrd prmtopfile = d.get('prmtop', None) inpcrdfile = d.get('inpcrd', None) # Integrator will never be used (Simulation requires one) integrator = openmm.VerletIntegrator(1.0) # create simulation object if use_crystal == 'yes': crystal = load_file(prmtopfile, inpcrdfile) if use_pme == 'yes': system = crystal.createSystem( nonbondedMethod=openmm_app.PME, nonbondedCutoff=cutoff * openmm_units.nanometer, ) else: system = crystal.createSystem( nonbondedMethod=openmm_app.NoCutoff, ) self.simulation = openmm_app.Simulation(crystal.topology, system, integrator) # set the box vectors inpcrd = openmm_app.AmberInpcrdFile(inpcrdfile) if inpcrd.boxVectors is not None: print(" setting box vectors") print(inpcrd.boxVectors) self.simulation.context.setPeriodicBoxVectors( *inpcrd.boxVectors) else: prmtop = openmm_app.AmberPrmtopFile(prmtopfile) if use_pme == 'yes': system = prmtop.createSystem( nonbondedMethod=openmm_app.PME, nonbondedCutoff=cutoff * openmm_units.nanometer, ) else: system = prmtop.createSystem( nonbondedMethod=openmm_app.NoCutoff, ) self.simulation = openmm_app.Simulation( prmtop.topology, system, integrator, )
def simulate(inpcrd_filenames, prmtop_filenames, path, niterations=10000, implicit=True, gpu=True, niters=0): """ The program simulates three systems: the ligand alone, protein alone, and complex. Input is a dict of files to the input coordinates (.inpcrd) and parameters (.prmtop) as well as the number of iterations. One iteration is one picosecond. Output is a dict of a list of the ennthalpies calculated using mmgbsa for each system. """ from simtk.openmm import app import simtk.openmm as mm from simtk import unit phases = inpcrd_filenames.keys() nsteps_per_iteration = 500 # 1 picosecond enthalpies = dict() for phase in phases: print("on phase", phase) enthalpies[phase] = np.zeros([niterations]) prmtop = app.AmberPrmtopFile(prmtop_filenames[phase]) inpcrd = app.AmberInpcrdFile(inpcrd_filenames[phase]) system = prmtop.createSystem(implicitSolvent=app.GBn2, nonbondedMethod=app.CutoffNonPeriodic, nonbondedCutoff=2.0*unit.nanometers, constraints=app.HBonds) integrator = mm.LangevinIntegrator(310.15*unit.kelvin, 1.0/unit.picoseconds, 2.0*unit.femtoseconds) integrator.setConstraintTolerance(0.00001) if gpu: platform = 'CUDA' else: platform = 'CPU' platform = mm.Platform.getPlatformByName(platform) if gpu: properties = {'CudaPrecision': 'mixed', 'CudaDeviceIndex' : '0'} else: properties = {} simulation = app.Simulation(prmtop.topology, system, integrator, platform, properties) simulation.context.setPositions(inpcrd.positions) if phase == 'com': simulation.reporters.append(app.PDBReporter(path + '/' + phase + '_output.pdb', 10000)) # Minimize & equilibrate simulation.minimizeEnergy() simulation.context.setVelocitiesToTemperature(310.15*unit.kelvin) simulation.step(100) # Run simulation for iteration in range(niterations): simulation.step(nsteps_per_iteration) state = simulation.context.getState(getEnergy=True) potential_energy = state.getPotentialEnergy() enthalpies[phase][iteration] = potential_energy.value_in_unit(unit.kilojoules_per_mole) del simulation del system del platform return enthalpies
def __init__(self, config: Config): """ :param resource_root: """ super().__init__() self.systemloader_config = config self.prmtop = app.AmberPrmtopFile( self.systemloader_config.resource_root + 'com.prmtop') self.inpcrd = app.AmberInpcrdFile( self.systemloader_config.resource_root + 'com.inpcrd')
def runEquilibration(equilibrationFiles, reportName, parameters, worker): """ Function that runs the whole equilibration process and returns the final pdb :param equilibrationFiles: tuple with the topology (prmtop) in the first position and the coordinates in the second (inpcrd) :type equilibrationFiles: tuple :param outputPDB: string with the pdb to save :type outputPDB: str :param parameters: Object with the parameters for the simulation :type parameters: :py:class:`/simulationrunner/SimulationParameters` -- SimulationParameters object :param worker: Number of the subprocess :type worker: int :returns: str -- a string with the outputPDB """ prmtop, inpcrd = equilibrationFiles prmtop = app.AmberPrmtopFile(prmtop) inpcrd = app.AmberInpcrdFile(inpcrd) PLATFORM = mm.Platform_getPlatformByName(str(parameters.runningPlatform)) if parameters.runningPlatform == "CUDA": platformProperties = {"Precision": "mixed", "DeviceIndex": getDeviceIndexStr(worker, parameters.devicesPerTrajectory, devicesPerReplica=parameters.maxDevicesPerReplica), "UseCpuPme": "false"} else: platformProperties = {} if worker == 0: utilities.print_unbuffered("Running %d steps of minimization" % parameters.minimizationIterations) if parameters.boxCenter or parameters.cylinderBases: dummies = findDummyAtom(prmtop) assert dummies is not None else: dummies = None simulation = minimization(prmtop, inpcrd, PLATFORM, parameters.constraintsMin, parameters, platformProperties, dummies) # Retrieving the state is expensive (especially when running on GPUs) so we # only called it once and then separate positions and velocities state = simulation.context.getState(getPositions=True, getVelocities=True) positions = state.getPositions() velocities = state.getVelocities() if worker == 0: utilities.print_unbuffered("Running %d steps of NVT equilibration" % parameters.equilibrationLengthNVT) simulation = NVTequilibration(prmtop, positions, PLATFORM, parameters.equilibrationLengthNVT, parameters.constraintsNVT, parameters, reportName, platformProperties, velocities=velocities, dummy=dummies) state = simulation.context.getState(getPositions=True, getVelocities=True) positions = state.getPositions() velocities = state.getVelocities() if worker == 0: utilities.print_unbuffered("Running %d steps of NPT equilibration" % parameters.equilibrationLengthNPT) simulation = NPTequilibration(prmtop, positions, PLATFORM, parameters.equilibrationLengthNPT, parameters.constraintsNPT, parameters, reportName, platformProperties, velocities=velocities, dummy=dummies) state = simulation.context.getState(getPositions=True) root, _ = os.path.splitext(reportName) outputPDB = "%s_NPT.pdb" % root with open(outputPDB, 'w') as fw: app.PDBFile.writeFile(simulation.topology, state.getPositions(), fw) return outputPDB
def test_openmm_etoh_sim(): path = './etoh_test/sim_openmm/' topology = 'etoh.prmtop' coordinates = 'etoh.rst7' md_out = 'etoh_openmm.csv' prmtop = app.AmberPrmtopFile(path+topology) inpcrd = app.AmberInpcrdFile(path+coordinates) settings = { 'nonbonded_method': app.PME, 'nonbonded_cutoff': 9*unit.angstrom, 'constraints': app.HBonds, 'temperature': 298.15*unit.kelvin, 'friction': 1/unit.picosecond, 'timestep': 0.002*unit.picosecond } system = prmtop.createSystem( nonbondedMethod = settings['nonbonded_method'], nonbondedCutoff = settings['nonbonded_cutoff'], constraints = settings['constraints'] ) barostat = mm.MonteCarloBarostat(1.0*unit.bar,298.15*unit.kelvin,25) system.addForce(barostat) integrator = LangevinIntegrator( settings['temperature'], settings['friction'], settings['timestep'] ) simulation = app.Simulation(prmtop.topology, system, integrator, mm.Platform.getPlatformByName('CPU')) simulation.context.setPositions(inpcrd.positions) simulation.context.setPeriodicBoxVectors(*inpcrd.boxVectors) simulation.reporters.append(NetCDFReporter(path+'etoh_openmm.nc', 250)) simulation.reporters.append( app.StateDataReporter( path+md_out, 250, step=True, time=True, potentialEnergy=True, kineticEnergy=True, totalEnergy=True, temperature=True, volume=True, density=True ) ) simulation.step(100000)
def step(array): global _INFILE global _BETA global _NSTEP beta = _BETA old_positions, Ntides, is_3prime = array internal = Aptamer("leaprc.ff12SB",_INFILE) identifier = Ntides.replace(" ","") internal.sequence(identifier,Ntides.strip()) internal.unify(identifier) internal.command("saveamberparm union %s.prmtop %s.inpcrd"%(identifier,identifier)) time.sleep(2) #print("WhereamI?") print("Identifier: "+Ntides) volume = (2*math.pi)**5 aptamer_top = app.AmberPrmtopFile("%s.prmtop"%identifier) aptamer_crd = app.AmberInpcrdFile("%s.inpcrd"%identifier) # print("loaded") # if is_3prime == 1: en_pos = [mcmc_sample(aptamer_top, aptamer_crd, old_positions, index, Nsteps=_NSTEP) for index in range(10)] # else: # en_pos_task = [mcmc_sample_five(aptamer_top, aptamer_crd, old_positions, index, Nsteps=200) for index in range(20)] # barrier() # en_pos = value(en_pos_task) en = [] positions = [] positions_s = [] for elem in en_pos: en += elem[0] #print(elem[2], elem[1]) positions_s.append([elem[2], elem[1]]) positions = min(positions_s)[1] fil = open("best_structure%s.pdb"%Ntides,"w") app.PDBFile.writeModel(aptamer_top.topology,positions,file=fil) fil.close() del fil Z = volume*math.fsum([math.exp(-beta*elem) for elem in en])/len(en) P = [math.exp(-beta*elem)/Z for elem in en] S = volume*math.fsum([-elem*math.log(elem*volume) for elem in P])/len(P) print("%s : %s"%(Ntides,S)) return positions, Ntides, S
def ligand_energy(): #self.command("saveamberparm ligand ligand.prmtop ligand.inpcrd") #time.sleep(1) from mpmath import mp as math math.prec = 200 lig_top = app.AmberPrmtopFile("ligand.prmtop") lig_crd = app.AmberInpcrdFile("ligand.inpcrd") lig_system = lig_top.createSystem(nonbondedMethod=NoCutoff, nonbondedCutoff=10*nanometer, constraints=HAngles, implicitSolvent=OBC1) lig_integrator = LangevinIntegrator(300*kelvin, 1/picosecond, 0.002*picoseconds) lig_simulation = Simulation(lig_top.topology, lig_system, lig_integrator) lig_simulation.context.setPositions(lig_crd.positions) lig_state = lig_simulation.context.getState(getEnergy = True) lig_energy = lig_state.getPotentialEnergy().value_in_unit(kilojoule_per_mole) return lig_energy
def from_amber(cls, prmtop, inpcrd, temperature=50 * u.kelvin): prmtop = app.AmberPrmtopFile(prmtop) inpcrd = app.AmberInpcrdFile(inpcrd) system = prmtop.createSystem(nonbondedMethod=app.PME, constraints=app.HBonds, nonbondedCutoff=10 * u.angstroms, switchDistance=8 * u.angstroms) thermodynamic_state = ThermodynamicState(system, temperature=temperature) sampler_state = SamplerState( positions=inpcrd.getPositions(asNumpy=True), box_vectors=inpcrd.boxVectors) return Esmacs(thermodynamic_state, sampler_state, prmtop.topology)
def make_xml_implicit_tyr(inpcrd_filename='constph/examples/calibration-implicit/tyr.inpcrd', prmtop_filename='constph/examples/calibration-implicit/tyr.prmtop', outfile='tyrosine_implicit'): temperature = 300.0 * unit.kelvin outfile1=open('{}.sys.xml'.format(outfile), 'w') outfile2=open('{}.state.xml'.format(outfile), 'w') platform_name = 'CPU' pH = 9.6 inpcrd = app.AmberInpcrdFile(inpcrd_filename) prmtop = app.AmberPrmtopFile(prmtop_filename) positions = inpcrd.getPositions() system = prmtop.createSystem(implicitSolvent=app.OBC2, nonbondedMethod=app.NoCutoff, constraints=app.HBonds) context = minimizer(platform_name, system, positions) outfile1.write(openmm.XmlSerializer.serialize(system)) outfile2.write(openmm.XmlSerializer.serialize(context.getState(getPositions=True)))
def test_binary_mixture_rename(): smiles_string0 = "CCCCCC" smiles_string1 = "CCCCCCCCC" with utils.enter_temp_directory( ): # Prevents creating tons of GAFF files everywhere. mol2_filename0 = "./A.mol2" frcmod_filename0 = "./A.frcmod" mol2_filename1 = "./B.mol2" frcmod_filename1 = "./B.frcmod" gaff_mol2_filenames = [mol2_filename0, mol2_filename1] frcmod_filenames = [frcmod_filename0, frcmod_filename1] prmtop_filename = "./box.prmtop" inpcrd_filename = "./box.inpcrd" openmoltools.openeye.smiles_to_antechamber(smiles_string0, mol2_filename0, frcmod_filename0) openmoltools.openeye.smiles_to_antechamber(smiles_string1, mol2_filename1, frcmod_filename1) openmoltools.utils.randomize_mol2_residue_names(gaff_mol2_filenames) box_pdb_filename = "./box.pdb" gaff_mol2_filenames = [mol2_filename0, mol2_filename1] n_monomers = [10, 20] packed_trj = packmol.pack_box( [md.load(mol2) for mol2 in gaff_mol2_filenames], n_monomers) packed_trj.save(box_pdb_filename) tleap_cmd = openmoltools.amber.build_mixture_prmtop( gaff_mol2_filenames, frcmod_filenames, box_pdb_filename, prmtop_filename, inpcrd_filename) prmtop = app.AmberPrmtopFile(prmtop_filename) inpcrd = app.AmberInpcrdFile(inpcrd_filename) system = prmtop.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=1.0 * u.nanometers, constraints=app.HBonds)
def ligand_box(padding): from mpmath import mp as math math.prec = 200 global forcefield_name process = pexpect.spawn('tleap -f'+forcefield_name) process.sendline('source leaprc.gaff') process.sendline("set default PBradii mbondi2") process.sendline("ligand = load"+_FORMAT+" "+_INFILE) process.sendline("saveamberparm ligand ligand.prmtop ligand.inpcrd") time.sleep(0.5) lig_crd = app.AmberInpcrdFile("ligand.inpcrd") positions = lig_crd.positions.value_in_unit(unit.angstroms) longest_distance = max(power(sum_a(power2(list(positions),2)),0.5))+padding box_x = max([abs(positions[i][0]) for i in range(len(positions))]) + padding box_y = max([abs(positions[i][1]) for i in range(len(positions))]) + padding box_z = max([abs(positions[i][2]) for i in range(len(positions))]) + padding return box_x, box_y, box_z, longest_distance
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)
def make_xml_implicit(inpcrd_filename, prmtop_filename, outfile): temperature = 300.0 * unit.kelvin outfile1 = open("{}.sys.xml".format(outfile), "w") outfile2 = open("{}.state.xml".format(outfile), "w") platform_name = "CPU" pH = 9.6 inpcrd = app.AmberInpcrdFile(inpcrd_filename) prmtop = app.AmberPrmtopFile(prmtop_filename) positions = inpcrd.getPositions() system = prmtop.createSystem(implicitSolvent=app.OBC2, nonbondedMethod=app.NoCutoff, constraints=app.HBonds) context = minimizer(platform_name, system, positions) outfile1.write(openmm.XmlSerializer.serialize(system)) outfile2.write( openmm.XmlSerializer.serialize(context.getState(getPositions=True)))
def build_peptide_tleap(amino_acids): """ Use tleap to generate a peptide topology and positions. Parameters ---------- amino_acids : list of str List of amino acids and caps in three-letter names e.g. ['ACE', 'ALA', 'NME'] Returns ------- topology : simtk.openmm.app.Topology object Topology of the amino acid positions : [n, 3] array positions of atoms """ aa_str = " ".join(amino_acids) filename = "".join(amino_acids) tleapstr = """ source oldff/leaprc.ff99SBildn system = sequence {{ {amino_acid} }} saveamberparm system {filename}.prmtop {filename}.inpcrd """.format(amino_acid=aa_str, filename=filename) cwd = os.getcwd() temp_dir = tempfile.mkdtemp() os.chdir(temp_dir) tleap_file = open("tleap_commands", "w") tleap_file.writelines(tleapstr) tleap_file.close() tleap_cmd_str = "tleap -f %s " % tleap_file.name # call tleap, log output to logger output = getoutput(tleap_cmd_str) logging.debug(output) prmtop = app.AmberPrmtopFile("{filename}.prmtop".format(filename=filename)) inpcrd = app.AmberInpcrdFile("{filename}.inpcrd".format(filename=filename)) topology = prmtop.topology positions = inpcrd.positions os.chdir(cwd) shutil.rmtree(temp_dir) return topology, positions
def make_xml_explicit_tyr(inpcrd_filename='constph/examples/calibration-explicit/tyr.inpcrd', prmtop_filename='constph/examples/calibration-explicit/tyr.prmtop', outfile='tyrosine_explicit'): temperature = 300.0 * unit.kelvin pressure = 1.0 * unit.atmospheres outfile1=open('{}.sys.xml'.format(outfile), 'w') outfile2=open('{}.state.xml'.format(outfile), 'w') platform_name = 'CPU' pH = 9.6 inpcrd = app.AmberInpcrdFile(inpcrd_filename) prmtop = app.AmberPrmtopFile(prmtop_filename) positions = inpcrd.getPositions() system = prmtop.createSystem(implicitSolvent=None, nonbondedMethod=app.CutoffPeriodic, constraints=app.HBonds) system.addForce(openmm.MonteCarloBarostat(pressure, temperature)) context = minimizer(platform_name, system, positions) outfile1.write(openmm.XmlSerializer.serialize(system)) outfile2.write(openmm.XmlSerializer.serialize(context.getState(getPositions=True)))
def convert_input(self): """ Converts inputs to OpenMM readable topologies and positions. Currently supports pdb inputs as well as Amber and Gromacs input files. """ if self.system_info_format == 'pdb': # instantiate OpenMM pdb object if type(self.system_info) is list: self.pdb = OM_app.PDBFile(self.system_info[0]) elif type(self.system_info) is str: self.pdb = OM_app.PDBFile(self.system_info) # instantiate OpenMM forcefield object self.forcefield = OM_app.ForceField(self.ff, self.ff_water) self.topology = self.pdb.topology self.positions = self.pdb.positions self.PeriodicBoxVector = self.topology.getPeriodicBoxVectors() elif self.system_info_format in ['Amber', 'amber']: for fil in self.system_info: if fil.endswith('prmtop'): self.forcefield = OM_app.AmberPrmtopFile(fil) self.topology = self.forcefield.topology self.use_pdb = False if fil.endswith('pdb'): self.pdb = OM_app.PDBFile(fil) self.forcefield = OM_app.ForceField(self.ff, self.ff_water) self.topology = self.pdb.topology self.use_pdb = True if fil.endswith('inpcrd'): self.inpcrd = OM_app.AmberInpcrdFile(fil) self.positions = self.inpcrd.positions self.PeriodicBoxVector = self.inpcrd.boxVectors elif self.system_info_format in ['Gromacs', 'gromacs']: for fil in self.system_info: if 'gro' in fil: self.pdb = OM_app.GromacsGroFile(fil) for fil in self.system_info: if 'top' in fil: self.forcefield = OM_app.GromacsTopFile( fil, periodicBoxVectors=self.pdb.getPeriodicBoxVectors()) self.topology = self.forcefield.topology
def setup_system(self, settings, seed=None): """ Provide a way to create an OpenMM system object with minimization or MD settings. Parameters ---------- settings : dict A dictionary containing simulation settings. Returns ------- simulation : simtk.openmm.app.Simulation The simulation object. system : simtk.openmm.System The system object. """ prmtop = app.AmberPrmtopFile(self.topology) app.AmberInpcrdFile(settings["coordinates"]) self.integrator = mm.LangevinIntegrator( settings["temperature"], settings["friction"], settings["timestep"] ) if seed is not None: self.integrator.setRandomNumberSeed(seed) try: log.debug( "Integrator random number seed: {}".format( self.integrator.getRandomNumberSeed() ) ) except AttributeError: pass system = prmtop.createSystem( nonbondedMethod=settings["nonbonded_method"], implicitSolvent=settings["solvent"], implicitSolventSaltConc=settings["salt"], constraints=settings["constraints"], ) # simulation = app.Simulation(prmtop.topology, system, integrator, # platform, prop) # simulation.context.setPositions(inpcrd.positions) return system
def create_openmm_systems(database, verbose=False, path_to_prmtops=None): """ Create an OpenMM system for each molecule in the database Arguments --------- database : dict dict containing FreeSolv molecules (prepared using prepare_database) verbose : Boolean, optional verbosity path_to_prmtops : str, optional, default=None Path to directory containing inpcrd and prmtop files. If None, will be set to ${FREESOLV_PATH}/mol2files_gaff/ Returns ------- database : dict The FreeSolv database dict containing OpenMM systems for each molecule """ if path_to_prmtops is None: FREESOLV_PATH = os.environ["FREESOLV_PATH"] path_to_prmtops = os.path.join(FREESOLV_PATH + "/mol2files_gaff/") for cid, entry in database.items(): prmtop_filename = os.path.join(path_to_prmtops, "%s.prmtop" % cid) inpcrd_filename = os.path.join(path_to_prmtops, "%s.inpcrd" % cid) # Create OpenMM System object for molecule in vacuum. prmtop = app.AmberPrmtopFile(prmtop_filename) inpcrd = app.AmberInpcrdFile(inpcrd_filename) system = prmtop.createSystem(nonbondedMethod=app.NoCutoff, constraints=app.HBonds, implicitSolvent=None, removeCMMotion=False) positions = inpcrd.getPositions() # Store system and positions. entry['system'] = system entry['positions'] = positions return database