polyphys.probe.histograms#

polyphys.probe.histograms#

The polyphys.probe.histograms module bins the positions of every species of a study in every frame of a trajectory: one-dimensional histograms along the directions of the geometry, kept per frame, and two-dimensional maps in the three Cartesian planes, kept as the mean map of each block of consecutive frames. SpatialHistograms is an MDAnalysis AnalysisBase, so it runs over a slice of frames in serial or, split across workers, in parallel; histogram_edges() builds the bin edges of one whole from its probe spec and parser, with the research code’s bin sizes and the studies’ geometry.

The research code binned the same species in one loop over the frames of each study’s probe function, after shifting every position by half the parser’s box, and summed the counts over the frames. Here the one-dimensional counts are kept per frame, so that the time dependence and the block statistics of a profile remain available, and the two-dimensional maps, which would not fit in memory per frame, are averaged over blocks of block_frames frames. The sum over frames of either is what the research code saved.

Contents#

Dependencies#

Notation#

\(F\), \(b\), \(K = \lceil F / b \rceil\)

The frames of a run, the block length, and the number of blocks; block \(k\) holds the frames \(kb, \ldots, \min((k + 1) b, F) - 1\) in the order the run visits them.

\(\mathbf{r}_i = (x_i, y_i, z_i)\)

The position of particle \(i\) after recentering, in the dump’s length unit, the monomer diameter in the studies.

\(r\), \(\theta\), \(z\)

In a cylinder whose axis is \(z\): \(\sqrt{x^2 + y^2}\), \(\operatorname{atan2}(y, x)\) in \([-\pi, \pi]\), and the axial coordinate. In a cube, \(r = |\mathbf{r}|\) from the box center.

\(D\), \(Z\), \(L\), \(a_w\)

The parser’s dcyl, lcyl, and lcube, and the wall-bead size \(a_w = 1\) of the cylindrical studies, so that the LAMMPS box is \((D + a_w) \times (D + a_w) \times Z\) or \(L^3\).

Examples

Two particles in a periodic cube of side 20, three frames, with the dump reader’s frame already translated to the origin, so that 'half' moves the box center to the origin:

>>> import MDAnalysis as mda
>>> import numpy as np
>>> frames = np.array([
...     [[10.0, 10.0, 10.0], [12.5, 10.0, 10.0]],
...     [[10.0, 10.0, 10.0], [10.0, 10.0, 11.0]],
...     [[10.0, 10.0, 10.0], [10.0, 13.5, 10.0]]])
>>> universe = mda.Universe.empty(2, trajectory=True)
>>> universe.load_new(frames, format='MEMORY', dimensions=np.tile(
...     [20.0, 20.0, 20.0, 90.0, 90.0, 90.0], (3, 1)))
<Universe with 2 atoms>
>>> edges = {'r': np.arange(0.0, 17.5, 1.0)}
>>> for key in 'xyz':
...     edges[key] = np.linspace(-10.0, 10.0, 5)
>>> analysis = SpatialHistograms(
...     {'Mon': universe.atoms}, edges, geometry='cubic', block_frames=2)
>>> analysis = analysis.run()
>>> analysis.results['rHistTMon'][:, :4]
array([[1, 0, 1, 0],
       [1, 1, 0, 0],
       [1, 0, 0, 1]])
>>> analysis.results['blockFrames']
array([2, 1])

Added in version 0.7.0.

Functions

histogram_edges(spec, parser)

The bin edges of one whole's histograms and maps.

Classes

SpatialHistograms(groups, edges, *, ...[, ...])

The positions of each species binned in every frame: one-dimensional histograms per frame and two-dimensional maps per block of frames.

class polyphys.probe.histograms.SpatialHistograms(groups, edges, *, geometry, block_frames, recenter='half', verbose=False)[source]#

Bases: polyphys.probe.core._ProbeAnalysis

The positions of each species binned in every frame: one-dimensional histograms per frame and two-dimensional maps per block of frames.

Added in version 0.7.0.

