本文整理汇总了Python中simtk.openmm.app.Topology类的典型用法代码示例。如果您正苦于以下问题:Python Topology类的具体用法?Python Topology怎么用?Python Topology使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Topology类的18个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _createTopology
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
开发者ID:egallicc,项目名称:openmm_gaussvol_plugin,代码行数:54,代码来源:desmonddmsfile.py
示例2: generateTopologyFromOEMol
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
开发者ID:jchodera,项目名称:openmoltools,代码行数:34,代码来源:forcefield_generators.py
示例3: _createTopology
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
开发者ID:rmcgibbo,项目名称:charm22starvalidation,代码行数:43,代码来源:dmsfile.py
示例4: topology
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
开发者ID:jpthompson17,项目名称:ParmEd,代码行数:46,代码来源:openmmloader.py
示例5: delete
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
开发者ID:alex-virodov,项目名称:openmm,代码行数:43,代码来源:modeller.py
示例6: __init__
def __init__(self, file, unitCellDimensions=None, includeDir='/usr/local/gromacs/share/gromacs/top', defines={}):
"""Load a top file.
Parameters:
- file (string) the name of the file to load
- unitCellDimensions (Vec3=None) the dimensions of the crystallographic unit cell
- includeDir (string=/usr/local/gromacs/share/gromacs/top) a directory in which to look for other files
included from the top file
- defines (map={}) preprocessor definitions that should be predefined when parsing the file
"""
self._includeDirs = (os.path.dirname(file), includeDir)
self._defines = defines
# Parse the file.
self._currentCategory = None
self._ifStack = []
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
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]
# 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])
开发者ID:vvoelz,项目名称:openmm,代码行数:83,代码来源:gromacstopfile.py
示例7: __init__
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.
#.........这里部分代码省略.........
开发者ID:pgrinaway,项目名称:openmm,代码行数:101,代码来源:pdbxfile.py
示例8: unloadStandardBonds
# coding=utf-8
"""Pre-configured OpenMM Topology object for use with the default protons forcefield."""
from simtk.openmm.app import Topology
import os
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
# Patch topology to unload standard bond definitions
def unloadStandardBonds(cls):
"""
Resets _standardBonds and _hasLoadedStandardBonds to original state.
"""
cls._hasLoadedStandardBonds = False
cls._standardBonds = dict()
Topology.unloadStandardBonds = classmethod(unloadStandardBonds)
Topology.unloadStandardBonds()
Topology.loadBondDefinitions(
os.path.join(PACKAGE_ROOT, "data", "bonds-amber10-constph.xml")
)
开发者ID:choderalab,项目名称:constph-openmm,代码行数:24,代码来源:topology.py
示例9: __init__
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'):
#.........这里部分代码省略.........
开发者ID:bas-rustenburg,项目名称:openmm,代码行数:101,代码来源:gromacstopfile.py
示例10: __init__
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]))
#.........这里部分代码省略.........
开发者ID:Bhattiasif,项目名称:openmm,代码行数:101,代码来源:pdbfile.py
示例11: convertWater
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
开发者ID:alex-virodov,项目名称:openmm,代码行数:67,代码来源:modeller.py
示例12: OpenMMAmberParm
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:
#.........这里部分代码省略.........
开发者ID:jpthompson17,项目名称:ParmEd,代码行数:101,代码来源:openmmloader.py
示例13: add
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
开发者ID:alex-virodov,项目名称:openmm,代码行数:42,代码来源:modeller.py
示例14: addExtraParticles
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.
#.........这里部分代码省略.........
开发者ID:alex-virodov,项目名称:openmm,代码行数:101,代码来源:modeller.py
示例15: addHydrogens
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: Negativ
|
请发表评论