Skip to content

Top-level API

The implemented source/target containers and point, coherent, and displacement observables are importable directly from gragra. This page documents the current numerical entry points; subpackage pages provide the lower-level and adapter interfaces.

These stable names are re-exports. gragra.point_acceleration and gragra.observables.point_acceleration are the same function object, and gragra.PointMass is gragra.gravity_sources.PointMass; the short path is the one to use and the one documented here.

Constants

gragra separates geometry from coupling: the kernels compute a purely geometric factor and know nothing about gravity's strength, and exactly one layer — the observables — multiplies by the gravitational constant. That makes the constant below the single point where the physical scale enters, and it is why the helpers in gragra.analytic are described as "G-free".

gragra.G_SI module-attribute

G_SI = 6.6743e-11

The value is the CODATA 2018 recommendation, 6.674 30 × 10⁻¹¹ m³ kg⁻¹ s⁻². It carries the largest relative uncertainty of any constant gragra uses — of order 2 × 10⁻⁵ — which is far above the numerical agreement the test suite asserts, so it, and not floating-point error, sets the accuracy floor of any absolute result.

Sources and targets

A calculation needs two things: a description of the mass that perturbs the field, and the points at which you want to know the answer. All four containers below are frozen dataclasses whose stored arrays are made read-only on construction, so a source cannot be mutated behind the back of a result computed from it.

The distinction between the first container and the next two is a deliberate discipline, not redundancy. WeightedPointSource is the general representation and accepts signed and complex weights; PointMass and PointMassCloud are positive-real conveniences that convert into one.

gragra.WeightedPointSource dataclass

Generic signed/complex perturbation source representation.

This is the core representation for gravitational perturbation solvers. Weights are restricted to mass elements (δm = δρ * dV) in kg, which may be negative (for underdensities) or complex-valued. A coherent transfer weight is a different abstraction with a different unit and does not belong in weights_kg.

Parameters:

Name Type Description Default
positions_m array - like

Coordinates table of shape (N, 3) in meters.

required
weights_kg array - like

Weights vector of shape (N,) in kilograms (float or complex).

required

This is the generic source type: positions as an (N, 3) float64 table and weights as an (N,) array whose kind is preserved — real input stays float64, complex input stays complex128, and the result's dtype follows. Weights are mass elements in kilograms, and they may be negative or complex, which is what makes it the right container for a density perturbation δm = δρ·dV rather than for a physical object.

gragra.PointMass dataclass

Convenience wrapper for a single positive-real point mass.

Parameters:

Name Type Description Default
mass_kg float

Mass in kilograms. Must be strictly positive and finite.

required
position_m array - like

Coordinates of shape (3,) in meters.

required

as_weighted_source

as_weighted_source() -> WeightedPointSource

Convert to the canonical WeightedPointSource format.

A single positive real mass at a single position, for when the source really is an object — a vehicle, a piece of equipment, a test mass. A mass that is zero, negative or non-finite raises ValueError at construction rather than producing a silently signed result; call as_weighted_source() to hand it to an observable.

gragra.PointMassCloud dataclass

Convenience wrapper for multiple positive-real point masses.

Parameters:

Name Type Description Default
masses_kg array - like

Masses of shape (N,) in kilograms. Must be strictly positive.

required
positions_m array - like

Coordinates of shape (N, 3) in meters.

required

as_weighted_source

as_weighted_source() -> WeightedPointSource

Convert to the canonical WeightedPointSource format.

The same positive-real convenience for many masses at once, with masses_kg of shape (N,) and positions_m of shape (N, 3). Summing the cloud gives exactly the same field as summing the individual masses, which is the cheapest available check that a discretization has been assembled correctly.

gragra.TargetPoints dataclass

Target positions as a length Quantity of shape (N, 3).

Equal positions may have distinct IDs. Input arrays are copied to immutable bytes; a returned NumPy view cannot be made writable.

The observation points as a length Quantity of shape (M, 3), stable string IDs, and their coordinate Frame. Low-level numerical observables continue to accept bare array-like target positions directly.

Observables

These three field quantities take a source and a set of targets, return an array whose leading axis is the target index and whose component axes are last, and accept the same softening_m, chunk_size and backend controls. All three return read-only arrays.

