polyphys.analyze.measurer#

polyphys.analyze.measurer#

The polyphys.analyze.measurer module measures one frame of positions: distances, sizes, and spans of a group of particles, the statistics of independent samples, the volumes of a bead cut by planes or by a sphere, and fixed-width bins and histograms of one frame.

Contents#

Core geometric and structural measurements: apply_pbc_orthogonal(), pair_distance(), end_to_end(), transverse_size(), max_distance(), and fsd().

Summary statistics: simple_stats() and sem().

Advanced geometric calculations: sphere_sphere_intersection() and spherical_segment().

Binning and histogram processing: create_bin_edge_and_hist(), fixedsize_bins(), radial_histogram(), radial_cyl_histogram(), axial_histogram(), azimuth_cyl_histogram(), and planar_cartesian_histogram().

Number-density and volume-fraction conversions live in polyphys.manage.utils.

References

For Feret’s statistical diameter:

  • Wang Y, Teraoka I, Hansen FY, Peters GH, Hassager O. “A Theoretical Study of the Separation Principle in Size Exclusion Chromatography.” Macromolecules 2010, 43, 3, 1651-1659. https://doi.org/10.1021/ma902377g

For spherical segment calculations:

For sphere-sphere intersection:

Functions

apply_pbc_orthogonal(pbc_lengths, ...)

Write the box length and its inverse of each axis in pbc into the given arrays.

axial_histogram(positions, edges, dim)

Bin signed coordinates along the selected axis dim.

azimuth_cyl_histogram(positions, edges, dim)

Bin the azimuthal angles of the positions about the axis along dim, in radians.

create_bin_edge_and_hist(bin_size, lmin, lmax)

Create bin edges of a fixed width and a zero-filled histogram.

end_to_end(positions)

Compute the end-to-end distance of a chain, the distance between its first and its last bead.

fixedsize_bins(bin_size, lmin, lmax[, ...])

Generate bin edges and zero-filled histogram arrays with consistent bin width.

fsd(positions, axis)

Compute the span of the positions along the selected axis.

max_distance(positions)

Compute the extent of the positions along each Cartesian axis.

pair_distance(positions[, pbc])

Compute the displacement vector from the first particle to the second, optionally under the minimum image convention.

planar_cartesian_histogram(positions, edges, dim)

Compute a two-dimensional histogram in the plane perpendicular to dim, in Cartesian coordinates.

radial_cyl_histogram(positions, edges, dim)

Bin the distances of the positions from the axis along dim, the cylindrical radial coordinate.

radial_histogram(positions, edges)

Bin the distances of the positions from the origin, the spherical radial coordinate.

sem(data)

Compute the standard error of the mean (SEM) of independent samples.

simple_stats(entity, data)

Compute basic statistics (mean, variance, SEM) for a physical entity.

sphere_sphere_intersection(r1, r2, d)

Compute the volume of intersection between two spheres.

spherical_segment(r, a, b)

Compute the volume of a spherical segment defined by two parallel planes.

transverse_size(positions, axis)

Compute the transverse size of a group of atoms, twice their mean distance from their center in the plane perpendicular to axis.

polyphys.analyze.measurer.apply_pbc_orthogonal(pbc_lengths, pbc_lengths_inverse, pbc)[source]#

Write the box length and its inverse of each axis in pbc into the given arrays.

The arrays are modified in place and also returned; an axis not in pbc keeps its value.

Parameters:
  • pbc_lengths (numpy.ndarray) – The box length along each axis, shape (n_dim,), typically (3,), in the length unit of the positions; modified in place.

  • pbc_lengths_inverse (numpy.ndarray) – The inverse box length along each axis, the same shape; modified in place.

  • pbc (typing.Dict[typing.Literal[0, 1, 2], float]) – Axis indices (0=x, 1=y, 2=z) mapped to their box lengths, positive.

Return type:

typing.Tuple[numpy.ndarray, numpy.ndarray]

Returns:

Raises:
  • ZeroDivisionError – If any specified length is zero, which would result in division by zero.

  • ValueError – If any specified length is negative, which is physically invalid for box dimensions.

