polyphys.analyze.density#
polyphys.analyze.density#
The polyphys.analyze.density module turns a histogram of bead centers
along one coordinate into two profiles: the local number density, which
counts centers per bin volume, and the local volume fraction, which counts
the volume the beads occupy. The second is the harder one, because a bead of
finite size reaches into the bins next to the one that holds its center.
Every routine is a NumPy or SciPy kernel on arrays: reading frames, binning
positions, and averaging over frames are the caller’s work, and the only
geometric inputs are the bin edges, the bead diameter, and the box lengths.
Notation#
- \(x\)
The binned coordinate: the axial position \(z\) of a cylinder, or the distance \(r\) from the axis of a cylinder or from a point in a cube. Lengths are in the caller’s unit, the monomer diameter in this package.
- \(e_0 < e_1 < \dots < e_B\)
The bin edges,
edges; bin \(i\) is \([e_i, e_{i+1})\), so there are \(B\) bins,n_bins.- \(V_i\)
The volume of bin \(i\),
volumes: a slab \(\pi D^2 (e_{i+1} - e_i) / 4\), a cylindrical shell \(\pi L (e_{i+1}^2 - e_i^2)\), or a spherical shell \(4 \pi (e_{i+1}^3 - e_i^3) / 3\).- \(H_i\), \(F\)
The number of bead centers counted in bin \(i\) over \(F\) frames,
countsandn_frames.- \(\rho_i = H_i / (F V_i)\)
The local number density of bin \(i\),
rho, in beads per cubic length unit.- \(a\), \(R_b = a / 2\), \(v = \pi a^3 / 6\)
The bead diameter
bead_diameter, its radius, and its volume.- \(s(x \to j)\)
The share kernel: the volume of one bead whose center is at coordinate \(x\) that lies inside bin \(j\). It sums to \(v\) over the bins when the bead is inside the domain.
- \(S_{ij}\)
The share matrix,
share: the volume of a test bead centered in bin \(i\) that lies in bin \(j\), with the bead at the bin center (shares='center') or averaged over the bin (shares='average').- \(\phi_i = \sum_j S_{ij} \rho_j\)
The local volume fraction of bin \(i\),
phi, dimensionless.
Contents#
bin_volumes(): the closed-form bin volumes.share_matrix(): the share matrix, built once per(edges, bead_diameter).sphere_cylinder_intersection(): the volume of a ball inside a coaxial cylinder, the kernel of the radial direction in a cylinder.number_density()andvolume_fraction(): the two profiles from counts, volumes, and the share matrix.normalize_profile(): an explicit normalization.density_profiles()andProfiles: the one-call form.
The volume fraction#
The volume fraction field is the indicator of “inside some bead”, and in the
continuum its average over a region is the density convolved with a ball of
radius \(R_b\). With the density piecewise constant on the bins, the
value at a point \(x\) is \(\sum_j \rho_j\, s(x \to j)\). The
research code evaluated this at the bin center, \(\phi_i = \sum_j
\rho_j\, s(c_i \to j)\) (thesis, appendix “Discrete local distributions
in the cylindrical coordinate system”, eq. 7); shares='center' keeps
that form. The default, shares='average', averages the kernel over the
bead’s position in its bin with the bin’s own measure,
which is the exact bin average under the one assumption already made for \(\rho\). Because the indicator is symmetric in the two points, \(V_i\, \bar{s}(i \to j) = V_j\, \bar{s}(j \to i)\), and from that one identity the averaged form conserves the total bead volume, \(\sum_i V_i \phi_i = \sum_j H_j v / F\), and returns \(\phi = \rho v\) for a uniform fluid, both to round-off. The centered form gets the second right and misses the first by \(O(h^2)\) along \(r\): up to 2.65 % of a bead volume for cylindrical shells and 7.27 % for spherical shells at a bin width \(h = a / 4\), and 0.71 % and 1.88 % at \(a / 8\), largest in the innermost bins. Both forms return \(\rho v\) only in the bins whose test bead stays inside the last edge; in the outermost radial bins the bead reaches past it and the row sums of the share matrix fall short of \(v\).
The kernels#
A slab’s kernel is a spherical segment
(spherical_segment()), and the averaged slab
kernel is its second antiderivative in closed form. A spherical shell’s kernel
is a difference of sphere-sphere intersection volumes
(sphere_sphere_intersection()). A cylindrical
shell’s kernel is a difference of ball-in-cylinder volumes,
sphere_cylinder_intersection(), which has no closed form and is
integrated numerically (intersection='exact'); the research code used the
sphere-sphere volume in its place (intersection='sphere'), whose error is
about \(0.047\, a / R\) of a bead volume at an edge of radius \(R\),
with \(a = 2 R_b\) the bead diameter, first order and independent of the
bin width. The shells’ averaged kernels are integrated by Gauss-Legendre rules
on the pieces between the kernels’ breakpoints, exactly where the integrand is
polynomial.
The axial direction of a cylinder is periodic: a bead that reaches past one end of the domain reaches into the bins at the other end. The radial directions are not.
Conventions the kernels do not fix#
bin_volumes() takes the slab diameter the caller passes.
density_profiles() passes \(D_\mathrm{eff} = D - a\), the
diameter of the region a bead center can reach, so that a uniform crowder
fluid returns the bulk volume fraction as the parsers define it,
\(\phi_c = N_c v_c / (\pi D_\mathrm{eff}^2 L / 4)\). Along
\(r\) no such choice arises. A spherical shell beyond half the box
length of a periodic cube overstates the volume inside the box, so
bin_volumes() warns there when it is told the box length.
Dependencies#
numpy and scipy.sparse.
polyphys.analyze.measurer:spherical_segment()andsphere_sphere_intersection().
References
Weisstein, Eric W. “Spherical Segment.” From MathWorld–A Wolfram Web Resource, eq. 14. https://mathworld.wolfram.com/SphericalSegment.html
Weisstein, Eric W. “Sphere-Sphere Intersection.” From MathWorld–A Wolfram Web Resource, eq. 16. https://mathworld.wolfram.com/Sphere-SphereIntersection.html
Weisstein, Eric W. “Circle-Circle Intersection.” From MathWorld–A Wolfram Web Resource, eq. 15. https://mathworld.wolfram.com/Circle-CircleIntersection.html
A. H. Sadeghi Isfahani, PhD thesis, University of Waterloo (2024), appendix “Discrete local distributions in the cylindrical coordinate system”, for the centered form.
C. Jeon, C. Hyeon, Y. Jung, and B.-Y. Ha, Soft Matter 12, 9786-9796 (2016), https://doi.org/10.1039/c6sm01924b, for the use of these profiles in the density sum rule (
polyphys.analyze.sumrule).
Added in version 0.6.0.
Module Attributes
How the test bead sits in its bin, averaged over the bin or at its center as in the research code. |
|
The kernel of a cylindrical shell, the ball-in-cylinder volume or the sphere-sphere volume the research code used in its place. |
|
No normalization, division by the sum over bins, or division by the integral against the bin volumes. |
Functions
|
Compute the volume of each bin along one coordinate, in closed form. |
|
Compute the local number density and volume fraction of one species in one call. |
|
Normalize a profile along its bins. |
|
Compute the local number density from bin counts and bin volumes. |
|
Build the share matrix: the volume of a test bead centered in each bin that lies in each other bin. |
|
Compute the volume of a ball that lies inside a cylinder whose axis passes at distance d from the ball's center. |
|
Compute the local volume fraction from the number density and the share matrix. |
Classes
|
The local number density and volume fraction of one species along one coordinate. |
- polyphys.analyze.density.IntersectionMode#
The kernel of a cylindrical shell, the ball-in-cylinder volume or the sphere-sphere volume the research code used in its place.
Added in version 0.6.0.
alias of
Literal[‘exact’, ‘sphere’]
- polyphys.analyze.density.NormalizeMode#
No normalization, division by the sum over bins, or division by the integral against the bin volumes.
Added in version 0.6.0.
alias of
Literal[‘none’, ‘sum’, ‘integral’]
- class polyphys.analyze.density.Profiles(rho, phi, volumes)[source]#
Bases:
objectThe local number density and volume fraction of one species along one coordinate.
Added in version 0.6.0.
- Variables:
rho (
numpy.ndarray) – The local number density, shape(n_bins,)or(n_frames, n_bins), in beads per cubic length unit, normalized as asked.phi (
numpy.ndarray) – The local volume fraction, the same shape, dimensionless, normalized as asked.volumes (
numpy.ndarray) – The bin volumes, shape(n_bins,).
- Parameters:
rho (NDArray[float64])
phi (NDArray[float64])
volumes (NDArray[float64])
- phi: numpy.typing.NDArray[numpy.float64]#
- rho: numpy.typing.NDArray[numpy.float64]#
- volumes: numpy.typing.NDArray[numpy.float64]#
How the test bead sits in its bin, averaged over the bin or at its center as in the research code.
Added in version 0.6.0.
alias of
Literal[‘average’, ‘center’]
- polyphys.analyze.density.bin_volumes(edges, geometry, direction, *, lcyl=None, dcyl=None, lcube=None)[source]#
Compute the volume of each bin along one coordinate, in closed form.
- Parameters:
edges (
numpy.typing.ArrayLike) – The bin edges, shape(n_bins + 1,), finite and strictly increasing; non-negative for a radial direction.geometry (
typing.Literal['cubic','cylindrical']) –'cylindrical'or'cubic'.direction (
typing.Literal['x','y','z','r','theta']) –'r'for shells, or'z'for the slabs of a cylinder.lcyl (
float|None) – The cylinder length, needed for('cylindrical', 'r').dcyl (
float|None) – The diameter of the slab, needed for('cylindrical', 'z'). The kernel takes it as given;density_profiles()passes the effective diameter \(D - a\).lcube (
float|None) – The side of the periodic cube, for('cubic', 'r'). When given, an outermost edge beyond half the side by more than one bin width raises a warning, since such a shell overstates the volume inside the box; the volumes are still returned.
- Returns:
The bin volumes, shape
(n_bins,), in the cube of the length unit: \(4\pi (e_{i+1}^3 - e_i^3) / 3\) for a spherical shell, \(\pi L (e_{i+1}^2 - e_i^2)\) for a cylindrical shell, and \(\pi D^2 (e_{i+1} - e_i) / 4\) for a slab.- Return type:
- Raises:
ValueError – If edges breaks its contract, if the pair is not supported, or if the box length the pair needs is missing or not positive.
- Warns:
UserWarning – If lcube is given and
edges[-1] > lcube / 2 + max bin width.
Notes
Time and space are \(O(n_\mathrm{bins})\). The half-side warning follows MAICoS’s
DensitySphere, which warns when itsrmaxexceeds half the smallest box vector and computes the shell volumes regardless.Examples
>>> import numpy as np >>> from polyphys.analyze.density import bin_volumes >>> np.round(bin_volumes([0, 1, 2], 'cubic', 'r'), 5) array([ 4.18879, 29.32153]) >>> np.round(bin_volumes([0, 1, 2], 'cylindrical', 'r', lcyl=3), 5) array([ 9.42478, 28.27433]) >>> np.round(bin_volumes([-1, 0, 1], 'cylindrical', 'z', dcyl=2), 5) array([3.14159, 3.14159])
Added in version 0.6.0.
- polyphys.analyze.density.density_profiles(counts, edges, bead_diameter, geometry, direction, *, n_frames=1, n_particles=None, lcyl=None, dcyl=None, lcube=None, shares='average', intersection='exact', normalize='none')[source]#
Compute the local number density and volume fraction of one species in one call.
- Parameters:
counts (
numpy.typing.ArrayLike) – The bead centers counted per bin, shape(n_bins,)summed over the frames or(n_frames, n_bins); seenumber_density().edges (
numpy.typing.ArrayLike) – The bin edges, shape(n_bins + 1,).bead_diameter (
float) – The bead diameter \(a\) of the species.geometry (
typing.Literal['cubic','cylindrical']) –'cylindrical'or'cubic'.direction (
typing.Literal['x','y','z','r','theta']) –'r'or'z'.n_frames (
int) – The number of frames summed into counts.n_particles (
int|None) – The number of beads of the species, to check that none was lost.lcyl (
float|None) – The cylinder length and diameter and the cube side, asbin_volumes()needs them. Along'z'the slabs take the effective diameterdcyl - bead_diameter, the diameter of the region a bead center can reach, so that a uniform fluid returns the bulk volume fraction as the parsers define it.dcyl (
float|None) – The cylinder length and diameter and the cube side, asbin_volumes()needs them. Along'z'the slabs take the effective diameterdcyl - bead_diameter, the diameter of the region a bead center can reach, so that a uniform fluid returns the bulk volume fraction as the parsers define it.lcube (
float|None) – The cylinder length and diameter and the cube side, asbin_volumes()needs them. Along'z'the slabs take the effective diameterdcyl - bead_diameter, the diameter of the region a bead center can reach, so that a uniform fluid returns the bulk volume fraction as the parsers define it.shares (
typing.Literal['average','center']) – Seeshare_matrix().intersection (
typing.Literal['exact','sphere']) – Seeshare_matrix().normalize (
typing.Literal['none','sum','integral']) – Applied to both profiles; seenormalize_profile(). Leave it at'none'for profiles that feedpolyphys.analyze.sumrule.
- Returns:
The two profiles and the bin volumes.
- Return type:
- Raises:
ValueError – As the four functions it calls raise, and if
dcyl <= bead_diameteralong'z'.
Notes
This builds the share matrix for one call. For many wholes or frames on the same bins, call
share_matrix()once andnumber_density()andvolume_fraction()per profile. Time is that ofshare_matrix()plus \(O(n_\mathrm{frames} \, n_\mathrm{bins} \, k)\).Examples
Three beads of diameter 1 per slab in a cylinder of effective diameter 2 (so
dcyl = 3): the slab area is \(\pi\), the density \(3 / \pi\), and the volume fraction \((3 / \pi)(\pi / 6) = 1 / 2\):>>> import numpy as np >>> from polyphys.analyze.density import density_profiles >>> out = density_profiles([3, 3, 3, 3], [0, 1, 2, 3, 4], 1.0, ... 'cylindrical', 'z', dcyl=3.0, n_particles=12) >>> np.round(out.rho, 6) array([0.95493, 0.95493, 0.95493, 0.95493]) >>> np.round(out.phi, 12) array([0.5, 0.5, 0.5, 0.5])
Added in version 0.6.0.
- polyphys.analyze.density.normalize_profile(profile, mode, volumes=None)[source]#
Normalize a profile along its bins.
- Parameters:
profile (
numpy.typing.ArrayLike) – A profile, shape(n_bins,)or(n_frames, n_bins).mode (
typing.Literal['none','sum','integral']) –'none'returns a copy;'sum'divides each row by its sum over the bins, as the research code did;'integral'divides each row by \(\sum_i p_i V_i\), so that the result integrates to 1 against the bin volumes.volumes (
numpy.typing.ArrayLike|None) – The bin volumes, shape(n_bins,); needed for'integral'.
- Returns:
The normalized profile, the same shape as profile.
- Return type:
- Raises:
ValueError – If mode is unknown, if
'integral'is asked for without volumes or with volumes of the wrong shape, or if a row’s normalizer is zero.
Notes
A normalized profile must not be passed to
polyphys.analyze.sumrule, whose species sum needs the physical scale of every profile. Time and space are \(O(n_\mathrm{frames} \, n_\mathrm{bins})\).Examples
>>> from polyphys.analyze.density import normalize_profile >>> normalize_profile([1.0, 3.0], 'sum') array([0.25, 0.75]) >>> normalize_profile([1.0, 3.0], 'integral', volumes=[2.0, 2.0]) array([0.125, 0.375])
Added in version 0.6.0.
- polyphys.analyze.density.number_density(counts, volumes, *, n_frames=1, n_particles=None)[source]#
Compute the local number density from bin counts and bin volumes.
- Parameters:
counts (
numpy.typing.ArrayLike) – The bead centers counted per bin, shape(n_bins,)summed over the frames, or(n_frames, n_bins)with one row per frame (then leave n_frames at 1). Non-negative.volumes (
numpy.typing.ArrayLike) – The bin volumes, shape(n_bins,), positive; seebin_volumes().n_frames (
int) – The number of frames the counts were summed over.n_particles (
int|None) – The number of beads of this species. When given, each row of counts must sum ton_frames * n_particles, so that no bead was dropped when the positions were binned.
- Returns:
\(\rho = H / (F V)\), the same shape as counts, in beads per cubic length unit.
- Return type:
- Raises:
ValueError – If the shapes do not match, a count is negative, a volume is not positive, n_frames is not positive, or the counts do not sum to
n_frames * n_particles.
Notes
Time and space are \(O(n_\mathrm{frames} \, n_\mathrm{bins})\).
Examples
>>> from polyphys.analyze.density import number_density >>> number_density([2, 4], [1.0, 2.0], n_frames=2) array([1., 1.]) >>> number_density([2, 4], [1.0, 2.0], n_frames=2, n_particles=3) array([1., 1.])
Added in version 0.6.0.
Build the share matrix: the volume of a test bead centered in each bin that lies in each other bin.
- Parameters:
edges (
numpy.typing.ArrayLike) – The bin edges, shape(n_bins + 1,), finite and strictly increasing; non-negative for a radial direction.bead_diameter (
float) – The bead diameter \(a\), positive; along the periodic'z'it must be smaller than the domain length.geometry (
typing.Literal['cubic','cylindrical']) –'cylindrical'or'cubic'.direction (
typing.Literal['x','y','z','r','theta']) –'r'for shells, or'z'for the periodic slabs of a cylinder.shares (
typing.Literal['average','center']) –'average'averages the test bead over its bin with the bin’s measure;'center'places it at the bin center, as the research code did.intersection (
typing.Literal['exact','sphere']) – The kernel of a cylindrical shell:sphere_cylinder_intersection()or the sphere-sphere volume the research code used. Ignored for the other pairs, whose kernels are exact closed forms.
- Returns:
S, shape(n_bins, n_bins), withS[i, j]the volume of a test bead of biniinside binj;S @ rhois the volume fraction. Each row has abouta / h + 2nonzero entries. Along a radial direction the row sum falls short of the bead volume in the outermost bins, where the bead reaches past the last edge.- Return type:
- Raises:
ValueError – If edges breaks its contract, if the pair is not supported, if bead_diameter is not positive or does not fit the period, or if shares or intersection is not a known mode.
Notes
The nonzero band is found with
numpy.searchsorted(); the entries are evaluated as the module docstring describes. Time is \(O(n_\mathrm{bins} \, k)\) kernel evaluations with \(k \approx a / h + 2\) the band width (times the Gauss nodes for'average', and times the axial nodes for'exact'), and space is \(O(n_\mathrm{bins} \, k)\). The matrix depends on the edges and the bead only, so build it once per space and reuse it for every whole and every frame.With
shares='average'the matrix satisfies \(V_i S_{ij} = V_j S_{ji}\), which makesvolume_fraction()conserve the total bead volume and return \(\rho v\) for a uniform fluid, both to round-off. Withshares='center'the row sums are still the bead volume, but the symmetry, and with it the conservation, holds only to \(O(h^2)\) along \(r\). The symmetry also needs the kernel to be the true indicator, so withintersection='sphere'it holds only to \(O(a / R)\).Examples
Four periodic slabs of width 1 and a bead of diameter 1: at the bin center the bead lies wholly in its own slab, so each row is the bead volume \(\pi / 6\) on the diagonal:
>>> import numpy as np >>> from polyphys.analyze.density import share_matrix >>> s = share_matrix([0, 1, 2, 3, 4], 1.0, 'cylindrical', 'z', ... shares='center') >>> np.round(s.toarray(), 4) array([[0.5236, 0. , 0. , 0. ], [0. , 0.5236, 0. , 0. ], [0. , 0. , 0.5236, 0. ], [0. , 0. , 0. , 0.5236]])
Averaged over the bin, the bead reaches into both neighbors, the last slab’s into the first through the periodic boundary, and every row still sums to \(\pi / 6\):
>>> s = share_matrix([0, 1, 2, 3, 4], 1.0, 'cylindrical', 'z') >>> np.allclose(s.sum(axis=1), np.pi / 6) True >>> bool(s[3, 0] > 0 and s[3, 0] == s[3, 2]) True
Added in version 0.6.0.
- polyphys.analyze.density.sphere_cylinder_intersection(r_sphere, r_cylinder, d)[source]#
Compute the volume of a ball that lies inside a cylinder whose axis passes at distance d from the ball’s center.
- Parameters:
- Returns:
The volume of the ball inside the cylinder.
- Return type:
- Raises:
ValueError – If r_sphere is not positive or d is negative.
Notes
The ball is sliced by planes normal to the axis. At height \(z\) the slice is a disc of radius \(\sqrt{R_b^2 - z^2}\) whose center is \(d\) from the axis, and the cylinder cuts the plane in a disc of radius \(R\) about the axis; the slice’s share is the lens area of the two discs (MathWorld, Circle-Circle Intersection, eq. 15), and the volume is its integral over \(z\). The integral has no closed form, so it is a Gauss-Legendre rule with 32 nodes on each of the three pieces between the heights where the lens changes regime; the result agrees with an adaptive quadrature to about \(10^{-8}\) of the ball’s volume. Time is \(O(1)\).
Two limits are exact: the ball lies inside the cylinder when \(R \ge d + R_b\), and outside it when \(R \le d - R_b\). On the axis, \(d = 0\), the volume inside a cylinder of radius \(R < R_b\) is \(\tfrac{4\pi}{3}\,[R_b^3 - (R_b^2 - R^2)^{3/2}]\).
Examples
>>> from polyphys.analyze.density import sphere_cylinder_intersection >>> round(sphere_cylinder_intersection(1.0, 2.0, 0.5), 10) 4.1887902048 >>> sphere_cylinder_intersection(1.0, 2.0, 3.5) 0.0
On the axis with a narrower cylinder, the closed form above gives \(\tfrac{4\pi}{3}(1 - 0.8^3)\):
>>> round(sphere_cylinder_intersection(1.0, 0.6, 0.0), 6) 2.04413 >>> round(4 * 3.141592653589793 / 3 * (1 - 0.8**3), 6) 2.04413
Added in version 0.6.0.
- polyphys.analyze.density.volume_fraction(rho, share)[source]#
Compute the local volume fraction from the number density and the share matrix.
- Parameters:
rho (
numpy.typing.ArrayLike) – The local number density, shape(n_bins,)or(n_frames, n_bins); seenumber_density().share (
scipy.sparse.csr_array) – The share matrix of the same bins and the bead’s diameter; seeshare_matrix().
- Returns:
\(\phi_i = \sum_j S_{ij} \rho_j\), the same shape as rho, dimensionless.
- Return type:
- Raises:
ValueError – If rho is not one- or two-dimensional, or its last axis does not match share.
Notes
One sparse matrix-vector product per row of rho: time \(O(n_\mathrm{frames} \, n_\mathrm{bins} \, k)\) with \(k\) the band width, space \(O(n_\mathrm{frames} \, n_\mathrm{bins})\).
Examples
A uniform density through the averaged share matrix returns \(\rho v\) in every slab, here \((3 / \pi) (\pi / 6) = 1/2\):
>>> import numpy as np >>> from polyphys.analyze.density import share_matrix, volume_fraction >>> s = share_matrix([0, 1, 2, 3, 4], 1.0, 'cylindrical', 'z') >>> np.round(volume_fraction(np.full(4, 3 / np.pi), s), 12) array([0.5, 0.5, 0.5, 0.5])
Added in version 0.6.0.