gragra.point_potential

point_potential(
    source: WeightedPointSource
    | PointMass
    | PointMassCloud,
    targets: TargetPoints | list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> FloatArray | ComplexArray

Calculate the gravitational potential at target points.

Potential Φ = G_SI * sum_j (w_j * K_Φ)

Complex outputs represent linear complex amplitudes or transfer-function-like responses, not directly real-valued time-domain gravitational fields.

Parameters:

Name Type Description Default
source WeightedPointSource, PointMass, or PointMassCloud

The source of gravitational perturbation.

required
targets TargetPoints or array - like

The target observation points.

required
softening_m float

Plummer softening parameter. Defaults to 0.0.

0.0
chunk_size int

Chunk size for source-axis loop. Defaults to None.

None
backend str

The calculation backend: 'numpy' (default), 'numba', 'cpp', or 'cupy' (GPU, point-direct only; requires a CuPy wheel matching the local CUDA/ROCm runtime and a working CUDA device).

'numpy'

Returns:

Type Description
FloatArray or ComplexArray

Gravitational potential of shape (M,).

The gravitational potential at each target, shape (M,). Note the sign convention: the potential of a positive mass is negative, so a naive "magnitude" comparison against another code is a comparison that cannot fail and cannot tell you anything.

gragra.point_acceleration

point_acceleration(
    source: WeightedPointSource
    | PointMass
    | PointMassCloud,
    targets: TargetPoints | list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> FloatArray | ComplexArray

Calculate the gravitational acceleration vector at target points.

Acceleration a = G_SI * sum_j (w_j * K_a)

Complex outputs represent linear complex amplitudes or transfer-function-like responses, not directly real-valued time-domain gravitational fields.

Parameters:

Name Type Description Default
source WeightedPointSource, PointMass, or PointMassCloud

The source of gravitational perturbation.

required
targets TargetPoints or array - like

The target observation points.

required
softening_m float

Plummer softening parameter. Defaults to 0.0.

0.0
chunk_size int

Chunk size for source-axis loop. Defaults to None.

None
backend str

The calculation backend: 'numpy' (default), 'numba', 'cpp', or 'cupy' (GPU, point-direct only; requires a CuPy wheel matching the local CUDA/ROCm runtime and a working CUDA device).

'numpy'

Returns:

Type Description
FloatArray or ComplexArray

Gravitational acceleration of shape (M, 3).

The acceleration vector at each target, shape (M, 3), pointing from the target toward the source for a positive mass. For a single 1 kg source at the origin observed at (1, 0, 0) m, the result is exactly -G_SI in x and zero in the other two components — a fixed point worth reproducing once when you set up.

gragra.point_gravity_gradient

point_gravity_gradient(
    source: WeightedPointSource
    | PointMass
    | PointMassCloud,
    targets: TargetPoints | list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> FloatArray | ComplexArray

Calculate the gravity gradient tensor at target points.

Gravity gradient tensor T_ij = G_SI * sum_j (w_j * K_T)

Note that for softening_m > 0, the softened tensor does not satisfy tr(T) = 0.

Complex outputs represent linear complex amplitudes or transfer-function-like responses, not directly real-valued time-domain gravitational fields.

Parameters:

Name Type Description Default
source WeightedPointSource, PointMass, or PointMassCloud

The source of gravitational perturbation.

required
targets TargetPoints or array - like

The target observation points.

required
softening_m float

Plummer softening parameter. Defaults to 0.0.

0.0
chunk_size int

Chunk size for source-axis loop. Defaults to None.

None
backend str

The calculation backend: 'numpy' (default), 'numba', 'cpp', or 'cupy' (GPU, point-direct only; requires a CuPy wheel matching the local CUDA/ROCm runtime and a working CUDA device).

'numpy'

Returns:

Type Description
FloatArray or ComplexArray

Gravity gradient tensor of shape (M, 3, 3).

The gravity-gradient tensor ∂aᵢ/∂xⱼ at each target, shape (M, 3, 3), differentiated with respect to the target coordinate. For the same 1 kg fixed point it is G_SI · diag(2, -1, -1). Its trace vanishes only when softening_m is exactly zero; with softening the field is that of a smeared mass distribution, which is not a vacuum solution.

Additional observables

These observables are part of the current research API and retain the subpackage implementations described in the source. They use the same array, unit, sign, and backend conventions as the direct point path.

gragra.displacement_field_acceleration

displacement_field_acceleration(
    dataset: SpecfemGLLDataset,
    targets: TargetPoints | list | tuple | ndarray,
    *,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> FloatArray

Calculate acceleration time series from a SPECFEM GLL displacement field.

Every GLL row contributes the background mass density_kg_m3 * quadrature_volume_m3. Its displacement is contracted with the existing G-free dipole kernel, then this Observable applies G_SI exactly once. The 0.2.0 reader rejects PML input and this wrapper fixes Plummer softening at zero. Targets must lie in a vacuum region (inside a cavity or above the free surface), because a rock-interior local term is outside the 0.2.0 contract.

Version 0.2.0 keeps the closed dataset's complete displacement array in memory, but computes the result one time index at a time. It does not stream HDF5 snapshots. Returns a read-only array of shape (Nt, M, 3).

Calculates a time-indexed acceleration array from a closed SpecfemGLLDataset. Each GLL quadrature row is retained as a separate background-mass contribution, and the output has shape (Nt, M, 3). The dataset retains every snapshot in memory; the observable computes one time index at a time and does not stream the HDF5 file.

Coherent observables

The coherent entry points take parametric weights: an (N, ...) array carrying one weight per source element per parameter — per propagation direction, per wavenumber, per snapshot — and return the response with those parameter axes preserved in front of the component axes. They accept raw position and weight arrays rather than a source container, because the weight column is no longer a plain (N,) mass vector.

Complex results here are linear complex amplitudes or transfer-function-like responses. They are not real-valued time-domain fields, and taking the real part of one is not the same thing as computing the field at t = 0 unless you have separately fixed the phase convention.

gragra.coherent_point_acceleration

coherent_point_acceleration(
    source_positions_m: list | tuple | ndarray,
    weights_kg: list | tuple | ndarray,
    targets_m: list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> np.ndarray

Calculate coherent gravitational acceleration at target points.

Complex outputs represent linear complex amplitudes or transfer-function-like responses, not directly real-valued time-domain gravitational fields.

backend selects the parametric acceleration contraction implementation ("numpy" default, "numba", "cpp", or "cupy"); all backends are numerically equivalent (the G-free geometric factor is identical) and the output dtype follows the weights. Raises ImportError if the selected compiled backend ("numba", "cpp", or "cupy") is not installed; raises RuntimeError if "cupy" is installed but no usable CUDA device/driver is present at call time.

The acceleration for parametric weights, with the parameter axes inserted before the trailing component axis. It is the coherent counterpart of point_acceleration and shares its kernel; the difference is entirely in the shape of the weights.

gragra.coherent_point_gravity_gradient

coherent_point_gravity_gradient(
    source_positions_m: list | tuple | ndarray,
    weights_kg: list | tuple | ndarray,
    targets_m: list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> np.ndarray

Calculate the coherent gravity gradient tensor at target points.

Complex outputs represent linear complex amplitudes or transfer-function-like responses, not directly real-valued time-domain gravitational fields.

Output shape is (M, *P, 3, 3) — the tensor axes trail the parametric axes (component-axis-last convention). The output dtype follows the weights (real -> float64, complex -> complex128) and the returned array is read-only. tr(T) = 0 (the vacuum Laplace property) holds only for softening_m = 0; the softened tensor is an approximation.

backend selects the parametric gradient contraction implementation ("numpy" default, "numba", "cpp", or "cupy"); all backends are numerically equivalent (the G-free geometric factor is identical). Raises ImportError if the selected compiled backend ("numba", "cpp", or "cupy") is not installed; raises RuntimeError if "cupy" is installed but no usable CUDA device/driver is present at call time.

The gravity-gradient tensor for parametric weights, ending in (..., 3, 3). The same trace caveat applies as for the non-coherent form: harmonicity holds only at zero softening.

gragra.coherent_gravitoelastic_tensor

coherent_gravitoelastic_tensor(
    source_positions_m: list | tuple | ndarray,
    weights_kg: list | tuple | ndarray,
    targets_m: list | tuple | ndarray,
    witness_displacement_m: list | tuple | ndarray,
    direction_weights: list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> np.ndarray

Calculate the gravitoelastic cross tensor c_ij = .

Formula: c_ij(r_m, r_w) = Σ_d w_d · δa_i(r_m) · conj(ξ_j(r_w)), where δa is the coherent gravitational acceleration response at targets_m sourced from source_positions_m/weights_kg, and ξ is a G-free witness displacement (e.g. from waves.plane_wave_displacement).

G order (see coherent_statistics_conventions.md §5): this is a G^1 quantity -- G_SI is multiplied exactly once, internally, via coherent_point_acceleration; witness_displacement_m must be G-free (its own kinematic definition never includes G_SI). Do not pass a G-included response as witness_displacement_m; there is no additional G_SI multiplication in this function and none should be applied by the caller either.

The source mass weights and the witness displacement must be built from the same wave parameters (k_hat, wavenumber_rad_m, phase0) -- e.g. via coherent.plane_wave_bulk_mass_weights and waves.plane_wave_displacement respectively -- otherwise the phase relationship this tensor encodes is not physically meaningful.

Parameters:

Name Type Description Default
source_positions_m array_like

Source positions, shape (N, 3).

required
weights_kg array_like

Complex bulk mass weights, shape (N, Ndir, Nf) (e.g. from coherent.plane_wave_bulk_mass_weights).

required
targets_m array_like

Acceleration target positions, shape (M, 3).

required
witness_displacement_m array_like

G-free witness displacement response, shape (W, Ndir, Nf, 3) (component axis trailing; e.g. from waves.plane_wave_displacement).

required
direction_weights array_like

Real-valued direction weights, shape (Ndir,). Negative values are allowed. This is a raw weighted sum (not divided by the sum of weights); normalization is the caller's responsibility.

required
softening_m float

Plummer softening length in meters. Default 0.0.

0.0
chunk_size int or None

Source-axis chunk size passed through to coherent_point_acceleration. Default None (no chunking).

None
backend str

Acceleration contraction backend ("numpy", "numba", "cpp", or "cupy"). Default "numpy".

'numpy'

Returns:

Type Description
ndarray

Cross tensor of shape (M, W, Nf, 3, 3) and dtype complex128. It is read-only. Axis order: i (acceleration component) is the second-to-last axis, j (witness displacement component, conjugated) is the last axis.

Notes
  • Under a directional ensemble model where waves from different directions are mutually uncorrelated, this average corresponds to the ensemble expectation. It does not apply to a coherent superposition of directionally correlated waves.
  • Since negative direction weights are allowed, this tensor is not guaranteed to be Hermitian positive semi-definite (PSD).
  • Complex outputs are second-order cross statistics, not time-domain fields; the phase encodes relative propagation delay/coherence between the acceleration response and the witness, not an absolute field phase.

The cross tensor cᵢⱼ = ⟨δaᵢ ξⱼ*⟩ between the gravity perturbation and a witness displacement — the quantity that says how much of a seismometer's reading predicts the gravity signal. It is a second-order statistic: the second argument is conjugated, the product is element-wise, and the result is always complex even for real inputs.

gragra.coherent_acceleration_csd

coherent_acceleration_csd(
    source_positions_m: list | tuple | ndarray,
    weights_kg: list | tuple | ndarray,
    targets_a_m: list | tuple | ndarray,
    targets_b_m: list | tuple | ndarray,
    direction_weights: list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> np.ndarray

Calculate the mirror-pair acceleration cross-spectral density (CSD).

Formula: CSD_ij(r_a, r_b) = Σ_d w_d · δa_i(r_a) · conj(δa_j(r_b)), where both δa responses are sourced from the same source_positions_m/weights_kg.

G order (see coherent_statistics_conventions.md §5): this is a G^2 quantity -- each of the two acceleration responses independently carries one G_SI factor (from its own coherent_point_acceleration call), and no additional G_SI multiplication is applied here.

Parameters:

Name Type Description Default
source_positions_m array_like

Source positions, shape (N, 3).

required
weights_kg array_like

Complex bulk mass weights, shape (N, Ndir, Nf).

required
targets_a_m array_like

First acceleration target positions, shape (Ma, 3).

required
targets_b_m array_like

Second (conjugated) acceleration target positions, shape (Mb, 3).

required
direction_weights array_like

Real-valued direction weights, shape (Ndir,). Negative values are allowed. Raw weighted sum; normalization is the caller's responsibility.

required
softening_m float

Plummer softening length in meters. Default 0.0.

0.0
chunk_size int or None

Source-axis chunk size passed through to coherent_point_acceleration (applied independently to each of the two acceleration evaluations). Default None.

None
backend str

Acceleration contraction backend ("numpy", "numba", "cpp", or "cupy"). Default "numpy".

'numpy'

Returns:

Type Description
ndarray

CSD tensor of shape (Ma, Mb, Nf, 3, 3) and dtype complex128. It is read-only. Axis order: i (targets_a component) is the second-to-last axis, j (targets_b component, conjugated) is the last axis.

Notes
  • Under a directional ensemble model where waves from different directions are mutually uncorrelated, this average corresponds to the ensemble expectation. It does not apply to a coherent superposition of directionally correlated waves.
  • Since negative direction weights are allowed, this tensor is not guaranteed to be Hermitian positive semi-definite (PSD).
  • Complex outputs are second-order cross statistics, not time-domain fields; the phase encodes relative propagation delay/coherence between the two target responses, not an absolute field phase.

The cross-spectral density of the acceleration between two sets of target points, for the mirror-pair geometry a detector actually measures. It is second order in the source weights, so it carries G², where the single-point observables carry G¹ and a bare witness displacement carries none.

Field transfer

The last top-level entry belongs to neither group: it takes a displacement field on a set of mass elements rather than a set of masses or weights.

gragra.displacement_transfer_acceleration

displacement_transfer_acceleration(
    sources_xyz: list | tuple | ndarray,
    mass_kg: list | tuple | ndarray,
    displacement_m: list | tuple | ndarray,
    targets: TargetPoints | list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> FloatArray | ComplexArray

Calculate the G_SI-scaled displacement-transfer (dipole/total) acceleration.

a_i = G_SI * (-sum_n mass_n * sum_j K_T_ij(r_n) * displacement_n[j])

See gragra.kernels.inverse_square.dipole_contract for the G-free contract this wraps (K_T is the gravity gradient kernel) and kernel_contract.md Section 2.2 for the six preconditions under which this is equivalent to the bulk+surface divergence path — a sub-volume embedded in surrounding material (e.g. rock) is NOT equivalent.

Unlike point_acceleration, this does not take a WeightedPointSource: mass_kg (real, finite, non-negative background mass elements) and displacement_m (real or complex displacement vectors, shape (N, 3)) are a two-argument vector-weight composition, not a weights_kg-only quantity (source-types.md CRITICAL).

Complex outputs represent linear complex amplitudes or transfer-function-like responses, not directly real-valued time-domain gravitational fields.

Parameters:

Name Type Description Default
sources_xyz (array - like, shape(N, 3))
required
mass_kg (array - like, shape(N), real, finite, non - negative)
required
displacement_m (array - like, shape(N, 3), real or complex)
required
targets TargetPoints or array - like
required
softening_m float

Plummer softening parameter in meters. Defaults to 0.0. Note that for softening_m > 0, the underlying K_T tensor does not satisfy tr(T) = 0 (kernel_contract.md §4), so this response inherits the same non-trace-free caveat (see dipole_contract).

0.0
chunk_size int
None
backend str

'numpy' (default), 'numba', 'cpp', or 'cupy' (GPU; requires a CuPy wheel matching the local CUDA/ROCm runtime and a working CUDA device).

'numpy'

Returns:

Type Description
(FloatArray or ComplexArray, shape(M, 3))

The acceleration produced by displacing masses by a small vector field — the dipole, or "total", path. Rather than differencing two configurations, it contracts the gravity-gradient kernel against the displacement directly, which avoids the catastrophic cancellation that differencing a sub-micrometre motion between two large fields would produce. This is the top-level route for taking a solver's displacement output into a gravity signal; see Displacement and density-perturbation fields for how to build the inputs, including the case where the bulk term is identically zero.