def attempt_to_load_top_from_simtk(topology): """ Load topology from SIMTK. Parameters ---------- topology : str or Path Returns ------- topology from mdtraj.Topology.from_openmm` Raises ------ Dependency error from :func:`_log_simtkimport_error`, program halts. """ topp = Path(topology) if topp.suffix == '.cif' and SIMTK: mol = app.PDBxFile(topp.str()) return mdtraj.Topology.from_openmm(mol.topology) elif topp.suffix == '.cif' and not SIMTK: _log_simtkimport_error() else: return topp.str()
def read(fpath, ftype=None): """Creates a `Structure` instance from a PDB/mmCIF file. Args: fpath (str): path to file to be parsed. ftype (:obj:`str`, optional): file type (PDB or mmCIF). `None` defaults to guessing the file type from the extension. Returns: :obj:`Structure`: new instance of `Structure` class defining a topology and positions for the input structure. Raises: StructureError: generic error class for problems during structure parsing or conversion with OpenMM. """ _pdb_formats = {'pdb', 'ent'} _cif_formats = {'cif', 'mmcif'} _formats = _pdb_formats | _cif_formats _formats_str = ','.join(_formats) logging.debug('Reading file: {}'.format(fpath)) fullpath = os.path.abspath(fpath) if not os.path.isfile(fullpath): emsg = 'File could not be read: {}'.format(fullpath) raise StructureError(emsg) fname, fext = os.path.splitext(fullpath) ftype = ftype if ftype is not None else fext[1:] logging.debug('Assigned file type: {}'.format(ftype)) if ftype in _pdb_formats: try: struct = app.PDBFile(fullpath) except Exception as e: emsg = 'Failed parsing file {} as \'PDB\' format'.format(fullpath) raise StructureError(emsg) from e elif ftype in _cif_formats: try: struct = app.PDBxFile(fullpath) except Exception as e: emsg = 'Failed parsing file {} as \'mmCIF\' format'.format(fullpath) raise StructureError(emsg) from e else: emsg = '\'{}\' is not one of the supported types: {}'.format(ftype, _formats_str) raise StructureError(emsg) logging.debug('File parsed successfully using OpenMM reader.') return Structure(os.path.basename(fname), struct)
def test_create_peptide_system_using_protons_xml(): """Test if protons.xml can be used to successfully create a peptide System object in OpenMM.""" app.Topology.loadBondDefinitions(bonds_path) # Load pdb file with protons compatible residue names pdbx = app.PDBxFile( get_test_data( "glu_ala_his-solvated-minimized-renamed.cif", "testsystems/tripeptides" ) ) forcefield = app.ForceField(ffxml_path, ions_spce_path, "spce.xml") # System Configuration nonbondedMethod = app.PME constraints = app.AllBonds rigidWater = True constraintTolerance = 1.0e-7 # Integration Options dt = 0.5 * unit.femtoseconds temperature = 300.0 * unit.kelvin friction = 1.0 / unit.picosecond pressure = 1.0 * unit.atmospheres barostatInterval = 25 # Simulation Options platform = mm.Platform.getPlatformByName("Reference") # Prepare the Simulation topology = pdbx.topology positions = pdbx.positions system = forcefield.createSystem( topology, nonbondedMethod=nonbondedMethod, constraints=constraints, rigidWater=rigidWater, ) system.addForce(mm.MonteCarloBarostat(pressure, temperature, barostatInterval)) integrator = GHMCIntegrator(temperature, friction, dt) integrator.setConstraintTolerance(constraintTolerance) # Clean up so that the classes remain unmodified # unit test specific errors might occur otherwise when loading files due # to class side effects app.Topology.unloadStandardBonds()
def _load_topology(topo_file): if topo_file.endswith(".cif"): structure = app.PDBxFile(topo_file) log.info("loaded topology with openmm.app.PDBxFile") topology = md.Topology.from_openmm(structure.topology) log.info("loaded topology with md.Topology.from_openmm") return topology elif topo_file.endswith('.pdb'): return topo_file else: raise TypeError("Unkown topology file type")
def load_pdbid_to_openmm(pdbid): """ create openmm topology without pdb file lifted from pandegroup/pdbfixer """ url = 'http://www.rcsb.org/pdb/files/%s.pdb' % pdbid file = urlopen(url) contents = file.read().decode('utf-8') file.close() file = StringIO(contents) if _guessFileFormat(file, url) == 'pdbx': pdbx = app.PDBxFile(contents) topology = pdbx.topology positions = pdbx.positions else: pdb = app.PDBFile(file) topology = pdb.topology positions = pdb.positions return topology, positions
def load_traj(topology, trajectory): """ Load trajectory with `MDTraj <http://mdtraj.org/1.9.3/index.html>`_. Uses `mdtraj.load <http://mdtraj.org/1.9.3/api/generated/mdtraj.load.html?highlight=load#mdtraj.load>`_. Example ------- >>> libmdt.load_traj('bigtopology.cif', 'trajectory.dcd') Parameters ---------- topology : str or Path Path to the topology file. Accepts MDTraj compatible `topology files <http://mdtraj.org/1.9.3/load_functions.html#trajectory-reference>`_. mmCIF format is loaded using `OpenMM <http://mdtraj.org/1.9.3/api/generated/mdtraj.Topology.html?highlight=from_openmm#mdtraj.Topology.from_openmm>`_. trajectory : str or Path Path to the trajectory file. Accepts MDTraj compatible `files <http://mdtraj.org/1.9.3/load_functions.html#trajectory-reference>`_ Returns ------- MDTraj trajectory `Trajectory object <http://mdtraj.org/1.9.3/api/generated/mdtraj.Trajectory.html#mdtraj-trajectory>`_. """ # noqa: E501 libio.report_input(topology, trajectory) topp = Path(topology) if topp.suffix == '.cif' and SIMTK: mol = app.PDBxFile(topp.str()) top = mdtraj.Topology.from_openmm(mol.topology) elif topp.suffix == '.cif' and not SIMTK: _log_simtkimport_error() else: top = topp.str() mdtrajectory = mdtraj.load(Path(trajectory).str(), top=top) return mdtrajectory
elif platform_name == 'CPU': cpu_threads = os.getenv('SLURM_CPUS_PER_TASK') if cpu_threads: properties['Threads'] = cpu_threads # Split input file name fname, fext = os.path.splitext(cmd.structure) if cmd.output: rootname = cmd.output else: rootname = fname + '_Eq' # Read structure structure = app.PDBxFile(cmd.structure) forcefield = app.ForceField(cmd.forcefield, cmd.solvent) # Define simulation parameters md_temp = cmd.temperature * units.kelvin md_pres = cmd.pressure * units.bar md_step = 2 * units.femtosecond md_fric = 1 / units.picosecond md_nbct = 1.0 * units.nanometer md_hamu = None md_cstr = app.HBonds if cmd.hmr: md_step *= 2.5 # make 5 fs md_hamu = 4 * units.amu
# Options ap.add_argument('--output', type=str, default='noDummies', help='File name for final system, in mmCIF format.') cmd = ap.parse_args() logging.info('Started') logging.info('Using:') logging.info(' trajectory: {}'.format(cmd.trajectory)) logging.info(' topology: {}'.format(cmd.topology)) # Read topology mol = app.PDBxFile(cmd.topology) top = md.Topology.from_openmm(mol.topology) # Read trajectory t = md.load(cmd.trajectory, top=top) logging.info('Trajectory Details:') logging.info(' no. of atoms: {}'.format(t.n_atoms)) logging.info(' no. of frames: {}'.format(t.n_frames)) # Remove dummies atomsel = t.top.select('not name DUM') n_dums = t.top.n_atoms - len(atomsel) logging.info(f'Removing {n_dums} dummy atoms') t = t.atom_slice(atomsel, inplace=True)
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)
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', 500,
def test_peptide_system_integrity(): """ Set up peptide, and assure that the systems particles have not been modified after driver instantiation. """ sys_details = SystemSetup() sys_details.timestep = 0.5 * unit.femtoseconds sys_details.temperature = 300.0 * unit.kelvin sys_details.collision_rate = 1.0 / unit.picosecond sys_details.pressure = 1.0 * unit.atmospheres sys_details.barostatInterval = 25 sys_details.constraint_tolerance = 1.0e-7 app.Topology.loadBondDefinitions(bonds_path) # Load pdb file with protons compatible residue names pdbx = app.PDBxFile( get_test_data( "glu_ala_his-solvated-minimized-renamed.cif", "testsystems/tripeptides" ) ) forcefield = app.ForceField(ffxml_path, ions_spce_path, "spce.xml") # System Configuration nonbondedMethod = app.PME constraints = app.AllBonds rigidWater = True sys_details.constraintTolerance = 1.0e-7 # Simulation Options platform = mm.Platform.getPlatformByName("Reference") # Prepare the Simulation topology = pdbx.topology positions = pdbx.positions system = forcefield.createSystem( topology, nonbondedMethod=nonbondedMethod, constraints=constraints, rigidWater=rigidWater, ) system.addForce( mm.MonteCarloBarostat( sys_details.pressure, sys_details.temperature, sys_details.barostatInterval ) ) integrator = create_compound_gbaoab_integrator(testsystem=sys_details) original_system = pattern_from_multiline( mm.XmlSerializer.serialize(system), "<Particle" ) driver = ForceFieldProtonDrive( sys_details.temperature, topology, system, forcefield, ffxml_path, pressure=sys_details.pressure, perturbations_per_trial=1, ) after_driver = pattern_from_multiline( mm.XmlSerializer.serialize(system), "<Particle" ) # Clean up so that the classes remain unmodified # unit test specific errors might occur otherwise when loading files due # to class side effects app.Topology.unloadStandardBonds() # Make sure there are no differences between the particles in each system assert original_system == after_driver
def test_create_peptide_calibration_with_residue_pools_using_protons_xml(): """Test if protons.xml can be used to successfully create a peptide Simulation object in OpenMM and Instantiate a ForceFieldProtonDrive, while using pools of residues to sample from, and calibrate histidine.""" sys_details = SystemSetup() sys_details.timestep = 0.5 * unit.femtoseconds sys_details.temperature = 300.0 * unit.kelvin sys_details.collision_rate = 1.0 / unit.picosecond sys_details.pressure = 1.0 * unit.atmospheres sys_details.barostatInterval = 25 sys_details.constraint_tolerance = 1.0e-7 app.Topology.loadBondDefinitions(bonds_path) # Load pdb file with protons compatible residue names pdbx = app.PDBxFile( get_test_data( "glu_ala_his-solvated-minimized-renamed.cif", "testsystems/tripeptides" ) ) forcefield = app.ForceField(ffxml_path, ions_spce_path, "spce.xml") # System Configuration nonbondedMethod = app.PME constraints = app.AllBonds rigidWater = True sys_details.constraintTolerance = 1.0e-7 # Simulation Options platform = mm.Platform.getPlatformByName("Reference") # Prepare the Simulation topology = pdbx.topology positions = pdbx.positions system = forcefield.createSystem( topology, nonbondedMethod=nonbondedMethod, constraints=constraints, rigidWater=rigidWater, ) system.addForce( mm.MonteCarloBarostat( sys_details.pressure, sys_details.temperature, sys_details.barostatInterval ) ) integrator = create_compound_gbaoab_integrator(testsystem=sys_details) driver = ForceFieldProtonDrive( sys_details.temperature, topology, system, forcefield, ffxml_path, pressure=sys_details.pressure, perturbations_per_trial=1, ) pools = {"glu": [0], "his": [1], "glu-his": [0, 1]} driver.define_pools(pools) driver.enable_calibration(SAMSApproach.ONESITE, group_index=1) sams_sampler = SAMSCalibrationEngine(driver) # SAMS on HIS simulation = app.Simulation(topology, system, integrator, platform) simulation.context.setPositions(positions) simulation.context.setVelocitiesToTemperature(sys_details.temperature) driver.attach_context(simulation.context) # run one step and one update simulation.step(1) driver.update(UniformProposal(), nattempts=1, residue_pool="his") sams_sampler.adapt_zetas() # Clean up so that the classes remain unmodified # unit test specific errors might occur otherwise when loading files due # to class side effects app.Topology.unloadStandardBonds()
def main(): """Main code""" args = parse_args() # Format logger if args.verbose: log_level = logging.DEBUG else: log_level = logging.INFO logging.basicConfig(stream=sys.stdout, level=log_level, format='[%(asctime)s] %(message)s', datefmt='%Y/%m/%d %H:%M:%S') if args.parallel: dist_func = pbc_mindist_parallel else: dist_func = pbc_mindist_serial logging.info('Started') logging.info('Using:') logging.info(f' trajectory: {args.trajectory}') logging.info(f' topology: {args.topology}') logging.info(f' parallelization: {args.parallel}') logging.info(f' atom selection: {args.atomsel}') # Read topology if args.topology.endswith('.cif'): mol = app.PDBxFile(args.topology) top = md.Topology.from_openmm(mol.topology) else: # assume PDB, TOP, etc top = args.topology # Read trajectory logging.info('Reading trajectory:') t = md.load(args.trajectory, top=top, stride=args.stride) logging.info(' no. of atoms: {}'.format(t.n_atoms)) logging.info(' no. of frames: {}'.format(t.n_frames)) # Select atoms if args.atomsel == 'alpha': atomsel = t.top.select('protein and name CA') logging.info(f'Selecting protein alpha carbons (N={len(atomsel)})') elif args.atomsel == 'heavy': atomsel = [ a.index for a in t.top.atoms if not a.residue.is_water and # no solvent not a.residue.name.startswith('POP') and # no lipids a.element.symbol in set(('C', 'N', 'O', 'P', 'S')) ] logging.info(f'Selecting protein heavy atoms (N={len(atomsel)})') elif args.atomsel == 'backbone': atomsel = t.top.select('protein and backbone') logging.info(f'Selecting protein backbone atoms (N={len(atomsel)})') elif args.atomsel == 'all': atomsel = t.top.select('protein') logging.info(f'Selecting all protein atoms (N={len(atomsel)})') t.atom_slice(atomsel, inplace=True) assert t.n_atoms > 1, 'Trajectory must contain more than one atom?' # Reimage trajectory if args.reimage: logging.info(f'Reimaging trajectory') mols = t.top.find_molecules() if len(mols) < 2: logging.warning('WARNING: NUMBER OF MOLECULES IS 1') logging.warning('REIMAGING IS VERY LIKELY TO FAIL!') logging.warning('CHECK THE CONNECTIVITY OF YOUR SYSTEM') t.image_molecules(inplace=True, anchor_molecules=mols[:1]) # Calculate distance logging.info(f'Calculating distances') info, min_dist = dist_func(t.xyz.astype('float64'), t.unitcell_vectors.astype('float64')) # Get smallest distance index f = np.argmin(min_dist) # Return info on minimum distance (and sqrt it) d = np.sqrt(min_dist[f]) i, j = info[f] logging.info((f'Minimum distance between periodic images is {d:6.3f} nm' f' between atoms {i} and {j} at frame {f}'))
ap = argparse.ArgumentParser(description=__doc__) ap.add_argument('topology', help='Topology file corresponding to DCD') ap.add_argument('trajectory', help='DCD trajectory file') ap.add_argument('--output', default=None, help='Root for naming PDB files: root + _ + frame + .pdb (e.g. trj_1.pdb)') ap.add_argument('--stride', default=1, type=int, help='Read only i-th frame. Default: reads all (i=1)') cmd = ap.parse_args() # Read/Parse Topology topology_fpath = check_file(cmd.topology) if topology_fpath.endswith('cif'): structure = app.PDBxFile(topology_fpath) topology = md.Topology.from_openmm(structure.topology) else: structure = md.load(cmd.topology) topology = structure.topology logging.info('Read topology from file: {}'.format(topology_fpath)) # Read trajectory trajectory_fpath = check_file(cmd.trajectory) logging.info('Reading trajectory from file: {}'.format(trajectory_fpath)) trj = md.load(trajectory_fpath, top=topology, stride=cmd.stride) logging.info('Removing PBCs and imaging molecules')
########################################################################## # this script was generated by openmm-builder. to customize it further, # you can save the file to disk and edit it with your favorite editor. ########################################################################## from __future__ import print_function from simtk.openmm import app import simtk.openmm as mm from simtk import unit from sys import stdout pdb = app.PDBxFile('CB7-viologen-vacuum.cif') forcefield = app.ForceField('CB7.xml', 'viologen.xml', 'gaff.xml', 'tip3p.xml') system = forcefield.createSystem(pdb.topology, nonbondedMethod=app.PME, nonbondedCutoff=1.0 * unit.nanometers, constraints=app.HBonds, rigidWater=True, ewaldErrorTolerance=0.0001) integrator = mm.LangevinIntegrator(300 * unit.kelvin, 1.0 / unit.picoseconds, 2.0 * unit.femtoseconds) integrator.setConstraintTolerance(0.0001) system.addForce( mm.MonteCarloBarostat(1 * unit.atmospheres, 300 * unit.kelvin, 25)) # Use a switching function for the nonbonded force, and use dispersion correction switching_distance = 0.85 * unit.nanometers for force in system.getForces(): if isinstance(force, mm.NonbondedForce): force.setUseSwitchingFunction(True)