Parameters:
  • groups (typing.Mapping[str, MDAnalysis.core.groups.AtomGroup])

  • ~MDAnalysis.core.groups.AtomGroup – Each species label mapped to its atoms, all in one universe, in the order results and save() list the species. A group may be empty, for a species a whole lacks; its histograms are then zero.

  • edges (typing.Mapping[str, numpy.ndarray]) – The bin edges, increasing, keyed as histogram_edges() returns them: the directions of geometry and 'x', 'y', 'z'.

  • geometry (typing.Literal['cubic', 'cylindrical']) – 'cylindrical', with the histograms along 'r', 'z', and 'theta' about the z axis, or 'cubic', with the histogram along 'r' from the box center.

  • block_frames (int) – The block length \(b\), positive: consecutive frames of the run whose maps are averaged into one stored map.

  • recenter (typing.Union[typing.Literal['none', 'half'], tuple[float, float, float]]) – How a frame’s positions are moved before binning: 'half' subtracts half the frame’s box lengths, 'none' nothing, a triple its values. The positions in the trajectory are untouched.

  • verbose (bool) – Whether to show a progress bar during run().

Variables:
  • groups (Mapping of EntityT to)

  • ~MDAnalysis.core.groups.AtomGroup – The species, a copy of the mapping given.

  • edges (Mapping of str to numpy.ndarray) – The edges, a copy of the mapping given, each float64.

  • geometry (GeometryT) – The geometry.

  • block_frames (int) – The block length.

  • recenter (RecenterT) – The recentering, a triple as floats.

  • results (Results) – After run(), for each species S and direction d of the geometry, dHistTS, int64 (n_frames, n_bins), the counts of frame i in row i, and dHistS, int64 (n_bins,), their sum over the frames; for each plane p in xy, xz, yz, pHistBlockS, float64 (n_blocks, n_a, n_b), the mean map of each block, rows along the plane’s first axis, and pHistS, float64 (n_a, n_b), the counts summed over the frames; and blockFrames, int64 (n_blocks,), the frames in each block.

  • n_frames (int) – After run(), the number of frames analyzed, from AnalysisBase.

  • frames (numpy.ndarray) – After run(), the indices of the frames analyzed, shape (n_frames,).

  • times (numpy.ndarray) – After run(), the times of the frames analyzed, shape (n_frames,), in the trajectory’s time unit.

Raises:

ValueError – If groups is empty, has an empty label, or spans two universes; if edges lacks a key the geometry needs or has edges that are not a one-dimensional increasing array of at least two values; if geometry is unknown; if block_frames is not a positive integer; if recenter is neither 'none', 'half', nor a triple of finite numbers; or, during run(), if a frame carries no box, or if a wrapped and recentered position falls outside the edges of a direction or a Cartesian axis.

Notes

Per frame and species, the positions are copied, wrapped, recentered, and binned. Wrapping maps each position into the box of the reader’s frame, \([0, L)\), along the directions the geometry makes periodic, every one in a cube and z in a cylinder: LAMMPS enforces the periodic boundaries only when it rebuilds the neighbor lists, so a dump can place an atom slightly outside the box [1], as the HnsCub dumps do by up to \(0.04\) monomer diameters. The box of the reader’s frame is MDAnalysis’s primary unit cell, \([0, L)\), where its LAMMPS dump reader puts the box by subtracting the lower bounds; a universe built in memory must place its positions there too. A position past a wall is not wrapped. The positions are binned with radial_cyl_histogram(), axial_histogram(), and azimuth_cyl_histogram() in a cylinder, radial_histogram() in a cube, and planar_cartesian_histogram() in each plane, with the xz map transposed to rows along x as the research code stored it. A position outside the edges after wrapping raises, so every frame’s counts sum to the species’ particle number: the research code’s np.histogram dropped such a position silently, and did not wrap.

Blocks are numbered over the frames of the whole run in the order run() visits them, whatever start, stop, step, or frames select, so that a run split across workers gives the same blocks as a serial one: _setup_frames records the run’s frame count before the split and _compute each worker’s offset into it. Each worker accumulates the block sums and frame counts of its own frames, which _get_aggregator adds (ResultsGroup.ndarray_sum), and its per-frame rows, which it concatenates (ResultsGroup.ndarray_vstack); _conclude then divides each block’s sum by its frame count and sums the counts over the frames.

Cost per frame: \(O(S N \log B)\) time for \(S\) species of \(N\) particles and \(B\) bins along a direction, from the sorted-edge search of np.histogram and np.histogram2d, and \(O(N)\) extra space for the recentered positions. Over a run, each one-dimensional histogram holds \(8 F B\) bytes and each map \(8 K B_a B_b\) bytes, for \(F\) frames, \(K = \lceil F / b \rceil\) blocks, and \(B_a \times B_b\) cells: with \(b = 100\) and \(200 \times 200\) cells, about 1 MB per block per species for the three planes. Wrapping adds \(O(N)\) time per frame and species.