Examples

>>> pbc_lengths = np.zeros(3)
>>> pbc_lengths_inverse = np.zeros(3)
>>> pbc = {0: 10.0, 2: 20.0}
>>> apply_pbc_orthogonal(pbc_lengths, pbc_lengths_inverse, pbc)
(array([10.,  0., 20.]), array([0.1 , 0.  , 0.05]))
polyphys.analyze.measurer.axial_histogram(positions, edges, dim)[source]#

Bin signed coordinates along the selected axis dim.

Parameters:
  • positions (numpy.ndarray) – Array of shape (n_atoms, n_dim) containing atom positions, in any order.

  • edges (numpy.ndarray) – A monotonically increasing array of bin edges, including the rightmost edge. The last bin includes its right edge. Every position must lie within the outermost edges: a coordinate along a periodic axis must already be wrapped into the box, since this function does not wrap.

  • dim (typing.Literal[0, 1, 2]) – The longitudinal axis (0=x, 1=y, 2=z); see polyphys.manage.types.

Returns:

hist – The counts per bin, shape (len(edges) - 1,), integer.

Return type:

numpy.ndarray

Raises:
  • ValueError – If dim is not one of {0, 1, 2}.

  • ValueError – If the positions array is not two-dimensional.

  • ValueError – If any position falls outside the outermost edges. np.histogram would drop it silently; here a dropped position means wrong edges or an unwrapped coordinate, so it is an error.

Examples

>>> positions= np.array([[1, 2, 3], [2, 3, 4], [1, 2, 2]])
>>> edges = np.array([0, 1, 2, 3, 4, 5])
>>> axial_histogram(positions, edges, dim=0)
array([0, 2, 1, 0, 0])
polyphys.analyze.measurer.azimuth_cyl_histogram(positions, edges, dim)[source]#

Bin the azimuthal angles of the positions about the axis along dim, in radians.

Parameters:
  • positions (numpy.ndarray) – Array of shape (n_atoms, n_dim) containing atom positions, in any order.

  • edges (numpy.ndarray) – A monotonically increasing array of bin edges, in radians, including the rightmost edge; the angles lie in [-pi, pi], as numpy.arctan2 returns them. The last bin includes its right edge. Every position must lie within the outermost edges: a coordinate along a periodic axis must already be wrapped into the box, since this function does not wrap.

  • dim (typing.Literal[0, 1, 2]) – The longitudinal axis (0=x, 1=y, 2=z); see polyphys.manage.types.

Returns:

hist – The counts per bin, shape (len(edges) - 1,), integer.

Return type:

numpy.ndarray

Raises:
  • ValueError – If dim is not one of {0, 1, 2}.

  • ValueError – If the positions array is not two-dimensional.

  • ValueError – If any position falls outside the outermost edges. np.histogram would drop it silently; here a dropped position means wrong edges or an unwrapped coordinate, so it is an error.

Examples

>>> positions= np.array([[1, 0, 0], [0, 1, 0], [-1, 0, 0]])
>>> edges = np.linspace(-np.pi, np.pi, 5)
>>> azimuth_cyl_histogram(positions, edges, dim=2)
array([0, 0, 1, 2])
polyphys.analyze.measurer.create_bin_edge_and_hist(bin_size, lmin, lmax, output=None)[source]#

Create bin edges of a fixed width and a zero-filled histogram.

The edges start at lmin and step by bin_size up to the first edge at or beyond lmax, so there are n_bins = ceil((lmax - lmin) / bin_size) bins of width bin_size. When the range is a whole number of bins up to the relative tolerance _BIN_COUNT_RTOL (1e-9), the last edge is exactly lmax; otherwise it exceeds lmax by less than one bin.

Parameters:
  • bin_size (float) – Size of each bin.

  • lmin (float) – Lower bound of the system in the direction of interest.

  • lmax (float) – Upper bound of the system in the direction of interest.

  • output (typing.Optional[str]) – Filename (including filepath) to which bin edges array is saved. A .npy extension will be appended to the filename if it does not already have one.

