def deserialize_input(self, content): """Retreive the state and topology from the message content The message protocol tries not to pass 'data' around within the messages, but instead pass paths to data. So far we're only sending paths on the local filesystem, but we might could generalize this to HTTP or S3 or something later. The assumption that data can be passed around on the local filesystem shouldn't be built deep into the code at all """ # todo: better name for this function? if content.starting_state.protocol == 'localfs': with open(content.starting_state.path) as f: self.log.info('Opening state file: %s', content.starting_state.path) state = XmlSerializer.deserialize(f.read()) else: raise ValueError('Unknown protocol') if content.topology_pdb.protocol == 'localfs': topology = PDBFile(content.topology_pdb.path).topology else: raise ValueError('Unknown protocol') return state, topology
def _extract_charges(self): """Extracts all of the charges from a system object. Returns ------- list of float """ from simtk import unit as simtk_unit charge_list = [] with open(self._system_path, 'r') as file: system = XmlSerializer.deserialize(file.read()) for force_index in range(system.getNumForces()): force = system.getForce(force_index) if not isinstance(force, openmm.NonbondedForce): continue for atom_index in range(force.getNumParticles()): charge = force.getParticleParameters(atom_index)[0] charge = charge.value_in_unit(simtk_unit.elementary_charge) charge_list.append(charge) return charge_list
def minimization(): # Load OpenMM System file = open(xml_filename, 'r') serialized_system = file.read() system = XmlSerializer.deserialize(serialized_system) # Select Integrator integrator = mm.LangevinIntegrator(TEMPERATURE, MIN_FRICTION, MIN_TIME_STEP) # Set Simulation simulation = app.Simulation(prmtop.topology, system, integrator, MIN_PLATFORM) # Set Position simulation.context.setPositions(inpcrd.positions) state = simulation.context.getState(getEnergy=True) if np.isnan(state.getPotentialEnergy() / kilojoule_per_mole): raise ValueError("The Potential Energy before minimization is NaN") # Minimization print('Minimizing...\n') simulation.minimizeEnergy(tolerance=MIN_TOLERANCE, maxIterations=MIN_STEPS) state = simulation.context.getState(getPositions=True, getEnergy=True) if np.isnan(state.getPotentialEnergy() / kilojoule_per_mole): raise ValueError("The Potential Energy after minimization is NaN") coords = state.getPositions() return coords
def from_xml(cls, path): with open(path) as f: xml = XmlSerializer.deserialize(f.read()) positions = xml.getPositions() velocities = xml.getVelocities() box = xml.getPeriodicBoxVectors() return cls(positions=positions, velocities=velocities, box=box)
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 __init__(self, **kwargs): Calculator.__init__(self, **kwargs) input = self.parameters.input fileType = self.parameters.fileType if fileType == "xyz": print("Generating OpenMM system") self.system,self.topology = self.setUpMM3(self.parameters.ASEmol, self.parameters.atomTypes) positions = [x for x in self.parameters.ASEmol.get_positions()] if fileType == "xml": print("Generating OpenMM system") f = open('OpenMM.xml','r') sys = f.read() #self.system = forcefield.createSystem(topology, nonbondedMethod=self.parameters.nonbondedMethod,nonbondedCutoff=self.parameters.nonbondedCutoff) self.system = XmlSerializer.deserialize(sys) #box_vec = self.system.getDefaultPeriodicBoxVectors() #self.parameters.ASEmol.set_cell([box_vec[0]._value[0]*10,box_vec[1]._value[1]*10,box_vec[2]._value[2]*10]) #self.parameters.ASEmol.pbc = (True,True,True) #self.parameters.ASEmol.wrap() positions = [x for x in self.parameters.ASEmol.get_positions()] # Create a dummy integrator, this doesn't really matter. self.integrator = VerletIntegrator(0.001 * picosecond) self.platform = Platform.getPlatformByName("CPU") self.context = openmm.Context(self.system, self.integrator) self.context.setPositions(positions * angstrom) state = self.context.getState(getEnergy=True) print("Energy: ", state.getPotentialEnergy(), len(positions)) self.n_atoms = len(positions)
def __init__(self, system, integrator=None): # if strings are passed in, assume that they are paths to # xml files on disk if isinstance(system, basestring): with open(system) as f: system = XmlSerializer.deserialize(f.read()) if isinstance(integrator, basestring): with open(integrator) as f: integrator = XmlSerializer.deserialize(f.read()) if integrator is None: # this integrator isn't really necessary, but it has to be something # for the openmm API to let us serialize the state integrator = VerletIntegrator(2*femtoseconds) self.context = Context(system, integrator, Platform.getPlatformByName('Reference'))
def __init__(self, system, integrator=None): # if strings are passed in, assume that they are paths to # xml files on disk if isinstance(system, basestring): with open(system) as f: system = XmlSerializer.deserialize(f.read()) if isinstance(integrator, basestring): with open(integrator) as f: integrator = XmlSerializer.deserialize(f.read()) if integrator is None: # this integrator isn't really necessary, but it has to be something # for the openmm API to let us serialize the state integrator = VerletIntegrator(2 * femtoseconds) self.context = Context(system, integrator, Platform.getPlatformByName('Reference'))
def start(self): # load up the system and integrator files with open(self.system_xml) as f: self.system = XmlSerializer.deserialize(f.read()) # reset the random number seed for any random # forces (andersen thermostat, montecarlo barostat) for i in range(self.system.getNumForces()): force = self.system.getForce(i) if hasattr(force, 'setRandomNumberSeed'): force.setRandomNumberSeed(random_seed()) with open(self.integrator_xml) as f: self.integrator = XmlSerializer.deserialize(f.read()) # reset the random number seed for a stochastic integrator if hasattr(self.integrator, 'setRandomNumberSeed'): self.integrator.setRandomNumberSeed(random_seed()) super(OpenMMSimulator, self).start()
def nvt(coords): # Load OpenMM System file = open(xml_filename, 'r') serialized_system = file.read() system = XmlSerializer.deserialize(serialized_system) # Select Integrator integrator = mm.LangevinIntegrator(TEMPERATURE, NVT_FRICTION, NVT_TIME_STEP) # Set Simulation simulation = app.Simulation(pdb.topology, system, integrator, NVT_PLATFORM, NVT_PROPERTIES) #DEBUG STUFF properties = NVT_PLATFORM.getPropertyValue(simulation.context, 'DeviceIndex') print(properties) print(NVT_PLATFORM.getPropertyNames()) print(NVT_PLATFORM.getSpeed()) #DEBUG STUFF # Set Position and velocities simulation.context.setPositions(coords) simulation.context.setVelocitiesToTemperature(TEMPERATURE) # Set Reporter simulation.reporters.append( app.DCDReporter(nvt_dcd_filename, NVT_OUTPUT_FREQ)) simulation.reporters.append( app.StateDataReporter(nvt_data_filename, NVT_DATA_FREQ, step=True, potentialEnergy=True, temperature=True, density=True)) state = simulation.context.getState(getEnergy=True) if np.isnan(state.getPotentialEnergy() / kilojoule_per_mole): raise ValueError("The Potential Energy before NVT is NaN") print('NVT...\n') simulation.step(NVT_STEPS) state = simulation.context.getState(getPositions=True, getVelocities=True, getEnergy=True) if np.isnan(state.getPotentialEnergy() / kilojoule_per_mole): raise ValueError("The Potential Energy after NVT is NaN") coords = state.getPositions() velocities = state.getVelocities() return coords, velocities
def npt(coords, velocities): # Create OpenMM System file = open(xml_filename, 'r') serialized_system = file.read() system = XmlSerializer.deserialize(serialized_system) # Select Integrator integrator = mm.LangevinIntegrator(TEMPERATURE, NPT_FRICTION, NPT_TIME_STEP) # Set Barostat system.addForce( mm.MonteCarloBarostat(PRESSURE, TEMPERATURE, BAROSTAT_FREQUENCY)) # Set Simulation simulation = app.Simulation(prmtop.topology, system, integrator, NPT_PLATFORM, NPT_PROPERTIES) # Set Position and velocities simulation.context.setPositions(coords) simulation.context.setVelocities(velocities) # Set Reporter simulation.reporters.append( app.DCDReporter(npt_dcd_filename, NPT_OUTPUT_FREQ)) simulation.reporters.append( app.StateDataReporter(npt_data_filename, NPT_DATA_FREQ, step=True, potentialEnergy=True, temperature=True, density=True)) state = simulation.context.getState(getEnergy=True) if np.isnan(state.getPotentialEnergy() / kilojoule_per_mole): raise ValueError("The Potential Energy before NPT is NaN") print('NPT...\n') simulation.step(NPT_STEPS) state = simulation.context.getState(getPositions=True, getVelocities=True, getEnergy=True) if np.isnan(state.getPotentialEnergy() / kilojoule_per_mole): raise ValueError("The Potential Energy after NPT is NaN") coords = state.getPositions() velocities = state.getVelocities() box = state.getPeriodicBoxVectors() return coords, velocities, box
def get_xml(xml_file): # TODO file access control attempt = 0 retries = 500 if not xml_file.endswith('.xml'): raise IOError("{} must end in '.xml' for reading as XML file".format(xml_file)) while True: try: with open(xml_file) as f: xml = f.read() cereal = XmlSerializer.deserialize(xml) return xml, cereal except ValueError as e: if attempt < retries: attempt += 1 time.sleep(5*random.random()) else: raise e
def from_dict(cls, dct): system_xml = dct['system_xml'] subsets = dct['subsets'] return cls(XmlSerializer.deserialize(system_xml), subsets)
def deserialize(file): with open(file) as stream: data = stream.read().replace('\n', '') return XmlSerializer.deserialize(data)
# coding: utf-8 import os import nglview as nv import pytraj as pt from progressbar import ProgressBar, Bar, Percentage, Timer, ETA, progressbar import simtk.unit as unit from simtk.openmm.app import PDBFile, DCDReporter, StateDataReporter, Simulation from simtk.openmm import XmlSerializer, LangevinIntegrator, MonteCarloBarostat, Platform # Initialization with open("restrained.xml", "r") as f: system = XmlSerializer.deserialize(f.read()) coords = PDBFile(os.path.join('simulations', 'npt_production', 'input.pdb')) dt = 4.0 * unit.femtoseconds Temp = 298.15 * unit.kelvin Pres = 1.01325 * unit.bar out_freq = 2500 print_freq = 50000 MD_steps = 12500000 bar_freq = int(MD_steps / print_freq) integrator = LangevinIntegrator(Temp, 1.0 / unit.picoseconds, dt) barostat = MonteCarloBarostat(Pres, Temp, 100) system.addForce(barostat) # Simulation Object
def production(coords, velocities, box): # Create OpenMM System file = open(xml_filename, 'r') serialized_system = file.read() system = XmlSerializer.deserialize(serialized_system) # Select Integrator integrator = mm.LangevinIntegrator(TEMPERATURE, PROD_FRICTION, PROD_TIME_STEP) # Set Barostat system.addForce( mm.MonteCarloBarostat(PRESSURE, TEMPERATURE, BAROSTAT_FREQUENCY)) # Set Simulation simulation = app.Simulation(prmtop.topology, system, integrator, PROD_PLATFORM, PROD_PROPERTIES) # Set Position and velocities simulation.context.setPositions(coords) if velocities is not None: simulation.context.setVelocities(velocities) else: #reset simulation.context.setVelocitiesToTemperature(TEMPERATURE) # Set Box #box = box.in_units_of(nanometer) simulation.context.setPeriodicBoxVectors(box[0], box[1], box[2]) # Set Reporter simulation.reporters.append( app.DCDReporter(prod_dcd_filename, PROD_OUTPUT_FREQ)) simulation.reporters.append( app.StateDataReporter(prod_data_filename, PROD_DATA_FREQ, step=True, potentialEnergy=True, temperature=True, density=True)) state = simulation.context.getState(getEnergy=True) if np.isnan(state.getPotentialEnergy() / kilojoule_per_mole): raise ValueError("The Potential Energy before Production is NaN") print('PRODUCTION...\n') converged = False while not converged: simulation.step(PROD_STEPS) d = pd.read_csv(prod_data_filename, names=["step", "U", "Temperature", "Density"], skiprows=1) density_ts = np.array(d.Density) [t0, g, Neff] = ts.detectEquilibration(density_ts, nskip=1000) density_ts = density_ts[t0:] density_mean_stderr = density_ts.std() / np.sqrt(Neff) print("Current density mean std error = %f g/mL" % density_mean_stderr) if density_mean_stderr < STD_ERROR_TOLERANCE: converged = True print("...Convergence is OK\n") state = simulation.context.getState(getPositions=True, getVelocities=True, getEnergy=True) if np.isnan(state.getPotentialEnergy() / kilojoule_per_mole): raise ValueError("The Potential Energy after Production is NaN") coords = state.getPositions() velocities = state.getVelocities() box = state.getPeriodicBoxVectors() return coords, velocities, box
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) final_potential = state.getPotentialEnergy() final_force = state.getForces(asNumpy=True) # Clean up del context, integrator
from simtk import openmm, unit from simtk.openmm import app from mdtraj.reporters import NetCDFReporter from simtk.openmm import XmlSerializer logger = logging.getLogger(__name__) platform = openmm.Platform.getPlatformByName('CUDA') integrator = openmm.LangevinIntegrator(310 * unit.kelvin, 1.0 / unit.picoseconds, 2 * unit.femtosecond) #integrator.setRandomNumberSeed(129) with open('openmm_system.xml', 'r') as infile: openmm_system = XmlSerializer.deserialize(infile.read()) pdbx = app.PDBxFile('mem_prot_md_system.pdbx') positions = [(pos[0], pos[1], pos[2] + 1 * unit.nanometers) for pos in pdbx.positions] openmm_simulation = app.Simulation(pdbx.topology, openmm_system, integrator, platform) ####### Reading positions from mdtraj trajectory ########################## #topology = md.Topology.from_openmm(pdbx.topology) #t = md.load('traj.nc',top=topology) #positions = t.openmm_positions(1999) ############################################################################ openmm_simulation.context.setPositions(positions) mdtraj_reporter = NetCDFReporter('steered_forward.nc', 500) openmm_simulation.reporters.append(mdtraj_reporter) openmm_simulation.reporters.append( app.StateDataReporter('state_forward.log',
def main(): import doctest import argparse parser = argparse.ArgumentParser( description= "Check OpenMM computed energies and forces across all platforms for a suite of test systems." ) parser.add_argument('-o', '--outfile', dest='logfile', action='store', type=str, default=None) parser.add_argument('-v', dest='verbose', action='store_true') parser.add_argument('-i', '--input', dest="input_data_path", action="store", type=str) parser.add_argument('-t', '--tuneplatform', dest="tune_pme_platform", action="store", type=str, default=None) parser.add_argument('-p', '--precision', dest="precision", action="store", type=str, default='single') args = parser.parse_args() verbose = args.verbose # Don't display extra debug information. config_root_logger(verbose, log_file_path=args.logfile) # Print version. logger.info("OpenMM version: %s" % openmm.version.version) logger.info("") # List all available platforms logger.info("Available platforms:") for platform_index in range(openmm.Platform.getNumPlatforms()): platform = openmm.Platform.getPlatform(platform_index) logger.info("%5d %s" % (platform_index, platform.getName())) logger.info("") # Test all systems on Reference platform. platform = openmm.Platform.getPlatformByName("Reference") print('Testing Reference platform...') doctest.testmod() # Compute energy error made on all test systems for other platforms. # Make a count of how often set tolerance is exceeded. tests_failed = 0 # number of times tolerance is exceeded tests_passed = 0 # number of times tolerance is not exceeded logger.info("%16s%16s %16s %16s %16s %16s" % ("platform", "precision", "potential", "error", "force mag", "rms error")) reference_platform = openmm.Platform.getPlatformByName("Reference") n_runs = get_num_runs(args.input_data_path) for run in range(n_runs): print("Deserializing XML files for RUN%d" % run) state = XmlSerializer.deserialize( read_file( os.path.join(args.input_data_path, "RUN%d" % run, "state0.xml"))) integrator = XmlSerializer.deserialize( read_file( os.path.join(args.input_data_path, "RUN%d" % run, "integrator.xml"))) system = XmlSerializer.deserialize( read_file( os.path.join(args.input_data_path, "RUN%d" % run, "system.xml"))) # Update system periodic box vectors based on state. system.setDefaultPeriodicBoxVectors(*state.getPeriodicBoxVectors()) # Create test system instance. positions = state.getPositions() # Get PME parameters forces = [ system.getForce(force_index) for force_index in range(system.getNumForces()) ] force_dict = {force.__class__.__name__: force for force in forces} print("PME parameters:") force = force_dict['NonbondedForce'] print(force.getPMEParameters()) (alpha, nx, ny, nz) = force.getPMEParameters() if alpha == 0.0 / unit.nanometers: # Set PME parameters explicitly. print("Setting PME parameters explicitly...") (alpha, nx, ny, nz) = calc_pme_parameters(system) print(alpha, nx, ny, nz) print(type(nx)) force.setPMEParameters(alpha, int(nx), int(ny), int(nz)) print(force.getPMEParameters()) if args.tune_pme_platform: # Tune PME parameters for specified platform. from optimizepme import optimizePME properties = dict() platform = openmm.Platform.getPlatformByName( args.tune_pme_platform) print( "Tuning PME parameters for platform '%s' precision model '%s'..." % (platform.getName(), args.precision)) if (platform.getName() == 'OpenCL'): properties['OpenCLPrecision'] = args.precision elif (platform.getName() == 'CUDA'): properties['CudaPrecision'] = args.precision minCutoff = 0.8 * unit.nanometers maxCutoff = 1.2 * unit.nanometers optimizePME(system, integrator, positions, platform, properties, minCutoff, maxCutoff) class_name = 'RUN%d' % run logger.info("%s (%d atoms)" % (class_name, system.getNumParticles())) # Compute reference potential and force [reference_potential, reference_force ] = compute_potential_and_force(system, positions, reference_platform) # Test all platforms. test_success = True for platform_index in range(openmm.Platform.getNumPlatforms()): try: platform = openmm.Platform.getPlatform(platform_index) platform_name = platform.getName() # Define precision models to test. if platform_name == 'Reference': precision_models = ['double'] else: precision_models = ['single'] if platform.supportsDoublePrecision(): precision_models.append('double') for precision_model in precision_models: # Set precision. if platform_name == 'CUDA': platform.setPropertyDefaultValue( 'CudaPrecision', precision_model) if platform_name == 'OpenCL': platform.setPropertyDefaultValue( 'OpenCLPrecision', precision_model) # Compute potential and force. [platform_potential, platform_force ] = compute_potential_and_force(system, positions, platform) # Compute error in potential. potential_error = platform_potential - reference_potential # Compute per-atom RMS (magnitude) and RMS error in force. force_unit = unit.kilocalories_per_mole / unit.nanometers natoms = system.getNumParticles() force_mse = (( (reference_force - platform_force) / force_unit)** 2).sum() / natoms * force_unit**2 force_rmse = unit.sqrt(force_mse) force_ms = ((platform_force / force_unit)** 2).sum() / natoms * force_unit**2 force_rms = unit.sqrt(force_ms) logger.info( "%16s%16s %16.6f kcal/mol %16.6f kcal/mol %16.6f kcal/mol/nm %16.6f kcal/mol/nm" % (platform_name, precision_model, platform_potential / unit.kilocalories_per_mole, potential_error / unit.kilocalories_per_mole, force_rms / force_unit, force_rmse / force_unit)) # Mark whether tolerance is exceeded or not. if abs(potential_error) > ENERGY_TOLERANCE: test_success = False logger.info( "%32s WARNING: Potential energy error (%.6f kcal/mol) exceeds tolerance (%.6f kcal/mol). Test failed." % ("", potential_error / unit.kilocalories_per_mole, ENERGY_TOLERANCE / unit.kilocalories_per_mole)) if abs(force_rmse) > FORCE_RMSE_TOLERANCE: test_success = False logger.info( "%32s WARNING: Force RMS error (%.6f kcal/mol/nm) exceeds tolerance (%.6f kcal/mol/nm). Test failed." % ("", force_rmse / force_unit, FORCE_RMSE_TOLERANCE / force_unit)) if verbose: for atom_index in range(natoms): for k in range(3): logger.info( "%12.6f" % (reference_force[atom_index, k] / force_unit), end="") logger.info(" : ", end="") for k in range(3): logger.info( "%12.6f" % (platform_force[atom_index, k] / force_unit), end="") except Exception as e: logger.info(e) if test_success: tests_passed += 1 else: tests_failed += 1 if (test_success is False): # Write XML files of failed tests to aid in debugging. # Place forces into different force groups. forces = [ system.getForce(force_index) for force_index in range(system.getNumForces()) ] force_group_names = dict() group_index = 0 for force_index in range(system.getNumForces()): force_name = forces[force_index].__class__.__name__ if force_name == 'NonbondedForce': forces[force_index].setForceGroup(group_index + 1) force_group_names[group_index] = 'NonbondedForce (direct)' group_index += 1 forces[force_index].setReciprocalSpaceForceGroup( group_index + 1) force_group_names[ group_index] = 'NonbondedForce (reciprocal)' group_index += 1 else: forces[force_index].setForceGroup(group_index + 1) force_group_names[group_index] = force_name group_index += 1 ngroups = len(force_group_names) # Test by force group. logger.info("Breakdown of discrepancies by Force component:") nforces = system.getNumForces() for force_group in range(ngroups): force_name = force_group_names[force_group] logger.info(force_name) [reference_potential, reference_force] = compute_potential_and_force_by_force_group( system, positions, reference_platform, force_group) logger.info( "%16s%16s %16s %16s %16s %16s" % ("platform", "precision", "potential", "error", "force mag", "rms error")) for platform_index in range(openmm.Platform.getNumPlatforms()): try: platform = openmm.Platform.getPlatform(platform_index) platform_name = platform.getName() # Define precision models to test. if platform_name == 'Reference': precision_models = ['double'] else: precision_models = ['single'] if platform.supportsDoublePrecision(): precision_models.append('double') for precision_model in precision_models: # Set precision. if platform_name == 'CUDA': platform.setPropertyDefaultValue( 'CudaPrecision', precision_model) if platform_name == 'OpenCL': platform.setPropertyDefaultValue( 'OpenCLPrecision', precision_model) # Compute potential and force. [platform_potential, platform_force ] = compute_potential_and_force_by_force_group( system, positions, platform, force_group) # Compute error in potential. potential_error = platform_potential - reference_potential # Compute per-atom RMS (magnitude) and RMS error in force. force_unit = unit.kilocalories_per_mole / unit.nanometers natoms = system.getNumParticles() force_mse = ( ((reference_force - platform_force) / force_unit)**2).sum() / natoms * force_unit**2 force_rmse = unit.sqrt(force_mse) force_ms = ((platform_force / force_unit)** 2).sum() / natoms * force_unit**2 force_rms = unit.sqrt(force_ms) logger.info( "%16s%16s %16.6f kcal/mol %16.6f kcal/mol %16.6f kcal/mol/nm %16.6f kcal/mol/nm" % (platform_name, precision_model, platform_potential / unit.kilocalories_per_mole, potential_error / unit.kilocalories_per_mole, force_rms / force_unit, force_rmse / force_unit)) except Exception as e: logger.info(e) pass logger.info("") logger.info("%d tests failed" % tests_failed) logger.info("%d tests passed" % tests_passed) if (tests_failed > 0): # Signal failure of test. sys.exit(1) else: sys.exit(0)
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
def _setup_simulation_objects(self, temperature, pressure, available_resources): """Initializes the objects needed to perform the simulation. This comprises of a context, and an integrator. Parameters ---------- temperature: simtk.unit.Quantity The temperature to run the simulation at. pressure: simtk.unit.Quantity The pressure to run the simulation at. available_resources: ComputeResources The resources available to run on. Returns ------- simtk.openmm.Context The created openmm context which takes advantage of the available compute resources. openmmtools.integrators.LangevinIntegrator The Langevin integrator which will propogate the simulation. """ import openmmtools from simtk.openmm import XmlSerializer # Create a platform with the correct resources. if not self.allow_gpu_platforms: from propertyestimator.backends import ComputeResources available_resources = ComputeResources( available_resources.number_of_threads) platform = setup_platform_with_resources(available_resources, self.high_precision) # Load in the system object from the provided xml file. with open(self.system_path, 'r') as file: system = XmlSerializer.deserialize(file.read()) # Disable the periodic boundary conditions if requested. if not self.enable_pbc: disable_pbc(system) pressure = None # Use the openmmtools ThermodynamicState object to help # set up a system which contains the correct barostat if # one should be present. openmm_state = openmmtools.states.ThermodynamicState( system=system, temperature=temperature, pressure=pressure) system = openmm_state.get_system(remove_thermostat=True) # Set up the integrator. thermostat_friction = pint_quantity_to_openmm(self.thermostat_friction) timestep = pint_quantity_to_openmm(self.timestep) integrator = openmmtools.integrators.LangevinIntegrator( temperature=temperature, collision_rate=thermostat_friction, timestep=timestep) # Create the simulation context. context = openmm.Context(system, integrator, platform) # Initialize the context with the correct positions etc. input_pdb_file = app.PDBFile(self.input_coordinate_file) if self.enable_pbc: # Optionally set up the box vectors. box_vectors = input_pdb_file.topology.getPeriodicBoxVectors() if box_vectors is None: raise ValueError('The input file must contain box vectors ' 'when running with PBC.') context.setPeriodicBoxVectors(*box_vectors) context.setPositions(input_pdb_file.positions) context.setVelocitiesToTemperature(temperature) return context, integrator
def main(): import doctest import argparse parser = argparse.ArgumentParser(description="Check OpenMM computed energies and forces across all platforms for a suite of test systems.") parser.add_argument('-o', '--outfile', dest='logfile', action='store', type=str, default=None) parser.add_argument('-v', dest='verbose', action='store_true') parser.add_argument('-i', '--input', dest="input_data_path", action="store", type=str) parser.add_argument('-t', '--tuneplatform', dest="tune_pme_platform", action="store", type=str, default=None) parser.add_argument('-p', '--precision', dest="precision", action="store", type=str, default='single') args = parser.parse_args() verbose = args.verbose # Don't display extra debug information. config_root_logger(verbose, log_file_path=args.logfile) # Print version. logger.info("OpenMM version: %s" % openmm.version.version) logger.info("") # List all available platforms logger.info("Available platforms:") for platform_index in range(openmm.Platform.getNumPlatforms()): platform = openmm.Platform.getPlatform(platform_index) logger.info("%5d %s" % (platform_index, platform.getName())) logger.info("") # Test all systems on Reference platform. platform = openmm.Platform.getPlatformByName("Reference") print('Testing Reference platform...') doctest.testmod() # Compute energy error made on all test systems for other platforms. # Make a count of how often set tolerance is exceeded. tests_failed = 0 # number of times tolerance is exceeded tests_passed = 0 # number of times tolerance is not exceeded logger.info("%16s%16s %16s %16s %16s %16s" % ("platform", "precision", "potential", "error", "force mag", "rms error")) reference_platform = openmm.Platform.getPlatformByName("Reference") n_runs=get_num_runs(args.input_data_path) for run in range(n_runs): print("Deserializing XML files for RUN%d" % run) state = XmlSerializer.deserialize(read_file(os.path.join(args.input_data_path,"RUN%d" % run, "state0.xml"))) integrator = XmlSerializer.deserialize(read_file(os.path.join(args.input_data_path,"RUN%d" % run, "integrator.xml"))) system = XmlSerializer.deserialize(read_file(os.path.join(args.input_data_path,"RUN%d" % run, "system.xml"))) # Update system periodic box vectors based on state. system.setDefaultPeriodicBoxVectors(*state.getPeriodicBoxVectors()) # Create test system instance. positions = state.getPositions() # Get PME parameters forces = [ system.getForce(force_index) for force_index in range(system.getNumForces()) ] force_dict = { force.__class__.__name__ : force for force in forces } print("PME parameters:") force = force_dict['NonbondedForce'] print(force.getPMEParameters()) (alpha, nx, ny, nz) = force.getPMEParameters() if alpha == 0.0 / unit.nanometers: # Set PME parameters explicitly. print("Setting PME parameters explicitly...") (alpha, nx, ny, nz) = calc_pme_parameters(system) print (alpha, nx, ny, nz) print(type(nx)) force.setPMEParameters(alpha, int(nx), int(ny), int(nz)) print(force.getPMEParameters()) if args.tune_pme_platform: # Tune PME parameters for specified platform. from optimizepme import optimizePME properties = dict() platform = openmm.Platform.getPlatformByName(args.tune_pme_platform) print("Tuning PME parameters for platform '%s' precision model '%s'..." % (platform.getName(), args.precision)) if (platform.getName() == 'OpenCL'): properties['OpenCLPrecision'] = args.precision elif (platform.getName() == 'CUDA'): properties['CudaPrecision'] = args.precision minCutoff = 0.8 * unit.nanometers maxCutoff = 1.2 * unit.nanometers optimizePME(system, integrator, positions, platform, properties, minCutoff, maxCutoff) class_name = 'RUN%d' % run logger.info("%s (%d atoms)" % (class_name, system.getNumParticles())) # Compute reference potential and force [reference_potential, reference_force] = compute_potential_and_force(system, positions, reference_platform) # Test all platforms. test_success = True for platform_index in range(openmm.Platform.getNumPlatforms()): try: platform = openmm.Platform.getPlatform(platform_index) platform_name = platform.getName() # Define precision models to test. if platform_name == 'Reference': precision_models = ['double'] else: precision_models = ['single'] if platform.supportsDoublePrecision(): precision_models.append('double') for precision_model in precision_models: # Set precision. if platform_name == 'CUDA': platform.setPropertyDefaultValue('CudaPrecision', precision_model) if platform_name == 'OpenCL': platform.setPropertyDefaultValue('OpenCLPrecision', precision_model) # Compute potential and force. [platform_potential, platform_force] = compute_potential_and_force(system, positions, platform) # Compute error in potential. potential_error = platform_potential - reference_potential # Compute per-atom RMS (magnitude) and RMS error in force. force_unit = unit.kilocalories_per_mole / unit.nanometers natoms = system.getNumParticles() force_mse = (((reference_force - platform_force) / force_unit)**2).sum() / natoms * force_unit**2 force_rmse = unit.sqrt(force_mse) force_ms = ((platform_force / force_unit)**2).sum() / natoms * force_unit**2 force_rms = unit.sqrt(force_ms) logger.info("%16s%16s %16.6f kcal/mol %16.6f kcal/mol %16.6f kcal/mol/nm %16.6f kcal/mol/nm" % (platform_name, precision_model, platform_potential / unit.kilocalories_per_mole, potential_error / unit.kilocalories_per_mole, force_rms / force_unit, force_rmse / force_unit)) # Mark whether tolerance is exceeded or not. if abs(potential_error) > ENERGY_TOLERANCE: test_success = False logger.info("%32s WARNING: Potential energy error (%.6f kcal/mol) exceeds tolerance (%.6f kcal/mol). Test failed." % ("", potential_error/unit.kilocalories_per_mole, ENERGY_TOLERANCE/unit.kilocalories_per_mole)) if abs(force_rmse) > FORCE_RMSE_TOLERANCE: test_success = False logger.info("%32s WARNING: Force RMS error (%.6f kcal/mol/nm) exceeds tolerance (%.6f kcal/mol/nm). Test failed." % ("", force_rmse/force_unit, FORCE_RMSE_TOLERANCE/force_unit)) if verbose: for atom_index in range(natoms): for k in range(3): logger.info("%12.6f" % (reference_force[atom_index,k]/force_unit), end="") logger.info(" : ", end="") for k in range(3): logger.info("%12.6f" % (platform_force[atom_index,k]/force_unit), end="") except Exception as e: logger.info(e) if test_success: tests_passed += 1 else: tests_failed += 1 if (test_success is False): # Write XML files of failed tests to aid in debugging. # Place forces into different force groups. forces = [ system.getForce(force_index) for force_index in range(system.getNumForces()) ] force_group_names = dict() group_index = 0 for force_index in range(system.getNumForces()): force_name = forces[force_index].__class__.__name__ if force_name == 'NonbondedForce': forces[force_index].setForceGroup(group_index+1) force_group_names[group_index] = 'NonbondedForce (direct)' group_index += 1 forces[force_index].setReciprocalSpaceForceGroup(group_index+1) force_group_names[group_index] = 'NonbondedForce (reciprocal)' group_index += 1 else: forces[force_index].setForceGroup(group_index+1) force_group_names[group_index] = force_name group_index += 1 ngroups = len(force_group_names) # Test by force group. logger.info("Breakdown of discrepancies by Force component:") nforces = system.getNumForces() for force_group in range(ngroups): force_name = force_group_names[force_group] logger.info(force_name) [reference_potential, reference_force] = compute_potential_and_force_by_force_group(system, positions, reference_platform, force_group) logger.info("%16s%16s %16s %16s %16s %16s" % ("platform", "precision", "potential", "error", "force mag", "rms error")) for platform_index in range(openmm.Platform.getNumPlatforms()): try: platform = openmm.Platform.getPlatform(platform_index) platform_name = platform.getName() # Define precision models to test. if platform_name == 'Reference': precision_models = ['double'] else: precision_models = ['single'] if platform.supportsDoublePrecision(): precision_models.append('double') for precision_model in precision_models: # Set precision. if platform_name == 'CUDA': platform.setPropertyDefaultValue('CudaPrecision', precision_model) if platform_name == 'OpenCL': platform.setPropertyDefaultValue('OpenCLPrecision', precision_model) # Compute potential and force. [platform_potential, platform_force] = compute_potential_and_force_by_force_group(system, positions, platform, force_group) # Compute error in potential. potential_error = platform_potential - reference_potential # Compute per-atom RMS (magnitude) and RMS error in force. force_unit = unit.kilocalories_per_mole / unit.nanometers natoms = system.getNumParticles() force_mse = (((reference_force - platform_force) / force_unit)**2).sum() / natoms * force_unit**2 force_rmse = unit.sqrt(force_mse) force_ms = ((platform_force / force_unit)**2).sum() / natoms * force_unit**2 force_rms = unit.sqrt(force_ms) logger.info("%16s%16s %16.6f kcal/mol %16.6f kcal/mol %16.6f kcal/mol/nm %16.6f kcal/mol/nm" % (platform_name, precision_model, platform_potential / unit.kilocalories_per_mole, potential_error / unit.kilocalories_per_mole, force_rms / force_unit, force_rmse / force_unit)) except Exception as e: logger.info(e) pass logger.info("") logger.info("%d tests failed" % tests_failed) logger.info("%d tests passed" % tests_passed) if (tests_failed > 0): # Signal failure of test. sys.exit(1) else: sys.exit(0)
def from_dict(cls, dct): system_xml = dct['system_xml'] return cls(XmlSerializer.deserialize(system_xml))
integrator_xml_filename = "integrator_2fs.xml" state_xml_filename = "pr_output_state.xml" state_pdb_filename = "pr_output_state.pdb" system_xml_filename = "pr_output_system.xml" checkpoint_filename = "pr_output_checkpoint.chk" traj_output_filename = "pr_output_traj.xtc" # Define the barostat for the system barostat = mm.MonteCarloBarostat(pressure, temperature) # Read in equilibrated system (PDB) pdb = PDBFile(input_pdb) # Deserialize system file and load system with open(input_system, 'r') as f: system = XmlSerializer.deserialize(f.read()) # Make and serialize integrator - Langevin dynamics print("Serializing integrator to %s" % os.path.join(output_prefix, integrator_xml_filename)) integrator = mm.LangevinIntegrator( temperature, collision_rate, timestep # Friction coefficient ) with open(os.path.join(output_prefix, integrator_xml_filename), "w") as outfile: xml = mm.XmlSerializer.serialize(integrator) outfile.write(xml) # Define the platform to use; CUDA, OpenCL, CPU, or Reference. Or do not specify
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)
def main(): parser = argparse.ArgumentParser( description= 'Compute a potential of mean force (PMF) for porin permeation.') parser.add_argument('--index', dest='index', action='store', type=int, help='Index of ') parser.add_argument('--output', dest='output_filename', action='store', default='output.nc', help='output netcdf filename (default: output.nc)') args = parser.parse_args() index = args.index output_filename = args.output_filename logger = logging.getLogger(__name__) logging.root.setLevel(logging.DEBUG) logging.basicConfig(level=logging.DEBUG) yank.utils.config_root_logger(verbose=True, log_file_path=None) # Configure ContextCache, platform and precision from yank.experiment import ExperimentBuilder platform = ExperimentBuilder._configure_platform('CUDA', 'mixed') try: openmmtools.cache.global_context_cache.platform = platform except RuntimeError: # The cache has been already used. Empty it before switching platform. openmmtools.cache.global_context_cache.empty() openmmtools.cache.global_context_cache.platform = platform # Topology pdbx = app.PDBxFile('mem_prot_md_system.pdbx') # This system contains the CVforce with parameters different than zero with open('openmm_system.xml', 'r') as infile: openmm_system = XmlSerializer.deserialize(infile.read()) ####### Indexes of configurations in trajectory ############################ configs = [ 39, 141, 276, 406, 562, 668, 833, 1109, 1272, 1417, 1456, 1471, 1537, 1645, 1777, 1882 ] ####### Indexes of states for series of replica exchange simulations ####### limits = [(0, 9), (10, 19), (20, 29), (30, 39), (40, 49), (50, 59), (60, 69), (70, 79), (80, 89), (90, 99), (100, 109), (110, 119), (120, 129), (130, 139), (140, 149), (150, 159)] ####### Reading positions from mdtraj trajectory ########################### topology = md.Topology.from_openmm(pdbx.topology) t = md.load('../../steered_md/comp7/forward/seed_0/steered_forward.nc', top=topology) positions = t.openmm_positions(configs[index]) thermodynamic_state_deserialized = states.ThermodynamicState( system=openmm_system, temperature=310 * unit.kelvin, pressure=1.0 * unit.atmospheres) sampler_state = states.SamplerState( positions=positions, box_vectors=t.unitcell_vectors[configs[index], :, :] * unit.nanometer) logger.debug(type(sampler_state)) move = mcmc.LangevinDynamicsMove(timestep=2 * unit.femtosecond, collision_rate=1.0 / unit.picoseconds, n_steps=500, reassign_velocities=False) simulation = ReplicaExchangeSampler(mcmc_moves=move, number_of_iterations=1) analysis_particle_indices = topology.select( '(protein and mass > 3.0) or (resname MER and mass > 3.0)') reporter = MultiStateReporter( output_filename, checkpoint_interval=2000, analysis_particle_indices=analysis_particle_indices) first, last = limits[index] # Initialize compound thermodynamic states protocol = { 'lambda_restraints': [i / 159 for i in range(first, last + 1)], 'K_parallel': [ 1250 * unit.kilojoules_per_mole / unit.nanometer**2 for i in range(first, last + 1) ], 'Kmax': [ 500 * unit.kilojoules_per_mole / unit.nanometer**2 for i in range(first, last + 1) ], 'Kmin': [ 500 * unit.kilojoules_per_mole / unit.nanometer**2 for i in range(first, last + 1) ] } my_composable_state = MyComposableState.from_system(openmm_system) compound_states = states.create_thermodynamic_state_protocol( thermodynamic_state_deserialized, protocol=protocol, composable_states=[my_composable_state]) simulation.create(thermodynamic_states=compound_states, sampler_states=[sampler_state], storage=reporter) simulation.equilibrate(50, mcmc_moves=move) simulation.run() ts = simulation._thermodynamic_states[0] context, _ = openmmtools.cache.global_context_cache.get_context(ts) files_names = [ 'state_{}_{}.log'.format(index, i) for i in range(first, last + 1) ] files = [] for i, file in enumerate(files_names): files.append(open(file, 'w')) mpi.distribute(write_cv, range(simulation.n_replicas), context, simulation, files, send_results_to=None) for i in range(10000): simulation.extend(n_iterations=2) mpi.distribute(write_cv, range(simulation.n_replicas), context, simulation, files, send_results_to=None)
def execute(self, directory, available_resources): import openmmtools import mdtraj from simtk import openmm, unit as simtk_unit from simtk.openmm import XmlSerializer trajectory = mdtraj.load_dcd(self.trajectory_file_path, self.coordinate_file_path) with open(self.system_path, 'rb') as file: system = XmlSerializer.deserialize(file.read().decode()) temperature = pint_quantity_to_openmm(self.thermodynamic_state.temperature) pressure = pint_quantity_to_openmm(self.thermodynamic_state.pressure) if self.enable_pbc: system.setDefaultPeriodicBoxVectors(*trajectory.openmm_boxes(0)) else: pressure = None openmm_state = openmmtools.states.ThermodynamicState(system=system, temperature=temperature, pressure=pressure) integrator = openmmtools.integrators.VelocityVerletIntegrator(0.01*simtk_unit.femtoseconds) # Setup the requested platform: platform = setup_platform_with_resources(available_resources, self.high_precision) openmm_system = openmm_state.get_system(True, True) if not self.enable_pbc: disable_pbc(openmm_system) openmm_context = openmm.Context(openmm_system, integrator, platform) potential_energies = np.zeros(trajectory.n_frames) reduced_potentials = np.zeros(trajectory.n_frames) for frame_index in range(trajectory.n_frames): if self.enable_pbc: box_vectors = trajectory.openmm_boxes(frame_index) openmm_context.setPeriodicBoxVectors(*box_vectors) positions = trajectory.xyz[frame_index] openmm_context.setPositions(positions) potential_energy = openmm_context.getState(getEnergy=True).getPotentialEnergy() potential_energies[frame_index] = potential_energy.value_in_unit(simtk_unit.kilojoule_per_mole) reduced_potentials[frame_index] = openmm_state.reduced_potential(openmm_context) kinetic_energies = StatisticsArray.from_pandas_csv(self.kinetic_energies_path)[ObservableType.KineticEnergy] statistics_array = StatisticsArray() statistics_array[ObservableType.PotentialEnergy] = potential_energies * unit.kilojoule / unit.mole statistics_array[ObservableType.KineticEnergy] = kinetic_energies statistics_array[ObservableType.ReducedPotential] = reduced_potentials * unit.dimensionless statistics_array[ObservableType.TotalEnergy] = (statistics_array[ObservableType.PotentialEnergy] + statistics_array[ObservableType.KineticEnergy]) statistics_array[ObservableType.Enthalpy] = (statistics_array[ObservableType.ReducedPotential] * self.thermodynamic_state.inverse_beta + kinetic_energies) if self.use_internal_energy: statistics_array[ObservableType.ReducedPotential] += kinetic_energies * self.thermodynamic_state.beta self.statistics_file_path = path.join(directory, 'statistics.csv') statistics_array.to_pandas_csv(self.statistics_file_path) return self._get_output_dictionary()
def execute(self, directory, available_resources): import mdtraj logging.info('Extracting dielectrics: ' + self.id) base_exception = super(ExtractAverageDielectric, self).execute(directory, available_resources) if isinstance(base_exception, ExtractAverageDielectric): return base_exception charge_list = [] from simtk.openmm import XmlSerializer with open(self._system_path, 'rb') as file: self._system = XmlSerializer.deserialize(file.read().decode()) for force_index in range(self._system.getNumForces()): force = self._system.getForce(force_index) if not isinstance(force, openmm.NonbondedForce): continue for atom_index in range(force.getNumParticles()): charge = force.getParticleParameters(atom_index)[0] charge /= unit.elementary_charge charge_list.append(charge) dipole_moments = mdtraj.geometry.dipole_moments( self.trajectory, charge_list) dipole_moments, self._equilibration_index, self._statistical_inefficiency = \ timeseries.decorrelate_time_series(dipole_moments) sample_indices = timeseries.get_uncorrelated_indices( len(self.trajectory[self._equilibration_index:]), self._statistical_inefficiency) sample_indices = [ index + self._equilibration_index for index in sample_indices ] volumes = self.trajectory[sample_indices].unitcell_volumes self._uncorrelated_values = unit.Quantity(dipole_moments, None) self._uncorrelated_volumes = volumes * unit.nanometer**3 value, uncertainty = bootstrap(self._bootstrap_function, self._bootstrap_iterations, self._bootstrap_sample_size, dipoles=dipole_moments, volumes=volumes) self._value = EstimatedQuantity(unit.Quantity(value, None), unit.Quantity(uncertainty, None), self.id) logging.info('Extracted dielectrics: ' + self.id) return self._get_output_dictionary()
properties[args.platform + '_' + v.replace('_', '')] = value if args.platform == 'fastest': platform = None else: platform = Platform.getPlatformByName(args.platform) print 'Reading PDB' pdb = PDBFile(args.topology_pdb) print 'Done' with open(args.system_xml) as f: system_xml = f.read() system = XmlSerializer.deserialize(system_xml) with open(args.integrator_xml) as f: integrator_xml = f.read() integrator = XmlSerializer.deserialize(integrator_xml) print 'Initialize Simulation' try: simulation = Simulation(pdb.topology, system, integrator, platform, properties) except Exception: print('EXCEPTION', (socket.gethostname())) raise print 'Done.'
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()
def from_dict(cls, dct): system_xml = dct["system_xml"] subsets = dct["subsets"] return cls(XmlSerializer.deserialize(system_xml), subsets)