References

Examples

One particle in a cylinder of radius 2 and length 4, two frames in the reader’s frame, the box from 0 to 4, recentered by a given shift to (1.5, 0, 1) and (0, 0.5, -1); the frame’s counts sum to its one particle along every direction:

>>> import MDAnalysis as mda
>>> import numpy as np
>>> frames = np.array([[[3.5, 2.0, 3.0]], [[2.0, 2.5, 1.0]]])
>>> universe = mda.Universe.empty(1, trajectory=True)
>>> universe.load_new(frames, format='MEMORY', dimensions=np.tile(
...     [4.0, 4.0, 4.0, 90.0, 90.0, 90.0], (2, 1)))
<Universe with 1 atoms>
>>> edges = {'r': np.array([0.0, 1.0, 2.0]),
...          'z': np.array([-2.0, 0.0, 2.0]),
...          'theta': np.linspace(-np.pi, np.pi, 5),
...          'x': np.array([-2.0, 0.0, 2.0]),
...          'y': np.array([-2.0, 0.0, 2.0])}
>>> analysis = SpatialHistograms(
...     {'Crd': universe.atoms}, edges, geometry='cylindrical',
...     block_frames=2, recenter=(2.0, 2.0, 2.0)).run()
>>> analysis.results['rHistTCrd'], analysis.results['zHistTCrd']
(array([[0, 1],
       [1, 0]]), array([[0, 1],
       [1, 0]]))
>>> analysis.results['xyHistBlockCrd']
array([[[0., 0.],
        [0., 1.]]])
>>> float(analysis.results['xyHistCrd'].sum())
2.0
classmethod from_spec(universe, spec, parser, *, verbose=False)[source]#

Build the analysis of a whole from its study’s probe spec.

The species are spec.histogram_species, each selected with its string in spec.selections; the edges are histogram_edges()’s; the geometry, block length, and recentering are the spec’s.

Added in version 0.7.0.

Parameters:
Returns:

The analysis, not yet run.

Return type:

typing.Self

Raises:

ValueError – If the spec names no histogram species, or from histogram_edges().

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', 'dcyl', 'dcrowd'),
...     species_sizes={'Mon': 'dmon', 'Crd': 'dcrowd'},
...     tseries_properties=('gyrTMon',))
>>> spec = ProbeSpec(
...     project, {'Mon': 'resid 1', 'Crd': 'resid 0'}, 'Mon',
...     ('gyrT',), unwrap=False, histogram_species=('Mon', 'Crd'),
...     block_frames=100, bin_sizes={'r': 0.5, 'z': 1.0,
...     'theta': np.pi / 2, 'x': 0.5, 'y': 0.5})
>>> whole = ChainCyl(
...     'N2r2.5lz5ac1nc1dt0.005bdump1adump1ens1', 'whole',
...     'all')
>>> universe = mda.Universe.empty(
...     3, n_residues=2, atom_resindex=[0, 1, 1], trajectory=True)
>>> universe.add_TopologyAttr('resid', [0, 1])
>>> universe.load_new(np.array([[[1.0, 2.0, 3.0], [2.0, 2.0, 5.0],
...     [3.0, 2.0, 5.0]]]), format='MEMORY', dimensions=np.array(
...     [[5.0, 5.0, 10.0, 90.0, 90.0, 90.0]]))
<Universe with 3 atoms>
>>> analysis = SpatialHistograms.from_spec(universe, spec, whole)
>>> [group.n_atoms for group in analysis.groups.values()]
[2, 1]
>>> analysis.run().results['rHistCrd']
array([0, 0, 0, 1, 0])
classmethod get_supported_backends()[source]#

The backends run() accepts: 'serial', 'multiprocessing', and 'dask'.

Examples

>>> SpatialHistograms.get_supported_backends()
('serial', 'multiprocessing', 'dask')
Return type:

tuple[str, ...]

save(save_to, name)[source]#

Save the edges, histograms, and maps under the research code’s names.

