本文整理汇总了Python中simtk.openmm.app.PDBFile.writeFile方法的典型用法代码示例。如果您正苦于以下问题:Python PDBFile.writeFile方法的具体用法?Python PDBFile.writeFile怎么用?Python PDBFile.writeFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类simtk.openmm.app.PDBFile
的用法示例。
在下文中一共展示了PDBFile.writeFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_hydrogens_to_mol
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
def add_hydrogens_to_mol(mol):
"""
Add hydrogens to a molecule object
TODO (LESWING) see if there are more flags to add here for default
:param mol: Rdkit Mol
:return: Rdkit Mol
"""
molecule_file = None
try:
pdbblock = Chem.MolToPDBBlock(mol)
pdb_stringio = StringIO()
pdb_stringio.write(pdbblock)
pdb_stringio.seek(0)
fixer = PDBFixer(pdbfile=pdb_stringio)
fixer.addMissingHydrogens(7.4)
hydrogenated_io = StringIO()
PDBFile.writeFile(fixer.topology, fixer.positions, hydrogenated_io)
hydrogenated_io.seek(0)
return Chem.MolFromPDBBlock(
hydrogenated_io.read(), sanitize=False, removeHs=False)
except ValueError as e:
logging.warning("Unable to add hydrogens", e)
raise MoleculeLoadException(e)
finally:
try:
os.remove(molecule_file)
except (OSError, TypeError):
pass
示例2: write_trajectory_dcd
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
def write_trajectory_dcd(netcdf_filename, topology, pdb_trajectory_filename, dcd_trajectory_filename):
"""
Write trajectory.
Parameters
----------
netcdf_filename : str
NetCDF filename.
topology : Topology
Topology object
pdb_trajectory_filename : str
PDB trajectory output filename
dcd_trajectory_filename : str
Output trajectory filename.
"""
ncfile = netCDF4.Dataset(netcdf_filename, 'r')
[nsamples, nstates] = ncfile.variables['logZ'].shape
# Write reference.pdb file
from simtk.openmm.app import PDBFile
outfile = open(pdb_trajectory_filename, 'w')
positions = unit.Quantity(ncfile.variables['positions'][0,:,:], unit.angstroms)
PDBFile.writeFile(topology, positions, file=outfile)
outfile.close()
# TODO: Export as DCD trajectory with MDTraj
from mdtraj.formats import DCDTrajectoryFile
with DCDTrajectoryFile(dcd_trajectory_filename, 'w') as f:
f.write(ncfile.variables['positions'][:,:,:])
示例3: _geometry_forward
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
def _geometry_forward(self, topology_proposal, old_sampler_state):
"""
Run geometry engine to propose new positions and compute logP
Parameters
----------
topology_proposal : TopologyProposal
Contains old/new Topology and System objects and atom mappings.
old_sampler_state : openmmtools.states.SamplerState
Configurational properties of the old system atoms.
Returns
-------
new_sampler_state : openmmtools.states.SamplerState
Configurational properties of new atoms proposed by geometry engine calculation.
geometry_logp_propose : float
The log probability of the forward-only proposal
"""
if self.verbose: print("Geometry engine proposal...")
# Generate coordinates for new atoms and compute probability ratio of old and new probabilities.
initial_time = time.time()
new_positions, geometry_logp_propose = self.geometry_engine.propose(topology_proposal, old_sampler_state.positions, self.sampler.thermodynamic_state.beta)
if self.verbose: print('proposal took %.3f s' % (time.time() - initial_time))
if self.geometry_pdbfile is not None:
print("Writing proposed geometry...")
from simtk.openmm.app import PDBFile
PDBFile.writeFile(topology_proposal.new_topology, new_positions, file=self.geometry_pdbfile)
self.geometry_pdbfile.flush()
new_sampler_state = SamplerState(new_positions, box_vectors=old_sampler_state.box_vectors)
return new_sampler_state, geometry_logp_propose
示例4: write_pdb
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
def write_pdb(self, path):
"""
Outputs a PDB file with the current contents of the system
"""
if self.master is None and self.positions is None:
raise ValueError('Topology and positions are needed to write output files.')
with open(path, 'w') as f:
PDBFile.writeFile(self.topology, self.positions, f)
示例5: check_hydrogens
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
def check_hydrogens(molecule, ID):
# Check that Hydrogens are in structure
if len(molecule.top.select("name == H")) == 0:
# If absent, then add Hydrogens using the Amber99sb force-field
try:
from simtk.openmm.app import PDBFile, Modeller, ForceField
pdb = PDBFile(ID + ".pdb")
modeller = Modeller(pdb.topology, pdb.positions)
forcefield = ForceField('amber99sb.xml','tip3p.xml')
modeller.addHydrogens(forcefield)
PDBFile.writeFile(modeller.topology, modeller.positions, open(ID + ".pdb", 'w'))
molecule = md.load(ID + ".pdb").remove_solvent()
except:
warnings.warn("""PDB topology missing Hydrogens. Either manually add
or install OpenMM through SIMTK to automatically correct.""")
pass
return molecule
示例6: download_pdb
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
def download_pdb(pdbid, file_pathway):
"""
Args:
pdbid: 4 letter string specifying the PDB ID of the file yoou want to fix
file_pathway: a string containing the pathway specifying how you want to organize the PDB files once written
Returns: nothing, but it does write the PDB file
***Note: this function does NOT fix any mistakes with the PDB file
"""
if not os.path.exists(file_pathway):
os.makedirs(file_pathway)
fixer = PDBFixer(pdbid=pdbid)
PDBFile.writeFile(fixer.topology, fixer.positions, open(os.path.join(file_pathway, '%s.pdb' % pdbid), 'w'))
示例7: __init__
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
def __init__(self, **kwargs):
super(AlanineDipeptideExplicitSimulatedTempering, self).__init__(**kwargs)
self.description = 'Alanine dipeptide in explicit solvent simulated tempering simulation'
# Create topology, positions, and system.
from openmmtools.testsystems import AlanineDipeptideExplicit
testsystem = AlanineDipeptideExplicit(nonbondedMethod=app.CutoffPeriodic)
self.topology = testsystem.topology
self.positions = testsystem.positions
self.system = testsystem.system
# DEBUG: Write PDB
from simtk.openmm.app import PDBFile
outfile = open('initial.pdb', 'w')
PDBFile.writeFile(self.topology, self.positions, outfile)
outfile.close()
# Add a MonteCarloBarostat
temperature = 270 * unit.kelvin # will be replaced as thermodynamic state is updated
pressure = 1.0 * unit.atmospheres
barostat = openmm.MonteCarloBarostat(pressure, temperature)
self.system.addForce(barostat)
# Create thermodynamic states.
Tmin = 270 * unit.kelvin
Tmax = 600 * unit.kelvin
ntemps = 256 # number of temperatures
from sams import ThermodynamicState
temperatures = unit.Quantity(np.logspace(np.log10(Tmin / unit.kelvin), np.log10(Tmax / unit.kelvin), ntemps), unit.kelvin)
self.thermodynamic_states = [ ThermodynamicState(system=self.system, temperature=temperature, pressure=pressure) for temperature in temperatures ]
# Create SAMS samplers
from sams.samplers import SamplerState, MCMCSampler, ExpandedEnsembleSampler, SAMSSampler
thermodynamic_state_index = 0 # initial thermodynamic state index
thermodynamic_state = self.thermodynamic_states[thermodynamic_state_index]
sampler_state = SamplerState(positions=self.positions)
self.mcmc_sampler = MCMCSampler(sampler_state=sampler_state, thermodynamic_state=thermodynamic_state, ncfile=self.ncfile)
#self.mcmc_sampler.pdbfile = open('output.pdb', 'w')
self.mcmc_sampler.topology = self.topology
self.mcmc_sampler.nsteps = 500
self.mcmc_sampler.timestep = 2.0 * unit.femtoseconds
self.mcmc_sampler.verbose = True
self.exen_sampler = ExpandedEnsembleSampler(self.mcmc_sampler, self.thermodynamic_states)
self.exen_sampler.verbose = True
self.sams_sampler = SAMSSampler(self.exen_sampler)
self.sams_sampler.verbose = True
示例8: fix_pdb
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
def fix_pdb(pdb_id, pdb_file, pdb_group):
chains_to_retain = get_required_chains(pdb_group)
chains_to_remove = []
for chain in PDBParser().get_structure(pdb_id, pdb_file)[0]:
if chain.get_id() not in chains_to_retain:
chains_to_remove.append(chain.get_id())
fixer = PDBFixer(filename=pdb_file)
fixer.removeChains(chainIds=chains_to_remove)
fixer.findMissingResidues()
fixer.findMissingAtoms()
fixer.addMissingAtoms()
fixer.removeHeterogens(True)
# KeepIds flag is critical here, otherwise we loose all information binding
pdb_file = dirname(pdb_file) + '/' + pdb_id + '.pdb'
PDBFile.writeFile(fixer.topology, fixer.positions, open(pdb_file, 'w'), keepIds=True)
return pdb_file
示例9: pdb_fix_pdbfixer
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
def pdb_fix_pdbfixer(pdbid, file_pathway, ph, chains_to_remove):
"""
Args:
pdbid: 4 letter string specifying the PDB ID of the file yoou want to fix
file_pathway: a string containing the pathway specifying how you want to organize the PDB files once written
ph: the pH at which hydrogens will be determined and added
chains_to_remove: dictionary containing pdbs with chains to remove
Returns: nothing, but it does right PDB files
"""
print(pdbid)
# Download the topology from rcsb based on pdbod
fixer = PDBFixer(pdbid=pdbid)
# Remove chains based on hand curated .csv file
if pdbid in chains_to_remove['pdbid']:
chains = chains_to_remove['chain_to_remove'][chain_to_remove['pdbid'].index(pdbid)]
chains_list = chains.split()
fixer.removeChains(chainIds=chains_list)
# Determine the first and last residue resolved in chain 0
chains = [chain for chain in fixer.topology.chains()]
resindices = [residue.index for residue in chains[0].residues()]
resindices = natsorted(resindices)
first_resindex = resindices[0]
last_resindex = resindices[-1]
# Find Missing residues and determine if they are C or N terminal fragments (which will be removed)
fixer.findMissingResidues()
if len(fixer.missingResidues) > 0:
if sorted(fixer.missingResidues.keys())[0][-1] <= first_resindex:
fixer.missingResidues.pop((sorted(fixer.missingResidues.keys())[0]))
if sorted(fixer.missingResidues.keys())[-1][-1] >= last_resindex:
fixer.missingResidues.pop((sorted(fixer.missingResidues.keys())[-1]))
fixer.findNonstandardResidues()
fixer.replaceNonstandardResidues()
fixer.findMissingAtoms()
fixer.addMissingAtoms()
fixer.addMissingHydrogens(ph)
# Write fixed PDB file, with all of the waters and ligands
PDBFile.writeFile(fixer.topology, fixer.positions, open(os.path.join(file_pathway,
'%s_fixed_ph%s.pdb' % (pdbid, ph)), 'w'),
keepIds=keepNumbers)
# Remove the ligand and write a pdb file
fixer.removeHeterogens(True)
PDBFile.writeFile(fixer.topology, fixer.positions, open(os.path.join(file_pathway,
'%s_fixed_ph%s_apo.pdb' % (pdbid, ph)), 'w'),
keepIds=keepNumbers)
# Remove the waters and write a pdb file
fixer.removeHeterogens(False)
PDBFile.writeFile(fixer.topology, fixer.positions, open(os.path.join(file_pathway,
'%s_fixed_ph%s_apo_nowater.pdb' % (pdbid, ph)),
'w'), keepIds=keepNumbers)
示例10: run
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
def run(options):
fixer = PDBFixer(options['pdb'])
fixer.addMissingHydrogens(7.0)
fixer.addSolvent(boxSize=Vec3(2.62,2.62,2.62)*nanometers, padding=None,
positiveIon='Na+', negativeIon='Cl-', ionicStrength=0.0*molar)
PDBFile.writeFile(fixer.topology, fixer.positions, open(options['outfile'], 'w'))
示例11: list
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
fixer.findMissingResidues()
# only add missing residues in the middle of the chain, do not add terminal ones
chains = list(fixer.topology.chains())
keys = fixer.missingResidues.keys()
missingResidues = dict()
for key in keys:
chain = chains[key[0]]
if not (key[1] == 0 or key[1] == len(list(chain.residues()))):
missingResidues[key] = fixer.missingResidues[key]
fixer.missingResidues = missingResidues
fixer.findMissingAtoms()
fixer.addMissingAtoms()
PDBFile.writeFile(fixer.topology, fixer.positions, open('4h12_fixed.pdb', 'w'))
# keep only protein and zinc ions
traj = md.load('4h12_fixed.pdb')
traj = traj.atom_slice(traj.top.select('(protein and not resname SAH) or resname ZN'))
# implement changes necessary for the use of the dummy atom Zn2+ model
# change residue name of the zincs from ZN to ZNB, and atom names from ZN to Zn
for residue in traj.top.chain(1).residues:
residue.name = 'ZNB'
for atom in traj.top.chain(1).atoms:
atom.name = 'Zn'
# change name of cysteines coordinating zincs to CYM (deprotonated cysteine)
for residue in traj.top.chain(0).residues:
if residue.index in [86, 92, 82, 69, 54, 52, 73, 184, 233, 238, 231]:
示例12: PDBFixer
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
from pdbfixer import PDBFixer
from simtk.openmm.app import PDBFile
fixer = PDBFixer(filename='3UE4.pdb')
fixer.removeChains(chainIds=['B'])
# Without fixer.missingResidues = {}, fixer.addMissingAtoms() throw an exception
# and if I call fixer.findMissingResidues() several terminal residues are added
fixer.missingResidues = {}
fixer.findMissingAtoms()
fixer.addMissingAtoms()
fixer.removeHeterogens(keepWater=False)
fixer.addMissingHydrogens(7.0)
PDBFile.writeFile(fixer.topology, fixer.positions, open('3UE4-pdbfixer.pdb', 'w'))
示例13: build_pdb
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
def build_pdb(sequence, filename, n_cap=None, c_cap=None, pH=7.0):
"""Build a PDB from a sequence and save to disk.
Parameters
----------
sequence : str
String representation of protein sequence as 1 letter codes.
filename : str
name of output filename
n_cap : str, optional, default=None
Either None or "ACE"
c_cap : str, optional, default=None
Either None, "NME", or "NH2"
pH : float, optional, default=7.0
pH to use when building amino acids.
"""
chain = pmx.Chain().create(sequence)
if c_cap is not None:
chain.add_cterm_cap()
if n_cap is not None:
chain.add_nterm_cap()
temp_file = tempfile.NamedTemporaryFile(suffix=".pdb")
temp_file.close
chain.write(temp_file.name)
# Now fix errors in element entries in CAP atoms
# Also convert
traj = mdtraj.load(temp_file.name)
top, bonds = traj.top.to_dataframe()
if n_cap == "ACE":
ind = np.where((top.name == "H3")&(top.resName == "ACE"))[0][0]
top.element.ix[ind] = "H"
if c_cap in ["NME", "NH2"]:
ind = np.where((top.name == "H3")&(top.resName == "NME"))[0][0]
top.element.ix[ind] = "H"
if c_cap == "NH2":
# Keep all atoms except the 3 NME methyl protons
keep_ind = np.where((top.resName != "NME") | ((top.name != "H1") & (top.name != "H2") & (top.name != "H3")))[0]
#Convert the NME carbon into a proton
convert_ind = np.where((top.resName == "NME") & (top.name == "C"))[0][0]
top.element.ix[convert_ind] = "H"
top.name.ix[convert_ind] = "HN2"
convert_ind = np.where((top.resName == "NME") & (top.name == "H"))[0][0]
top.name.ix[convert_ind] = "HN1"
top.resName.ix[np.where((top.resName == "NME"))[0]] = "NH2"
traj._topology = mdtraj.Topology.from_dataframe(top, bonds)
traj.restrict_atoms(keep_ind)
top, bonds = traj.top.to_dataframe()
if n_cap or c_cap:
traj._topology = mdtraj.Topology.from_dataframe(top, bonds)
traj.save(temp_file.name) # Save output with fixed element names in caps.
# Now fix missing charged termini.
#structure = pdbfixer.pdbfixer.PdbStructure(open(temp_file.name))
fixer = pdbfixer.pdbfixer.PDBFixer(temp_file.name)
fixer.findMissingResidues()
fixer.findNonstandardResidues()
fixer.replaceNonstandardResidues()
fixer.findMissingAtoms()
fixer.addMissingAtoms()
fixer.addMissingHydrogens(pH)
PDBFile.writeFile(fixer.topology, fixer.positions, open(filename, 'w'))
示例14: PDBFixer
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
from pdbfixer import PDBFixer
from simtk.openmm.app import PDBFile
fixer = PDBFixer(pdbid='3UE4')
fixer.removeChains(chainIds=['B'])
# Without fixer.missingResidues = {}, fixer.addMissingAtoms() throw an exception
# and if I call fixer.findMissingResidues() several terminal residues are added
fixer.missingResidues = {}
fixer.findMissingAtoms()
fixer.addMissingAtoms()
fixer.removeHeterogens(keepWater=False)
#fixer.addMissingHydrogens(7.0)
PDBFile.writeFile(fixer.topology, fixer.positions, open('../kinases/abl/3UE4-pdbfixer.pdb', 'w'))
示例15: MCMCSampler
# 需要导入模块: from simtk.openmm.app import PDBFile [as 别名]
# 或者: from simtk.openmm.app.PDBFile import writeFile [as 别名]
mcmc_sampler = MCMCSampler(sampler_state=sampler_state, thermodynamic_state=thermodynamic_state, ncfile=ncfile, platform=platform)
mcmc_sampler.timestep = timestep
mcmc_sampler.nsteps = 500
#mcmc_sampler.pdbfile = open('output.pdb', 'w') # uncomment this if you want to write a PDB trajectory as you simulate; WARNING: LARGE!
mcmc_sampler.topology = topology
mcmc_sampler.verbose = True
exen_sampler = ExpandedEnsembleSampler(mcmc_sampler, thermodynamic_states)
exen_sampler.verbose = True
sams_sampler = SAMSSampler(exen_sampler)
sams_sampler.verbose = True
# DEBUG: Write PDB of initial frame
print("Writing initial frame to 'initial.pdb'...")
from simtk.openmm.app import PDBFile
outfile = open('initial.pdb', 'w')
PDBFile.writeFile(topology, positions, outfile)
outfile.close()
# Run the simulation
print('Running simulation...')
#exen_sampler.update_scheme = 'restricted-range' # scheme for deciding which alchemical state to jump to
exen_sampler.update_scheme = 'global-jump' # scheme for deciding which alchemical state to jump to
#exen_sampler.locality = thermodynamic_state_neighbors # neighbors to examine for each state
sams_sampler.update_method = 'rao-blackwellized' # scheme for updating free energy estimates
niterations = 20000 # number of iterations to run
sams_sampler.run(niterations) # run sampler
ncfile.close()
# Analyze
from sams import analysis
# States