Returns:

  • bin_edges : Array of bin edges, shape (n_bins + 1,), equal to lmin + bin_size * k for k = 0, ..., n_bins.

  • hist : Zero-initialized histogram of dtype np.int64 and shape (n_bins,). The 64-bit integer type keeps per-frame counts accumulated in place (hist += np.histogram(...)[0]) from overflowing.

Return type:

typing.Tuple[numpy.ndarray, numpy.ndarray]

Raises:

ValueError – If lmin is not less than lmax.

Notes

The .npy extension is handled internally by np.save.

The edges come from np.linspace, so their number is exactly n_bins + 1; a float-step np.arange can return one edge too many when bin_size is not exactly representable (for example 0.3). The bin count treats a ratio within 1e-9 of a whole number as that whole number; see _BIN_COUNT_RTOL for why.

Time and space are O(n_bins).

Examples

>>> edges, hist =         create_bin_edge_and_hist(bin_size=1.0, lmin=0.0, lmax=5.0)
>>> edges
array([0., 1., 2., 3., 4., 5.])
>>> hist
array([0, 0, 0, 0, 0])

A step that is not exactly representable still gives one edge per bin plus one, ending exactly at lmax:

>>> edges, hist = create_bin_edge_and_hist(0.3, -6.0, 6.0)
>>> print(len(edges), len(hist), edges[0], edges[-1])
41 40 -6.0 6.0

A range that is not a multiple of bin_size is covered by one more bin:

>>> create_bin_edge_and_hist(0.7, 0.0, 2.0)[0]
array([0. , 0.7, 1.4, 2.1])
polyphys.analyze.measurer.end_to_end(positions)[source]#

Compute the end-to-end distance of a chain, the distance between its first and its last bead.

Parameters:

positions (numpy.ndarray) – Array of shape (n_atoms, n_dim) containing atomic positions, in backbone order from the first monomer to the last.

Returns:

The end-to-end distance, in the length unit of positions.

Return type:

typing.Union[numpy.floating, numpy.ndarray]

Raises:

ValueError – If positions contains fewer than two atoms.

Notes

The positions are centered on their center of geometry first; the distance does not depend on that translation.

Examples

>>> positions = np.array([[0.0, 0.0, 0.0],
...                       [1.0, 0.0, 0.0],
...                       [2.0, 0.0, 0.0]])
>>> end_to_end(positions)
np.float64(2.0)
>>> positions = np.array([[1.0, 1.0, 1.0],
...                       [2.0, 2.0, 2.0],
...                       [3.0, 3.0, 3.0]])
>>> end_to_end(positions)
np.float64(3.4641016151377544)
polyphys.analyze.measurer.fixedsize_bins(bin_size, lmin, lmax, bin_type='ordinary', save_bin_edges=None)[source]#

Generate bin edges and zero-filled histogram arrays with consistent bin width.

Every bin type returns n_bins + 1 equally spaced edges of width bin_size that cover [lmin, lmax].

Parameters:
  • bin_size (float) – Width of each bin.

  • lmin (float) – Start of the range

  • lmax (float) – End of the range

  • bin_type (typing.Literal['ordinary', 'nonnegative', 'periodic']) –

    Type of binning. With n_bins = ceil((lmax - lmin) / bin_size) bins, the excess length n_bins * bin_size - (lmax - lmin) is zero when the range is a whole number of bins and is otherwise shared out as follows:

    • ’ordinary’: Extends lmin and lmax symmetrically, by half the excess each. Examples are Cartesian coordinates and spherical polar coordinate.

    • ’nonnegative’: Extends lmin and lmax symmetrically if the extended lmin stays nonnegative; otherwise lmin is set to 0 and lmax to n_bins * bin_size. Examples are radial directions in the polar, spherical, and cylindrical coordinate systems.

    • ’periodic’: Periodic binning over one period, lmax - lmin, which must be a whole number of bins; the edges run from lmin to lmax exactly. Examples are azimuthal directions in cylindrical and spherical coordinate systems.

    See the Notes for how “a whole number of bins” is decided.

    See polyphys.manage.types.

  • save_bin_edges (typing.Optional[str]) – Filename (including filepath) to which bin edges array is saved. A .npy extension will be appended to the filename if it does not already have one.