For each species S and direction d: <name>-dEdgeS.npy, <name>-dHistS.npy (summed over the frames), and <name>-dHistTS.npy (per frame); for each Cartesian axis c: <name>-cEdge.npy; for each plane p and species: <name>-pHistS.npy (summed) and <name>-pHistBlockS.npy (per block); and <name>-blockFrames.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-all'.

Returns:

The files written, in the order above.

Return type:

list[pathlib.Path]

Raises:

RuntimeError – If run() has not been called.

Examples

>>> import tempfile
>>> import MDAnalysis as mda
>>> import numpy as np
>>> universe = mda.Universe.empty(1, trajectory=True)
>>> universe.load_new(np.array([[[1.0, 1.0, 1.0]]]), format='MEMORY',
...                   dimensions=np.array([[4.0, 4.0, 4.0, 90.0,
...                                         90.0, 90.0]]))
<Universe with 1 atoms>
>>> edges = {key: np.array([-2.0, 0.0, 2.0]) for key in 'xyz'}
>>> edges['r'] = np.array([0.0, 2.0, 4.0])
>>> analysis = SpatialHistograms(
...     {'Mon': universe.atoms}, edges, geometry='cubic',
...     block_frames=1).run()
>>> with tempfile.TemporaryDirectory() as tmp:
...     paths = analysis.save(tmp, 'N1ens1-all')
...     len(paths), paths[0].name, paths[-1].name
(13, 'N1ens1-all-rEdgeMon.npy', 'N1ens1-all-blockFrames.npy')
polyphys.probe.histograms.histogram_edges(spec, parser)[source]#

The bin edges of one whole’s histograms and maps.

The bin sizes are the spec’s, resolved for this whole by resolve(); the ranges follow the geometry, so that every position inside the confinement falls between the edges:

  • Cylinder: 'r' over \([0, (D + a_w) / 2]\), the wall surface, with ‘nonnegative’ bins; 'z' over \([-Z / 2, Z / 2]\) and 'x', 'y' over \([-(D + a_w) / 2, (D + a_w) / 2]\) with ‘ordinary’ bins; 'theta' over \([-\pi, \pi]\) with ‘periodic’ bins.

  • Cube: 'r' over \([0, \sqrt{3} L / 2]\), the corner, with ‘nonnegative’ bins; 'x', 'y', 'z' over \([-L / 2, L / 2]\) with ‘ordinary’ bins.

The research code ranged 'r', 'x', and 'y' of a cylinder over \(D / 2\) and 'r' of a cube over \(L / 2\), and silently dropped the positions beyond them; the maintainer extended the ranges on 2026-11-04, since SpatialHistograms raises on such a position instead.

Added in version 0.7.0.

Parameters:
  • spec (polyphys.spec.ProbeSpec) – The study’s probe spec, whose bin_sizes holds every key that geometry needs: 'r', 'z', 'theta', 'x', 'y' for a cylinder; 'r', 'x', 'y', 'z' for a cube.

  • parser (polyphys.manage.parser.ParserBase) – The whole’s parser, with dcyl and lcyl or lcube.

Returns:

The edges keyed by direction, each float64 and increasing, with n_bins + 1 entries, in the order the geometry needs them.

Return type:

dict[str, numpy.ndarray]

Raises:

ValueError – If spec.bin_sizes lacks a key the geometry needs, or if a resolved bin size is not a finite positive number.

Notes

\(O(B)\) time and space for \(B\) edges in all.

Examples

>>> 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', 'dcyl', 'dcrowd'),
...     species_sizes={'Mon': 'dmon', 'Crd': 'dcrowd'},
...     tseries_properties=('gyrTMon',))
>>> spec = ProbeSpec(
...     project, {'Mon': 'resid 1', 'Crd': 'resid 0'}, 'Mon', ('gyrT',),
...     unwrap=False, histogram_species=('Mon', 'Crd'), block_frames=100,
...     bin_sizes={'r': 0.5, 'z': 1.0, 'theta': np.pi / 2, 'x': 0.5,
...                'y': 0.5})
>>> whole = ChainCyl(
...     'N20r2.5lz5ac1nc0dt0.005bdump1adump1ens1', 'whole',
...     'all')
>>> edges = histogram_edges(spec, whole)
>>> list(edges)
['r', 'z', 'theta', 'x', 'y']
>>> edges['r']
array([0. , 0.5, 1. , 1.5, 2. , 2.5])
>>> edges['z'][[0, -1]], edges['theta'].size
(array([-5.,  5.]), 5)