本文整理汇总了Python中simtk.openmm.app.Topology.addChain方法的典型用法代码示例。如果您正苦于以下问题:Python Topology.addChain方法的具体用法?Python Topology.addChain怎么用?Python Topology.addChain使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类simtk.openmm.app.Topology
的用法示例。
在下文中一共展示了Topology.addChain方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _createTopology
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
def _createTopology(self):
"""Build the topology of the system
"""
top = Topology()
positions = []
velocities = []
boxVectors = []
for x, y, z in self._conn.execute('SELECT x, y, z FROM global_cell'):
boxVectors.append(mm.Vec3(x, y, z))
unitCellDimensions = [boxVectors[0][0], boxVectors[1][1], boxVectors[2][2]]
top.setUnitCellDimensions(unitCellDimensions*angstrom)
atoms = {}
lastChain = None
lastResId = None
c = top.addChain()
q = """SELECT id, name, anum, resname, resid, chain, x, y, z, vx, vy, vz
FROM particle ORDER BY id"""
for (atomId, atomName, atomNumber, resName, resId, chain, x, y, z, vx, vy, vz) in self._conn.execute(q):
newChain = False
if chain != lastChain:
lastChain = chain
c = top.addChain()
newChain = True
if resId != lastResId or newChain:
lastResId = resId
if resName in PDBFile._residueNameReplacements:
resName = PDBFile._residueNameReplacements[resName]
r = top.addResidue(resName, c)
if resName in PDBFile._atomNameReplacements:
atomReplacements = PDBFile._atomNameReplacements[resName]
else:
atomReplacements = {}
if atomNumber == 0 and atomName.startswith('Vrt'):
elem = None
else:
elem = Element.getByAtomicNumber(atomNumber)
if atomName in atomReplacements:
atomName = atomReplacements[atomName]
atoms[atomId] = top.addAtom(atomName, elem, r)
positions.append(mm.Vec3(x, y, z))
velocities.append(mm.Vec3(vx, vy, vz))
for p0, p1 in self._conn.execute('SELECT p0, p1 FROM bond'):
top.addBond(atoms[p0], atoms[p1])
positions = positions*angstrom
velocities = velocities*angstrom/femtosecond
return top, positions, velocities
示例2: generateTopologyFromOEMol
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
def generateTopologyFromOEMol(molecule):
"""
Generate an OpenMM Topology object from an OEMol molecule.
Parameters
----------
molecule : openeye.oechem.OEMol
The molecule from which a Topology object is to be generated.
Returns
-------
topology : simtk.openmm.app.Topology
The Topology object generated from `molecule`.
"""
# Create a Topology object with one Chain and one Residue.
from simtk.openmm.app import Topology
topology = Topology()
chain = topology.addChain()
resname = molecule.GetTitle()
residue = topology.addResidue(resname, chain)
# Create atoms in the residue.
for atom in molecule.GetAtoms():
name = atom.GetName()
element = Element.getByAtomicNumber(atom.GetAtomicNum())
atom = topology.addAtom(name, element, residue)
# Create bonds.
atoms = { atom.name : atom for atom in topology.atoms() }
for bond in molecule.GetBonds():
topology.addBond(atoms[bond.GetBgn().GetName()], atoms[bond.GetEnd().GetName()])
return topology
示例3: __init__
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
def __init__(self, file):
"""Load a prmtop file."""
top = Topology()
## The Topology read from the prmtop file
self.topology = top
# Load the prmtop file
prmtop = amber_file_parser.PrmtopLoader(file)
self._prmtop = prmtop
# Add atoms to the topology
PDBFile._loadNameReplacementTables()
lastResidue = None
c = top.addChain()
for index in range(prmtop.getNumAtoms()):
resNumber = prmtop.getResidueNumber(index)
if resNumber != lastResidue:
lastResidue = resNumber
resName = prmtop.getResidueLabel(iAtom=index).strip()
if resName in PDBFile._residueNameReplacements:
resName = PDBFile._residueNameReplacements[resName]
r = top.addResidue(resName, c)
if resName in PDBFile._atomNameReplacements:
atomReplacements = PDBFile._atomNameReplacements[resName]
else:
atomReplacements = {}
atomName = prmtop.getAtomName(index).strip()
if atomName in atomReplacements:
atomName = atomReplacements[atomName]
# Try to guess the element.
upper = atomName.upper()
if upper.startswith('CL'):
element = elem.chlorine
elif upper.startswith('NA'):
element = elem.sodium
elif upper.startswith('MG'):
element = elem.magnesium
else:
try:
element = elem.get_by_symbol(atomName[0])
except KeyError:
element = None
top.addAtom(atomName, element, r)
# Add bonds to the topology
atoms = list(top.atoms())
for bond in prmtop.getBondsWithH():
top.addBond(atoms[bond[0]], atoms[bond[1]])
for bond in prmtop.getBondsNoH():
top.addBond(atoms[bond[0]], atoms[bond[1]])
# Set the periodic box size.
if prmtop.getIfBox():
top.setUnitCellDimensions(tuple(x.value_in_unit(unit.nanometer) for x in prmtop.getBoxBetaAndDimensions()[1:4])*unit.nanometer)
示例4: _createTopology
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
def _createTopology(self):
'''Build the topology of the system
'''
top = Topology()
positions = []
boxVectors = []
for x, y, z in self._conn.execute('SELECT x, y, z FROM global_cell'):
boxVectors.append(mm.Vec3(x, y, z)*angstrom)
unitCellDimensions = [boxVectors[0][0], boxVectors[1][1], boxVectors[2][2]]
top.setUnitCellDimensions(unitCellDimensions)
atoms = {}
lastChain = None
lastResId = None
c = top.addChain()
q = '''SELECT id, name, anum, resname, resid, chain, x, y, z
FROM particle'''
for (atomId, atomName, atomNumber, resName, resId, chain, x, y, z) in self._conn.execute(q):
if chain != lastChain:
lastChain = chain
c = top.addChain()
if resId != lastResId:
lastResId = resId
if resName in PDBFile._residueNameReplacements:
resName = PDBFile._residueNameReplacements[resName]
r = top.addResidue(resName, c)
if resName in PDBFile._atomNameReplacements:
atomReplacements = PDBFile._atomNameReplacements[resName]
else:
atomReplacements = {}
if atomName in atomReplacements:
atomName = atomReplacements[atomName]
elem = Element.getByAtomicNumber(atomNumber)
atoms[atomId] = top.addAtom(atomName, elem, r)
positions.append(mm.Vec3(x, y, z)*angstrom)
for p0, p1 in self._conn.execute('SELECT p0, p1 FROM bond'):
top.addBond(atoms[p0], atoms[p1])
return top, positions
示例5: add
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
def add(self, addTopology, addPositions):
"""Add chains, residues, atoms, and bonds to the model.
Specify what to add by providing a new Topology object and the corresponding atomic positions.
All chains, residues, atoms, and bonds contained in the Topology are added to the model.
Parameters:
- addTopoology (Topology) a Topology whose contents should be added to the model
- addPositions (list) the positions of the atoms to add
"""
# Copy over the existing model.
newTopology = Topology()
newTopology.setUnitCellDimensions(deepcopy(self.topology.getUnitCellDimensions()))
newAtoms = {}
newPositions = []*nanometer
for chain in self.topology.chains():
newChain = newTopology.addChain()
for residue in chain.residues():
newResidue = newTopology.addResidue(residue.name, newChain)
for atom in residue.atoms():
newAtom = newTopology.addAtom(atom.name, atom.element, newResidue)
newAtoms[atom] = newAtom
newPositions.append(deepcopy(self.positions[atom.index]))
for bond in self.topology.bonds():
newTopology.addBond(newAtoms[bond[0]], newAtoms[bond[1]])
# Add the new model
newAtoms = {}
for chain in addTopology.chains():
newChain = newTopology.addChain()
for residue in chain.residues():
newResidue = newTopology.addResidue(residue.name, newChain)
for atom in residue.atoms():
newAtom = newTopology.addAtom(atom.name, atom.element, newResidue)
newAtoms[atom] = newAtom
newPositions.append(deepcopy(addPositions[atom.index]))
for bond in addTopology.bonds():
newTopology.addBond(newAtoms[bond[0]], newAtoms[bond[1]])
self.topology = newTopology
self.positions = newPositions
示例6: delete
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
def delete(self, toDelete):
"""Delete chains, residues, atoms, and bonds from the model.
You can specify objects to delete at any granularity: atoms, residues, or chains. Passing
in an Atom object causes that Atom to be deleted. Passing in a Residue object causes that
Residue and all Atoms it contains to be deleted. Passing in a Chain object causes that
Chain and all Residues and Atoms it contains to be deleted.
In all cases, when an Atom is deleted, any bonds it participates in are also deleted.
You also can specify a bond (as a tuple of Atom objects) to delete just that bond without
deleting the Atoms it connects.
Parameters:
- toDelete (list) a list of Atoms, Residues, Chains, and bonds (specified as tuples of Atoms) to delete
"""
newTopology = Topology()
newTopology.setUnitCellDimensions(deepcopy(self.topology.getUnitCellDimensions()))
newAtoms = {}
newPositions = []*nanometer
deleteSet = set(toDelete)
for chain in self.topology.chains():
if chain not in deleteSet:
needNewChain = True;
for residue in chain.residues():
if residue not in deleteSet:
needNewResidue = True
for atom in residue.atoms():
if atom not in deleteSet:
if needNewChain:
newChain = newTopology.addChain()
needNewChain = False;
if needNewResidue:
newResidue = newTopology.addResidue(residue.name, newChain)
needNewResidue = False;
newAtom = newTopology.addAtom(atom.name, atom.element, newResidue)
newAtoms[atom] = newAtom
newPositions.append(deepcopy(self.positions[atom.index]))
for bond in self.topology.bonds():
if bond[0] in newAtoms and bond[1] in newAtoms:
if bond not in deleteSet and (bond[1], bond[0]) not in deleteSet:
newTopology.addBond(newAtoms[bond[0]], newAtoms[bond[1]])
self.topology = newTopology
self.positions = newPositions
示例7: __init__
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
def __init__(self, file):
"""Load a PDBx/mmCIF file.
The atom positions and Topology can be retrieved by calling
getPositions() and getTopology().
Parameters
----------
file : string
the name of the file to load. Alternatively you can pass an open
file object.
"""
top = Topology()
## The Topology read from the PDBx/mmCIF file
self.topology = top
self._positions = []
# Load the file.
inputFile = file
if isinstance(file, str):
inputFile = open(file)
reader = PdbxReader(inputFile)
data = []
reader.read(data)
block = data[0]
# Build the topology.
atomData = block.getObj('atom_site')
atomNameCol = atomData.getAttributeIndex('auth_atom_id')
atomIdCol = atomData.getAttributeIndex('id')
resNameCol = atomData.getAttributeIndex('auth_comp_id')
resNumCol = atomData.getAttributeIndex('auth_seq_id')
resInsertionCol = atomData.getAttributeIndex('pdbx_PDB_ins_code')
chainIdCol = atomData.getAttributeIndex('auth_asym_id')
elementCol = atomData.getAttributeIndex('type_symbol')
altIdCol = atomData.getAttributeIndex('label_alt_id')
modelCol = atomData.getAttributeIndex('pdbx_PDB_model_num')
xCol = atomData.getAttributeIndex('Cartn_x')
yCol = atomData.getAttributeIndex('Cartn_y')
zCol = atomData.getAttributeIndex('Cartn_z')
lastChainId = None
lastResId = None
atomTable = {}
atomsInResidue = set()
models = []
for row in atomData.getRowList():
atomKey = ((row[resNumCol], row[chainIdCol], row[atomNameCol]))
model = ('1' if modelCol == -1 else row[modelCol])
if model not in models:
models.append(model)
self._positions.append([])
modelIndex = models.index(model)
if row[altIdCol] != '.' and atomKey in atomTable and len(self._positions[modelIndex]) > atomTable[atomKey].index:
# This row is an alternate position for an existing atom, so ignore it.
continue
if modelIndex == 0:
# This row defines a new atom.
if lastChainId != row[chainIdCol]:
# The start of a new chain.
chain = top.addChain(row[chainIdCol])
lastChainId = row[chainIdCol]
lastResId = None
if lastResId != row[resNumCol] or lastChainId != row[chainIdCol] or (lastResId == '.' and row[atomNameCol] in atomsInResidue):
# The start of a new residue.
resId = (None if resNumCol == -1 else row[resNumCol])
resIC = ('' if resInsertionCol == -1 else row[resInsertionCol])
res = top.addResidue(row[resNameCol], chain, resId, resIC)
lastResId = row[resNumCol]
atomsInResidue.clear()
element = None
try:
element = elem.get_by_symbol(row[elementCol])
except KeyError:
pass
atom = top.addAtom(row[atomNameCol], element, res, row[atomIdCol])
atomTable[atomKey] = atom
atomsInResidue.add(row[atomNameCol])
else:
# This row defines coordinates for an existing atom in one of the later models.
try:
atom = atomTable[atomKey]
except KeyError:
raise ValueError('Unknown atom %s in residue %s %s for model %s' % (row[atomNameCol], row[resNameCol], row[resNumCol], model))
if atom.index != len(self._positions[modelIndex]):
raise ValueError('Atom %s for model %s does not match the order of atoms for model %s' % (row[atomIdCol], model, models[0]))
self._positions[modelIndex].append(Vec3(float(row[xCol]), float(row[yCol]), float(row[zCol]))*0.1)
for i in range(len(self._positions)):
self._positions[i] = self._positions[i]*nanometers
## The atom positions read from the PDBx/mmCIF file. If the file contains multiple frames, these are the positions in the first frame.
self.positions = self._positions[0]
self.topology.createStandardBonds()
self._numpyPositions = None
# Record unit cell information, if present.
#.........这里部分代码省略.........
示例8: __init__
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
def __init__(self, file, periodicBoxVectors=None, unitCellDimensions=None, includeDir=None, defines=None):
"""Load a top file.
Parameters
----------
file : str
the name of the file to load
periodicBoxVectors : tuple of Vec3=None
the vectors defining the periodic box
unitCellDimensions : Vec3=None
the dimensions of the crystallographic unit cell. For
non-rectangular unit cells, specify periodicBoxVectors instead.
includeDir : string=None
A directory in which to look for other files included from the
top file. If not specified, we will attempt to locate a gromacs
installation on your system. When gromacs is installed in
/usr/local, this will resolve to /usr/local/gromacs/share/gromacs/top
defines : dict={}
preprocessor definitions that should be predefined when parsing the file
"""
if includeDir is None:
includeDir = _defaultGromacsIncludeDir()
self._includeDirs = (os.path.dirname(file), includeDir)
# Most of the gromacs water itp files for different forcefields,
# unless the preprocessor #define FLEXIBLE is given, don't define
# bonds between the water hydrogen and oxygens, but only give the
# constraint distances and exclusions.
self._defines = OrderedDict()
self._defines['FLEXIBLE'] = True
self._genpairs = True
if defines is not None:
for define, value in defines.iteritems():
self._defines[define] = value
# Parse the file.
self._currentCategory = None
self._ifStack = []
self._elseStack = []
self._moleculeTypes = {}
self._molecules = []
self._currentMoleculeType = None
self._atomTypes = {}
self._bondTypes= {}
self._angleTypes = {}
self._dihedralTypes = {}
self._implicitTypes = {}
self._pairTypes = {}
self._cmapTypes = {}
self._processFile(file)
# Create the Topology from it.
top = Topology()
## The Topology read from the prmtop file
self.topology = top
if periodicBoxVectors is not None:
if unitCellDimensions is not None:
raise ValueError("specify either periodicBoxVectors or unitCellDimensions, but not both")
top.setPeriodicBoxVectors(periodicBoxVectors)
else:
top.setUnitCellDimensions(unitCellDimensions)
PDBFile._loadNameReplacementTables()
for moleculeName, moleculeCount in self._molecules:
if moleculeName not in self._moleculeTypes:
raise ValueError("Unknown molecule type: "+moleculeName)
moleculeType = self._moleculeTypes[moleculeName]
if moleculeCount > 0 and moleculeType.has_virtual_sites:
raise ValueError('Virtual sites not yet supported by Gromacs parsers')
# Create the specified number of molecules of this type.
for i in range(moleculeCount):
atoms = []
lastResidue = None
c = top.addChain()
for index, fields in enumerate(moleculeType.atoms):
resNumber = fields[2]
if resNumber != lastResidue:
lastResidue = resNumber
resName = fields[3]
if resName in PDBFile._residueNameReplacements:
resName = PDBFile._residueNameReplacements[resName]
r = top.addResidue(resName, c)
if resName in PDBFile._atomNameReplacements:
atomReplacements = PDBFile._atomNameReplacements[resName]
else:
atomReplacements = {}
atomName = fields[4]
if atomName in atomReplacements:
atomName = atomReplacements[atomName]
# Try to guess the element.
upper = atomName.upper()
if upper.startswith('CL'):
element = elem.chlorine
elif upper.startswith('NA'):
element = elem.sodium
elif upper.startswith('MG'):
#.........这里部分代码省略.........
示例9: __init__
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
def __init__(self, file):
"""Load a PDB file.
The atom positions and Topology can be retrieved by calling getPositions() and getTopology().
Parameters
----------
file : string
the name of the file to load
"""
top = Topology()
## The Topology read from the PDB file
self.topology = top
# Load the PDB file
if isinstance(file, PdbStructure):
pdb = file
else:
inputfile = file
own_handle = False
if isinstance(file, str):
inputfile = open(file)
own_handle = True
pdb = PdbStructure(inputfile, load_all_models=True)
if own_handle:
inputfile.close()
PDBFile._loadNameReplacementTables()
# Build the topology
atomByNumber = {}
for chain in pdb.iter_chains():
c = top.addChain(chain.chain_id)
for residue in chain.iter_residues():
resName = residue.get_name()
if resName in PDBFile._residueNameReplacements:
resName = PDBFile._residueNameReplacements[resName]
r = top.addResidue(resName, c, str(residue.number))
if resName in PDBFile._atomNameReplacements:
atomReplacements = PDBFile._atomNameReplacements[resName]
else:
atomReplacements = {}
for atom in residue.atoms:
atomName = atom.get_name()
if atomName in atomReplacements:
atomName = atomReplacements[atomName]
atomName = atomName.strip()
element = atom.element
if element is None:
# Try to guess the element.
upper = atomName.upper()
if upper.startswith('CL'):
element = elem.chlorine
elif upper.startswith('NA'):
element = elem.sodium
elif upper.startswith('MG'):
element = elem.magnesium
elif upper.startswith('BE'):
element = elem.beryllium
elif upper.startswith('LI'):
element = elem.lithium
elif upper.startswith('K'):
element = elem.potassium
elif upper.startswith('ZN'):
element = elem.zinc
elif( len( residue ) == 1 and upper.startswith('CA') ):
element = elem.calcium
else:
try:
element = elem.get_by_symbol(atomName[0])
except KeyError:
pass
newAtom = top.addAtom(atomName, element, r, str(atom.serial_number))
atomByNumber[atom.serial_number] = newAtom
self._positions = []
for model in pdb.iter_models(True):
coords = []
for chain in model.iter_chains():
for residue in chain.iter_residues():
for atom in residue.atoms:
pos = atom.get_position().value_in_unit(nanometers)
coords.append(Vec3(pos[0], pos[1], pos[2]))
self._positions.append(coords*nanometers)
## The atom positions read from the PDB file. If the file contains multiple frames, these are the positions in the first frame.
self.positions = self._positions[0]
self.topology.setPeriodicBoxVectors(pdb.get_periodic_box_vectors())
self.topology.createStandardBonds()
self.topology.createDisulfideBonds(self.positions)
self._numpyPositions = None
# Add bonds based on CONECT records.
connectBonds = []
for connect in pdb.models[0].connects:
i = connect[0]
for j in connect[1:]:
if i in atomByNumber and j in atomByNumber:
connectBonds.append((atomByNumber[i], atomByNumber[j]))
#.........这里部分代码省略.........
示例10: addExtraParticles
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
def addExtraParticles(self, forcefield):
"""Add missing extra particles to the model that are required by a force field.
Some force fields use "extra particles" that do not represent actual atoms, but still need to be included in
the System. Examples include lone pairs, Drude particles, and the virtual sites used in some water models
to adjust the charge distribution. Extra particles can be recognized by the fact that their element is None.
This method is primarily used to add extra particles, but it can also remove them. It tries to match every
residue in the Topology to a template in the force field. If there is no match, it will both add and remove
extra particles as necessary to make it match.
Parameters:
- forcefield (ForceField) the ForceField defining what extra particles should be present
"""
# Create copies of all residue templates that have had all extra points removed.
templatesNoEP = {}
for resName, template in forcefield._templates.iteritems():
if any(atom.element is None for atom in template.atoms):
index = 0
newIndex = {}
newTemplate = ForceField._TemplateData(resName)
for i, atom in enumerate(template.atoms):
if atom.element is not None:
newIndex[i] = index
index += 1
newTemplate.atoms.append(ForceField._TemplateAtomData(atom.name, atom.type, atom.element))
for b1, b2 in template.bonds:
if b1 in newIndex and b2 in newIndex:
newTemplate.bonds.append((newIndex[b1], newIndex[b2]))
newTemplate.atoms[newIndex[b1]].bondedTo.append(newIndex[b2])
newTemplate.atoms[newIndex[b2]].bondedTo.append(newIndex[b1])
for b in template.externalBonds:
if b in newIndex:
newTemplate.externalBonds.append(newIndex[b])
templatesNoEP[template] = newTemplate
# Record which atoms are bonded to each other atom, with and without extra particles.
bondedToAtom = []
bondedToAtomNoEP = []
for atom in self.topology.atoms():
bondedToAtom.append(set())
bondedToAtomNoEP.append(set())
for atom1, atom2 in self.topology.bonds():
bondedToAtom[atom1.index].add(atom2.index)
bondedToAtom[atom2.index].add(atom1.index)
if atom1.element is not None and atom2.element is not None:
bondedToAtomNoEP[atom1.index].add(atom2.index)
bondedToAtomNoEP[atom2.index].add(atom1.index)
# If the force field has a DrudeForce, record the types of Drude particles and their parents since we'll
# need them for picking particle positions.
drudeTypeMap = {}
for force in forcefield._forces:
if isinstance(force, DrudeGenerator):
for type in force.typeMap:
drudeTypeMap[type] = force.typeMap[type][0]
# Create the new Topology.
newTopology = Topology()
newTopology.setUnitCellDimensions(deepcopy(self.topology.getUnitCellDimensions()))
newAtoms = {}
newPositions = []*nanometer
for chain in self.topology.chains():
newChain = newTopology.addChain()
for residue in chain.residues():
newResidue = newTopology.addResidue(residue.name, newChain)
# Look for a matching template.
matchFound = False
signature = _createResidueSignature([atom.element for atom in residue.atoms()])
if signature in forcefield._templateSignatures:
for t in forcefield._templateSignatures[signature]:
if _matchResidue(residue, t, bondedToAtom) is not None:
matchFound = True
if matchFound:
# Just copy the residue over.
for atom in residue.atoms():
newAtom = newTopology.addAtom(atom.name, atom.element, newResidue)
newAtoms[atom] = newAtom
newPositions.append(deepcopy(self.positions[atom.index]))
else:
# There's no matching template. Try to find one that matches based on everything except
# extra points.
template = None
residueNoEP = Residue(residue.name, residue.index, residue.chain)
residueNoEP._atoms = [atom for atom in residue.atoms() if atom.element is not None]
if signature in forcefield._templateSignatures:
for t in forcefield._templateSignatures[signature]:
if t in templatesNoEP:
matches = _matchResidue(residueNoEP, templatesNoEP[t], bondedToAtomNoEP)
if matches is not None:
template = t;
# Record the corresponding atoms.
#.........这里部分代码省略.........
示例11: addHydrogens
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
def addHydrogens(self, forcefield, pH=7.0, variants=None, platform=None):
"""Add missing hydrogens to the model.
Some residues can exist in multiple forms depending on the pH and properties of the local environment. These
variants differ in the presence or absence of particular hydrogens. In particular, the following variants
are supported:
Aspartic acid:
ASH: Neutral form with a hydrogen on one of the delta oxygens
ASP: Negatively charged form without a hydrogen on either delta oxygen
Cysteine:
CYS: Neutral form with a hydrogen on the sulfur
CYX: No hydrogen on the sulfur (either negatively charged, or part of a disulfide bond)
Glutamic acid:
GLH: Neutral form with a hydrogen on one of the epsilon oxygens
GLU: Negatively charged form without a hydrogen on either epsilon oxygen
Histidine:
HID: Neutral form with a hydrogen on the ND1 atom
HIE: Neutral form with a hydrogen on the NE2 atom
HIP: Positively charged form with hydrogens on both ND1 and NE2
Lysine:
LYN: Neutral form with two hydrogens on the zeta nitrogen
LYS: Positively charged form with three hydrogens on the zeta nitrogen
The variant to use for each residue is determined by the following rules:
1. The most common variant at the specified pH is selected.
2. Any Cysteine that participates in a disulfide bond uses the CYX variant regardless of pH.
3. For a neutral Histidine residue, the HID or HIE variant is selected based on which one forms a better hydrogen bond.
You can override these rules by explicitly specifying a variant for any residue. Also keep in mind that this
function will only add hydrogens. It will never remove ones that are already present in the model, regardless
of the specified pH.
Definitions for standard amino acids and nucleotides are built in. You can call loadHydrogenDefinitions() to load
additional definitions for other residue types.
Parameters:
- forcefield (ForceField) the ForceField to use for determining the positions of hydrogens
- pH (float=7.0) the pH based on which to select variants
- variants (list=None) an optional list of variants to use. If this is specified, its length must equal the number
of residues in the model. variants[i] is the name of the variant to use for residue i (indexed starting at 0).
If an element is None, the standard rules will be followed to select a variant for that residue.
- platform (Platform=None) the Platform to use when computing the hydrogen atom positions. If this is None,
the default Platform will be used.
Returns: a list of what variant was actually selected for each residue, in the same format as the variants parameter
"""
# Check the list of variants.
residues = list(self.topology.residues())
if variants is not None:
if len(variants) != len(residues):
raise ValueError("The length of the variants list must equal the number of residues")
else:
variants = [None]*len(residues)
actualVariants = [None]*len(residues)
# Load the residue specifications.
if not Modeller._hasLoadedStandardHydrogens:
Modeller.loadHydrogenDefinitions(os.path.join(os.path.dirname(__file__), 'data', 'hydrogens.xml'))
# Make a list of atoms bonded to each atom.
bonded = {}
for atom in self.topology.atoms():
bonded[atom] = []
for atom1, atom2 in self.topology.bonds():
bonded[atom1].append(atom2)
bonded[atom2].append(atom1)
# Define a function that decides whether a set of atoms form a hydrogen bond, using fairly tolerant criteria.
def isHbond(d, h, a):
if norm(d-a) > 0.35*nanometer:
return False
deltaDH = h-d
deltaHA = a-h
deltaDH /= norm(deltaDH)
deltaHA /= norm(deltaHA)
return acos(dot(deltaDH, deltaHA)) < 50*degree
# Loop over residues.
newTopology = Topology()
newTopology.setUnitCellDimensions(deepcopy(self.topology.getUnitCellDimensions()))
newAtoms = {}
newPositions = []*nanometer
newIndices = []
acceptors = [atom for atom in self.topology.atoms() if atom.element in (elem.oxygen, elem.nitrogen)]
for chain in self.topology.chains():
newChain = newTopology.addChain()
for residue in chain.residues():
newResidue = newTopology.addResidue(residue.name, newChain)
isNTerminal = (residue == chain._residues[0])
isCTerminal = (residue == chain._residues[-1])
#.........这里部分代码省略.........
示例12: addSolvent
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
def addSolvent(self, forcefield, model='tip3p', boxSize=None, padding=None, positiveIon='Na+', negativeIon='Cl-', ionicStrength=0*molar):
"""Add solvent (both water and ions) to the model to fill a rectangular box.
The algorithm works as follows:
1. Water molecules are added to fill the box.
2. Water molecules are removed if their distance to any solute atom is less than the sum of their van der Waals radii.
3. If the solute is charged, enough positive or negative ions are added to neutralize it. Each ion is added by
randomly selecting a water molecule and replacing it with the ion.
4. Ion pairs are added to give the requested total ionic strength.
The box size can be specified in three ways. First, you can explicitly give a box size to use. Alternatively, you can
give a padding distance. The largest dimension of the solute (along the x, y, or z axis) is determined, and a cubic
box of size (largest dimension)+2*padding is used. Finally, if neither a box size nor a padding distance is specified,
the existing Topology's unit cell dimensions are used.
Parameters:
- forcefield (ForceField) the ForceField to use for determining van der Waals radii and atomic charges
- model (string='tip3p') the water model to use. Supported values are 'tip3p', 'spce', 'tip4pew', and 'tip5p'.
- boxSize (Vec3=None) the size of the box to fill with water
- padding (distance=None) the padding distance to use
- positiveIon (string='Na+') the type of positive ion to add. Allowed values are 'Cs+', 'K+', 'Li+', 'Na+', and 'Rb+'
- negativeIon (string='Cl-') the type of negative ion to add. Allowed values are 'Cl-', 'Br-', 'F-', and 'I-'. Be aware
that not all force fields support all ion types.
- ionicString (concentration=0*molar) the total concentration of ions (both positive and negative) to add. This
does not include ions that are added to neutralize the system.
"""
# Pick a unit cell size.
if boxSize is not None:
if is_quantity(boxSize):
boxSize = boxSize.value_in_unit(nanometer)
box = Vec3(boxSize[0], boxSize[1], boxSize[2])*nanometer
elif padding is not None:
maxSize = max(max((pos[i] for pos in self.positions))-min((pos[i] for pos in self.positions)) for i in range(3))
box = (maxSize+2*padding)*Vec3(1, 1, 1)
else:
box = self.topology.getUnitCellDimensions()
if box is None:
raise ValueError('Neither the box size nor padding was specified, and the Topology does not define unit cell dimensions')
box = box.value_in_unit(nanometer)
invBox = Vec3(1.0/box[0], 1.0/box[1], 1.0/box[2])
# Identify the ion types.
posIonElements = {'Cs+':elem.cesium, 'K+':elem.potassium, 'Li+':elem.lithium, 'Na+':elem.sodium, 'Rb+':elem.rubidium}
negIonElements = {'Cl-':elem.chlorine, 'Br-':elem.bromine, 'F-':elem.fluorine, 'I-':elem.iodine}
if positiveIon not in posIonElements:
raise ValueError('Illegal value for positive ion: %s' % positiveIon)
if negativeIon not in negIonElements:
raise ValueError('Illegal value for negative ion: %s' % negativeIon)
positiveElement = posIonElements[positiveIon]
negativeElement = negIonElements[negativeIon]
# Load the pre-equilibrated water box.
vdwRadiusPerSigma = 0.5612310241546864907
if model == 'tip3p':
waterRadius = 0.31507524065751241*vdwRadiusPerSigma
elif model == 'spce':
waterRadius = 0.31657195050398818*vdwRadiusPerSigma
elif model == 'tip4pew':
waterRadius = 0.315365*vdwRadiusPerSigma
elif model == 'tip5p':
waterRadius = 0.312*vdwRadiusPerSigma
else:
raise ValueError('Unknown water model: %s' % model)
pdb = PDBFile(os.path.join(os.path.dirname(__file__), 'data', model+'.pdb'))
pdbTopology = pdb.getTopology()
pdbPositions = pdb.getPositions().value_in_unit(nanometer)
pdbResidues = list(pdbTopology.residues())
pdbBoxSize = pdbTopology.getUnitCellDimensions().value_in_unit(nanometer)
# Have the ForceField build a System for the solute from which we can determine van der Waals radii.
system = forcefield.createSystem(self.topology)
nonbonded = None
for i in range(system.getNumForces()):
if isinstance(system.getForce(i), NonbondedForce):
nonbonded = system.getForce(i)
if nonbonded is None:
raise ValueError('The ForceField does not specify a NonbondedForce')
cutoff = [nonbonded.getParticleParameters(i)[1].value_in_unit(nanometer)*vdwRadiusPerSigma+waterRadius for i in range(system.getNumParticles())]
waterCutoff = waterRadius
if len(cutoff) == 0:
maxCutoff = waterCutoff
else:
maxCutoff = max(waterCutoff, max(cutoff))
# Copy the solute over.
newTopology = Topology()
newTopology.setUnitCellDimensions(box)
newAtoms = {}
newPositions = []*nanometer
for chain in self.topology.chains():
newChain = newTopology.addChain()
for residue in chain.residues():
newResidue = newTopology.addResidue(residue.name, newChain)
for atom in residue.atoms():
newAtom = newTopology.addAtom(atom.name, atom.element, newResidue)
#.........这里部分代码省略.........
示例13: convertWater
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
def convertWater(self, model='tip3p'):
"""Convert all water molecules to a different water model.
Parameters:
- model (string='tip3p') the water model to convert to. Supported values are 'tip3p', 'spce', 'tip4pew', and 'tip5p'.
@deprecated Use addExtraParticles() instead. It performs the same function but in a more general way.
"""
if model in ('tip3p', 'spce'):
sites = 3
elif model == 'tip4pew':
sites = 4
elif model == 'tip5p':
sites = 5
else:
raise ValueError('Unknown water model: %s' % model)
newTopology = Topology()
newTopology.setUnitCellDimensions(deepcopy(self.topology.getUnitCellDimensions()))
newAtoms = {}
newPositions = []*nanometer
for chain in self.topology.chains():
newChain = newTopology.addChain()
for residue in chain.residues():
newResidue = newTopology.addResidue(residue.name, newChain)
if residue.name == "HOH":
# Copy the oxygen and hydrogens
oatom = [atom for atom in residue.atoms() if atom.element == elem.oxygen]
hatoms = [atom for atom in residue.atoms() if atom.element == elem.hydrogen]
if len(oatom) != 1 or len(hatoms) != 2:
raise ValueError('Illegal water molecule (residue %d): contains %d oxygen(s) and %d hydrogen(s)' % (residue.index, len(oatom), len(hatoms)))
o = newTopology.addAtom(oatom[0].name, oatom[0].element, newResidue)
h1 = newTopology.addAtom(hatoms[0].name, hatoms[0].element, newResidue)
h2 = newTopology.addAtom(hatoms[1].name, hatoms[1].element, newResidue)
newAtoms[oatom[0]] = o
newAtoms[hatoms[0]] = h1
newAtoms[hatoms[1]] = h2
po = deepcopy(self.positions[oatom[0].index])
ph1 = deepcopy(self.positions[hatoms[0].index])
ph2 = deepcopy(self.positions[hatoms[1].index])
newPositions.append(po)
newPositions.append(ph1)
newPositions.append(ph2)
# Add virtual sites.
if sites == 4:
newTopology.addAtom('M', None, newResidue)
newPositions.append(0.786646558*po + 0.106676721*ph1 + 0.106676721*ph2)
elif sites == 5:
newTopology.addAtom('M1', None, newResidue)
newTopology.addAtom('M2', None, newResidue)
v1 = (ph1-po).value_in_unit(nanometer)
v2 = (ph2-po).value_in_unit(nanometer)
cross = Vec3(v1[1]*v2[2]-v1[2]*v2[1], v1[2]*v2[0]-v1[0]*v2[2], v1[0]*v2[1]-v1[1]*v2[0])
newPositions.append(po - (0.34490826*v1 - 0.34490826*v2 - 6.4437903*cross)*nanometer)
newPositions.append(po - (0.34490826*v1 - 0.34490826*v2 + 6.4437903*cross)*nanometer)
else:
# Just copy the residue over.
for atom in residue.atoms():
newAtom = newTopology.addAtom(atom.name, atom.element, newResidue)
newAtoms[atom] = newAtom
newPositions.append(deepcopy(self.positions[atom.index]))
for bond in self.topology.bonds():
if bond[0] in newAtoms and bond[1] in newAtoms:
newTopology.addBond(newAtoms[bond[0]], newAtoms[bond[1]])
self.topology = newTopology
self.positions = newPositions
示例14: OpenMMAmberParm
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
class OpenMMAmberParm(AmberParm):
"""
OpenMM-compatible subclass of AmberParm. This object should still work with
the ParmEd API while also being compatible with OpenMM's environment
"""
# Define default force groups for all of the bonded terms. This allows them
# to be turned on and off selectively. This is a way to implement per-term
# energy decomposition to compare individual components
BOND_FORCE_GROUP = 0
ANGLE_FORCE_GROUP = 1
DIHEDRAL_FORCE_GROUP = 2
NONBONDED_FORCE_GROUP = 3
GB_FORCE_GROUP = 3
def openmm_LJ(self):
"""
Same as fill_LJ, except it uses 0.5 for the LJ radius for H-atoms with
no vdW parameters (per OpenMM's standard)
Returns:
list, list : The 1st list is the list of all Rmin/2 terms. The
2nd is the list of all epsilon (or well depth) terms.
"""
LJ_radius = [] # empty LJ_radii so it can be re-filled
LJ_depth = [] # empty LJ_depths so it can be re-filled
one_sixth = 1 / 6 # we need to raise some numbers to the 1/6th power
ntypes = self.pointers['NTYPES']
acoef = self.parm_data['LENNARD_JONES_ACOEF']
bcoef = self.parm_data['LENNARD_JONES_BCOEF']
for i in range(ntypes):
lj_index = self.parm_data["NONBONDED_PARM_INDEX"][ntypes*i+i] - 1
if acoef[lj_index] < 1.0e-10:
LJ_radius.append(0.5)
LJ_depth.append(0)
else:
factor = (2 * acoef[lj_index] / bcoef[lj_index])
LJ_radius.append(pow(factor, one_sixth) * 0.5)
LJ_depth.append(bcoef[lj_index] / 2 / factor)
# Now check that we haven't modified any off-diagonals, since that will
# not work with OpenMM
for i in range(ntypes):
for j in range(ntypes):
idx = self.parm_data['NONBONDED_PARM_INDEX'][ntypes*i+j] - 1
rij = LJ_radius[i] + LJ_radius[j]
wdij = sqrt(LJ_depth[i] * LJ_depth[j])
a = acoef[idx]
b = bcoef[idx]
if a == 0 or b == 0:
if a != 0 or b != 0 or (wdij != 0 and rij != 0):
raise OpenMMError('Off-diagonal LJ modifications '
'detected. These are incompatible '
'with the OpenMM API')
elif (abs((a - (wdij * rij**12)) / a) > 1e-6 or
abs((b - (2 * wdij * rij**6)) / b) > 1e-6):
raise OpenMMError(
'Off-diagonal LJ modifications detected. These are '
'incompatible with the OpenMM API. Acoef=%s; '
'computed=%s. Bcoef=%s; computed=%s' %
(acoef, wdij*rij**12, bcoef, 2*wdij*rij**6)
)
return LJ_radius, LJ_depth
def openmm_14_LJ(self):
"""
Returns the radii and depths for the LJ interactions between 1-4 pairs.
For Amber topology files this is the same as the normal LJ parameters,
but is done here so that OpenMMChamberParm can inherit and override this
behavior without having to duplicate all of the system creation code.
"""
return self.openmm_LJ()
@property
def topology(self):
"""
The OpenMM Topology object. Cached when possible, but any changes to the
topology object lists results in the topology being deleted and rebuilt
"""
# If anything changed, rebuild the topology
if not self._topology_changed():
try:
return self._topology
except AttributeError:
pass
else:
self.remake_parm()
self._topology = Topology()
# Add all of the atoms to the topology file in the same chain
chain = self._topology.addChain()
last_residue = None
for i, atm in enumerate(self.atom_list):
resnum = atm.residue.idx
if last_residue != resnum:
#.........这里部分代码省略.........
示例15: __init__
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addChain [as 别名]
def __init__(self, file, extraParticleIdentifier='EP'):
"""Load a PDB file.
The atom positions and Topology can be retrieved by calling getPositions() and getTopology().
Parameters
----------
file : string
the name of the file to load
extraParticleIdentifier : string='EP'
if this value appears in the element column for an ATOM record, the Atom's element will be set to None to mark it as an extra particle
"""
metalElements = ['Al','As','Ba','Ca','Cd','Ce','Co','Cs','Cu','Dy','Fe','Gd','Hg','Ho','In','Ir','K','Li','Mg',
'Mn','Mo','Na','Ni','Pb','Pd','Pt','Rb','Rh','Sm','Sr','Te','Tl','V','W','Yb','Zn']
top = Topology()
## The Topology read from the PDB file
self.topology = top
# Load the PDB file
if isinstance(file, PdbStructure):
pdb = file
else:
inputfile = file
own_handle = False
if isinstance(file, str):
inputfile = open(file)
own_handle = True
pdb = PdbStructure(inputfile, load_all_models=True, extraParticleIdentifier=extraParticleIdentifier)
if own_handle:
inputfile.close()
PDBFile._loadNameReplacementTables()
# Build the topology
atomByNumber = {}
for chain in pdb.iter_chains():
c = top.addChain(chain.chain_id)
for residue in chain.iter_residues():
resName = residue.get_name()
if resName in PDBFile._residueNameReplacements:
resName = PDBFile._residueNameReplacements[resName]
r = top.addResidue(resName, c, str(residue.number))
if resName in PDBFile._atomNameReplacements:
atomReplacements = PDBFile._atomNameReplacements[resName]
else:
atomReplacements = {}
for atom in residue.atoms:
atomName = atom.get_name()
if atomName in atomReplacements:
atomName = atomReplacements[atomName]
atomName = atomName.strip()
element = atom.element
if element == 'EP':
element = None
elif element is None:
# Try to guess the element.
upper = atomName.upper()
while len(upper) > 1 and upper[0].isdigit():
upper = upper[1:]
if upper.startswith('CL'):
element = elem.chlorine
elif upper.startswith('NA'):
element = elem.sodium
elif upper.startswith('MG'):
element = elem.magnesium
elif upper.startswith('BE'):
element = elem.beryllium
elif upper.startswith('LI'):
element = elem.lithium
elif upper.startswith('K'):
element = elem.potassium
elif upper.startswith('ZN'):
element = elem.zinc
elif( len( residue ) == 1 and upper.startswith('CA') ):
element = elem.calcium
else:
try:
element = elem.get_by_symbol(upper[0])
except KeyError:
pass
newAtom = top.addAtom(atomName, element, r, str(atom.serial_number))
atomByNumber[atom.serial_number] = newAtom
self._positions = []
for model in pdb.iter_models(True):
coords = []
for chain in model.iter_chains():
for residue in chain.iter_residues():
for atom in residue.atoms:
pos = atom.get_position().value_in_unit(nanometers)
coords.append(Vec3(pos[0], pos[1], pos[2]))
self._positions.append(coords*nanometers)
## The atom positions read from the PDB file. If the file contains multiple frames, these are the positions in the first frame.
self.positions = self._positions[0]
self.topology.setPeriodicBoxVectors(pdb.get_periodic_box_vectors())
self.topology.createStandardBonds()
self.topology.createDisulfideBonds(self.positions)
#.........这里部分代码省略.........