polyphys.probe.chain_size#
polyphys.probe.chain_size#
The polyphys.probe.chain_size module measures the size and shape of
one polymer chain in every frame of a trajectory: its end-to-end distance,
its span along the cylinder axis, its transverse size, its radius of
gyration, and the asphericity, shape parameter, and principal axes of its
gyration tensor. ChainSize is an MDAnalysis
AnalysisBase, so it runs over a slice of
frames in serial or, split across workers, in parallel, and stores one
array per observable in its results.
The research code measured the same seven quantities in one loop over the frames of each study’s probe function, after shifting every position by half the box. Every quantity here is invariant under such a shift, because each one first recenters the chain on its center of geometry or of mass, so the shift is dropped.
Contents#
ChainSize, the per-frame chain-size analysis.
Dependencies#
Python standard library: pathlib, typing.
MDAnalysis 2.8 or later, through the
mdaextra:AnalysisBase,ResultsGroup, and the shape methods ofAtomGroup.polyphys.analyze.measurer:fsd(),end_to_end(), andtransverse_size().polyphys.probe.core:_ProbeAnalysis, the base whoseruncloses the pool of themultiprocessingbackend, and_compute_part, which computes each part of a split run on its own copy of the analysis.
Notation#
- \(N\)
The number of beads in the chain,
atomgroup.n_atoms.- \(\mathbf{r}_i\), \(m_i\)
The position and mass of bead \(i\), in the dump’s length and mass units; the studies use the monomer diameter and mass.
- \(\mathbf{r}_\mathrm{cg}\), \(\mathbf{r}_\mathrm{cm}\)
The center of geometry \(\sum_i \mathbf{r}_i / N\) and the center of mass \(\sum_i m_i \mathbf{r}_i / \sum_i m_i\).
- \(\mathbf{S}\), \(\lambda_1 \ge \lambda_2 \ge \lambda_3\)
The gyration tensor \(S_{ab} = \sum_i m_i (r_{i,a} - r_{\mathrm{cm},a}) (r_{i,b} - r_{\mathrm{cm},b}) / \sum_i m_i\), and its eigenvalues, which MDAnalysis’s
gyration_momentsreturns.
Examples
A straight chain of four beads one unit apart, in a one-frame universe:
>>> import MDAnalysis as mda
>>> import numpy as np
>>> universe = mda.Universe.empty(4, trajectory=True)
>>> universe.add_TopologyAttr('masses', np.ones(4))
>>> universe.atoms.positions = np.array(
... [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0]])
>>> analysis = ChainSize(universe.atoms, ('rfloryT', 'asphericityT')).run()
>>> analysis.results['rfloryT'], analysis.results['asphericityT']
(array([3.]), array([1.]))
Added in version 0.7.0.
Classes
|
The size and shape of one polymer chain, measured in every frame. |
- class polyphys.probe.chain_size.ChainSize(atomgroup, observables, *, chain='Mon', unwrap=False, axis=2, verbose=False)[source]#
Bases:
polyphys.probe.core._ProbeAnalysisThe size and shape of one polymer chain, measured in every frame.
Added in version 0.7.0.
- Parameters:
atomgroup (
MDAnalysis.core.groups.AtomGroup) – The chain, at least two beads, in atom-ID order: the order along the backbone, whichUniverse.select_atomsgives.observables (
typing.Sequence[str]) – The observables to measure, each a name inCHAIN_SIZE_OBSERVABLES, in the orderresultsandsave()list them.chain (
str) – The species label of the chain, which names the filessave()writes,<name>-<observable><chain>.npy.unwrap (
bool) – Whether the chain is unwrapped across the periodic boundaries before its gyration tensor is formed, forasphericityT. The research code unwrapped in a periodic cube and not in a cylinder. Every other observable reads the positions as the dump gives them, so the chain must be whole; see Notes.axis (
typing.Literal[0,1,2]) – The cylinder axis,0,1, or2forx,y, orz, along whichfsdTspans and across whichtransSizeTspreads.verbose (
bool) – Whether to show a progress bar duringrun().
- Variables:
atomgroup (
AtomGroup) – The chain.observables (
tupleofPropertyT) – The observables, in order.chain (
EntityT) – The species label of the chain.unwrap (
bool) – Whether the chain is unwrapped forasphericityT.axis (
AxisT) – The cylinder axis.results (
Results) – Afterrun(), one float64 array per observable, keyed by its name: shape(n_frames,)for every scalar,(n_frames, 3, 3)forprincipalT.n_frames (
int) – Afterrun(), the number of frames analyzed, fromAnalysisBase.frames (
numpy.ndarray) – Afterrun(), the indices of the frames analyzed, shape(n_frames,).times (
numpy.ndarray) – Afterrun(), the times of the frames analyzed, shape(n_frames,), in the trajectory’s time unit.
- Raises:
ValueError – If observables is empty, repeats a name, or names an observable that is not in
CHAIN_SIZE_OBSERVABLES; if chain is empty; if axis is not0,1, or2; or if atomgroup has fewer than two beads. Duringrun(), if a chain bond spans half the frame’s box or more along a direction, which means the dump splits the chain across a periodic boundary; the message names the frame.
Notes
The observables, with the species label
Monas the studies name them:rfloryTMon\(|\mathbf{r}_N - \mathbf{r}_1|\), the end-to-end distance (
end_to_end()).fsdTMon\(\max_i z_i - \min_i z_i\) along axis, the span or Feret diameter (
fsd()).transSizeTMon\(2 \langle |\mathbf{r}_{i,\perp} - \mathbf{r}_{\mathrm{cg},\perp}| \rangle_i\), twice the mean distance from the center of geometry in the plane across axis (
transverse_size()).gyrTMon\(R_g = \sqrt{\lambda_1 + \lambda_2 + \lambda_3}\), the mass-weighted radius of gyration (
AtomGroup.radius_of_gyration).asphericityTMon\(\frac{3}{2} \sum_k (\lambda_k - \bar\lambda)^2 / (\sum_k \lambda_k)^2\), from 0 for a spherically symmetric chain to 1 for a straight one (
AtomGroup.asphericity(wrap=False, unwrap=unwrap)).shapeTMon\(27 \prod_k (\lambda_k - \bar\lambda) / (\sum_k \lambda_k)^3\), from \(-1/4\) for a flat chain with two equal eigenvalues and a zero one, such as a planar ring, through 0 for a spherically symmetric one, to 2 for a straight one (
AtomGroup.shape_parameter(wrap=False)).principalTMonThe \(3 \times 3\) matrix of principal axes of the moment of inertia, one eigenvector per row, by decreasing eigenvalue (
AtomGroup.principal_axes(wrap=False)).
The asphericity and shape parameter follow Dima and Thirumalai [1], as MDAnalysis implements them.
shapeTandprincipalTread the positions as the dump wraps them, whatever unwrap is, as the research code did; unwrap reachesasphericityTonly.Whole molecules: every observable but an unwrapped
asphericityTreads the positions as the dump gives them, so the dump must hold the chain whole, as the studies’ dumps do. In each frame,run()checks that no bond \((i, j)\) of the chain spans half the box or more along any direction \(a\), \(|r_{i,a} - r_{j,a}| \ge L_a / 2\) for the frame’s box length \(L_a\), and raises on the first frame that fails. A bond is far shorter than half the box (the studies’ FENE bound \(R_0 = 1.5\),docs/source/design.md), so a bond that long has been split by the boundary. The check is skipped when the frame carries no box or the topology has no bonds, and whenasphericityTwith unwrap is the only observable, since unwrapping makes that one whole itself.No per-frame shift of the positions is applied: each observable recenters the chain itself, so the research code’s shift of every position by half the box changed none of these values.
The MDAnalysis contract:
_prepareallocates one float64 array per observable for the frames of the run,_single_framewrites the current frame’s row, and_concludedoes nothing. The class is marked parallelizable, withserial,multiprocessing, anddaskbackends; each worker fills the arrays of its own frames, which_get_aggregatorconcatenates along the frame axis (ResultsGroup.ndarray_hstackfor a scalar series,ResultsGroup.ndarray_vstackforprincipalT).Cost per frame: \(O(N)\) time for every observable, since each is a sum over the beads followed by at most a \(3 \times 3\) eigenproblem, plus the \(O(N + N_\mathrm{bonds})\) unwrap of the chain when unwrap is set, and the \(O(N_\mathrm{bonds})\) check that the chain is whole; \(O(N + N_\mathrm{bonds})\) extra space for the recentered positions and the bond spans. Over a run, \(O(F)\) space per scalar series and \(O(9 F)\) for
principalT, for \(F\) frames. Positions come from MDAnalysis as float32, so each value carries a relative round-off of about \(10^{-7}\).References
Examples
Two frames of a three-bead chain, the second frame stretched along z:
>>> import MDAnalysis as mda >>> import numpy as np >>> frames = np.array([ ... [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0]], ... [[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 2.0]]]) >>> universe = mda.Universe.empty(3, trajectory=True) >>> universe.add_TopologyAttr('masses', np.ones(3)) >>> universe.load_new(frames, format='MEMORY') <Universe with 3 atoms> >>> analysis = ChainSize(universe.atoms, ('rfloryT', 'fsdT', 'gyrT'), ... axis=2) >>> analysis = analysis.run() >>> np.round(analysis.results['rfloryT'], 6) array([1.414214, 2. ]) >>> analysis.results['fsdT'] array([0., 2.])
The frames to analyze are chosen as in any MDAnalysis analysis:
>>> ChainSize(universe.atoms, ('fsdT',)).run(start=1).results['fsdT'] array([2.])
- classmethod from_spec(universe, spec, *, axis=2, verbose=False)[source]#
Build the analysis of a study’s chain from its probe spec.
The chain is
universe.select_atoms(spec.selections[spec.chain]); the observables, the chain label, and unwrap are the spec’s.Added in version 0.7.0.
- Parameters:
universe (
MDAnalysis.core.universe.Universe) – The trajectory, asmake_universe()opens it.spec (
polyphys.spec.ProbeSpec) – The study’s probe spec.axis (
typing.Literal[0,1,2]) – The cylinder axis.verbose (
bool) – Whether to show a progress bar duringrun().
- Returns:
The analysis, not yet run.
- Return type:
- Raises:
ValueError – If the selection picks fewer than two beads.
Examples
>>> import MDAnalysis as mda >>> import numpy as np >>> from polyphys.tests.synthetic import ChainCyl >>> from polyphys.spec import ProbeSpec, ProjectSpec >>> project = ProjectSpec( ... parser=ChainCyl, group='bug', divisor=0.025, ... crowder_attr='phi_bulk_c', ... physical_attrs=('space', 'nmon'), ... species_sizes={'Mon': 'dmon', 'Crd': 'dcrowd'}, ... tseries_properties=('gyrTMon', 'rfloryTMon')) >>> spec = ProbeSpec(project, {'Mon': 'resid 1'}, 'Mon', ... ('rfloryT',), unwrap=False) >>> universe = mda.Universe.empty(3, n_residues=1, ... atom_resindex=[0, 0, 0], ... trajectory=True) >>> universe.add_TopologyAttr('resid', [1]) >>> universe.add_TopologyAttr('masses', np.ones(3)) >>> universe.atoms.positions = np.array( ... [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0]]) >>> analysis = ChainSize.from_spec(universe, spec) >>> analysis.chain, analysis.atomgroup.n_atoms ('Mon', 3) >>> analysis.run().results['rfloryT'] array([2.])
- classmethod get_supported_backends()[source]#
The backends
run()accepts:'serial','multiprocessing', and'dask'.Examples
>>> ChainSize.get_supported_backends() ('serial', 'multiprocessing', 'dask')
- save(save_to, name)[source]#
Save each observable’s array as
<name>-<observable><chain>.npy.Added in version 0.7.0.
- Parameters:
save_to (
str|os.PathLike[str]) – An existing directory.name (
str) – The artifact’s name,<parser.name>-<parser.group>in the studies, such as'N200...ens1-bug'.
- Returns:
The files written, one per observable, in order.
- Return type:
- Raises:
RuntimeError – If
run()has not been called.
Examples
>>> import tempfile >>> import MDAnalysis as mda >>> import numpy as np >>> universe = mda.Universe.empty(2, trajectory=True) >>> universe.add_TopologyAttr('masses', np.ones(2)) >>> universe.atoms.positions = np.array([[0.0, 0.0, 0.0], ... [0.0, 0.0, 3.0]]) >>> analysis = ChainSize(universe.atoms, ('rfloryT', 'fsdT')).run() >>> with tempfile.TemporaryDirectory() as tmp: ... paths = analysis.save(tmp, 'N2ens1-bug') ... [path.name for path in paths], np.load(paths[1]).tolist() (['N2ens1-bug-rfloryTMon.npy', 'N2ens1-bug-fsdTMon.npy'], [3.0])