Returns:

Dictionary with keys:

  • ’n_bins’ : int Number of bins.

  • ’bin_edges’ : np.ndarray A monotonically increasing array of bin edges, including the rightmost edge.

  • ’collector’ : np.ndarray Zero-initialized array of dtype np.int64 and shape (n_bins,) for histogram counts. The 64-bit integer type keeps per-frame counts accumulated in place (collector += np.histogram(...)[0]) from overflowing.

  • ’collector_std’ : np.ndarray Zero-initialized array of dtype np.float64 and shape (n_bins,) for standard deviation values or the squared counts they are computed from.

  • ’range’Tuple[float, float]

    Updated range of bins (lmin, lmax).

Return type:

typing.Dict[str, typing.Any]

Raises:
  • ValueError – If lmin is not less than lmax.

  • ValueError – If bin_type is ‘nonnegative’ and lmin is negative: clipping the lower end to zero would leave the range below zero uncovered.

  • ValueError – If bin_type is ‘periodic’ and lmax - lmin is not a multiple of bin_size. A last bin running past the period would cover values that never occur, so a density normalized by its width would be biased low.

Notes

The .npy extension is handled internally by np.save.

The edges come from np.linspace, so their number is exactly n_bins + 1, and the first and last edges enclose lmin and lmax exactly: a position at either end of the range falls inside the bins, and np.histogram counts a value equal to the last edge in the last bin.

Deciding whether the range is a whole number of bins. The ratio (lmax - lmin) / bin_size is computed in float64, so a range that is exactly a whole number of bins can come out a few ulps above or below that integer: 2.1 / 0.3 is 7.000000000000001, and 530 * 0.03 is a few 1e-15 below 15.9. Taking the ceiling of such a ratio adds a bin and, for ‘ordinary’ bins, shifts every edge by half a bin; comparing it directly can leave the end edges a few 1e-15 inside the range, where a position at exactly lmin or lmax is lost. The ratio is therefore compared with the nearest integer at the relative tolerance _BIN_COUNT_RTOL = 1e-9. That tolerance sits between the two scales that matter: the accumulated round-off in the ratio, a few times the float64 epsilon (about 1e-15), and the smallest deviation a user can intend, which the seven significant digits of the box sizes and bead diameters in the simulation filenames put at about 1e-7. It is closer to the intent side on purpose, because the two misclassifications are not equally bad: calling a true multiple a non-multiple adds a bin and shifts the grid, while calling an intended non-multiple a multiple moves the edges by less than 1e-9 * (lmax - lmin).

The symmetric extension of the ‘ordinary’ bins follows MDAnalysis’s fixedwidth_bins; the nearest-integer bin count departs from it, for the reasons above.

Time and space are O(n_bins).

References

MDAnalysis lib.util.fixedwidth_bins: MDAnalysis/mdanalysis

Examples

>>> result = fixedsize_bins(1.0, 0.0, 5.0)
>>> result['n_bins']
5
>>> result['bin_edges']
array([0., 1., 2., 3., 4., 5.])

A range that is a whole number of bins up to round-off is tiled exactly:

>>> result = fixedsize_bins(0.3, 0.0, 2.1)
>>> edges = result['bin_edges']
>>> print(result['n_bins'], edges[0], edges[-1])
7 0.0 2.1

A radial range whose lower end would fall below zero is clipped there, and the bins keep their width:

>>> result = fixedsize_bins(1.0, 0.1, 2.5, bin_type='nonnegative')
>>> result['bin_edges']
array([0., 1., 2., 3.])

Azimuthal bins of 5 degrees span exactly one period:

>>> result = fixedsize_bins(np.pi / 36, -np.pi, np.pi, bin_type='periodic')
>>> print(result['n_bins'], result['bin_edges'][-1] == np.pi)
72 True
polyphys.analyze.measurer.fsd(positions, axis)[source]#

