def serialize(self): """Return the System and positions in serialized XML form. Returns ------- system_xml : str Serialized XML form of System object. state_xml : str Serialized XML form of State object containing particle positions. """ from simtk.openmm import XmlSerializer # Serialize System. system_xml = XmlSerializer.serialize(self._system) # Serialize positions via State. if self._system.getNumParticles() == 0: # Cannot serialize the State of a system with no particles. state_xml = None else: platform = openmm.Platform.getPlatformByName('Reference') integrator = openmm.VerletIntegrator(1.0 * unit.femtoseconds) context = openmm.Context(self._system, integrator, platform) context.setPositions(self._positions) state = context.getState(getPositions=True) del context, integrator state_xml = XmlSerializer.serialize(state) return (system_xml, state_xml)
def serialize_simulation(self) -> str: ROOT_TAG = 'OpenMMSimulation' """ Generate an XML string from a simulation. :param simulation: The simulation to serialize. :return: A string with the content of an XML file describing the simulation. """ implementation = getDOMImplementation() document = implementation.createDocument(None, ROOT_TAG, None) # Extract the PDB positions = self.context.getState(getPositions=True).getPositions() pdb_content = StringIO() app.PDBFile.writeFile(self.topology, positions, pdb_content) pdb_node = document.createElement('pdb') pdb_node.appendChild(document.createTextNode(pdb_content.getvalue())) # Extract the system system_xml_str = XmlSerializer.serialize(self.system) system_document = parseString(system_xml_str) # Extract the integrator integrator_xml_str = XmlSerializer.serialize(self.integrator) integrator_document = parseString(integrator_xml_str) # Combine the element in a single root = document.documentElement root.appendChild(pdb_node) root.appendChild(system_document.documentElement) root.appendChild(integrator_document.documentElement) return root.toprettyxml()
def serialize(item, filename): """ Serialize an OpenMM System, State, or Integrator. Parameters ---------- item : System, State, or Integrator The thing to be serialized filename : str The filename to serialize to """ from simtk.openmm import XmlSerializer if filename[-2:] == 'gz': import gzip with gzip.open(filename, 'wb') as outfile: serialized_thing = XmlSerializer.serialize(item) outfile.write(serialized_thing.encode()) if filename[-3:] == 'bz2': import bz2 with bz2.open(filename, 'wb') as outfile: serialized_thing = XmlSerializer.serialize(item) outfile.write(serialized_thing.encode()) else: with open(filename, 'w') as outfile: serialized_thing = XmlSerializer.serialize(item) outfile.write(serialized_thing)
def dump_xml(system=None, integrator=None, state=None): """ Dump system, integrator, and state to XML for debugging. """ from simtk.openmm import XmlSerializer def write_file(filename, contents): outfile = open(filename, 'w') outfile.write(contents) outfile.close() if system: write_file('system.xml', XmlSerializer.serialize(system)) if integrator: write_file('integrator.xml', XmlSerializer.serialize(integrator)) if state: write_file('state.xml', XmlSerializer.serialize(state)) return
def fix_system(system_xml_filename): """ Set the PME parameters explicitly in a specified system XML file if they are not already set. The file is renamed with '.old' appended, and a corrected file written in its place. Parameters ---------- system_xml_filename : str The name of the serialized system XML file to be modified """ system = XmlSerializer.deserialize(read_file(system_xml_filename)) forces = { system.getForce(force_index).__class__.__name__: system.getForce(force_index) for force_index in range(system.getNumForces()) } force = forces['NonbondedForce'] (alpha, nx, ny, nz) = force.getPMEParameters() if alpha == 0.0 / unit.nanometers: (alpha, nx, ny, nz) = calc_pme_parameters(system) force.setPMEParameters(alpha, nx, ny, nz) serialized_system = XmlSerializer.serialize(system) os.rename(system_xml_filename, system_xml_filename + '.old') write_file(system_xml_filename, serialized_system) return
def check_system(system): """ Check OpenMM System object for pathologies, like duplicate atoms in torsions. Parameters ---------- system : simtk.openmm.System """ forces = { system.getForce(index).__class__.__name__: system.getForce(index) for index in range(system.getNumForces()) } force = forces['PeriodicTorsionForce'] for index in range(force.getNumTorsions()): [i, j, k, l, periodicity, phase, barrier] = force.getTorsionParameters(index) if len(set([i, j, k, l])) < 4: # TODO: Serialize system.xml on exceptions. msg = 'Torsion index %d of self._topology_proposal.new_system has duplicate atoms: %d %d %d %d\n' % ( index, i, j, k, l) msg += 'Serialzed system to system.xml for inspection.\n' from simtk.openmm import XmlSerializer serialized_system = XmlSerializer.serialize(system) outfile = open('system.xml', 'w') outfile.write(serialized_system) outfile.close() raise Exception(msg)
def test_rb_energy_round_trip(tmpdir): """ Make sure that no parameters are lost when reading in RBterms. """ with tmpdir.as_cwd(): # load the molecule and parameterise mol = Ligand.from_file(file_name=get_data("cyclohexane.sdf")) XML().run(molecule=mol, input_files=[get_data("cyclohexane.xml")]) # load the serialised system we extract the parameters from as our reference ref_system = XmlSerializer.deserializeSystem( open("serialised.xml").read()) parm_top = load_topology(mol.to_openmm_topology(), system=ref_system, xyz=mol.openmm_coordinates()) ref_energy = energy_decomposition_system(parm_top, ref_system, platform="Reference") # now we need to build the system from our stored parameters mol.write_parameters(file_name="test.xml") ff = app.ForceField("test.xml") qube_system = ff.createSystem(mol.to_openmm_topology()) with open("qube.xml", "w") as xml_out: xml_out.write(XmlSerializer.serialize(qube_system)) qube_struc = load_topology(mol.to_openmm_topology(), system=qube_system, xyz=mol.openmm_coordinates()) qube_energy = energy_decomposition_system(qube_struc, qube_system, platform="Reference") # compare the decomposed energies of the groups for force_group, energy in ref_energy: for qube_force, qube_e in qube_energy: if force_group == qube_force: assert energy == pytest.approx(qube_e, abs=2e-3)
def build(self, trajectory): """Create a serialized XML state from the first frame in a trajectory Parameteters ------------ trajectory : mdtraj.trajectory.Trajectory The trajectory to take the frame from. We'll use both the the positions and the box vectors (if you're using periodic boundary conditions) """ periodic = False if trajectory.unitcell_vectors is not None: a, b, c = trajectory.unitcell_lengths[0] np.testing.assert_array_almost_equal(trajectory.unitcell_angles[0], np.ones(3) * 90) self.context.setPeriodicBoxVectors([a, 0, 0] * nanometers, [0, b, 0] * nanometers, [0, 0, c] * nanometers) periodic = True self.context.setPositions(trajectory.openmm_positions(0)) state = self.context.getState(getPositions=True, getVelocities=True, getForces=True, getEnergy=True, getParameters=True, enforcePeriodicBox=periodic) return XmlSerializer.serialize(state)
def _execute(self, directory, available_resources): from paprika.restraints.openmm import ( apply_dat_restraint, apply_positional_restraints, ) from simtk.openmm import XmlSerializer # Load in the system to add the restraints to. system = self.input_system.system # Define a custom force group per type of restraint to help # with debugging / analysis. force_groups = { "static": 10, "conformational": 11, "guest": 12, "symmetry": 13, "wall": 14, } # Apply the serialized restraints. restraints = self.load_restraints(self.restraints_path) for restraint_type in force_groups: if restraint_type not in restraints: continue for restraint in restraints[restraint_type]: apply_dat_restraint( system, restraint, self.phase, self.window_index, flat_bottom=restraint_type in ["symmetry", "wall"], force_group=force_groups[restraint_type], ) # Apply the positional restraints to the dummy atoms. apply_positional_restraints( self.input_system.topology_path, system, force_group=15 ) output_system_path = os.path.join(directory, "output.xml") with open(output_system_path, "w") as file: file.write(XmlSerializer.serialize(system)) self.output_system = ParameterizedSystem( substance=self.input_system.substance, force_field=self.input_system.force_field, topology_path=self.input_system.topology_path, system_path=output_system_path, )
def calculate_fragment_energetics(frag_no=1): """ * Create an OpenMM system with a fragment. * Calculate the energy of the system and print. :param frag_no: The number of the fragment being analysed (used to access files). """ os.chdir(f'group2/frag{frag_no}') # Necessary due to size of calculation sys.setrecursionlimit(15000) pdb = PDBFile(f'QUBE_pro_frag{frag_no}.pdb') forcefield = ForceField(f'QUBE_pro_frag{frag_no}_plus.xml') system = forcefield.createSystem( pdb.topology, nonbondedMethod=NoCutoff, ) system = apply_opls_combo(system) with open(f'QUBE_pro_frag{frag_no}_out.xml', 'w') as outfile: serialized_system = XmlSerializer.serialize(system) outfile.write(serialized_system) # Create the integrator to do Langevin dynamics integrator = LangevinIntegrator( 298.15 * unit.kelvin, # Temperature of heat bath 1.0 / unit.picoseconds, # Friction coefficient 2.0 * unit.femtoseconds, # Time step ) platform = Platform.getPlatformByName('CPU') simulation = Simulation(pdb.topology, system, integrator, platform) simulation.context.setPositions(pdb.positions) print('energy from openmm library') print(simulation.context.getState(getEnergy=True).getPotentialEnergy()) structure = parmed.load_file(f'QUBE_pro_frag{frag_no}.pdb') energy_comps = parmed.openmm.energy_decomposition_system(structure, system) total_energy = 0.0 for comp in energy_comps: total_energy += comp[1] print(*comp) print(f'Total energy {total_energy: 6.6f}')
def main(): parser = argparse.ArgumentParser(description='Parameterizes a small \ molecule ligand for use with OpenMM \ using OpenFF') parser.add_argument('-l', '--ligand', action='store', nargs=1, dest='ligand', help='The ligand .sdf file to generate \ parameters for') parser.add_argument('-i', '--input_directory', action='store', nargs=1, dest='input', default=['./'], help='Directory where \ input pdb files are stored') parser.add_argument('-o', '--output_directory', action='store', nargs=1, dest='output', default=['./'], help='Directory where \ output log should be written') args = vars(parser.parse_args()) #Load SDF file from minimize_lig.py lig_sdf = args['input'][0] + '/' + args['ligand'][0] lig_name = lig_sdf.split('.sdf')[-2] lig_off_molecule = Molecule(args['output'][0] + '/' + lig_sdf) force_field = ForceField('test_forcefields/smirnoff99Frosst.offxml') start = time.time() ligand_system = force_field.create_openmm_system( lig_off_molecule.to_topology()) end = time.time() print(end - start) with open(lig_name + '.xml', 'w') as f: f.write(XmlSerializer.serialize(ligand_system))
def test_round_trip_energy(tmpdir, molecule, method, openff, antechamber): """ Make sure that no terms are missing when storing parameters from source by comparing energies. Note we relax the comparison to abs=2e-3 due to differences in nonbonded cutoffs, phase rounding and the ordering improper torsions are applied. """ if method == "openff": engine = openff else: engine = antechamber with tmpdir.as_cwd(): mol = Ligand.from_file(get_data(molecule)) # parametrise the system engine.run(mol) # this will make a serialised system in the folder so get the reference energy ref_system = XmlSerializer.deserializeSystem( open("serialised.xml").read()) parm_top = load_topology(mol.to_openmm_topology(), system=ref_system, xyz=mol.openmm_coordinates()) ref_energy = energy_decomposition_system(parm_top, ref_system, platform="Reference") # now we need to build the system from our stored parameters mol.write_parameters(file_name="test.xml") ff = app.ForceField("test.xml") qube_system = ff.createSystem(mol.to_openmm_topology()) with open("qube.xml", "w") as xml_out: xml_out.write(XmlSerializer.serialize(qube_system)) qube_struc = load_topology(mol.to_openmm_topology(), system=qube_system, xyz=mol.openmm_coordinates()) qube_energy = energy_decomposition_system(qube_struc, qube_system, platform="Reference") # compare the decomposed energies of the groups for force_group, energy in ref_energy: for qube_force, qube_e in qube_energy: if force_group == qube_force: assert energy == pytest.approx(qube_e, abs=2e-3)
def build(self, trajectory): """Create a serialized XML state from the first frame in a trajectory Parameteters ------------ trajectory : mdtraj.trajectory.Trajectory The trajectory to take the frame from. We'll use both the the positions and the box vectors (if you're using periodic boundary conditions) """ periodic = False if trajectory.unitcell_vectors is not None: a, b, c = trajectory.unitcell_lengths[0] np.testing.assert_array_almost_equal(trajectory.unitcell_angles[0], np.ones(3)*90) self.context.setPeriodicBoxVectors([a, 0, 0] * nanometers, [0, b, 0] * nanometers, [0, 0, c] * nanometers) periodic = True self.context.setPositions(trajectory.openmm_positions(0)) state = self.context.getState(getPositions=True, getVelocities=True, getForces=True, getEnergy=True, getParameters=True, enforcePeriodicBox=periodic) return XmlSerializer.serialize(state)
def check_system(system): """ Check OpenMM System object for pathologies, like duplicate atoms in torsions. Parameters ---------- system : simtk.openmm.System """ forces = { system.getForce(index).__class__.__name__ : system.getForce(index) for index in range(system.getNumForces()) } force = forces['PeriodicTorsionForce'] for index in range(force.getNumTorsions()): [i, j, k, l, periodicity, phase, barrier] = force.getTorsionParameters(index) if len(set([i,j,k,l])) < 4: msg = 'Torsion index %d of self._topology_proposal.new_system has duplicate atoms: %d %d %d %d\n' % (index,i,j,k,l) msg += 'Serialzed system to system.xml for inspection.\n' from simtk.openmm import XmlSerializer serialized_system = XmlSerializer.serialize(system) outfile = open('system.xml', 'w') outfile.write(serialized_system) outfile.close() raise Exception(msg)
def to_dict(self): system_xml = XmlSerializer.serialize(self.system) return {'system_xml': system_xml, 'subsets': self.subsets}
def serialize(obj, dirname, objname): filename = './%s/%s' % (dirname, objname) if not os.path.exists(dirname): os.makedirs(dirname) with open(filename, 'w') as objfile: objfile.write(XmlSerializer.serialize(obj))
# DEBUG: Write out initial conditions. print "Serializing..." def write_file(filename, contents): file = open(filename, 'w') file.write(contents) file.close() from simtk.openmm import XmlSerializer state = context.getState(getPositions=True, getVelocities=True, getEnergy=True, getForces=True) write_file(os.path.join(data_directory, '%05d.system.xml' % replicate), XmlSerializer.serialize(system)) write_file(os.path.join(data_directory, '%05d.state.xml' % replicate), XmlSerializer.serialize(state)) write_file(os.path.join(data_directory, '%05d.integrator.xml' % replicate), XmlSerializer.serialize(integrator)) # Record initial data. state = context.getState(getEnergy=True) reduced_volume = state.getPeriodicBoxVolume() / (nparticles * sigma**3) reduced_density = 1.0 / reduced_volume reduced_potential = state.getPotentialEnergy() / kT print "replicate %5d / %5d : initial : density %8.3f | potential %8.3f" % ( replicate, nreplicates, reduced_density, reduced_potential) outfile.write('%8d %12.6f %12.6f\n' % (0, reduced_density, reduced_potential))
async def run(io): print(dir(parmed)) if not os.path.exists(datapath + 'complex.xml') or not os.path.exists(datapath + 'complex.pdb'): print('1: loading Ligand molecule') ligand_off_molecule = Molecule(datapath + 'ligand.sdf') # Load the SMIRNOFF-format Parsley force field #force_field = ForceField('openff_unconstrained-1.0.0.offxml') print("2: Loading the Force Field") force_field = ForceField('openff_unconstrained-1.2.0.offxml') # Parametrize the ligand molecule by creating a Topology object from it print("3: Create Ligand System") ligand_system = force_field.create_openmm_system( ligand_off_molecule.to_topology()) # Read in the coordinates of the ligand from the PDB file ligand_pdbfile = PDBFile(datapath + 'ligand.pdb') # Convert OpenMM System object containing ligand parameters into a ParmEd Structure. print("4: Transforming Ligand System to Parmed") ligand_structure = parmed.openmm.load_topology( ligand_pdbfile.topology, ligand_system, xyz=ligand_pdbfile.positions) print("5: Loading the protein pdb file") receptor_pdbfile = PDBFile(datapath + 'receptor.pdb') # Load the AMBER protein force field through OpenMM. omm_forcefield = app.ForceField('amber14-all.xml') # Parameterize the protein. print("6: Create protein system") receptor_system = omm_forcefield.createSystem( receptor_pdbfile.topology) # Convert the protein System into a ParmEd Structure. print("7: Convert protein system to parmed") receptor_structure = parmed.openmm.load_topology( receptor_pdbfile.topology, receptor_system, xyz=receptor_pdbfile.positions) print("8: Combinding protein & ligand system") complex_structure = receptor_structure + ligand_structure print(dir(complex_structure)) print("9: Create Openmm system") # Convert the Structure to an OpenMM System in vacuum. complex_system = complex_structure.createSystem( nonbondedMethod=NoCutoff, nonbondedCutoff=9.0 * unit.angstrom, constraints=HBonds, removeCMMotion=False) complex_structure.save(datapath + 'complex.pdb', overwrite=True) complex_structure = parmed.load_file(datapath + 'complex.pdb') with open(datapath + 'complex.xml', 'w') as f: f.write(XmlSerializer.serialize(complex_system)) complex_structure = parmed.load_file(datapath + 'complex.pdb') with open(datapath + 'complex.xml', 'r') as f: complex_system = XmlSerializer.deserialize(f.read()) print(dir(complex_structure)) platform = openmm.Platform.getPlatformByName('OpenCL') properties = {'OpenCLPrecision': 'mixed'} integrator = openmm.LangevinIntegrator(300 * unit.kelvin, 91 / unit.picosecond, 0.002 * unit.picoseconds) simulation = openmm.app.Simulation(complex_structure, complex_system, integrator, platform) simulation.context.setPositions(complex_structure.positions) print(" starting minimization") state = simulation.context.getState(getEnergy=True, getForces=True) lastEnergy = state.getPotentialEnergy() potEnergyValue = state.getPotentialEnergy().value_in_unit( unit.kilojoules_per_mole) m = ' Starting pot energy: {:.3f} kJ/mol'.format(potEnergyValue) print(m) await io.emit("setMessage", m) # io.emit("setMessage", m) t0 = time.time() emit_freq = 1 maxIter = 20 # iterations=1 for i in range(100): simulation.minimizeEnergy(tolerance=0, maxIterations=maxIter) state = simulation.context.getState(getPositions=True, getEnergy=True) currentEnergy = state.getPotentialEnergy() positions = state.getPositions( asNumpy=True) * 10 #convert to angstroms p = positions._value.flatten().tolist() # if(abs(lastEnergy._value-currentEnergy._value)<100): # m =' Last pot energy:'+ currentEnergy.__str__()+ " step: {}".format(i+1) # await io.emit("setPositions", {'positions':p, 'message':m}) # break lastEnergy = currentEnergy #print("positions", p[0], p[1], p[2]) m = ' Current pot energy: {:.3f} kJ/mol - step: {:d}'.format( currentEnergy.value_in_unit(unit.kilojoules_per_mole), i + 1) #print(m) if not (i + 1) % emit_freq: await io.emit("setPositions", { 'positions': p, 'message': m, 'step': i }) # io.emit("setPositions", {'positions':p, 'message':m}) # await io.emit("setEnergy", m) #simulation.context.setPositions(complex_structure.positions) state = simulation.context.getState(getPositions=True, getEnergy=True, getForces=True) print(' Final pot energy:', state.getPotentialEnergy()) print(" in ", time.time() - t0) return state
timestep = 1.0 * units.femtoseconds integrator = openmm.VerletIntegrator(timestep) context = openmm.Context(system, integrator) # Set positions context.setPositions(positions) # Evaluate the potential energy. state = context.getState(getEnergy=True, getForces=True, getPositions=True) initial_potential = state.getPotentialEnergy() initial_force = state.getForces(asNumpy=True) # Clean up del context, integrator from simtk.openmm import XmlSerializer # Serialize. system_xml = XmlSerializer.serialize(system) state_xml = XmlSerializer.serialize(state) # Deserialize. system = XmlSerializer.deserialize(system_xml) state = XmlSerializer.deserialize(state_xml) # Compute final potential and force. # Create a Context. timestep = 1.0 * units.femtoseconds integrator = openmm.VerletIntegrator(timestep) context = openmm.Context(system, integrator) # Set positions context.setPositions(positions) # Evaluate the potential energy. state = context.getState(getEnergy=True, getForces=True, getPositions=True)
open(fixed_receptor_file, 'w')) fixed_receptor = PDBFile(fixed_receptor_file) receptor_system = omm_forcefield.createSystem(fixed_receptor.topology) receptor_structure = parmed.openmm.load_topology( fixed_receptor.topology, receptor_system, xyz=fixed_receptor.positions) complex_structure = receptor_structure + ligand_structure complex_system = complex_structure.createSystem( nonbondedMethod=NoCutoff, nonbondedCutoff=9.0 * unit.angstrom, constraints=HBonds, removeCMMotion=False) complex_structure.save(f'{path}/complex.pdb', overwrite=True) with open(f'{path}/system.xml', 'w') as f: f.write(XmlSerializer.serialize(complex_system)) integrator = mm.LangevinIntegrator(300 * unit.kelvin, 1.0 / unit.picoseconds, 2.0 * unit.femtoseconds) integrator.setConstraintTolerance(0.00001) platform = mm.Platform.getPlatformByName('CUDA') properties = {'CudaPrecision': 'mixed'} simulation = app.Simulation(complex_structure.topology, complex_system, integrator, platform, properties) simulation.context.setPositions(complex_structure.positions) print('Minimizing...') simulation.minimizeEnergy() simulation.context.setVelocitiesToTemperature(300 * unit.kelvin)
# Set initial conditions. print "Setting initial positions..." context.setPositions(initial_positions) print "Setting initial velocities appropriate for temperature..." context.setVelocitiesToTemperature(temperature) # DEBUG: Write out initial conditions. print "Serializing..." def write_file(filename, contents): file = open(filename, 'w') file.write(contents) file.close() from simtk.openmm import XmlSerializer state = context.getState(getPositions=True, getVelocities=True, getEnergy=True, getForces=True) write_file(os.path.join(data_directory, '%05d.system.xml' % replicate), XmlSerializer.serialize(system)) write_file(os.path.join(data_directory, '%05d.state.xml' % replicate), XmlSerializer.serialize(state)) write_file(os.path.join(data_directory, '%05d.integrator.xml' % replicate), XmlSerializer.serialize(integrator)) # Record initial data. state = context.getState(getEnergy=True) reduced_volume = state.getPeriodicBoxVolume() / (nparticles * sigma**3) reduced_density = 1.0 / reduced_volume reduced_potential = state.getPotentialEnergy() / kT print "replicate %5d / %5d : initial : density %8.3f | potential %8.3f" % (replicate, nreplicates, reduced_density, reduced_potential) outfile.write('%8d %12.6f %12.6f\n' % (0, reduced_density, reduced_potential)) # Run simulation. for iteration in range(niterations): # Integrate the simulation. integrator.step(nsteps_per_iteration)
if BuildPackmol: pdb = PDBFile('mixture.pdb') positions = pdb.positions # these are in nanometers else: positions = Pos * nanometer simulation.context.setPositions(positions) app.pdbfile.PDBFile.writeModel(simulation.topology, positions, open('test.pdb', 'w')) simulation.context.setPeriodicBoxVectors( periodicboxvectors[0], periodicboxvectors[1], periodicboxvectors[2]) # Set the periodic box vectors # write out xml from simtk.openmm import XmlSerializer serialized_system_gromacs = XmlSerializer.serialize(system) outfile = open('system.xml', 'w') outfile.write(serialized_system_gromacs) outfile.close() # report on platform periodicboxvectors = simulation.context.getState().getPeriodicBoxVectors( ) # Get the periodic box vectors p = simulation.context.getPlatform() force_dict = groupForces(system) nbf_obj = system.getForces()[force_dict['NonbondedForce']] write2log(logname, "Box Size: {}".format(periodicboxvectors)) write2log(logname, "simulation platform: {} \n".format(p.getName())) write2log(logname, "{} \n".format(p.getPropertyNames())) if useGPU:
nonbondedCutoff=1 * nanometer, constraints=HBonds, hydrogenMass=4 * amu) # Add barostat print('Adding barostat...') system.addForce(MonteCarloBarostat(1 * bar, 300 * kelvin)) # Set up integrator integrator = openmmtools.integrators.LangevinIntegrator( 300 * kelvin, 1 / picosecond, timestep) # Serialize and save the system to an xml file print("Seralizing the system to ", output_prefix + ".xml") with open(output_prefix + '.xml', 'w') as f: f.write(XmlSerializer.serialize(system)) # Set up platform print("Setting up the platform...") platform = Platform.getPlatformByName('CUDA') platform.setPropertyDefaultValue('Precision', 'mixed') # Set up simulation print("Setting up the simulation...") simulation = Simulation(modeller.topology, system, integrator, platform) simulation.context.setPositions(modeller.positions) # Minimize the energy print("Minimizing the energy...") print(' initial : %8.3f kcal/mol' % (simulation.context.getState(getEnergy=True).getPotentialEnergy() /
def to_dict(self): system_xml = XmlSerializer.serialize(self.system) return {'system_xml': system_xml}
sys.setrecursionlimit(15000) pdb = app.PDBFile('QUBE_pro.pdb') forcefield = app.ForceField('QUBE_pro.xml') system = forcefield.createSystem( pdb.topology, nonbondedMethod=app.NoCutoff, nonbondedCutoff=500.0 * unit.angstroms, switchDistance=496.0 * unit.angstroms, ) system = apply_opls_combo(system, switching_distance=496.0 * unit.angstroms) with open('QUBE_pro_out.xml', 'w') as outfile: serialized_system = XmlSerializer.serialize(system) outfile.write(serialized_system) # Create the integrator to do Langevin dynamics integrator = LangevinIntegrator( 298.15 * unit.kelvin, # Temperature of heat bath 1.0 / unit.picoseconds, # Friction coefficient 2.0 * unit.femtoseconds, # Time step ) platform = Platform.getPlatformByName('CPU') simulation = app.Simulation(pdb.topology, system, integrator, platform) simulation.context.setPositions(pdb.positions) print('energy from openmm library') print(simulation.context.getState(getEnergy=True).getPotentialEnergy())
def _execute(self, directory, available_resources): from simtk.openmm import XmlSerializer solute_components = [ component for component in self.solute.components if component.role == Component.Role.Solute ] solvent_1_components = [ component for component in self.solvent_1.components if component.role == Component.Role.Solvent ] solvent_2_components = [ component for component in self.solvent_2.components if component.role == Component.Role.Solvent ] if len(solute_components) != 1: raise ValueError( "There must only be a single component marked as a solute.") if len(solvent_1_components) == 0 and len(solvent_2_components) == 0: raise ValueError( "At least one of the solvents must not be vacuum.") # Because of quirks in where Yank looks files while doing temporary # directory changes, we need to copy the coordinate files locally so # they are correctly found. shutil.copyfile( self.solvent_1_coordinates, os.path.join(directory, self._local_solvent_1_coordinates), ) shutil.copyfile(self.solvent_1_system, os.path.join(directory, self._local_solvent_1_system)) shutil.copyfile( self.solvent_2_coordinates, os.path.join(directory, self._local_solvent_2_coordinates), ) shutil.copyfile(self.solvent_2_system, os.path.join(directory, self._local_solvent_2_system)) # Disable the pbc of the any solvents which should be treated # as vacuum. vacuum_system_path = None if len(solvent_1_components) == 0: vacuum_system_path = self._local_solvent_1_system elif len(solvent_2_components) == 0: vacuum_system_path = self._local_solvent_2_system if vacuum_system_path is not None: logger.info( f"Disabling the periodic boundary conditions in {vacuum_system_path} " f"by setting the cutoff type to NoCutoff") with open(os.path.join(directory, vacuum_system_path), "r") as file: vacuum_system = XmlSerializer.deserialize(file.read()) disable_pbc(vacuum_system) with open(os.path.join(directory, vacuum_system_path), "w") as file: file.write(XmlSerializer.serialize(vacuum_system)) # Set up the yank input file. super(SolvationYankProtocol, self)._execute(directory, available_resources) if self.setup_only: return solvent_1_yank_path = os.path.join(directory, "experiments", "solvent1.nc") solvent_2_yank_path = os.path.join(directory, "experiments", "solvent2.nc") self.solvent_1_trajectory_path = os.path.join(directory, "solvent1.dcd") self.solvent_2_trajectory_path = os.path.join(directory, "solvent2.dcd") self._extract_trajectory(solvent_1_yank_path, self.solvent_1_trajectory_path) self._extract_trajectory(solvent_2_yank_path, self.solvent_2_trajectory_path)
# Write initial model print('Writing initial solvated system to %s' % solvated_pdb_filename) with open(output_prefix + solvated_pdb_filename, 'w') as outfile: app.PDBFile.writeFile(modeller.topology, modeller.positions, file=outfile, keepIds=True) # Create the system print('Creating OpenMM System...') system = system_generator.create_system(modeller.topology) # Serialize and save the system to an xml file print("Seralizing the system to ", output_prefix + system_xml_filename) with open(output_prefix + system_xml_filename, 'w') as f: f.write(XmlSerializer.serialize(system)) # Serialize integrator print('Creating integrator and serialize it to %s' % integrator_xml_filename) integrator = openmm.LangevinIntegrator(temperature, collision_rate, timestep) with open(output_prefix + integrator_xml_filename, 'w') as outfile: xml = openmm.XmlSerializer.serialize(integrator) outfile.write(xml) # Minimize print('Minimizing energy...') context = openmm.Context(system, integrator) context.setPositions(modeller.positions) print(' initial : %8.3f kcal/mol' % (context.getState(getEnergy=True).getPotentialEnergy() / unit.kilocalories_per_mole))
def main(): """Set up for a ROCSALT simulation. """ parser = argparse.ArgumentParser( description='Compute relative affinities of compounds screened in ROCS' ) parser.add_argument('--ligands_filenames', dest='ligands_filenames', action='store', nargs='*', help='ligands mol2 files', required=True) parser.add_argument('--receptor_filenames', dest='receptor_filenames', action='store', nargs='*', help='receptor pdb file or prmtop/inpcrd amber files', required=True) args = parser.parse_args() # Determine the path to files input ligands_filenames = [os.path.abspath(i) for i in args.ligands_filenames] receptor_filenames = [os.path.abspath(i) for i in args.receptor_filenames] # Set up the OpenMM system and ParmEd structure rocsalt = RocsaltSystem(ligands_filenames[0], ligands_filenames[1], *receptor_filenames) # Serialize OpenMM system with open('complex_system.xml', 'w') as f: f.write(XmlSerializer.serialize(rocsalt.phases[0].system)) with open('solvent_system.xml', 'w') as f: f.write(XmlSerializer.serialize(rocsalt.phases[1].system)) # Write pdb for index, phase in enumerate(['complex', 'solvent']): coords = rocsalt.phases[index].structure.get_coordinates( frame=0) * unit.angstroms xyz = np.zeros(shape=(1, coords.shape[0], 3)) xyz[0, :, :] = coords.in_units_of(unit.nanometers) / unit.nanometers cell_size = [ rocsalt.phases[index].structure.box[i] * unit.angstroms for i in range(3) ] cell_angles = [ rocsalt.phases[index].structure.box[i] for i in range(3, 6) ] t = md.Trajectory(xyz, topology=rocsalt.phases[index].mdtraj_top, unitcell_lengths=np.asarray([ l.in_units_of(unit.nanometers) / unit.nanometers for l in cell_size ]), unitcell_angles=np.asarray([a for a in cell_angles])) t.image_molecules(inplace=True) t.save_pdb(f'{phase}_phase.pdb') # Serialize ParmEd structure with open('complex_structure.pickle', 'wb') as file: pickle.dump(rocsalt.phases[0].structure, file) with open('solvent_structure.pickle', 'wb') as file: pickle.dump(rocsalt.phases[1].structure, file)
def execute(self, directory, available_resources): from openforcefield.topology import Molecule, Topology logging.info('Generating topology: ' + self.id) pdb_file = app.PDBFile(self.coordinate_file_path) try: with open(self.force_field_path) as file: force_field_source = ForceFieldSource.parse_json(file.read()) except Exception as e: return PropertyEstimatorException( directory=directory, message='{} could not load the ForceFieldSource: {}'.format( self.id, e)) if not isinstance(force_field_source, SmirnoffForceFieldSource): return PropertyEstimatorException( directory=directory, message='Only SMIRNOFF force fields are supported by this ' 'protocol.') force_field = force_field_source.to_force_field() unique_molecules = [] charged_molecules = [] if self.apply_known_charges: charged_molecules = self._generate_known_charged_molecules() # Load in any additional, user specified charged molecules. for charged_molecule_path in self.charged_molecule_paths: charged_molecule = Molecule.from_file(charged_molecule_path, 'MOL2') charged_molecules.append(charged_molecule) for component in self.substance.components: molecule = Molecule.from_smiles(smiles=component.smiles) if molecule is None: return PropertyEstimatorException( directory=directory, message='{} could not be converted to a Molecule'.format( component)) unique_molecules.append(molecule) topology = Topology.from_openmm(pdb_file.topology, unique_molecules=unique_molecules) if len(charged_molecules) > 0: system = force_field.create_openmm_system( topology, charge_from_molecules=charged_molecules) else: system = force_field.create_openmm_system(topology) if system is None: return PropertyEstimatorException( directory=directory, message='Failed to create a system from the' 'provided topology and molecules') from simtk.openmm import XmlSerializer system_xml = XmlSerializer.serialize(system) self.system_path = os.path.join(directory, 'system.xml') with open(self.system_path, 'wb') as file: file.write(system_xml.encode('utf-8')) logging.info('Topology generated: ' + self.id) return self._get_output_dictionary()
continue resname = f'{resa}_{resb}' prefix = os.path.join(folder, resname, resname) print() print() print(prefix) # Prepare AMBER system amber_struct = ParmEd.load_file(prefix + '.prmtop', prefix + '.inpcrd') #print(pmd_struct.atoms) amber_system = amber_struct.createSystem(nonbondedMethod=NoCutoff, #nonbondedCutoff=9.0*unit.angstrom, #constraints=HBonds, removeCMMotion=False) with open('amb_sys.xml','w') as of: of.write(XmlSerializer.serialize(amber_system)) amber_top = amber_struct.topology amber_energy = calc_energy(amber_system, amber_top, amber_struct.positions) print(amber_energy) # prepare openff system mol = Molecule.from_file(f'{prefix}.mol2') #mol = Molecule.from_file('%s.mol2' %(prefix)) #print(mol.to_smiles()) from utils import fix_carboxylate_bond_orders fix_carboxylate_bond_orders(mol) print(mol.to_smiles()) off_top = mol.to_topology()
simulation = Simulation(prmtop.topology, system, integrator, platform) simulation.context.setPositions(pdb.positions) print("Done recording a context for positions.") context = simulation.context context.setVelocitiesToTemperature(temperature) print("Done assigning velocities.") storage_path = os.path.join(work_dir,'traj.nc') #potential_path = os.path.join(work_dir,'potential.txt') simulation.reporters.append(NetCDFReporter(storage_path, reportInterval=250000, coordinates=True)) #simulation.reporters.append(StateDataReporter(potential_path, 1, step=True, potentialEnergy=True)) print("Done specifying simulation.") simulation.step(steps) # Serialize state print('Serializing state to state.xml...') state = context.getState(getPositions=True, getVelocities=True, getEnergy=True, getForces=True) with open('state.xml', 'w') as outfile: xml = XmlSerializer.serialize(state) outfile.write(xml) # Serialize system print('Serializing System to system.xml...') system.setDefaultPeriodicBoxVectors(*state.getPeriodicBoxVectors()) with open('system.xml', 'w') as outfile: xml = XmlSerializer.serialize(system) outfile.write(xml) print(f"Done with {steps} steps of simulation.") print(' final : %8.3f kcal/mol' % (context.getState(getEnergy=True).getPotentialEnergy()/unit.kilocalories_per_mole))
app.Topology.loadBondDefinitions('../residues-nle.xml') pdb = app.PDBFile(NATIVE) forcefield = app.ForceField('amber99sbildn.xml', 'tip3p.xml', '../amber99sbildn-nle.xml') system = forcefield.createSystem(pdb.topology, nonbondedMethod=app.PME, nonbondedCutoff=9.5 * unit.angstroms, constraints=app.HBonds, rigidWater=True, ewaldErrorTolerance=0.0005) # system.addForce(mm.MonteCarloBarostat(1 * unit.atmosphere, TEMPERATURE, 25)) print("Writing system.xml") with open('system.xml', 'w') as f: f.write(XmlSerializer.serialize(system)) # Create Integrator integrator = mm.LangevinIntegrator(TEMPERATURE, 1.0 / unit.picoseconds, TIMESTEP) integrator.setConstraintTolerance(0.00001) print("Writing integrator.xml") with open('integrator.xml', 'w') as f: f.write(XmlSerializer.serialize(integrator)) # platform = mm.Platform.getPlatformByName('CUDA') # properties = {'CudaPrecision': 'mixed'} # simulation = app.Simulation(modeller.topology, system, integrator, platform, # properties)
0: "{target} <- {expr}", 1: "{target} <- {expr}", 2: "{target} <- sum({expr})", 3: "constrain positions", 4: "constrain velocities", 5: "allow forces to update the context state", 6: "if:", 7: "while:", 8: "end" } for scheme in schemes: print(scheme) integrator = LangevinSplittingIntegrator(scheme) # Export integrator to XML with open(os.path.join(DATA_PATH, "{}.xml".format(scheme), "wt")) as f: f.writelines(XmlSerializer.serialize(integrator)) # Also pretty-print (using `step_type_dict`) readable_lines = [] for i in range(integrator.getNumComputations()): step_type, target, expr = integrator.getComputationStep(i) readable_lines.append( step_type_dict[step_type].format(target=target, expr=expr) + "\n") print(readable_lines) # Save pretty-printed results to .txt with open(os.path.join(DATA_PATH, "{}.txt".format(scheme), "wt")) as f: f.writelines(readable_lines)
def execute(self, directory, available_resources): from simtk.openmm import XmlSerializer solute_components = [ component for component in self.solute.components if component.role == Substance.ComponentRole.Solute ] solvent_1_components = [ component for component in self.solvent_1.components if component.role == Substance.ComponentRole.Solvent ] solvent_2_components = [ component for component in self.solvent_2.components if component.role == Substance.ComponentRole.Solvent ] if len(solute_components) != 1: return PropertyEstimatorException( directory, 'There must only be a single component marked as a solute.') if len(solvent_1_components) == 0 and len(solvent_2_components) == 0: return PropertyEstimatorException( directory, 'At least one of the solvents must not be vacuum.') # Because of quirks in where Yank looks files while doing temporary # directory changes, we need to copy the coordinate files locally so # they are correctly found. shutil.copyfile( self.solvent_1_coordinates, os.path.join(directory, self._local_solvent_1_coordinates)) shutil.copyfile(self.solvent_1_system, os.path.join(directory, self._local_solvent_1_system)) shutil.copyfile( self.solvent_2_coordinates, os.path.join(directory, self._local_solvent_2_coordinates)) shutil.copyfile(self.solvent_2_system, os.path.join(directory, self._local_solvent_2_system)) # Disable the pbc of the any solvents which should be treated # as vacuum. vacuum_system_path = None if len(solvent_1_components) == 0: vacuum_system_path = self._local_solvent_1_system elif len(solvent_2_components) == 0: vacuum_system_path = self._local_solvent_2_system if vacuum_system_path is not None: logging.info( f'Disabling the periodic boundary conditions in {vacuum_system_path} ' f'by setting the cutoff type to NoCutoff') with open(os.path.join(directory, vacuum_system_path), 'r') as file: vacuum_system = XmlSerializer.deserialize(file.read()) disable_pbc(vacuum_system) with open(os.path.join(directory, vacuum_system_path), 'w') as file: file.write(XmlSerializer.serialize(vacuum_system)) # Set up the yank input file. result = super(SolvationYankProtocol, self).execute(directory, available_resources) if isinstance(result, PropertyEstimatorException): return result if self.setup_only: return self._get_output_dictionary() solvent_1_yank_path = os.path.join(directory, 'experiments', 'solvent1.nc') solvent_2_yank_path = os.path.join(directory, 'experiments', 'solvent2.nc') self.solvent_1_trajectory_path = os.path.join(directory, 'solvent1.dcd') self.solvent_2_trajectory_path = os.path.join(directory, 'solvent2.dcd') self._extract_trajectory(solvent_1_yank_path, self.solvent_1_trajectory_path) self._extract_trajectory(solvent_2_yank_path, self.solvent_2_trajectory_path) return self._get_output_dictionary()
# also serialize all the testsystems from simtk.openmm import XmlSerializer from benchmark.testsystems import system_loaders for name in system_loaders.keys(): print(name) for constrained in [True, False]: top, sys, pos = system_loaders[name](constrained) c = "constrained" if not constrained: c = "unconstrained" with open("{}_{}.xml".format(name, c), "wt") as f: f.writelines(XmlSerializer.serialize(sys))
def _execute(self, directory, available_resources): import parmed.geometry from paprika.evaluator import Setup from simtk.openmm import NonbondedForce, XmlSerializer, app # Extract the host atoms to determine the offset of the dummy atoms. # noinspection PyTypeChecker input_structure: parmed.Structure = parmed.load_file( self.input_coordinate_path, structure=True ) # Add the dummy atoms to the structure. offset = self.offset.to(unit.angstrom).magnitude Setup.add_dummy_atoms_to_structure( input_structure, [ numpy.array([0, 0, -offset]), numpy.array([0, 0, -3.0 - offset]), numpy.array([0, 2.2, -5.2 - offset]), ], numpy.zeros(3), ) # Shift the structure to avoid issues with the PBC input_structure.coordinates += numpy.array( [ input_structure.box[0] * 0.5, input_structure.box[1] * 0.5, -input_structure.coordinates[-1, 2] + 1.0, ] ) # Save the final coordinates. self.output_coordinate_path = os.path.join(directory, "output.pdb") with open(self.output_coordinate_path, "w") as file: app.PDBFile.writeFile( input_structure.topology, input_structure.positions, file, True ) # Add the dummy atoms to the system. system = self.input_system.system for _ in range(3): system.addParticle(mass=207) for force_index in range(system.getNumForces()): force = system.getForce(force_index) if not isinstance(force, NonbondedForce): continue force.addParticle(0.0, 1.0, 0.0) force.addParticle(0.0, 1.0, 0.0) force.addParticle(0.0, 1.0, 0.0) output_system_path = os.path.join(directory, "output.xml") with open(output_system_path, "w") as file: file.write(XmlSerializer.serialize(system)) self.output_system = ParameterizedSystem( self.input_system.substance, self.input_system.force_field, self.output_coordinate_path, output_system_path, )
def to_dict(self): system_xml = XmlSerializer.serialize(self.system) return {"system_xml": system_xml, "subsets": self.subsets}