本文整理汇总了Python中simtk.openmm.app.Topology.addBond方法的典型用法代码示例。如果您正苦于以下问题:Python Topology.addBond方法的具体用法?Python Topology.addBond怎么用?Python Topology.addBond使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类simtk.openmm.app.Topology
的用法示例。
在下文中一共展示了Topology.addBond方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generateTopologyFromOEMol
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addBond [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
示例2: __init__
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addBond [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)
示例3: _createTopology
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addBond [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
示例4: _createTopology
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addBond [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: delete
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addBond [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
示例6: add
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addBond [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
示例7: __init__
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addBond [as 别名]
#.........这里部分代码省略.........
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.
cell = block.getObj('cell')
if cell is not None and cell.getRowCount() > 0:
row = cell.getRow(0)
(a, b, c) = [float(row[cell.getAttributeIndex(attribute)])*0.1 for attribute in ('length_a', 'length_b', 'length_c')]
(alpha, beta, gamma) = [float(row[cell.getAttributeIndex(attribute)])*math.pi/180.0 for attribute in ('angle_alpha', 'angle_beta', 'angle_gamma')]
self.topology.setPeriodicBoxVectors(computePeriodicBoxVectors(a, b, c, alpha, beta, gamma))
# Add bonds based on struct_conn records.
connectData = block.getObj('struct_conn')
if connectData is not None:
res1Col = connectData.getAttributeIndex('ptnr1_label_seq_id')
res2Col = connectData.getAttributeIndex('ptnr2_label_seq_id')
atom1Col = connectData.getAttributeIndex('ptnr1_label_atom_id')
atom2Col = connectData.getAttributeIndex('ptnr2_label_atom_id')
asym1Col = connectData.getAttributeIndex('ptnr1_label_asym_id')
asym2Col = connectData.getAttributeIndex('ptnr2_label_asym_id')
typeCol = connectData.getAttributeIndex('conn_type_id')
connectBonds = []
for row in connectData.getRowList():
type = row[typeCol][:6]
if type in ('covale', 'disulf', 'modres'):
key1 = (row[res1Col], row[asym1Col], row[atom1Col])
key2 = (row[res2Col], row[asym2Col], row[atom2Col])
if key1 in atomTable and key2 in atomTable:
connectBonds.append((atomTable[key1], atomTable[key2]))
if len(connectBonds) > 0:
# Only add bonds that don't already exist.
existingBonds = set(top.bonds())
for bond in connectBonds:
if bond not in existingBonds and (bond[1], bond[0]) not in existingBonds:
top.addBond(bond[0], bond[1])
existingBonds.add(bond)
示例8: __init__
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addBond [as 别名]
#.........这里部分代码省略.........
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'):
element = elem.magnesium
else:
try:
element = elem.get_by_symbol(atomName[0])
except KeyError:
element = None
atoms.append(top.addAtom(atomName, element, r))
# Add bonds to the topology
for fields in moleculeType.bonds:
top.addBond(atoms[int(fields[0])-1], atoms[int(fields[1])-1])
示例9: __init__
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addBond [as 别名]
#.........这里部分代码省略.........
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]))
if len(connectBonds) > 0:
# Only add bonds that don't already exist.
existingBonds = set(top.bonds())
for bond in connectBonds:
if bond not in existingBonds and (bond[1], bond[0]) not in existingBonds:
top.addBond(bond[0], bond[1])
existingBonds.add(bond)
示例10: addExtraParticles
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addBond [as 别名]
#.........这里部分代码省略.........
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.
matchingAtoms = {}
for atom, match in zip(residueNoEP.atoms(), matches):
templateAtomName = t.atoms[match].name
for templateAtom in template.atoms:
if templateAtom.name == templateAtomName:
matchingAtoms[templateAtom] = atom
break
if template is None:
raise ValueError('Residue %d (%s) does not match any template defined by the ForceField.' % (residue.index+1, residue.name))
# Add the regular atoms.
for atom in residue.atoms():
if atom.element is not None:
newAtoms[atom] = newTopology.addAtom(atom.name, atom.element, newResidue)
newPositions.append(deepcopy(self.positions[atom.index]))
# Add the extra points.
templateAtomPositions = len(template.atoms)*[None]
for index, atom in enumerate(template.atoms):
if atom in matchingAtoms:
templateAtomPositions[index] = self.positions[matchingAtoms[atom].index].value_in_unit(nanometer)
for index, atom in enumerate(template.atoms):
if atom.element is None:
newTopology.addAtom(atom.name, None, newResidue)
position = None
for site in template.virtualSites:
if site.index == index:
# This is a virtual site. Compute its position by the correct rule.
if site.type == 'average2':
position = site.weights[0]*templateAtomPositions[index+site.atoms[0]] + site.weights[1]*templateAtomPositions[index+site.atoms[1]]
elif site.type == 'average3':
position = site.weights[0]*templateAtomPositions[index+site.atoms[0]] + site.weights[1]*templateAtomPositions[index+site.atoms[1]] + site.weights[2]*templateAtomPositions[index+site.atoms[2]]
elif site.type == 'outOfPlane':
v1 = templateAtomPositions[index+site.atoms[1]] - templateAtomPositions[index+site.atoms[0]]
v2 = templateAtomPositions[index+site.atoms[2]] - templateAtomPositions[index+site.atoms[0]]
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])
position = templateAtomPositions[index+site.atoms[0]] + site.weights[0]*v1 + site.weights[1]*v2 + site.weights[2]*cross
if position is None and atom.type in drudeTypeMap:
# This is a Drude particle. Put it on top of its parent atom.
for atom2, pos in zip(template.atoms, templateAtomPositions):
if atom2.type in drudeTypeMap[atom.type]:
position = deepcopy(pos)
if position is None:
# We couldn't figure out the correct position. As a wild guess, just put it at the center of the residue
# and hope that energy minimization will fix it.
knownPositions = [x for x in templateAtomPositions if x is not None]
position = sum(knownPositions)/len(knownPositions)
newPositions.append(position*nanometer)
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
示例11: addHydrogens
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addBond [as 别名]
#.........这里部分代码省略.........
acceptorPos = self.positions[acceptor.index]
if isHbond(nd1Pos, hd1Pos, acceptorPos):
nd1IsBonded = True
break
if isHbond(ne2Pos, he2Pos, acceptorPos):
ne2IsBonded = True
if ne2IsBonded and not nd1IsBonded:
variant = 'HIE'
else:
variant = 'HID'
elif residue.name == 'HIS':
variant = 'HIP'
if variant is not None and variant not in spec.variants:
raise ValueError('Illegal variant for %s residue: %s' % (residue.name, variant))
actualVariants[residue.index] = variant
# Make a list of hydrogens that should be present in the residue.
parents = [atom for atom in residue.atoms() if atom.element != elem.hydrogen]
parentNames = [atom.name for atom in parents]
hydrogens = [h for h in spec.hydrogens if (variant is None and pH <= h.maxph) or (h.variants is None and pH <= h.maxph) or (h.variants is not None and variant in h.variants)]
hydrogens = [h for h in hydrogens if h.terminal is None or (isNTerminal and h.terminal == 'N') or (isCTerminal and h.terminal == 'C')]
hydrogens = [h for h in hydrogens if h.parent in parentNames]
# Loop over atoms in the residue, adding them to the new topology along with required hydrogens.
for parent in residue.atoms():
# Add the atom.
newAtom = newTopology.addAtom(parent.name, parent.element, newResidue)
newAtoms[parent] = newAtom
newPositions.append(deepcopy(self.positions[parent.index]))
if parent in parents:
# Match expected hydrogens with existing ones and find which ones need to be added.
existing = [atom for atom in bonded[parent] if atom.element == elem.hydrogen]
expected = [h for h in hydrogens if h.parent == parent.name]
if len(existing) < len(expected):
# Try to match up existing hydrogens to expected ones.
matches = []
for e in existing:
match = [h for h in expected if h.name == e.name]
if len(match) > 0:
matches.append(match[0])
expected.remove(match[0])
else:
matches.append(None)
# If any hydrogens couldn't be matched by name, just match them arbitrarily.
for i in range(len(matches)):
if matches[i] is None:
matches[i] = expected[-1]
expected.remove(expected[-1])
# Add the missing hydrogens.
for h in expected:
newH = newTopology.addAtom(h.name, elem.hydrogen, newResidue)
newIndices.append(newH.index)
delta = Vec3(0, 0, 0)*nanometer
if len(bonded[parent]) > 0:
for other in bonded[parent]:
delta += self.positions[parent.index]-self.positions[other.index]
else:
delta = Vec3(random.random(), random.random(), random.random())*nanometer
delta *= 0.1*nanometer/norm(delta)
delta += 0.05*Vec3(random.random(), random.random(), random.random())*nanometer
delta *= 0.1*nanometer/norm(delta)
newPositions.append(self.positions[parent.index]+delta)
newTopology.addBond(newAtom, newH)
else:
# Just copy over the residue.
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]])
# The hydrogens were added at random positions. Now use the ForceField to fix them up.
system = forcefield.createSystem(newTopology, rigidWater=False)
atoms = list(newTopology.atoms())
for i in range(system.getNumParticles()):
if atoms[i].element != elem.hydrogen:
# This is a heavy atom, so make it immobile.
system.setParticleMass(i, 0)
if platform is None:
context = Context(system, VerletIntegrator(0.0))
else:
context = Context(system, VerletIntegrator(0.0), platform)
context.setPositions(newPositions)
LocalEnergyMinimizer.minimize(context)
self.topology = newTopology
self.positions = context.getState(getPositions=True).getPositions()
return actualVariants
示例12: addSolvent
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addBond [as 别名]
#.........这里部分代码省略.........
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)
newAtoms[atom] = newAtom
newPositions.append(deepcopy(self.positions[atom.index]))
for bond in self.topology.bonds():
newTopology.addBond(newAtoms[bond[0]], newAtoms[bond[1]])
# Sort the solute atoms into cells for fast lookup.
if len(self.positions) == 0:
positions = []
else:
positions = self.positions.value_in_unit(nanometer)
cells = {}
numCells = tuple((max(1, int(floor(box[i]/maxCutoff))) for i in range(3)))
cellSize = tuple((box[i]/numCells[i] for i in range(3)))
for i in range(len(positions)):
cell = tuple((int(floor(positions[i][j]/cellSize[j]))%numCells[j] for j in range(3)))
if cell in cells:
cells[cell].append(i)
else:
cells[cell] = [i]
# Create a generator that loops over atoms close to a position.
def neighbors(pos):
centralCell = tuple((int(floor(pos[i]/cellSize[i])) for i in range(3)))
offsets = (-1, 0, 1)
for i in offsets:
for j in offsets:
for k in offsets:
cell = ((centralCell[0]+i+numCells[0])%numCells[0], (centralCell[1]+j+numCells[1])%numCells[1], (centralCell[2]+k+numCells[2])%numCells[2])
if cell in cells:
for atom in cells[cell]:
yield atom
# Define a function to compute the distance between two points, taking periodic boundary conditions into account.
示例13: convertWater
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addBond [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 addBond [as 别名]
#.........这里部分代码省略.........
@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:
last_residue = resnum
resname = atm.residue.resname
res = self._topology.addResidue(resname, chain)
elem = element.get_by_symbol(pt.Element[atm.element])
self._topology.addAtom(atm.atname, elem, res)
# Add bonds to the topology (both with and without hydrogen)
atoms = list(self._topology.atoms())
for bnd in self.bonds_inc_h + self.bonds_without_h:
self._topology.addBond(atoms[bnd.atom1.starting_index],
atoms[bnd.atom2.starting_index])
# Set the box dimensions
if self.ptr('ifbox'):
if hasattr(self, 'rst7'):
self._topology.setUnitCellDimensions(
self.rst7.box[:3]*u.angstrom
)
else:
self._topology.setUnitCellDimensions(
self.parm_data['BOX_DIMENSIONS'][1:4]*u.angstrom
)
return self._topology
def _get_gb_params(self, gb_model=HCT):
""" Gets the GB parameters. Need this method to special-case GB neck """
if gb_model is GBn:
screen = [0.5 for atom in self.atom_list]
for i, atom in enumerate(self.atom_list):
if atom.element == 6:
screen[i] = 0.48435382330
elif atom.element == 1:
screen[i] = 1.09085413633
elif atom.element == 7:
screen[i] = 0.700147318409
elif atom.element == 8:
screen[i] = 1.06557401132
elif atom.element == 16:
screen[i] = 0.602256336067
elif gb_model is GBn2:
# Add non-optimized values as defaults
示例15: __init__
# 需要导入模块: from simtk.openmm.app import Topology [as 别名]
# 或者: from simtk.openmm.app.Topology import addBond [as 别名]
#.........这里部分代码省略.........
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)
self._numpyPositions = None
# Add bonds based on CONECT records. Bonds between metals of elements specified in metalElements and residues in standardResidues are not added.
connectBonds = []
for connect in pdb.models[-1].connects:
i = connect[0]
for j in connect[1:]:
if i in atomByNumber and j in atomByNumber:
if atomByNumber[i].element is not None and atomByNumber[j].element is not None:
if atomByNumber[i].element.symbol not in metalElements and atomByNumber[j].element.symbol not in metalElements:
connectBonds.append((atomByNumber[i], atomByNumber[j]))
elif atomByNumber[i].element.symbol in metalElements and atomByNumber[j].residue.name not in PDBFile._standardResidues:
connectBonds.append((atomByNumber[i], atomByNumber[j]))
elif atomByNumber[j].element.symbol in metalElements and atomByNumber[i].residue.name not in PDBFile._standardResidues:
connectBonds.append((atomByNumber[i], atomByNumber[j]))
else:
connectBonds.append((atomByNumber[i], atomByNumber[j]))
if len(connectBonds) > 0:
# Only add bonds that don't already exist.
existingBonds = set(top.bonds())
for bond in connectBonds:
if bond not in existingBonds and (bond[1], bond[0]) not in existingBonds:
top.addBond(bond[0], bond[1])
existingBonds.add(bond)