Compute the span of the positions along the selected axis.

The span is the largest coordinate minus the smallest along axis, for one configuration; nothing is averaged over frames or orientations. The name fsd is kept from Feret’s statistical diameter, the caliper distance along a fixed direction.

Parameters:
  • positions (numpy.ndarray) – Array of shape (n_atoms, n_dim) of atom positions, in any order; the span does not depend on it.

  • axis (typing.Literal[0, 1, 2]) – Axis index (0=x, 1=y, 2=z) along which to compute the span; see polyphys.manage.types.

Returns:

The span along axis, in the units of positions.

Return type:

float

Raises:

IndexError – If axis is out of bounds for positions.

References

Wang Y, Teraoka I, Hansen FY, Peters GH, Hassager O. “A Theoretical Study of the Separation Principle in Size Exclusion Chromatography.” Macromolecules 2010, 43, 3, 1651-1659. https://doi.org/10.1021/ma902377g

Examples

>>> positions = np.array([[1, 2, 3], [4, 8, 6]])
>>> fsd(positions, axis=1)
np.float64(6.0)
polyphys.analyze.measurer.max_distance(positions)[source]#

Compute the extent of the positions along each Cartesian axis.

Parameters:

positions (numpy.ndarray) – Array of shape (n_atoms, n_dim) containing atom positions, in any order.

Returns:

The largest coordinate minus the smallest along each axis, shape (n_dim,), in the length unit of positions.

Return type:

numpy.ndarray

Raises:

ValueError – If positions is empty.

Notes

The positions are centered on their center of geometry first; the extent does not depend on that translation.

Examples

>>> positions = np.array([[0, 0, 0], [4, 2, 6], [2, 3, 0]])
>>> max_distance(positions)
array([4., 3., 6.])
polyphys.analyze.measurer.pair_distance(positions, pbc=None)[source]#

Compute the displacement vector from the first particle to the second, optionally under the minimum image convention.

Parameters:
Returns:

The signed displacement positions[1] - positions[0] along each axis, shape (n_dim,), float64, in the length unit of positions; with pbc, each periodic component is folded into [-L/2, L/2].

Return type:

numpy.ndarray

Raises:

ValueError – If positions does not contain exactly two sets of coordinates.

Notes

The result is the component-wise displacement, not its Euclidean norm.

Examples

>>> positions = np.array([[1.0, 2.0, 3.0], [4.0, 2.0, 3.0]])
>>> pair_distance(positions)
array([3., 0., 0.])
>>> pbc = {0: 8.0}
>>> positions = np.array([[1.0, 2.0, 3.0], [9.5, 2.0, 3.0]])
>>> pair_distance(positions, pbc)
array([0.5, 0. , 0. ])
polyphys.analyze.measurer.planar_cartesian_histogram(positions, edges, dim)[source]#

Compute a two-dimensional histogram in the plane perpendicular to dim, in Cartesian coordinates.

Parameters:
  • positions (numpy.ndarray) – Array of shape (n_atoms, n_dim) containing atom positions, in any order.

  • edges (typing.List[numpy.ndarray]) – Two monotonically increasing arrays of bin edges, one per planar axis, each including its rightmost edge. The last bin along each axis includes its right edge. Every position must lie within the outermost edges along both axes: a coordinate along a periodic axis must already be wrapped into the box, since this function does not wrap.

  • dim (typing.Literal[0, 1, 2]) – Cartesian axis (0=x, 1=y, 2=z). The right-hand rule is used to pass the planar axes to the np.histogram2d: When dim=0 (x), dim=1 (y) and dim=2 (z) values are passed respectively. When dim=1 (y), dim=2 (z) and dim=0 (x) values are passed respectively. When dim=2 (z), dim=0 (x) and dim=1 (y) values are passed respectively. See polyphys.manage.types.

Returns:

hist – The counts per cell, shape (len(edges[0]) - 1, len(edges[1]) - 1), float64, as numpy.histogram2d() returns them, with rows along the first planar axis.

