本文整理汇总了Python中mdtraj.core.topology.Topology.add_residue方法的典型用法代码示例。如果您正苦于以下问题:Python Topology.add_residue方法的具体用法?Python Topology.add_residue怎么用?Python Topology.add_residue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mdtraj.core.topology.Topology
的用法示例。
在下文中一共展示了Topology.add_residue方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_water_topology_on_disc
# 需要导入模块: from mdtraj.core.topology import Topology [as 别名]
# 或者: from mdtraj.core.topology.Topology import add_residue [as 别名]
def create_water_topology_on_disc(n):
topfile = tempfile.mktemp('.pdb')
top = Topology()
chain = top.add_chain()
for i in xrange(n):
res = top.add_residue('r%i' % i, chain)
h1 = top.add_atom('H', hydrogen, res)
o = top.add_atom('O', oxygen, res)
h2 = top.add_atom('H', hydrogen, res)
top.add_bond(h1, o)
top.add_bond(h2, o)
xyz = np.zeros((n * 3, 3))
Trajectory(xyz, top).save_pdb(topfile)
return topfile
示例2: topology
# 需要导入模块: from mdtraj.core.topology import Topology [as 别名]
# 或者: from mdtraj.core.topology.Topology import add_residue [as 别名]
def topology(self):
"""Get the topology out from the file
Returns
-------
topology : mdtraj.Topology
A topology object
"""
try:
raw = self._get_node('/', name='topology')[0]
if not isinstance(raw, string_types):
raw = raw.decode()
topology_dict = json.loads(raw)
except self.tables.NoSuchNodeError:
return None
topology = Topology()
for chain_dict in sorted(topology_dict['chains'], key=operator.itemgetter('index')):
chain = topology.add_chain()
for residue_dict in sorted(chain_dict['residues'], key=operator.itemgetter('index')):
try:
resSeq = residue_dict["resSeq"]
except KeyError:
resSeq = None
warnings.warn('No resSeq information found in HDF file, defaulting to zero-based indices')
try:
segment_id = residue_dict["segmentID"]
except KeyError:
segment_id = ""
residue = topology.add_residue(residue_dict['name'], chain, resSeq=resSeq, segment_id=segment_id)
for atom_dict in sorted(residue_dict['atoms'], key=operator.itemgetter('index')):
try:
element = elem.get_by_symbol(atom_dict['element'])
except KeyError:
element = elem.virtual
topology.add_atom(atom_dict['name'], element, residue)
atoms = list(topology.atoms)
for index1, index2 in topology_dict['bonds']:
topology.add_bond(atoms[index1], atoms[index2])
return topology
示例3: topology
# 需要导入模块: from mdtraj.core.topology import Topology [as 别名]
# 或者: from mdtraj.core.topology.Topology import add_residue [as 别名]
def topology(self):
"""Get the topology out from the file
Returns
-------
topology : mdtraj.Topology
A topology object
"""
try:
raw = self._get_node("/", name="topology")[0]
if not isinstance(raw, string_types):
raw = raw.decode()
topology_dict = json.loads(raw)
except self.tables.NoSuchNodeError:
return None
topology = Topology()
for chain_dict in sorted(topology_dict["chains"], key=operator.itemgetter("index")):
chain = topology.add_chain()
for residue_dict in sorted(chain_dict["residues"], key=operator.itemgetter("index")):
try:
resSeq = residue_dict["resSeq"]
except KeyError:
resSeq = None
warnings.warn("No resSeq information found in HDF file, defaulting to zero-based indices")
residue = topology.add_residue(residue_dict["name"], chain, resSeq=resSeq)
for atom_dict in sorted(residue_dict["atoms"], key=operator.itemgetter("index")):
try:
element = elem.get_by_symbol(atom_dict["element"])
except KeyError:
element = None
topology.add_atom(atom_dict["name"], element, residue)
atoms = list(topology.atoms)
for index1, index2 in topology_dict["bonds"]:
topology.add_bond(atoms[index1], atoms[index2])
return topology
示例4: mutate
# 需要导入模块: from mdtraj.core.topology import Topology [as 别名]
# 或者: from mdtraj.core.topology.Topology import add_residue [as 别名]
def mutate(self, mut_res_idx, mut_new_resname):
"""Mutate residue
Parameters
----------
mut_res_idx : int
Index of residue to mutate.
mut_new_resname : str
Three-letter code of residue to mutate to.
"""
assert (self.topology.residue(mut_res_idx).name != mut_new_resname), "mutating the residue to itself!"
# Build new topology
newTopology = Topology()
for chain in self.topology.chains:
newChain = newTopology.add_chain()
for residue in chain._residues:
res_idx = residue.index
if res_idx == mut_res_idx:
# create mutated residue
self._add_mutated_residue(mut_new_resname, newTopology, newChain, res_idx, residue)
else:
# copy old residue atoms directly
newResidue = newTopology.add_residue(residue.name, newChain, res_idx)
for atom in residue.atoms:
newTopology.add_atom(atom.name,
md.core.element.get_by_symbol(atom.element.symbol),
newResidue, serial=atom.index)
# The bond connectivity should stay identical
for atm1, atm2 in self.topology._bonds:
new_atm1 = newTopology.atom(atm1.index)
new_atm2 = newTopology.atom(atm2.index)
newTopology.add_bond(new_atm1, new_atm2)
self._prev_topology = self.topology.copy()
self.topology = newTopology
示例5: PDBTrajectoryFile
# 需要导入模块: from mdtraj.core.topology import Topology [as 别名]
# 或者: from mdtraj.core.topology.Topology import add_residue [as 别名]
#.........这里部分代码省略.........
@property
def unitcell_angles(self):
"The unitcell angles (3-tuple) in this PDB file. May be None"
return self._unitcell_angles
@property
def closed(self):
"Whether the file is closed"
return not self._open
def close(self):
"Close the PDB file"
if self._mode == 'w' and not self._footer_written:
self._write_footer()
if self._open:
self._file.close()
self._open = False
def _read_models(self):
if not self._mode == 'r':
raise ValueError('file not opened for reading')
self._topology = Topology()
pdb = PdbStructure(self._file, load_all_models=True)
atomByNumber = {}
for chain in pdb.iter_chains():
c = self._topology.add_chain()
for residue in chain.iter_residues():
resName = residue.get_name()
if resName in PDBTrajectoryFile._residueNameReplacements:
resName = PDBTrajectoryFile._residueNameReplacements[resName]
r = self._topology.add_residue(resName, c, residue.number)
if resName in PDBTrajectoryFile._atomNameReplacements:
atomReplacements = PDBTrajectoryFile._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:
element = self._guess_element(atomName, residue)
newAtom = self._topology.add_atom(atomName, element, r, serial=atom.serial_number)
atomByNumber[atom.serial_number] = newAtom
# load all of the positions (from every model)
_positions = []
for model in pdb.iter_models(use_all_models=True):
coords = []
for chain in model.iter_chains():
for residue in chain.iter_residues():
for atom in residue.atoms:
coords.append(atom.get_position())
_positions.append(coords)
if not all(len(f) == len(_positions[0]) for f in _positions):
raise ValueError('PDB Error: All MODELs must contain the same number of ATOMs')
self._positions = np.array(_positions)
## The atom positions read from the PDB file
示例6: _to_topology
# 需要导入模块: from mdtraj.core.topology import Topology [as 别名]
# 或者: from mdtraj.core.topology.Topology import add_residue [as 别名]
def _to_topology(self, atom_list, chain_types=None, residue_types=None):
"""Create a mdtraj.Topology from a Compound.
Parameters
----------
atom_list :
chain_types :
residue_types :
Returns
-------
top : mtraj.Topology
"""
if isinstance(chain_types, Compound):
chain_types = [Compound]
if isinstance(chain_types, (list, set)):
chain_types = tuple(chain_types)
if isinstance(residue_types, Compound):
residue_types = [Compound]
if isinstance(residue_types, (list, set)):
residue_types = tuple(residue_types)
top = Topology()
atom_mapping = {}
default_chain = top.add_chain()
default_residue = top.add_residue('RES', default_chain)
last_residue_compound = None
last_chain_compound = None
last_residue = None
last_chain = None
for atom in atom_list:
# Chains
for parent in atom.ancestors():
if chain_types and isinstance(parent, chain_types):
if parent != last_chain_compound:
last_chain_compound = parent
last_chain = top.add_chain()
last_chain_default_residue = top.add_residue('RES', last_chain)
last_chain.compound = last_chain_compound
break
else:
last_chain = default_chain
last_chain.compound = last_chain_compound
# Residues
for parent in atom.ancestors():
if residue_types and isinstance(parent, residue_types):
if parent != last_residue_compound:
last_residue_compound = parent
last_residue = top.add_residue(parent.__class__.__name__, last_chain)
last_residue.compound = last_residue_compound
break
else:
if last_chain != default_chain:
last_residue = last_chain_default_residue
else:
last_residue = default_residue
last_residue.compound = last_residue_compound
# Add the actual atoms
try:
elem = get_by_symbol(atom.name)
except KeyError:
elem = get_by_symbol("VS")
at = top.add_atom(atom.name, elem, last_residue)
at.charge = atom.charge
atom_mapping[atom] = at
# Remove empty default residues.
chains_to_remove = [chain for chain in top.chains if chain.n_atoms == 0]
residues_to_remove = [res for res in top.residues if res.n_atoms == 0]
for chain in chains_to_remove:
top._chains.remove(chain)
for res in residues_to_remove:
for chain in top.chains:
try:
chain._residues.remove(res)
except ValueError: # Already gone.
pass
for atom1, atom2 in self.bonds():
# Ensure that both atoms are part of the compound. This becomes an
# issue if you try to convert a sub-compound to a topology which is
# bonded to a different subcompound.
if all(a in atom_mapping.keys() for a in [atom1, atom2]):
top.add_bond(atom_mapping[atom1], atom_mapping[atom2])
return top
示例7: load_hoomdxml
# 需要导入模块: from mdtraj.core.topology import Topology [as 别名]
# 或者: from mdtraj.core.topology.Topology import add_residue [as 别名]
def load_hoomdxml(filename, top=None):
"""Load a single conformation from an HOOMD-Blue XML file.
For more information on this file format, see:
http://codeblue.umich.edu/hoomd-blue/doc/page_xml_file_format.html
Notably, all node names and attributes are in all lower case.
HOOMD-Blue does not contain residue and chain information explicitly.
For this reason, chains will be found by looping over all the bonds and
finding what is bonded to what.
Each chain consisists of exactly one residue.
Parameters
----------
filename : string
The path on disk to the XML file
Returns
-------
trajectory : md.Trajectory
The resulting trajectory, as an md.Trajectory object, with corresponding
Topology.
Notes
-----
This function requires the NetworkX python package.
"""
from mdtraj.core.trajectory import Trajectory
from mdtraj.core.topology import Topology
topology = Topology()
tree = cElementTree.parse(filename)
config = tree.getroot().find('configuration')
position = config.find('position')
bond = config.find('bond')
atom_type = config.find('type') # MDTraj calls this "name"
box = config.find('box')
box.attrib = dict((key.lower(), val) for key, val in box.attrib.items())
# be generous for case of box attributes
lx = float(box.attrib['lx'])
ly = float(box.attrib['ly'])
lz = float(box.attrib['lz'])
try:
xy = float(box.attrib['xy'])
xz = float(box.attrib['xz'])
yz = float(box.attrib['yz'])
except:
xy = 0.0
xz = 0.0
yz = 0.0
unitcell_vectors = np.array([[[lx, xy*ly, xz*lz],
[0.0, ly, yz*lz],
[0.0, 0.0, lz ]]])
positions, types = [], {}
for pos in position.text.splitlines()[1:]:
positions.append((float(pos.split()[0]),
float(pos.split()[1]),
float(pos.split()[2])))
for idx, atom_name in enumerate(atom_type.text.splitlines()[1:]):
types[idx] = str(atom_name.split()[0])
if len(types) != len(positions):
raise ValueError('Different number of types and positions in xml file')
# ignore the bond type
bonds = [(int(b.split()[1]), int(b.split()[2])) for b in bond.text.splitlines()[1:]]
chains = _find_chains(bonds)
ions = [i for i in range(len(types)) if not _in_chain(chains, i)]
# add chains, bonds and ions (each chain = 1 residue)
for chain in chains:
t_chain = topology.add_chain()
t_residue = topology.add_residue('A', t_chain)
for atom in chain:
topology.add_atom(types[atom], 'U', t_residue)
for ion in ions:
t_chain = topology.add_chain()
t_residue = topology.add_residue('A', t_chain)
topology.add_atom(types[atom], 'U', t_residue)
for bond in bonds:
atom1, atom2 = bond[0], bond[1]
topology.add_bond(topology.atom(atom1), topology.atom(atom2))
traj = Trajectory(xyz=np.array(positions), topology=topology)
traj.unitcell_vectors = unitcell_vectors
return traj
示例8: __init__
# 需要导入模块: from mdtraj.core.topology import Topology [as 别名]
# 或者: from mdtraj.core.topology.Topology import add_residue [as 别名]
def __init__(self, topology, use_chains=None):
if use_chains is None:
use_chains = range(len(topology._chains))
self._ref_topology = topology.copy()
# Build new topology
newTopology = Topology()
new_atm_idx = 0
res_idx = 1
prev_ca = None
ca_idxs = []
self._sidechain_idxs = []
self._sidechain_mass = []
self._chain_indices = []
for chain_count, chain in enumerate(topology._chains):
if chain_count in use_chains:
newChain = newTopology.add_chain()
for residue in chain._residues:
#resSeq = getattr(residue, 'resSeq', None) or residue.index
newResidue = newTopology.add_residue(residue.name, newChain, res_idx)
# map CA
new_ca = newTopology.add_atom('CA', md.core.element.get_by_symbol('C'),
newResidue, serial=new_atm_idx)
self._chain_indices.append(chain_count)
if prev_ca is None:
prev_ca = new_ca
else:
# only bond atoms in the same chain.
if new_ca.residue.chain.index == prev_ca.residue.chain.index:
newTopology.add_bond(prev_ca, new_ca)
prev_ca = new_ca
try:
ca_idxs.append([[ atm.index for atm in residue.atoms if \
(atm.name == "CA") ][0], new_atm_idx ])
except:
print(residue)
print(chain)
for atm in residue.atoms:
atm.name
raise
new_atm_idx += 1
if residue.name == 'GLY':
self._sidechain_idxs.append([])
self._sidechain_mass.append([])
else:
# map CB
cb_name = "CB%s" % atom_types.residue_code[residue.name]
new_cb = newTopology.add_atom(cb_name, md.core.element.get_by_symbol('C'),
newResidue, serial=new_atm_idx)
self._chain_indices.append(chain_count)
newTopology.add_bond(new_cb, new_ca)
self._sidechain_idxs.append([[ atm.index for atm in residue.atoms if \
(atm.is_sidechain) and (atm.element.symbol != "H") ], new_atm_idx ])
self._sidechain_mass.append(np.array([ atm.element.mass for atm in residue.atoms if \
(atm.is_sidechain) and (atm.element.symbol != "H") ]))
new_atm_idx += 1
res_idx += 1
self._ca_idxs = np.array(ca_idxs)
self.topology = newTopology
assert self.topology.n_atoms == len(self._chain_indices)