本文整理汇总了Python中mdtraj.utils.in_units_of函数的典型用法代码示例。如果您正苦于以下问题:Python in_units_of函数的具体用法?Python in_units_of怎么用?Python in_units_of使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了in_units_of函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: read_as_traj
def read_as_traj(self, n_frames=None, stride=None, atom_indices=None):
"""Read a trajectory from a gro file
Parameters
----------
n_frames : int, optional
If positive, then read only the next `n_frames` frames. Otherwise read all
of the frames in the file.
stride : np.ndarray, optional
Read only every stride-th frame.
atom_indices : array_like, optional
If not none, then read only a subset of the atoms coordinates from the
file. This may be slightly slower than the standard read because it required
an extra copy, but will save memory.
Returns
-------
trajectory : Trajectory
A trajectory object containing the loaded portion of the file.
"""
from mdtraj.core.trajectory import Trajectory
topology = self.topology
if atom_indices is not None:
topology = topology.subset(atom_indices)
coordinates, time, unitcell_vectors = self.read(stride=stride, atom_indices=atom_indices)
if len(coordinates) == 0:
return Trajectory(xyz=np.zeros((0, topology.n_atoms, 3)), topology=topology)
coordinates = in_units_of(coordinates, self.distance_unit, Trajectory._distance_unit, inplace=True)
unitcell_vectors = in_units_of(unitcell_vectors, self.distance_unit, Trajectory._distance_unit, inplace=True)
traj = Trajectory(xyz=coordinates, topology=topology, time=time)
traj.unitcell_vectors = unitcell_vectors
return traj
示例2: read_as_traj
def read_as_traj(self, topology, atom_indices=None):
"""Read an AMBER ASCII restart file as a trajectory.
Parameters
----------
topology : Topology
The system topology
atom_indices : array_like, optional
If not none, then read only a subset of the atoms coordinates from the
file. This may be slightly slower than the standard read because it required
an extra copy, but will save memory.
Returns
-------
trajectory : Trajectory
A trajectory object with 1 frame created from the file.
"""
from mdtraj.core.trajectory import Trajectory
if atom_indices is not None:
topology = topology.subset(atom_indices)
xyz, time, cell_lengths, cell_angles = self.read(atom_indices=atom_indices)
xyz = in_units_of(xyz, self.distance_unit, Trajectory._distance_unit,
inplace=True)
cell_lengths = in_units_of(cell_lengths, self.distance_unit,
Trajectory._distance_unit, inplace=True)
return Trajectory(xyz=xyz, topology=topology, time=time,
unitcell_lengths=cell_lengths,
unitcell_angles=cell_angles)
示例3: save_pdb
def save_pdb(self, filename, force_overwrite=True):
"""Save trajectory to RCSB PDB format
Parameters
----------
filename : str
filesystem path in which to save the trajectory
force_overwrite : bool, default=True
Overwrite anything that exists at filename, if its already there
"""
self._check_valid_unitcell()
with PDBTrajectoryFile(filename, 'w', force_overwrite=force_overwrite) as f:
for i in xrange(self.n_frames):
if self._have_unitcell:
f.write(in_units_of(self._xyz[i], Trajectory._distance_unit, f.distance_unit),
self.topology,
modelIndex=i,
unitcell_lengths=in_units_of(self.unitcell_lengths[i], Trajectory._distance_unit, f.distance_unit),
unitcell_angles=self.unitcell_angles[i])
else:
f.write(in_units_of(self._xyz[i], Trajectory._distance_unit, f.distance_unit),
self.topology,
modelIndex=i)
示例4: convert
def convert(data, in_units, out_units, out_fields):
# do unit conversion
if 'xyz' in out_fields and 'xyz' in data:
data['xyz'] = in_units_of(data['xyz'], in_units, out_units, inplace=True)
if 'box' in out_fields:
if 'box' in data:
data['box'] = in_units_of(data['box'], in_units, out_units, inplace=True)
elif 'cell_angles' in data and 'cell_lengths' in data:
a, b, c = data['cell_lengths'].T
alpha, beta, gamma = data['cell_angles'].T
data['box'] = np.dstack(md.utils.unitcell.lengths_and_angles_to_box_vectors(a, b, c, alpha, beta, gamma))
data['box'] = in_units_of(data['box'], in_units, out_units, inplace=True)
del data['cell_lengths']
del data['cell_angles']
if 'cell_lengths' in out_fields:
if 'cell_lengths' in data:
data['cell_lengths'] = in_units_of(data['cell_lengths'], in_units, out_units, inplace=True)
elif 'box' in data:
a, b, c, alpha, beta, gamma = md.utils.unitcell.box_vectors_to_lengths_and_angles(data['box'][:, 0], data['box'][:, 1], data['box'][:, 2])
data['cell_lengths'] = np.vstack((a, b, c)).T
data['cell_angles'] = np.vstack((alpha, beta, gamma)).T
data['cell_lengths'] = in_units_of(data['cell_lengths'], in_units, out_units, inplace=True)
del data['box']
ignored_keys = ["'%s'" % s for s in set(data) - set(out_fields)]
formated_fields = ', '.join("'%s'" % o for o in out_fields)
if len(ignored_keys) > 0:
warn('%s data from input file(s) will be discarded. '
'output format only supports fields: %s' % (', '.join(ignored_keys),
formated_fields))
warn.active = False
return data
示例5: load_gro
def load_gro(filename, stride=None, atom_indices=None, frame=None):
"""Load a GROMACS GRO file.
Parameters
----------
filename : str
Path to the GRO file on disk.
stride : int, default=None
Only read every stride-th model from the file
atom_indices : array_like, optional
If not none, then read only a subset of the atoms coordinates from the
file. These indices are zero-based.
frame : int, optional
Use this option to load only a single frame from a trajectory on disk.
If frame is None, the default, the entire trajectory will be loaded.
If supplied, ``stride`` will be ignored.
"""
from mdtraj.core.trajectory import _parse_topology, Trajectory
with GroTrajectoryFile(filename, 'r') as f:
topology = f.topology
if frame is not None:
f.seek(frame)
coordinates, time, unitcell_vectors = f.read(n_frames=1, atom_indices=atom_indices)
else:
coordinates, time, unitcell_vectors = f.read(stride=stride, atom_indices=atom_indices)
coordinates = in_units_of(coordinates, f.distance_unit, Trajectory._distance_unit, inplace=True)
unitcell_vectors = in_units_of(unitcell_vectors, f.distance_unit, Trajectory._distance_unit, inplace=True)
traj = Trajectory(xyz=coordinates, topology=topology, time=time)
traj.unitcell_vectors = unitcell_vectors
return traj
示例6: write
def write(self, xyz, types=None):
"""Write one or more frames of data to a xyz file.
Parameters
----------
xyz : np.ndarray, shape=(n_frames, n_atoms, 3)
The cartesian coordinates of the atoms to write.
types : np.ndarray, shape(3, )
The type of each particle.
"""
if not self._mode == 'w':
raise ValueError('write() is only available when file is opened '
'in mode="w"')
if not types:
# Make all particles the same type.
types = ['X' for _ in xrange(xyz.shape[1])]
xyz = ensure_type(xyz, np.float32, 3, 'xyz', can_be_none=False,
shape=(None, None, 3), warn_on_cast=False,
add_newaxis_on_deficient_ndim=True)
in_units_of(xyz, 'nanometers', self.distance_unit, inplace=True)
for i in range(xyz.shape[0]):
self._fh.write('{0}\n'.format(xyz.shape[1]))
self._fh.write("Created with MDTraj {0}, {1}\n".format(version, str(date.today())))
for j, coord in enumerate(xyz[i]):
self._fh.write('{0} {1:8.3f} {2:8.3f} {3:8.3f}\n'.format(
types[j], coord[0], coord[1], coord[2]))
示例7: load_hdf5
def load_hdf5(filename, stride=None, atom_indices=None, frame=None):
"""Load an MDTraj hdf5 trajectory file from disk.
Parameters
----------
filename : str
String filename of HDF Trajectory file.
stride : int, default=None
Only read every stride-th frame
atom_indices : array_like, optional
If not none, then read only a subset of the atoms coordinates from the
file. This may be slightly slower than the standard read because it
requires an extra copy, but will save memory.
frame : int, optional
Use this option to load only a single frame from a trajectory on disk.
If frame is None, the default, the entire trajectory will be loaded.
If supplied, ``stride`` will be ignored.
Examples
--------
>>> import mdtraj as md
>>> traj = md.load_hdf5('output.h5')
>>> print traj
<mdtraj.Trajectory with 500 frames, 423 atoms at 0x110740a90>
>>> traj2 = md.load_hdf5('output.h5', stride=2, top='topology.pdb')
>>> print traj2
<mdtraj.Trajectory with 250 frames, 423 atoms at 0x11136e410>
Returns
-------
trajectory : md.Trajectory
The resulting trajectory, as an md.Trajectory object.
See Also
--------
mdtraj.HDF5TrajectoryFile : Low level interface to HDF5 files
"""
from mdtraj.trajectory import _parse_topology, Trajectory
atom_indices = cast_indices(atom_indices)
with HDF5TrajectoryFile(filename) as f:
if frame is not None:
f.seek(frame)
data = f.read(n_frames=1, atom_indices=atom_indices)
else:
data = f.read(stride=stride, atom_indices=atom_indices)
topology = f.topology
in_units_of(data.coordinates, f.distance_unit, Trajectory._distance_unit, inplace=True)
in_units_of(data.cell_lengths, f.distance_unit, Trajectory._distance_unit, inplace=True)
if atom_indices is not None:
topology = f.topology.subset(atom_indices)
trajectory = Trajectory(xyz=data.coordinates, topology=topology,
time=data.time, unitcell_lengths=data.cell_lengths,
unitcell_angles=data.cell_angles)
return trajectory
示例8: read_as_traj
def read_as_traj(self, topology, n_frames=None, stride=None, atom_indices=None):
"""Read a trajectory from a lammpstrj file
Parameters
----------
topology : Topology
The system topology
n_frames : int, optional
If positive, then read only the next `n_frames` frames. Otherwise read all
of the frames in the file.
stride : np.ndarray, optional
Read only every stride-th frame.
atom_indices : array_like, optional
If not none, then read only a subset of the atoms coordinates from the
file. This may be slightly slower than the standard read because it required
an extra copy, but will save memory.
Returns
-------
trajectory : Trajectory
A trajectory object containing the loaded portion of the file.
See Also
--------
read : Returns the raw data from the file
Notes
-----
If coordinates are specified in more than one style, the first complete
trio of x/y/z coordinates will be read in according to the following
order:
1) x,y,z (unscaled coordinates)
2) xs,ys,zs (scaled atom coordinates)
3) xu,yu,zu (unwrapped atom coordinates)
4) xsu,ysu,zsu (scaled unwrapped atom coordinates)
E.g., if the file contains x, y, z, xs, ys, zs then x, y, z will be used.
if the file contains x, y, xs, ys, zs then xs, ys, zs will be used.
"""
from mdtraj.core.trajectory import Trajectory
if atom_indices is not None:
topology = topology.subset(atom_indices)
initial = int(self._frame_index)
xyz, cell_lengths, cell_angles = self.read(n_frames=n_frames, stride=stride, atom_indices=atom_indices)
if len(xyz) == 0:
return Trajectory(xyz=np.zeros((0, topology.n_atoms, 3)), topology=topology)
in_units_of(xyz, self.distance_unit, Trajectory._distance_unit, inplace=True)
in_units_of(cell_lengths, self.distance_unit, Trajectory._distance_unit, inplace=True)
if stride is None:
stride = 1
time = (stride*np.arange(len(xyz))) + initial
t = Trajectory(xyz=xyz, topology=topology, time=time)
t.unitcell_lengths = cell_lengths
t.unitcell_angles = cell_angles
return t
示例9: parse_box
def parse_box(self, style):
"""Extract lengths and angles from a frame.
Parameters
----------
style : str
Type of box, 'triclinic' or 'orthogonal'.
Returns
-------
lengths : ndarray
angles : ndarray
Notes
-----
For more info on how LAMMPS defines boxes:
http://lammps.sandia.gov/doc/Section_howto.html#howto_12
"""
box = np.empty(shape=(3, 2))
if style == 'triclinic':
factors = np.empty(3)
for i in range(3):
line = self._fh.readline().split()
box[i] = line[:2]
factors[i] = line[2]
xy, xz, yz = factors
xlo = box[0, 0] - np.min([0.0, xy, xz, xy+xz])
xhi = box[0, 1] - np.max([0.0, xy, xz, xy+xz])
ylo = box[1, 0] - np.min([0.0, yz])
yhi = box[1, 1] - np.max([0.0, yz])
zlo = box[2, 0]
zhi = box[2, 1]
lx = xhi - xlo
ly = yhi - ylo
lz = zhi - zlo
a = lx
b = np.sqrt(ly**2 + xy**2)
c = np.sqrt(lz**2 + xz**2 + yz**2)
alpha = np.arccos((xy*xz + ly*yz) / (b*c))
beta = np.arccos(xz / c)
gamma = np.arccos(xy / b)
lengths = np.array([a, b, c])
in_units_of(lengths, self.distance_unit, 'nanometers', inplace=True)
angles = np.degrees(np.array([alpha, beta, gamma]))
elif style == 'orthogonal':
box[0] = self._fh.readline().split() # x-dim of box
box[1] = self._fh.readline().split() # y-dim of box
box[2] = self._fh.readline().split() # z-dim of box
lengths = np.diff(box, axis=1).reshape(1, 3)[0] # box lengths
in_units_of(lengths, self.distance_unit, 'nanometers', inplace=True)
angles = np.empty(3)
angles.fill(90.0)
return lengths, angles
示例10: load_arc
def load_arc(filename, top=None, stride=None, atom_indices=None):
"""Load a TINKER .arc file from disk.
Parameters
----------
filename : str
String filename of TINKER .arc file.
top : {str, Trajectory, Topology}
The .arc format does not contain topology information. Pass in either
the path to a pdb file, a trajectory, or a topology to supply this
information.
stride : int, default=None
Only read every stride-th frame
atom_indices : array_like, optional
If not none, then read only a subset of the atoms coordinates from the
file.
Returns
-------
trajectory : md.Trajectory
The resulting trajectory, as an md.Trajectory object.
See Also
--------
mdtraj.ArcTrajectoryFile : Low level interface to TINKER .arc files
"""
from mdtraj.trajectory import _parse_topology, Trajectory
# we make it not required in the signature, but required here. although this
# is a little weird, its good because this function is usually called by a
# dispatch from load(), where top comes from **kwargs. So if its not supplied
# we want to give the user an informative error message
if top is None:
raise ValueError('"top" argument is required for load_arc')
if not isinstance(filename, string_types):
raise TypeError('filename must be of type string for load_arc. '
'you supplied %s' % type(filename))
topology = _parse_topology(top)
atom_indices = _cast_indices(atom_indices)
if atom_indices is not None:
topology = topology.subset(atom_indices)
with ArcTrajectoryFile(filename) as f:
xyz = f.read(stride=stride, atom_indices=atom_indices)
in_units_of(xyz, f.distance_unit, Trajectory._distance_unit, inplace=True)
time = np.arange(len(xyz))
if stride is not None:
# if we loaded with a stride, the Trajectories's time field should
# respect that
time *= stride
t = Trajectory(xyz=xyz, topology=topology, time=time)
return t
示例11: load_netcdf
def load_netcdf(filename, top=None, stride=None, atom_indices=None, frame=None):
"""Load an AMBER NetCDF file. Since the NetCDF format doesn't contain
information to specify the topology, you need to supply a topology
Parameters
----------
filename : str
filename of AMBER NetCDF file.
top : {str, Trajectory, Topology}
The NetCDF format does not contain topology information. Pass in either
the path to a pdb file, a trajectory, or a topology to supply this
information.
stride : int, default=None
Only read every stride-th frame
atom_indices : array_like, optional
If not none, then read only a subset of the atoms coordinates from the
file. This may be slightly slower than the standard read because it
requires an extra copy, but will save memory.
frame : int, optional
Use this option to load only a single frame from a trajectory on disk.
If frame is None, the default, the entire trajectory will be loaded.
If supplied, ``stride`` will be ignored.
Returns
-------
trajectory : md.Trajectory
The resulting trajectory, as an md.Trajectory object.
See Also
--------
mdtraj.NetCDFTrajectoryFile : Low level interface to NetCDF files
"""
from mdtraj.core.trajectory import _parse_topology, Trajectory
topology = _parse_topology(top)
atom_indices = cast_indices(atom_indices)
if atom_indices is not None:
topology = topology.subset(atom_indices)
with NetCDFTrajectoryFile(filename) as f:
if frame is not None:
f.seek(frame)
xyz, time, cell_lengths, cell_angles = f.read(n_frames=1, atom_indices=atom_indices)
else:
xyz, time, cell_lengths, cell_angles = f.read(stride=stride, atom_indices=atom_indices)
xyz = in_units_of(xyz, f.distance_unit, Trajectory._distance_unit, inplace=True)
cell_lengths = in_units_of(cell_lengths, f.distance_unit, Trajectory._distance_unit, inplace=True)
trajectory = Trajectory(xyz=xyz, topology=topology, time=time,
unitcell_lengths=cell_lengths,
unitcell_angles=cell_angles)
return trajectory
示例12: load_lh5
def load_lh5(filename, top=None, stride=None, atom_indices=None, frame=None):
"""Load an deprecated MSMBuilder2 LH5 trajectory file.
Parameters
----------
filename : str
filename of AMBER NetCDF file.
top : {str, Trajectory, Topology}
The NetCDF format does not contain topology information. Pass in either
the path to a pdb file, a trajectory, or a topology to supply this
information.
stride : int, default=None
Only read every stride-th frame
atom_indices : array_like, optional
If not none, then read only a subset of the atoms coordinates from the
file. This may be slightly slower than the standard read because it
requires an extra copy, but will save memory.
frame : int, optional
Use this option to load only a single frame from a trajectory on disk.
If frame is None, the default, the entire trajectory will be loaded.
If supplied, ``stride`` will be ignored.
See Also
--------
mdtraj.LH5TrajectoryFile : Low level interface to LH5 files
"""
from mdtraj import Trajectory
atom_indices = cast_indices(atom_indices)
with LH5TrajectoryFile(filename) as f:
if frame is not None:
f.seek(frame)
xyz = f.read(n_frames=1, atom_indices=atom_indices)
else:
xyz = f.read(stride=stride, atom_indices=atom_indices)
topology = f.topology
in_units_of(xyz, f.distance_unit, Trajectory._distance_unit, inplace=True)
if atom_indices is not None:
topology = f.topology.subset(atom_indices)
time = np.arange(len(xyz))
if frame is not None:
time += frame
elif stride is not None:
time *= stride
return Trajectory(xyz=xyz, topology=topology, time=time)
示例13: save_dcd
def save_dcd(self, filename, force_overwrite=True):
"""Save trajectory to CHARMM/NAMD DCD format
Parameters
----------
filename : str
filesystem path in which to save the trajectory
force_overwrite : bool, default=True
Overwrite anything that exists at filenames, if its already there
"""
self._check_valid_unitcell()
with DCDTrajectoryFile(filename, 'w', force_overwrite=force_overwrite) as f:
f.write(in_units_of(self.xyz, Trajectory._distance_unit, f.distance_unit),
cell_lengths=in_units_of(self.unitcell_lengths, Trajectory._distance_unit, f.distance_unit),
cell_angles=self.unitcell_angles)
示例14: read_as_traj
def read_as_traj(self, topology, n_frames=None, stride=None, atom_indices=None):
"""Read a trajectory from a mdcrd file
Parameters
----------
topology : Topology
The system topology
n_frames : int, optional
If positive, then read only the next `n_frames` frames. Otherwise read all
of the frames in the file.
stride : np.ndarray, optional
Read only every stride-th frame.
atom_indices : array_like, optional
If not none, then read only a subset of the atoms coordinates from the
file. This may be slightly slower than the standard read because it required
an extra copy, but will save memory.
Returns
-------
trajectory : Trajectory
A trajectory object containing the loaded portion of the file.
"""
from mdtraj.core.trajectory import Trajectory
if atom_indices is not None:
topology = topology.subset(atom_indices)
initial = int(self._frame_index)
xyz, cell_lengths = self.read(n_frames=n_frames, stride=stride, atom_indices=atom_indices)
if len(xyz) == 0:
return Trajectory(xyz=np.zeros((0, topology.n_atoms, 3)), topology=topology)
in_units_of(xyz, self.distance_unit, Trajectory._distance_unit, inplace=True)
in_units_of(cell_lengths, self.distance_unit, Trajectory._distance_unit, inplace=True)
if cell_lengths is None:
cell_angles = None
else:
# Assume that its a rectilinear box
cell_angles = 90.0 * np.ones_like(cell_lengths)
if stride is None:
stride = 1
time = (stride*np.arange(len(xyz))) + initial
t = Trajectory(xyz=xyz, topology=topology, time=time)
t.unitcell_lengths = cell_lengths
t.unitcell_angles = cell_angles
return t
示例15: save_netcdf
def save_netcdf(self, filename, force_overwrite=True):
"""Save trajectory in AMBER NetCDF format
Parameters
----------
filename : str
filesystem path in which to save the trajectory
force_overwrite : bool, default=True
Overwrite anything that exists at filename, if its already there
"""
self._check_valid_unitcell()
with NetCDFTrajectoryFile(filename, 'w', force_overwrite=force_overwrite) as f:
f.write(coordinates=in_units_of(self._xyz, Trajectory._distance_unit, NetCDFTrajectoryFile.distance_unit),
time=self.time,
cell_lengths=in_units_of(self.unitcell_lengths, Trajectory._distance_unit, f.distance_unit),
cell_angles=self.unitcell_angles)