本文整理汇总了Python中mdtraj.core.element.get_by_symbol函数的典型用法代码示例。如果您正苦于以下问题:Python get_by_symbol函数的具体用法?Python get_by_symbol怎么用?Python get_by_symbol使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_by_symbol函数的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: from_openmm
def from_openmm(cls, value):
"""Create a mdtraj topology from an OpenMM topology
Parameters
----------
value : simtk.openmm.app.Topology
An OpenMM topology that you wish to convert to a
mdtraj topology.
"""
app = import_('simtk.openmm.app')
if not isinstance(value, app.Topology):
raise TypeError('value must be an OpenMM Topology. '
'You supplied a %s' % type(value))
out = cls()
atom_mapping = {}
for chain in value.chains():
c = out.add_chain()
for residue in chain.residues():
r = out.add_residue(residue.name, c)
for atom in residue.atoms():
if atom.element is None:
element = elem.virtual
else:
element = elem.get_by_symbol(atom.element.symbol)
a = out.add_atom(atom.name, element, r)
atom_mapping[atom] = a
for a1, a2 in value.bonds():
out.add_bond(atom_mapping[a1], atom_mapping[a2])
return out
开发者ID:cing,项目名称:mdtraj,代码行数:34,代码来源:topology.py
示例2: _guess_element
def _guess_element(self, atom_name, residue):
"Try to guess the element name"
upper = atom_name.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
# TJL has edited this. There are a few issues here. First,
# parsing for the element is non-trivial, so I do my best
# below. Second, there is additional parsing code in
# pdbstructure.py, and I am unsure why it doesn't get used
# here...
elif len(residue) > 1 and upper.startswith('CE'):
element = elem.carbon # (probably) not Celenium...
elif len(residue) > 1 and upper.startswith('CD'):
element = elem.carbon # (probably) not Cadmium...
elif residue.name in ['TRP', 'ARG', 'GLN', 'HIS'] and upper.startswith('NE'):
element = elem.nitrogen # (probably) not Neon...
elif residue.name in ['ASN'] and upper.startswith('ND'):
element = elem.nitrogen # (probably) not ND...
elif residue.name == 'CYS' and upper.startswith('SG'):
element = elem.sulfur # (probably) not SG...
else:
try:
element = elem.get_by_symbol(atom_name[0])
except KeyError:
try:
symbol = atom_name[0:2].strip().rstrip("AB0123456789").lstrip("0123456789")
element = elem.get_by_symbol(symbol)
except KeyError:
element = None
return element
开发者ID:ChayaSt,项目名称:mdtraj,代码行数:47,代码来源:pdbfile.py
示例3: butane_toy_model
def butane_toy_model():
# Starting configuration is close to a cis conformation
phi0 = np.pi
phi_ini = 2*np.pi*0.8
xyz = np.zeros((1, 4, 3), float)
xyz[:,0,:] = np.array([1, -1, 0])
xyz[:,1,:] = np.array([0, -1, 0])
xyz[:,2,:] = np.array([0, 0, 0])
xyz[:,3,0] = np.cos(phi_ini)
xyz[:,3,2] = np.sin(phi_ini)
# Coordinates must be positive in gromacs
shift = np.array([5,5,5])
xyz += shift
# Create a mdtraj Topology for our butane molecule.
newtop = md.Topology()
chain = newtop.add_chain()
for i in range(4):
res = newtop.add_residue("GLY", chain, i)
new_ca = newtop.add_atom('CA', get_by_symbol('C'), res, serial=i)
#if i >= 1:
# prev_ca = chain.atom(i - 1)
# newtop.add_bond(prev_ca, new_ca)
model = mdb.models.Model(newtop, bead_repr="CA")
model.mapping.add_atoms(mass=10)
top = model.mapping.top
# Add bond interactions
model.Hamiltonian._add_bond("HARMONIC_BOND", top.atom(0), top.atom(1), 100, 1)
model.Hamiltonian._add_bond("HARMONIC_BOND", top.atom(1), top.atom(2), 100, 1)
model.Hamiltonian._add_bond("HARMONIC_BOND", top.atom(2), top.atom(3), 100, 1)
# Add angle interactions
model.Hamiltonian._add_angle("HARMONIC_ANGLE", top.atom(0), top.atom(1),
top.atom(2), 20, np.pi/2)
model.Hamiltonian._add_angle("HARMONIC_ANGLE", top.atom(1), top.atom(2),
top.atom(3), 20, np.pi/2)
# Add dihedral interaction
model.Hamiltonian._add_dihedral("COSINE_DIHEDRAL", top.atom(0), top.atom(1),
top.atom(2), top.atom(3), 0.1, phi0, 1)
return xyz, top, model
开发者ID:ajkluber,项目名称:model_builder,代码行数:48,代码来源:run_butane.py
示例4: _read_topology
def _read_topology(self):
if not self._open:
raise ValueError('I/O operation on closed file')
if not self._mode == 'r':
raise ValueError('file not opened for reading')
pdb.PDBTrajectoryFile._loadNameReplacementTables()
n_atoms = None
topology = md.Topology()
chain = topology.add_chain()
residue = None
atomReplacements = {}
for ln, line in enumerate(self._file):
if ln == 1:
n_atoms = int(line.strip())
elif ln > 1 and ln < n_atoms + 2:
(thisresnum, thisresname, thisatomname, thisatomnum) = \
[line[i*5:i*5+5].strip() for i in range(4)]
thisresnum, thisatomnum = map(int, (thisresnum, thisatomnum))
if residue is None or residue.resSeq != thisresnum:
if thisresname in pdb.PDBTrajectoryFile._residueNameReplacements:
thisresname = pdb.PDBTrajectoryFile._residueNameReplacements[thisresname]
residue = topology.add_residue(thisresname, chain, resSeq=thisresnum)
if thisresname in pdb.PDBTrajectoryFile._atomNameReplacements:
atomReplacements = pdb.PDBTrajectoryFile._atomNameReplacements[thisresname]
else:
atomReplacements = {}
thiselem = thisatomname
element = None
if len(thiselem) > 1:
thiselem = thiselem[0] + sub('[A-Z0-9]','',thiselem[1:])
try:
element = elem.get_by_symbol(thiselem)
except KeyError:
pass
if thisatomname in atomReplacements:
thisatomname = atomReplacements[thisatomname]
topology.add_atom(thisatomname, element=element, residue=residue,
serial=thisatomnum)
return n_atoms, topology
开发者ID:xuw10,项目名称:mdtraj,代码行数:44,代码来源:gro.py
示例5: topology
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
开发者ID:anyuzx,项目名称:mdtraj,代码行数:43,代码来源:hdf5.py
示例6: topology
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
开发者ID:khinsen,项目名称:mdtraj,代码行数:39,代码来源:hdf5.py
示例7: _topology_from_arrays
def _topology_from_arrays(AtomID, AtomNames, ChainID, ResidueID, ResidueNames):
"""Build topology object from the arrays stored in the lh5 file"""
# Delayed import due to wacky recursive imports in compatibilty
from mdtraj import Topology
topology = Topology()
# assert that the ChainID is just an array of empty strings, which appears
# to be the case in our test systems for this legacy format
if not np.all(chainid == '' for chainid in ChainID):
raise NotImplementedError('Im not prepared to parse multiple chains')
chain0 = topology.add_chain()
# register the residues
registered_residues = {}
for i in np.argsort(ResidueID):
residue_name = ResidueNames[i]
if not isinstance(residue_name, basestring):
residue_name = residue_name.decode()
if ResidueID[i] not in registered_residues:
res = topology.add_residue(residue_name, chain0)
registered_residues[ResidueID[i]] = res
# register the atoms
for i in np.argsort(AtomID):
atom_name = AtomNames[i]
if not isinstance(atom_name, basestring):
atom_name = atom_name.decode()
element_symbol = atom_name.lstrip('0123456789')[0]
try:
element = elem.get_by_symbol(element_symbol)
except KeyError:
element = elem.virtual
topology.add_atom(atom_name, element,
registered_residues[ResidueID[i]])
topology.create_standard_bonds()
return topology
开发者ID:schilli,项目名称:mdtraj,代码行数:39,代码来源:lh5.py
示例8: from_dataframe
def from_dataframe(cls, atoms, bonds=None):
"""Create a mdtraj topology from a pandas data frame
Parameters
----------
atoms : pandas.DataFrame
The atoms in the topology, represented as a data frame. This data
frame should have columns "serial" (atom index), "name" (atom name),
"element" (atom's element), "resSeq" (index of the residue)
"resName" (name of the residue), "chainID" (index of the chain),
and optionally "segmentID", following the same conventions
as wwPDB 3.0 format.
bonds : np.ndarray, shape=(n_bonds, 2), dtype=int, optional
The bonds in the topology, represented as an n_bonds x 2 array
of the indices of the atoms involved in each bond. Specifiying
bonds here is optional. To create standard protein bonds, you can
use `create_standard_bonds` to "fill in" the bonds on your newly
created Topology object
See Also
--------
create_standard_bonds
"""
pd = import_('pandas')
if bonds is None:
bonds = np.zeros((0, 2))
for col in ["name", "element", "resSeq",
"resName", "chainID", "serial"]:
if col not in atoms.columns:
raise ValueError('dataframe must have column %s' % col)
if "segmentID" not in atoms.columns:
atoms["segmentID"] = ""
out = cls()
if not isinstance(atoms, pd.DataFrame):
raise TypeError('atoms must be an instance of pandas.DataFrame. '
'You supplied a %s' % type(atoms))
if not isinstance(bonds, np.ndarray):
raise TypeError('bonds must be an instance of numpy.ndarray. '
'You supplied a %s' % type(bonds))
if not np.all(np.arange(len(atoms)) == atoms.index):
raise ValueError('atoms must be uniquely numbered '
'starting from zero.')
out._atoms = [None for i in range(len(atoms))]
for ci in np.unique(atoms['chainID']):
chain_atoms = atoms[atoms['chainID'] == ci]
c = out.add_chain()
for ri in np.unique(chain_atoms['resSeq']):
residue_atoms = chain_atoms[chain_atoms['resSeq'] == ri]
rnames = residue_atoms['resName']
residue_name = np.array(rnames)[0]
segids = residue_atoms['segmentID']
segment_id = np.array(segids)[0]
if not np.all(rnames == residue_name):
raise ValueError('All of the atoms with residue index %d '
'do not share the same residue name' % ri)
r = out.add_residue(residue_name, c, ri,segment_id)
for atom_index, atom in residue_atoms.iterrows():
atom_index = int(atom_index) # Fixes bizarre hashing issue on Py3K. See #545
a = Atom(atom['name'], elem.get_by_symbol(atom['element']),
atom_index, r, serial=atom['serial'])
out._atoms[atom_index] = a
r._atoms.append(a)
for ai1, ai2 in bonds:
out.add_bond(out.atom(ai1), out.atom(ai2))
out._numAtoms = out.n_atoms
return out
开发者ID:cing,项目名称:mdtraj,代码行数:76,代码来源:topology.py
示例9: _to_topology
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
开发者ID:oliviacane,项目名称:mbuild,代码行数:92,代码来源:compound.py
示例10: __init__
#.........这里部分代码省略.........
self.serial_number = int(pdb_line[6:11], 16)
else:
try:
self.serial_number = int(pdb_line[6:11])
except ValueError:
try:
self.serial_number = int(pdb_line[6:11], 16)
pdbstructure._atom_numbers_are_hex = True
except ValueError:
# Just give it the next number in sequence.
self.serial_number = pdbstructure._next_atom_number
self.name_with_spaces = pdb_line[12:16]
alternate_location_indicator = pdb_line[16]
self.residue_name_with_spaces = pdb_line[17:20]
# In some MD codes, notably ffamber in gromacs, residue name has a fourth character in
# column 21
possible_fourth_character = pdb_line[20:21]
if possible_fourth_character != " ":
# Fourth character should only be there if official 3 are already full
if len(self.residue_name_with_spaces.strip()) != 3:
raise ValueError('Misaligned residue name: %s' % pdb_line)
self.residue_name_with_spaces += possible_fourth_character
self.residue_name = self.residue_name_with_spaces.strip()
self.chain_id = pdb_line[21]
if pdbstructure is not None and pdbstructure._residue_numbers_are_hex:
self.residue_number = int(pdb_line[22:26], 16)
else:
try:
self.residue_number = int(pdb_line[22:26])
except ValueError:
try:
self.residue_number = int(pdb_line[22:26], 16)
pdbstructure._residue_numbers_are_hex = True
except ValueError:
# When VMD runs out of hex values it starts filling in the residue ID field with ****
# Look at the most recent atoms to figure out whether this is a new residue or not.
if pdbstructure._current_model is None or pdbstructure._current_model._current_chain is None or pdbstructure._current_model._current_chain._current_residue is None:
# This is the first residue in the model.
self.residue_number = pdbstructure._next_residue_number
else:
currentRes = pdbstructure._current_model._current_chain._current_residue
if currentRes.name_with_spaces != self.residue_name_with_spaces:
# The residue name has changed.
self.residue_number = pdbstructure._next_residue_number
elif self.name_with_spaces in currentRes.atoms_by_name:
# There is already an atom with this name.
self.residue_number = pdbstructure._next_residue_number
else:
self.residue_number = currentRes.number
self.insertion_code = pdb_line[26]
# coordinates, occupancy, and temperature factor belong in Atom.Location object
x = float(pdb_line[30:38])
y = float(pdb_line[38:46])
z = float(pdb_line[46:54])
try:
occupancy = float(pdb_line[54:60])
except ValueError:
occupancy = 1.0
try:
temperature_factor = float(pdb_line[60:66])
except ValueError:
temperature_factor = 0.0
self.locations = {}
loc = Atom.Location(alternate_location_indicator, np.array([x,y,z]), occupancy, temperature_factor, self.residue_name_with_spaces)
self.locations[alternate_location_indicator] = loc
self.default_location_id = alternate_location_indicator
# segment id, element_symbol, and formal_charge are not always present
self.segment_id = pdb_line[72:76].strip()
self.element_symbol = pdb_line[76:78].strip()
try: self.formal_charge = int(pdb_line[78:80])
except ValueError: self.formal_charge = None
# figure out atom element
try:
# First try to find a sensible element symbol from columns 76-77
self.element = element.get_by_symbol(self.element_symbol)
except KeyError:
# otherwise, deduce element from first two characters of atom name
# remove digits found in some hydrogen atom names
symbol = self.name_with_spaces[0:2].strip().lstrip("0123456789")
try:
# Some molecular dynamics PDB files, such as gromacs with ffamber force
# field, include 4-character hydrogen atom names beginning with "H".
# Hopefully elements like holmium (Ho) and mercury (Hg) will have fewer than four
# characters in the atom name. This problem is the fault of molecular
# dynamics code authors who feel the need to make up their own atom
# nomenclature because it is too tedious to read that provided by the PDB.
# These are the same folks who invent their own meanings for biochemical terms
# like "dipeptide". Clowntards.
if len(self.name) == 4 and self.name[0:1] == "H":
self.element = element.hydrogen
else:
self.element = element.get_by_symbol(symbol)
except KeyError:
# OK, I give up
self.element = None
if pdbstructure is not None:
pdbstructure._next_atom_number = self.serial_number+1
pdbstructure._next_residue_number = self.residue_number+1
开发者ID:evanfeinberg,项目名称:mdtraj,代码行数:101,代码来源:pdbstructure.py
示例11: load_prmtop
#.........这里部分代码省略.........
elif line.startswith('%COMMENT'):
continue
elif not ignoring:
flag=flags[-1]
format, numItems, itemType, itemLength, itemPrecision = raw_format[flag]
iLength=int(itemLength)
line = line.rstrip()
for index in range(0, len(line), iLength):
item = line[index:index+iLength]
if item:
raw_data[flag].append(item.strip())
# Add atoms to the topology
pdb.PDBTrajectoryFile._loadNameReplacementTables()
previous_residue = None
c = top.add_chain()
n_atoms = int(_get_pointer_value('NATOM', raw_data))
# built a dictionary telling us which atom belongs to which residue
residue_pointer_dict = {}
res_pointers = raw_data['RESIDUE_POINTER']
first_atom = [int(p)-1 for p in res_pointers] # minus 1 necessary
first_atom.append(n_atoms)
res = 0
for i in range(n_atoms):
while first_atom[res+1] <= i:
res += 1
residue_pointer_dict[i] = res
# add each residue/atom to the topology object
for index in range(n_atoms):
res_number = residue_pointer_dict[index]
if res_number != previous_residue:
previous_residue = res_number
# check
res_name = raw_data['RESIDUE_LABEL'][residue_pointer_dict[index]].strip()
if res_name in pdb.PDBTrajectoryFile._residueNameReplacements:
res_name = pdb.PDBTrajectoryFile._residueNameReplacements[res_name]
r = top.add_residue(res_name, c)
if res_name in pdb.PDBTrajectoryFile._atomNameReplacements:
atom_replacements = pdb.PDBTrajectoryFile._atomNameReplacements[res_name]
else:
atom_replacements = {}
atom_name = raw_data['ATOM_NAME'][index].strip()
if atom_name in atom_replacements:
atom_name = atom_replacements[atom_name]
# Get the element from the prmtop file if available
if 'ATOMIC_NUMBER' in raw_data:
try:
element = elem.Element.getByAtomicNumber(int(raw_data['ATOMIC_NUMBER'][index]))
except KeyError:
element = elem.virtual
else:
# Try to guess the element from the atom name.
upper = atom_name.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('ZN'):
element = elem.zinc
else:
try:
element = elem.get_by_symbol(atom_name[0])
except KeyError:
element = elem.virtual
top.add_atom(atom_name, element, r)
# Add bonds to the topology
bond_pointers = raw_data["BONDS_INC_HYDROGEN"] + raw_data["BONDS_WITHOUT_HYDROGEN"]
atoms = list(top.atoms)
bond_list = []
for ii in range(0,len(bond_pointers),3):
if int(bond_pointers[ii])<0 or int(bond_pointers[ii+1])<0:
raise Exception("Found negative bonded atom pointers %s"
% ((bond_pointers[ii],
bond_pointers[ii+1]),))
else:
bond_list.append((int(bond_pointers[ii])//3, int(bond_pointers[ii+1])//3))
for bond in bond_list:
top.add_bond(atoms[bond[0]], atoms[bond[1]])
return top
开发者ID:OndrejMarsalek,项目名称:mdtraj,代码行数:101,代码来源:prmtop.py
注:本文中的mdtraj.core.element.get_by_symbol函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论