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#
SpatialHistograms, the per-frame and per-block binning.histogram_edges(), the bin edges of a whole.
Dependencies#
Python standard library: math, pathlib, typing.
MDAnalysis 2.8 or later, through the
mdaextra:AnalysisBaseandResultsGroup.polyphys.analyze.measurer: the histogram helpersfixedsize_bins(),radial_histogram(),radial_cyl_histogram(),axial_histogram(),azimuth_cyl_histogram(), andplanar_cartesian_histogram().polyphys.spec:ProbeSpecandRecenterT.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#
- \(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, andlcube, 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
|
The bin edges of one whole's histograms and maps. |
Classes
|
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._ProbeAnalysisThe 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
resultsandsave()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 ashistogram_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 thezaxis, 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 duringrun().
- Variables:
~MDAnalysis.core.groups.AtomGroup – The species, a copy of the mapping given.
edges (
Mappingofstrtonumpy.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) – Afterrun(), for each speciesSand directiondof the geometry,dHistTS, int64(n_frames, n_bins), the counts of frameiin rowi, anddHistS, int64(n_bins,), their sum over the frames; for each planepinxy,xz,yz,pHistBlockS, float64(n_blocks, n_a, n_b), the mean map of each block, rows along the plane’s first axis, andpHistS, float64(n_a, n_b), the counts summed over the frames; andblockFrames, int64(n_blocks,), the frames in each block.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 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, duringrun(), 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
zin 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 withradial_cyl_histogram(),axial_histogram(), andazimuth_cyl_histogram()in a cylinder,radial_histogram()in a cube, andplanar_cartesian_histogram()in each plane, with thexzmap transposed to rows alongxas 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’snp.histogramdropped such a position silently, and did not wrap.Blocks are numbered over the frames of the whole run in the order
run()visits them, whateverstart,stop,step, orframesselect, so that a run split across workers gives the same blocks as a serial one:_setup_framesrecords the run’s frame count before the split and_computeeach worker’s offset into it. Each worker accumulates the block sums and frame counts of its own frames, which_get_aggregatoradds (ResultsGroup.ndarray_sum), and its per-frame rows, which it concatenates (ResultsGroup.ndarray_vstack);_concludethen 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.histogramandnp.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 inspec.selections; the edges arehistogram_edges()’s; the geometry, block length, and recentering 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, withhistogram_species,bin_sizes, andblock_framesset.parser (
polyphys.manage.parser.ParserBase) – The whole’s parser, for the edges.verbose (
bool) – Whether to show a progress bar duringrun().
- Returns:
The analysis, not yet run.
- Return type:
- 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')
- save(save_to, name)[source]#
Save the edges, histograms, and maps under the research code’s names.
For each species
Sand directiond:<name>-dEdgeS.npy,<name>-dHistS.npy(summed over the frames), and<name>-dHistTS.npy(per frame); for each Cartesian axisc:<name>-cEdge.npy; for each planepand 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:
- 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, sinceSpatialHistogramsraises on such a position instead.Added in version 0.7.0.
- Parameters:
spec (
polyphys.spec.ProbeSpec) – The study’s probe spec, whosebin_sizesholds every key thatgeometryneeds:'r','z','theta','x','y'for a cylinder;'r','x','y','z'for a cube.parser (
polyphys.manage.parser.ParserBase) – The whole’s parser, withdcylandlcylorlcube.
- Returns:
The edges keyed by direction, each float64 and increasing, with
n_bins + 1entries, in the order the geometry needs them.- Return type:
- Raises:
ValueError – If
spec.bin_sizeslacks 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)