Return type:

numpy.ndarray

Raises:
  • ValueError – If dim is not one of {0, 1, 2}.

  • ValueError – If the positions array is not two-dimensional.

  • ValueError – If any position falls outside the outermost edges. np.histogram would drop it silently; here a dropped position means wrong edges or an unwrapped coordinate, so it is an error.

  • ValueError – If the length of edges is not two.

Examples

>>> positions= np.array([[1, 1, 0], [2, 2, 0], [3, 3, 0]])
>>> edges = [np.array([0, 2, 4]), np.array([0, 2, 4])]
>>> planar_cartesian_histogram(positions, edges, dim=2)
array([[1., 0.],
       [0., 2.]])
polyphys.analyze.measurer.radial_cyl_histogram(positions, edges, dim)[source]#

Bin the distances of the positions from the axis along dim, the cylindrical radial coordinate.

Parameters:
  • positions (numpy.ndarray) – Array of shape (n_atoms, n_dim) containing atom positions, in any order.

  • edges (numpy.ndarray) – A monotonically increasing array of bin edges, including the rightmost edge. The last bin includes its right edge. Every position must lie within the outermost edges: a coordinate along a periodic axis must already be wrapped into the box, since this function does not wrap.

  • dim (typing.Literal[0, 1, 2]) – Axis direction (0=x, 1=y, 2=z); see polyphys.manage.types.

Returns:

hist – The counts per bin, shape (len(edges) - 1,), integer.

Return type:

numpy.ndarray

Raises:
  • ValueError – If dim is not one of {0, 1, 2}.

  • ValueError – If the positions array is not two-dimensional.

  • ValueError – If any position falls outside the outermost edges. np.histogram would drop it silently; here a dropped position means wrong edges or an unwrapped coordinate, so it is an error.

Examples

>>> import numpy as np
>>> positions = np.array([[1, 0, 0], [0, 2, 0], [0, 0, 3], [0, 3, 4]])
>>> edges = np.array([0, 1, 2, 3, 4])
>>> radial_cyl_histogram(positions, edges, dim=1)
array([1, 1, 0, 2])
polyphys.analyze.measurer.radial_histogram(positions, edges)[source]#

Bin the distances of the positions from the origin, the spherical radial coordinate.

Parameters:
  • positions (numpy.ndarray) – Array of shape (n_atoms, n_dim) containing atom positions, in any order.

  • edges (numpy.ndarray) – A monotonically increasing array of bin edges, including the rightmost edge. The last bin includes its right edge. Every position must lie within the outermost edges: a coordinate along a periodic axis must already be wrapped into the box, since this function does not wrap.

Returns:

hist – The counts per bin, shape (len(edges) - 1,), integer.

Return type:

numpy.ndarray

Raises:
  • ValueError – If the positions array is not two-dimensional.

  • ValueError – If any position falls outside the outermost edges. np.histogram would drop it silently; here a dropped position means wrong edges or an unwrapped coordinate, so it is an error.

Examples

>>> positions= np.array([[1, 0, 0], [0, 1, 0], [0, 0, 2]])
>>> edges = np.array([0, 1, 2, 3])
>>> radial_histogram(positions, edges)
array([0, 2, 1])
polyphys.analyze.measurer.sem(data)[source]#

Compute the standard error of the mean (SEM) of independent samples.

Parameters:

data (numpy.ndarray) – One-dimensional array of sample data.

Returns:

The standard error of the mean, in the unit of data.

Return type:

float

Raises:

ValueError – If data is empty or holds one sample, whose sample standard deviation with ddof=1 divides by n - 1 = 0.

Notes

SEM is calculated using sample standard deviation (ddof=1) and sample size. The estimate assumes independent samples, such as the means of independent replicates. For a time series of correlated frames it understates the error; use polyphys.analyze.stats.sem_blocked() instead.

Examples

>>> import numpy as np
>>> sem(np.array([1.0, 2.0, 3.0]))
np.float64(0.5773502691896258)
polyphys.analyze.measurer.simple_stats(entity, data)[source]#

