Chunking, softening and tolerances¶
"""What softening replaces the point mass with, and what chunking changes.
The softened trace is compared against the closed-form Plummer density rather
than merely being shown to be non-zero: that is what distinguishes "a
different mass distribution" from "the same field with the singularity
patched out".
"""
import numpy as np
from gragra import (
G_SI,
PointMass,
WeightedPointSource,
point_acceleration,
point_gravity_gradient,
)
mass_kg = 1.0
softening_m = 0.5
source = PointMass(mass_kg=mass_kg, position_m=[0.0, 0.0, 0.0])
target = [[1.0, 0.0, 0.0]]
# With no softening the gravity-gradient tensor is exactly trace-free: outside
# the source the field satisfies Laplace's equation.
sharp = point_gravity_gradient(source, target, softening_m=0.0)
assert np.trace(sharp[0]) == 0.0
# With softening it is not, and the residual is not numerical noise. It is
# -4 pi G rho evaluated at the observation point, for the Plummer density
# rho(r) = 3 M eps^2 / (4 pi r_eff^5), r_eff^2 = r^2 + eps^2,
# which is the mass distribution that softening_m substitutes for the point
# mass. The observation point is inside that distribution, so Poisson's
# equation rather than Laplace's applies there.
softened = point_gravity_gradient(source, target, softening_m=softening_m)
r_eff_sq = 1.0 + softening_m**2
plummer_density_kg_m3 = 3.0 * mass_kg * softening_m**2 / (4.0 * np.pi * r_eff_sq**2.5)
assert np.isclose(
np.trace(softened[0]),
-4.0 * np.pi * G_SI * plummer_density_kg_m3,
rtol=1e-13,
atol=0.0,
)
# chunk_size bounds the size of the intermediate arrays and nothing else. On
# the NumPy backend it does change the order in which the source sum is
# accumulated, so two chunk sizes agree to rounding rather than bit for bit;
# the residual is normalised by the largest component instead of being
# compared against zero.
generator = np.random.default_rng(20260805)
cloud = WeightedPointSource(
positions_m=generator.normal(scale=10.0, size=(2000, 3)),
weights_kg=generator.normal(scale=5.0, size=2000),
)
observation_points = [[40.0, 0.0, 0.0], [0.0, 35.0, 5.0]]
whole = point_acceleration(cloud, observation_points, chunk_size=None)
tiled = point_acceleration(cloud, observation_points, chunk_size=64)
relative_deviation = np.max(np.abs(whole - tiled)) / np.max(np.abs(whole))
assert relative_deviation < 1e-12
# A zero separation with no softening is an error naming the offending pair,
# never a silently softened or infinite value ...
try:
point_acceleration(source, [[0.0, 0.0, 0.0]], softening_m=0.0)
except ValueError as error:
assert "target point 0 and source point 0" in str(error)
else:
raise AssertionError("a zero separation must not be accepted")
# ... and a non-positive chunk_size is rejected rather than reinterpreted.
try:
point_acceleration(source, target, chunk_size=0)
except ValueError as error:
assert "chunk_size" in str(error)
else:
raise AssertionError("chunk_size <= 0 must be rejected")
Chunking¶
What chunk_size does¶
chunk_size bounds the size of the intermediate (M, N, ...) array
materialized while summing over sources, trading memory for more
Python-level iterations. It is purely a memory/performance knob on the CPU
backends — chunk_size=None (no chunking) and any positive chunk_size
produce numerically equivalent results within float64 roundoff tolerance
(typically rtol ≤ 1e-13 across test suites), and chunk_size<=0 raises ValueError.
Reproducibility across backends¶
On "numba" and "cpp", the compiled loops do not use chunk_size for tiling,
so results within each backend are strictly independent of chunk_size.
On "numpy", chunking accumulates intermediate partial sums via out += ...,
which can change the floating-point summation order; while consistent to near machine
precision, unconditional bit-level identity is not guaranteed for arbitrary inputs.
On "cupy" this guarantee relaxes to a device/kernel tolerance:
chunk_size becomes a genuine VRAM-tiling parameter, the in-chunk reduction
is a non-associative parallel sum, and changing chunk_size changes the
last bits of the answer. Reproducibility there means "same device, same
CuPy version, same chunk_size" — not "same everywhere". See
Compute backends for the full backend contract.
Softening¶
What softening changes¶
Plummer softening is a smoothed-mass approximation, not a regularisation
of the exact field. Setting softening_m > 0 is exactly equivalent to
replacing the point mass with a Plummer sphere of density
ρ(r) = 3Mε²/(4π r_eff⁵). The near field is a genuinely different mass
distribution, not the same field with a singularity removed.
Why the gradient trace stops vanishing¶
Because softening changes the mass distribution, tr(T) = 0 — the
vacuum Laplace-equation property of the exact point-mass gravity-gradient
tensor — holds only for softening_m == 0. With softening_m > 0 the
observation point sits inside the (now-finite) mass distribution, so
Poisson's equation applies there instead, and the trace residual equals
−4πGρ evaluated at that point for the Plummer density above — not
numerical noise, a genuine physical effect of the approximation. A
collision (r == 0) with softening_m == 0 raises ValueError naming the
offending source/target index pair; softening_m < 0 always raises.
Comparing results numerically¶
NumPy's default atol=1e-8 is meaningless at gragra's output scale.
G_SI ≈ 6.7 × 10⁻¹¹, so np.allclose at default tolerances accepts a
result of exactly zero as "close to" a genuine, non-zero acceleration, and
accepts a sign-flipped result as "close to" the correct one. Every
comparison on this site states an explicit tolerance for exactly this
reason — never rely on np.allclose's defaults when checking a gragra
result.
Non-zero fixed points¶
Where the arithmetic is exact at a chosen configuration (unit mass, unit
distance, zero softening — see
Coordinates, signs and units), compare with an exact
equality, not a tolerance. Where the comparison must be a tolerance, use
an explicit rtol with atol=0.0 so a structurally zero component cannot
silently pass. Prefer abs(component) over np.linalg.norm for a
scalar magnitude check: norm can dispatch to a BLAS routine whose
internal scaling makes bit-for-bit behaviour implementation-dependent
across OpenBLAS/MKL and Python versions, where a plain abs does not.
Quantities whose target value is zero¶
A bare rtol/atol judgement against a target of exactly zero is
ill-posed — rtol scales with the target, so it scales with zero. Instead,
normalize the residual by the largest relevant component (as the chunking
snippet above does) or, where a closed-form magnitude is available, compare
against that magnitude directly.
Cancellation-sensitive quantities¶
Some results (mixed-sign weighted sums, cross-statistics with cancelling directional terms) are sensitive to the coefficients cancelling almost exactly. For those, a residual tolerance is scaled by the sum of the absolute values of the terms that were summed, not by the (possibly much smaller) result — otherwise a genuinely large cancellation error can be misread as a passing near-zero residual. See Coherent responses and cross statistics for where this applies.