Compute basic statistics (mean, variance, SEM) for a physical entity.

Parameters:
  • entity (str) – The name that prefixes the keys of the result.

  • data (numpy.ndarray) – One-dimensional array of independent samples.

Returns:

The mean, the sample variance with ddof=1, and the SEM, the sample standard deviation with ddof=1 over the square root of the number of samples, keyed '<entity>_mean', '<entity>_var', and '<entity>_sem'.

Return type:

typing.Dict[str, float | numpy.floating]

Raises:

ValueError – If data is empty or holds one sample, whose unbiased variance divides by n - 1 = 0.

Examples

>>> import numpy as np
>>> simple_stats('energy', np.array([1.0, 2.0, 3.0]))  # noqa: E501
{'energy_mean': np.float64(2.0), 'energy_var': np.float64(1.0), 'energy_sem': np.float64(0.5773502691896258)}
polyphys.analyze.measurer.sphere_sphere_intersection(r1, r2, d)[source]#

Compute the volume of intersection between two spheres.

The sphere with radius r1 is separated from the sphere with radius r2 by a distance d along the x-axis. Thus, the vector form of the distance between their centers is (d, 0, 0) in Cartesian coordinates.

Parameters:
  • r1 (float) – Radius of the first sphere.

  • r2 (float) – Radius of the second sphere.

  • d (float) – Distance between the centers of the two spheres along the x-axis.

Returns:

vol – Volume of the intersection between the two spheres.

Return type:

float

References

Weisstein, Eric W. “Sphere-Sphere Intersection.” From MathWorld–A Wolfram Web Resource. https://mathworld.wolfram.com/Sphere-SphereIntersection.html

Examples

>>> sphere_sphere_intersection(3, 4, 2)
94.90227807719167
>>> sphere_sphere_intersection(3, 4, 10)
0.0
polyphys.analyze.measurer.spherical_segment(r, a, b)[source]#

Compute the volume of a spherical segment defined by two parallel planes.

Parameters:
  • r (float) – Radius of the sphere. Must be positive.

  • a (float) – Distance of the first plane from the center of the sphere, along the axis of symmetry.

  • b (float) – Distance of the second plane from the center of the sphere, along the axis of symmetry.

Returns:

vol – Volume of the spherical segment.

Return type:

float

Raises:

ValueError – If r is not a positive number.

Notes

  • a and b can be positive or negative values, as long as they fall within the range [-r, r].

  • The function will adjust a and b to -r or r if they exceed these bounds.

  • If a = r or b = r, the spherical segment becomes a spherical cap.

  • If both a and b lie outside the range [-r, r] and share the same sign, the volume is zero.

References

Weisstein, Eric W. “Spherical Segment.” From MathWorld–A Wolfram Web Resource. https://mathworld.wolfram.com/SphericalSegment.html

Examples

>>> spherical_segment(3, 1, 2)
20.94395102393195
>>> spherical_segment(3, -3, 3)
113.09733552923255
polyphys.analyze.measurer.transverse_size(positions, axis)[source]#

Compute the transverse size of a group of atoms, twice their mean distance from their center in the plane perpendicular to axis.

Parameters:
  • positions (numpy.ndarray) – Array of shape (n_atoms, n_dim) containing atomic positions, in any order.

  • axis (typing.Literal[0, 1, 2]) – The axis (0 for x, 1 for y, and 2 for z) perpendicular to the plane in which the size is measured.

Returns:

Twice the mean distance of the atoms from their center of geometry in the plane perpendicular to axis, a diameter, in the length unit of positions.

Return type:

float

Raises:

IndexError – If axis is out of bounds for positions.

Notes

The distance is calculated in a reference frame centered at the center of geometry of atoms in the plane perpendicular to a given axis.

Examples

>>> positions = np.array([[1, 0, 0], [1, 2, 2]])
>>> transverse_size(positions, axis=0)
np.float64(2.8284271247461903)
>>> transverse_size(positions, axis=1)
np.float64(2.0)