Skip to content

Fields, waves and coherent

This page covers everything downstream of a raw displacement or a plane wave: turning a field into mass elements, building kinematic wave solutions, and combining per-direction responses into coherent statistics. None of it multiplies by G_SI except the Observables re-exports at the end, which are documented in full on Sources, targets and geometry and Top-level API and are only cross-referenced here.

Fields

gragra.fields turns a displacement or density-perturbation field into the mass elements an observable can integrate: a bulk term from δρ = −∇·(ρ₀ξ), a surface term from the displacement of an interface, or both. See Displacement and density-perturbation fields for the physics; this section is the reference for the container types and the diagnostic helpers.

gragra.fields.DensityTimeSeries dataclass

Bases: _Series

An immutable real density series on fixed volume elements, retaining the strictly increasing time axis, source geometry, IDs, and density convention.

gragra.fields.DensityPhasors dataclass

Bases: _Series

An immutable complex density-amplitude series on fixed volume elements, with positive frequencies and explicit time and spatial phase references.

gragra.fields.FixedMeshDisplacementSeries dataclass

Bases: _Series

An immutable fixed-mesh displacement series that keeps background mass and vector displacement separate for time or frequency-domain observations.

gragra.fields.FixedMeshSurfaceDensitySeries dataclass

Bases: _Series

An immutable fixed-quadrature surface-density series whose signed density and area are separate from the unit normals and immutable face metadata.

gragra.fields.DisplacementGrid dataclass

Helper representing a bulk displacement field on a regular or rectilinear grid.

This helper calculates density perturbations from displacement vectors on a structured regular/rectilinear grid (where coordinate spacings along axes can be non-uniform) using linearized mass conservation.

Parameters:

Name Type Description Default
x_m array - like

1D coordinates of the grid points along the x-axis in meters. Spacings between elements can be non-uniform (rectilinear).

required
y_m array - like

1D coordinates of the grid points along the y-axis in meters. Spacings between elements can be non-uniform (rectilinear).

required
z_m array - like

1D coordinates of the grid points along the z-axis in meters. Spacings between elements can be non-uniform (rectilinear).

required
displacement_m array - like

4D array of shape (Nx, Ny, Nz, 3) containing displacement vectors. Can be real (float64) or complex (complex128 for harmonic amplitude).

required

as_density_perturbation_grid

as_density_perturbation_grid(
    rho0_kg_m3: float | NDArray[float64],
) -> DensityPerturbationGrid

Compute the density perturbation grid from the displacement field.

Calculated via delta_density = -rho0 * div(u) - u . grad(rho0), using second-order central finite differences.

Parameters:

Name Type Description Default
rho0_kg_m3 float or (Nx, Ny, Nz) ndarray

float: uniform background density. ndarray (Nx, Ny, Nz): spatially varying background density. Full delta_rho = -rho0*div(u) - u.grad(rho0) is computed using np.gradient (edge_order=2) for both div(u) and grad(rho0).

required

Returns:

Type Description
DensityPerturbationGrid

The computed density perturbation grid helper.

Notes

Limitation: When rho0_kg_m3 is a single uniform scalar, this evaluates only the bulk term delta_rho = -rho0 * div(u). Spatially varying background densities on unstructured meshes are handled differently.

A bulk displacement field on a regular or rectilinear grid, paired with a BackgroundDensityModel to derive δρ = −∇·(ρ₀ξ) via finite differences.

gragra.fields.DensityPerturbationGrid dataclass

Helper for bulk density perturbation fields on regular/rectilinear grids.

This helper facilitates importing density perturbation data defined on a structured regular/rectilinear grid (where coordinate spacings along axes can be non-uniform) and converting it into a gragra source representation.

Parameters:

Name Type Description Default
x_m array - like

1D coordinates of the grid points along the x-axis in meters. Spacings between elements can be non-uniform (rectilinear).

required
y_m array - like

1D coordinates of the grid points along the y-axis in meters. Spacings between elements can be non-uniform (rectilinear).

required
z_m array - like

1D coordinates of the grid points along the z-axis in meters. Spacings between elements can be non-uniform (rectilinear).

required
delta_density_kg_m3 array - like

3D array of shape (Nx, Ny, Nz) containing density perturbations in kg/m^3. Can be real (float64) or complex (complex128 for harmonic amplitude).

required
cell_size_m float, tuple, or array-like

Uniform cell dimensions (dx, dy, dz) in meters. If None, cell sizes are implicitly estimated from local coordinate spacing via np.gradient (requires Nx, Ny, Nz >= 2).

None

as_volume_element_source

as_volume_element_source() -> VolumeElementSource

Convert the regular grid representation to a VolumeElementSource.

Each grid point represents the center of a volume element.

Returns:

Type Description
VolumeElementSource

The volume element source.

A bulk density-perturbation field already expressed as δρ on a regular/rectilinear grid, for callers who have δρ directly rather than a displacement to differentiate.

gragra.plotting.plot_field

plot_field(
    field: DensityPerturbationGrid | DisplacementGrid,
    *,
    frame: Frame,
    plane: str | None = None,
    index: int | None = None,
    part: str | None = None,
    component: str | None = None,
    unit: str = "m",
    max_points: int | None = None,
    ax: Axes | None = None,
) -> Figure

Plot density perturbation or displacement field data faithful to native grid coordinates.

Parameters:

Name Type Description Default
field DensityPerturbationGrid or DisplacementGrid

Input field helper object.

required
frame Frame

Frame in which the field coordinates are defined.

required
plane ('xy', 'xz', 'yz')

2D plane slice along native grid axes. Must be specified together with index. If omitted (None), creates a 3D plot.

'xy'
index int

Integer grid index along the axis orthogonal to plane. Must be specified together with plane.

None
part ('real', 'imag', 'abs', 'phase')

Complex decomposition. Required if field values are complex. Disallowed if field values are real.

'real'
component ('x', 'y', 'z', 'norm')

Vector component for DisplacementGrid. If specified, plots a scalar field of that component. If None for DisplacementGrid, plots displacement vectors (quiver). Disallowed for DensityPerturbationGrid.

'x'
unit str

Coordinate axis display unit (must be a valid length unit).

"m"
max_points int

Deterministic downsampling limit for displayed points/arrows. If None, all points are displayed.

None
ax Axes

Existing Axes to draw into. Must be empty, Cartesian rectilinear, with linear scales.

None

Returns:

Type Description
Figure

The figure containing the plot.

Plot a density perturbation or displacement field faithful to native grid coordinates without modifying the input field object.

gragra.plotting.hist

hist(
    setup: EvaluationSetup | ResolvedEvaluation,
    quantity: str,
    *,
    target_id: str | None = None,
    bins: int | str | ndarray | Quantity = "auto",
    weight: str = "count",
    xunit: str | UnitBase | None = None,
    frame: Frame | None = None,
    norm: str | None = None,
) -> Histogram

Histogram one source-element diagnostic as a GWexpy Histogram.

Calling this function loads GWexpy, and with it Matplotlib's pyplot. Importing gragra.plotting and obtaining hist does not load them.

Parameters:

Name Type Description Default
setup EvaluationSetup or ResolvedEvaluation

Fixed request built from a point-sum source, for example point_sum(source, ...).at(targets). Analytic models have no source elements and raise ValueError.

required
quantity registered source quantity

Diagnostic to histogram. Every registered scalar source quantity and the existing height selector are accepted. Exact aliases are resolved from the fixed source-quantity registry. gravity_gradient_kernel_norm requires norm="frobenius" or norm="spectral" and bins each source's G-free tensor norm.

required
target_id str

Target used by distance-dependent source quantities. It is required when the setup has more than one target. It must be omitted for target-independent quantities such as density and height.

None
bins int, "auto", 1-D array, or astropy Quantity

An integer gives that many equal bins over the data range. "auto" uses NumPy's automatic rule. A 1-D array gives the bin edges. Plain arrays are read in xunit. A Quantity is converted to xunit and must have a compatible unit. Edges must be real, finite and strictly increasing.

"auto"
weight ('count', 'volume')

"count" gives each element weight 1, so the values are dimensionless. "volume" weights each element by its volume in m^3. Density and volume are available only for sources whose mass weights can be checked against them: a VolumeElementSource, or a source from gragra.gravity_sources.discretize whose discretization records cell_volume_m3. Other sources raise ValueError. density with weight="volume" is accepted only under the same condition. For a source from gragra.gravity_sources.discretize, the volume is the discretized cell volume without boundary-cell correction, so it can differ from the geometric volume of the sphere.

"count"
xunit str or astropy unit

Unit of the horizontal axis (the bin edges) only. The default is kg/m3 for density, m for height and distance, and the registered SI unit for other quantities. The unit must be equivalent to the default. Converting xunit never changes the volume weights.

None
frame Frame

Frame used for height. None means the computation frame of the setup, which is the frame of the source. It is not the root frame. This differs from plot_field, where frame is used only for the figure labels. Here, height is transformed into frame. Distances are invariant under frame changes, so distance and inverse_square are always computed in the computation frame. For those quantities frame only has to be connected to it. For density, frame is checked for connection and is otherwise ignored.

None
norm ('frobenius', 'spectral')

Explicit norm for gravity_gradient_kernel_norm. It is rejected for other quantities.

"frobenius"

Returns:

Type Description
Histogram

Counts or volumes per bin. The vertical unit is dimensionless for weight="count" and m^3 for weight="volume". Elements outside the edges are added to underflow and overflow; they are not dropped. sumw2 is not set because the sums are deterministic.

Raises:

Type Description
TypeError

When setup is not an EvaluationSetup or ResolvedEvaluation, when frame is not a Frame or None, or when the source binding is not a supported point source.

ValueError

For an unsupported quantity or weight; for an analytic model; for a missing, unknown or unexpected target_id, including a target_id given with density or height; for an xunit that is not a valid unit or not equivalent to the default; for a bin unit that is not compatible with xunit; for an integer bin count that is a bool, below 1, or above 1,000,000; for edges that are not a 1-D sequence of at least two real, finite, strictly increasing values; for complex bins; for an xunit conversion that overflows or underflows float64, or whose conversion factor is not representable in float64; for a data range that overflows float64 when edges are derived; for density or volume that cannot be verified, including a source without density or volume and a source from gragra.gravity_sources.discretize whose cell_volume_m3 is missing or invalid; for a frame that is not connected to the computation frame; for a non-finite value; for squared separations that overflow, or that are zero or subnormal for a nonzero separation; and for an "auto" bin count above 1,000,000. For distance and inverse_square, a source element that coincides with the selected target, or lies so close to it across frames that the coordinate difference is not reliable, raises a ValueError subclass carrying source_index and target_id attributes.

Notes

Density, height, distance and inverse_square are geometric or mass diagnostics. They do not multiply by G, and they do not apply a mass weight. inverse_square is not the magnitude of a gravitational acceleration. This function does not establish the scientific acceptance of any physical model.

Density is rejected for WeightedPointSource, PointMass and PointMassCloud, and for any source without the volume information that would let its mass weights be matched to a density. The weights are not inverted to recover a density.

When all values are equal, NumPy widens the data range to value +/- 0.5 before it derives the edges. This happens only for integer bins and "auto". Explicit edges are not widened. The last edge belongs to the last bin, so a value equal to the last edge is not counted as overflow.

The "auto" bin count is estimated before any edges are allocated. The estimate follows the NumPy version that is installed, because NumPy changed its auto rule. If the estimate exceeds 1,000,000 bins, the call raises ValueError; pass explicit edges in that case. Values are float64, so NumPy's integer minimum-width rule does not apply.

For distance and inverse_square, a nonzero separation whose square is zero or subnormal is rejected. This check is stricter than the validate() method of the setup. Where the squared separation is near the float64 minimum, 1/r**2 loses precision. Only the selected target is checked. validate() checks every target, so this function can succeed while validate() fails for another target.

When frame differs from the computation frame, each point is transformed separately in Python. The call is therefore slow for large sources.

Histogram per-element density, height, distance, inverse-distance, inverse-square, inverse-cube, and density-over-distance diagnostics of a discrete point-sum setup as a GWexpy Histogram, with counts or volumes per bin. See Source diagnostics for the quantity names, units, and frame rules.

gragra.plotting.plot_hist

plot_hist(
    setup: EvaluationSetup
    | ResolvedEvaluation
    | RadialHistogramResult,
    quantity: str | None = None,
    *,
    target_id: str | None = None,
    bins: int | str | ndarray | Quantity = "auto",
    weight: str = "count",
    xunit: str | UnitBase | None = None,
    frame: Frame | None = None,
    norm: str | None = None,
    ax: Axes | None = None,
) -> Figure | tuple[Figure, Axes, RadialHistogramResult]

Draw a source histogram as a step plot.

For an evaluation setup, arguments have the same meaning as in hist() and the function returns a Figure. For a RadialHistogramResult, call plot_hist(result); it draws the result's normalized values against the raw histogram edges and returns (figure, axes, result). The result overload does not re-bin. Calling this function loads GWexpy and Matplotlib's pyplot.

Parameters:

Name Type Description Default
setup (EvaluationSetup, ResolvedEvaluation or RadialHistogramResult)

Fixed source request or a precomputed radial histogram result.

required
quantity registered source quantity

Diagnostic to draw. See hist().

None
target_id str

Target used by distance-dependent source quantities. It is required when the setup has more than one target and must be omitted for target-independent quantities.

None
bins int, "auto", 1-D array, or astropy Quantity

Bin count or bin edges, read as in hist(). An integer above 100,000 is rejected before anything is computed. "auto", explicit edges and Quantity edges are checked after hist() has built the histogram.

"auto"
weight ('count', 'volume')

"count" counts elements. "volume" sums their volumes in m^3. The sources that allow each weight are those of hist().

"count"
xunit str or astropy unit

Unit of the horizontal axis (the bin edges). The default depends on the quantity; see hist().

None
frame Frame

Frame used for height. See hist().

None
norm ('frobenius', 'spectral')

Explicit norm for gravity_gradient_kernel_norm. See hist().

"frobenius"
ax Axes

Empty, 2-D Cartesian axes with linear scales to draw on. If omitted, a new figure is created. The axes is not closed.

None

Returns:

Type Description
Figure or tuple

Setup calls return the open figure. Result calls return the open figure, axes and same result object.

Raises:

Type Description
TypeError

For the same setup, frame and binding errors as hist().

ValueError

For an ax that is not an empty, 2-D, linear Matplotlib Axes; for more than 100,000 bins, which is stricter than the 1,000,000 limit of hist(); and for every other error that hist() raises. The axes check and the integer bin-count check run before anything is drawn.

Notes

With bins="auto" the bin count is known only after hist() has estimated it, so the 100,000-bin limit is checked after the histogram is built. Integer bin counts are checked before the call.

When the underflow or overflow is nonzero, the axes shows a text note with both values. Those elements are not part of the drawn bins.

Draw a hist result as a step plot on a new or supplied empty Matplotlib axes and return the figure. A RadialHistogramResult can also be passed directly; that overload draws its normalized values against the stored edges without re-binning and returns (figure, axes, result). See gragra.plotting.radial_histogram for the radial histogram API.

gragra.plotting.plot_map

plot_map(
    setup: EvaluationSetup | ResolvedEvaluation,
    quantity: str,
    *,
    target_id: str | None = None,
    view: Literal["3d", "xy", "xz", "yz"] = "3d",
    frame: Frame | None = None,
    direction: tuple[float, float, float]
    | ndarray
    | None = None,
    coord_unit: str = "m",
    max_points: int | None = None,
    color_scale: Literal["linear", "log"] = "linear",
    ax: Axes | None = None,
) -> Figure

Plot discrete source diagnostics over space in 2D or 3D.

Calling this function loads Matplotlib's pyplot. Importing gragra.plotting and obtaining plot_map does not load it.

Parameters:

Name Type Description Default
setup EvaluationSetup or ResolvedEvaluation

Fixed request built from a point-sum source. Analytic models raise ValueError.

required
quantity {"kernel_norm", "delta_a_norm", "delta_a_x", "delta_a_y",

"delta_a_z", "delta_a_projection"} Diagnostic to plot.

required
target_id str

Target used for kernel and acceleration vectors. Required when the setup has more than one target.

None
view ('3d', 'xy', 'xz', 'yz')

3D scatter plot or 2D projection plane.

"3d"
frame Frame

Coordinate frame in which positions, vectors, and components are expressed. If None, the setup's computation_frame is used.

None
direction 3-element sequence or array

Direction vector for "delta_a_projection". Required if and only if quantity="delta_a_projection".

None
coord_unit str

Length unit for spatial coordinates. Must be compatible with meters.

"m"
max_points int or None

Maximum number of source points displayed. If specified, points are thinned with deterministic linear spacing. Must be a positive integer or None (no thinning; all points displayed). Total physical sum is always computed across all points.

None
color_scale ('linear', 'log')

Colormap normalization scaling.

"linear"
ax Axes

Empty Axes to draw on. Must match the view dimension (3D Axes for "3d", 2D Cartesian for projections) and use linear scales.

None

Returns:

Type Description
Figure

Figure containing the drawn scatter plot and colorbar.

Plot Newtonian kernel or gravitational acceleration contributions of discrete source elements across space in 3D or 2D projections. Total physical sum is preserved and agrees with PointSumModel evaluation within floating-point tolerance (rtol=1e-12, atol=1e-20); it is not bitwise identical. See Source diagnostics for details.

gragra.plotting.plot_shape

plot_shape(
    target: Any,
    *,
    view: str = "3d",
    ax: Axes | None = None,
    display_frame: Frame | None = None,
    color: str | None = None,
    alpha: float | None = None,
    **kwargs: Any,
) -> tuple[Figure, Axes]

Plot an analytical source shape (Cuboid, Cylinder, SphericalShell).

Parameters:

Name Type Description Default
target Any

A geometry object, analytic model, or evaluation setup.

required
view str

The projection view. Currently "3d" is supported.

"3d"
ax Axes | None

An optional Matplotlib Axes instance. If None, a new Figure and Axes are created.

None
display_frame Frame | None

The destination coordinate frame for rendering. Defaults to the geometry frame's root.

None
color str | None

Surface / face color for the shape.

None
alpha float | None

Transparency alpha (0.0 to 1.0).

None
**kwargs Any

Additional keyword arguments passed to Matplotlib surface / collection artists.

{}

Returns:

Type Description
tuple[Figure, Axes]

The created or updated figure and axes.

Render 3D geometric shapes of analytical sources as surfaces or wireframes on Matplotlib 3D axes.

gragra.plotting.formula_to_latex

formula_to_latex(expression: str) -> str

Convert a verified ASCII formula expression into its LaTeX representation.

Parameters:

Name Type Description Default
expression str

The ASCII formula string, exactly as recorded in ResolvedEvaluation.formulas.

required

Returns:

Type Description
str

The LaTeX representation.

Raises:

Type Description
ValueError

If the expression is not one of the verified symbol formula expressions, such as model notes, prose descriptions, or unknown formulas.

Format verified analytical source equations and potential formulas into LaTeX math expressions.

gragra.plotting.plot_contribution_hist

plot_contribution_hist(
    setup: Any,
    quantity: str = "norm",
    *,
    target_id: str | None = None,
    bins: int | str | ndarray | Quantity = "auto",
    frame: Frame | None = None,
    ax: Axes | None = None,
) -> tuple[Figure, Axes]

Plot per-element gravitational acceleration contribution histogram.

Parameters:

Name Type Description Default
setup EvaluationSetup or ResolvedEvaluation

A setup built from a discrete point source.

required
quantity ('norm', 'x', 'y', 'z')

Contribution component to histogram.

"norm"
target_id str | None

Target identifier.

None
bins int, "auto", 1-D array, or astropy Quantity

Binning specification.

"auto"
frame Frame | None

Coordinate frame for vectors.

None
ax Axes | None

Axes to draw on.

None

Returns:

Type Description
tuple[Figure, Axes]

Figure and axes containing the histogram.

Histogram per-element gravitational acceleration contributions (norm or Cartesian components) towards one target.

gragra.plotting.plot_cumulative_contribution

plot_cumulative_contribution(
    setup: Any,
    *,
    quantity: str = "norm",
    target_id: str | None = None,
    bins: int | str | ndarray | Quantity = "auto",
    frame: Frame | None = None,
    ax: Axes | None = None,
) -> tuple[Figure, Axes]

Plot cumulative gravitational acceleration a(<R) versus distance.

Parameters:

Name Type Description Default
setup EvaluationSetup or ResolvedEvaluation

A setup built from a discrete point source.

required
quantity ('norm', 'delta_a_norm', 'x', 'y', 'z')

Component of cumulative acceleration vector to plot.

"norm"
target_id str | None

Target identifier.

None
bins int, "auto", 1-D array, or astropy Quantity

Distance binning specification.

"auto"
frame Frame | None

Coordinate frame for vectors.

None
ax Axes | None

Axes to draw on.

None

Returns:

Type Description
tuple[Figure, Axes]

Figure and axes containing the cumulative curve.

Plot the magnitude of the cumulative acceleration vector, or a Cartesian component, versus source–target distance (see the Source diagnostics guide for the norm vs sum-of-norms distinction).

gragra.plotting.plot_result

plot_result(
    result: Any,
    *,
    observable: str = "acceleration",
    component: str | None = None,
    part: str = "magnitude",
    target_id: str | None = None,
    view: str = "auto",
    plane: str | None = None,
    ax: Axes | None = None,
) -> tuple[Figure, Axes]

Plot physical fields, time series, or spectra from an EvaluationResult.

Parameters:

Name Type Description Default
result EvaluationResult

The evaluation result object to plot.

required
observable ('potential', 'acceleration', 'gradient')

The physical observable to plot.

"potential"
component str | None

For vector/tensor observables: "norm", "x", "y", "z", "xx", "xy", etc. Defaults to "norm" for vector/tensor observables, or None for scalars.

None
part ('magnitude', 'abs', 'real', 'imag', 'phase', 'angle')

For complex spectral or phasor quantities, specifies which representation to plot. Defaults to "magnitude".

"magnitude"
target_id str | None

Target identifier. Required for series/spectra if multiple targets exist.

None
view str

Projection view or plot type: "xy", "xz", "yz", "slice", "scatter", "spectrum", "line", or "auto".

"auto"
plane str | None

Optional alias for view plane (e.g. "xy", "xz", "yz").

None
ax Axes | None

Optional existing Matplotlib Axes.

None

Returns:

Type Description
tuple[Figure, Axes]

Figure and axes containing the plot.

Visualize physical fields, time series, or spectra directly from an EvaluationResult container.

gragra.plotting.RadialHistogramResult dataclass

A raw GWexpy histogram and its selected finite-bin values.

histogram always contains unnormalized integrated contributions in the source quantity's unit, including raw underflow and overflow. values contains only finite-bin values after normalization is applied.

unit property

unit: UnitBase

Unit of the selected finite-bin values.

cumulative

cumulative(fraction: bool = False) -> u.Quantity

Return raw cumulative integrated values through each finite bin.

The sequence starts with underflow and ends at the last finite bin's right edge. Overflow is excluded. fraction=True divides by the signed all-source total and therefore requires a finite nonzero total.

Keeps the raw integrated GWexpy histogram and flow values alongside normalized finite-bin values, the signed all-source normalization total, and the selected target context.

gragra.plotting.radial_histogram

radial_histogram(
    setup: EvaluationSetup | ResolvedEvaluation,
    quantity: str,
    *,
    target_id: str | None = None,
    bins: int | str | ndarray | Quantity = "auto",
    normalization: str = "none",
    frame: Frame | None = None,
    norm: str | None = None,
    softening_m: float = 0.0,
) -> RadialHistogramResult

Aggregate a source contribution quantity in distance bins.

Every registered scalar source quantity can be integrated by distance. Extensive quantities such as mass_over_r2 are summed directly. Intensive quantities such as density_over_r2 are multiplied by their verified source-cell volumes before binning. Fixed aliases from the source-quantity registry resolve to canonical IDs. Distances and ratios use the unsoftened Euclidean radius. gravity_gradient_kernel_norm requires norm="frobenius" or norm="spectral"; each source kernel is normed before radial grouping. Its kernel uses softening_m while radial bin membership continues to use the unsoftened radius.

The raw histogram stores integrated finite-bin and flow contributions in the integrated quantity's unit. values uses one of four normalizations: none retains the integrated unit, per_length divides each bin by its width, fraction divides by the signed all-source total, and fraction_per_length performs both operations. The fraction denominator includes sources outside the displayed bin range.

Integrates registered scalar source quantities by unsoftened distance. Extensive values are summed directly; intensive values are multiplied by verified source volumes. Raw flows and optional per-length or signed-fraction normalization are retained.

gragra.plotting.GravityGradientRadialHistogramResult dataclass

Signed static GG tensor sums grouped by source-target distance.

unit property

unit: UnitBase

Unit of the tensor contributions, normally s^-2.

histogram

histogram(component: str) -> Histogram

Return one signed tensor component as a GWexpy radial histogram.

Stores all nine signed components of the static gravity-gradient tensor in finite distance bins, underflow, overflow, and the all-source total. Each component can be returned as a GWexpy Histogram.

gragra.plotting.gravity_gradient_radial_histogram

gravity_gradient_radial_histogram(
    setup: EvaluationSetup | ResolvedEvaluation,
    *,
    target_id: str | None = None,
    bins: int | str | ndarray | Quantity = "auto",
    softening_m: float | None = None,
) -> GravityGradientRadialHistogramResult

Sum the signed static gravity-gradient tensor in distance bins.

Each source term is evaluated by the established point gravity-gradient kernel with its Plummer softening and physical mass weight. Bin membership uses the unsoftened Euclidean source-target distance. The result retains all nine signed tensor components, including underflow and overflow.

Sums static gravity-gradient source tensors by unsoftened source-target distance using the existing softened point kernel. The result retains all signed components and the source-field computation frame.

gragra.plotting.DynamicRadialHistogramResult dataclass

One selected dynamic diagnostic as a radial GWexpy histogram.

values and histogram.values contain finite radial bins. The histogram's underflow and overflow hold the corresponding radial-flow values. valid aligns with finite bins; flow validity is kept separately because phase and interference can be undefined in a flow group.

unit property

unit: UnitBase

Unit of the selected finite-bin values.

Stores one selected dynamic radial metric as a GWexpy Histogram, with finite-bin validity and separate underflow/overflow validity.

gragra.plotting.dynamic_radial_histogram

dynamic_radial_histogram(
    result: SourceContributionResult
    | Sequence[SourceContributionResult],
    quantity: str,
    *,
    target_id: str | None = None,
    frequency_hz: object | None = None,
    component: str | None = None,
    frequency_weights: object | None = None,
    direction_weights: object | None = None,
) -> DynamicRadialHistogramResult

Build a radial Histogram from stored dynamic source groups.

result must come from source_contributions(..., radial_edges_m=...) so its immutable group data already represent underflow, finite distance bins, and overflow. Frequency-resolved quantities require one exact frequency_hz. RMS amplitude fraction instead requires frequency_weights and may combine compatible results using direction_weights. Interference share may also combine compatible directional results; its cross term and total power are averaged before the ratio is formed. A Histogram stores real values, so cumulative complex responses are selected as real and imaginary parts separately.

Converts stored radial groups from SourceContributionResult into a GWexpy Histogram for real or imaginary response, amplitude, phase, amplitude fraction, RMS amplitude fraction, interference share, or cumulative complex response. Frequency-resolved metrics select one exact frequency, target, and component; RMS can use frequency and direction weights, and interference share can use compatible directional results with direction weights.

gragra.plotting.SourceFieldResult dataclass

A native GWexpy Field plus an explicit validity mask and provenance.

Wraps a native GWexpy scalar, vector, or tensor field with an aligned validity mask and immutable grid, target, frequency, and provenance metadata.

gragra.plotting.source_field

source_field(
    data: object,
    quantity: str,
    *,
    target_id: str | None = None,
    grid: object,
    aggregation: str,
    frequency_hz: object | None = None,
    norm: str | None = None,
    projection: object | None = None,
    spatial_projection: str | None = None,
    softening_m: float | None = None,
)

Return a ScalarField, VectorField, or TensorField for source positions.

grid is an explicit tuple (x_edges, y_edges, z_edges). Each edge vector is finite and strictly increasing and defines closed coverage at both outer boundaries. Internal boundaries go to the cell on their right; the final edge is included in the last cell. Every source is assigned once. Static extensive values and physical contributions use sum; static intensive values use a verified volume-weighted mean. Dynamic source responses are additive and use sum.

GG_xx/GG_xy and the other named GG component aliases select one signed component from the static gravity-gradient contribution. GG retains the full tensor, and GG_kernel selects the G-free tensor kernel. GG_kernel_norm requires norm="frobenius" or norm="spectral" and applies that norm to each source tensor before spatial aggregation.

Static fields receive a structural singleton time axis at zero seconds. Dynamic fields keep every stored frequency when frequency_hz is omitted; an exact stored frequency can be selected explicitly. Set spatial_projection to "xy", "xz" or "yz" to sum along the omitted spatial axis, or to compute a volume-weighted mean for intensive static values. Use :func:source_field_result for phase and interference-fraction maps so their validity mask is retained.

For GG_kernel, norm applies after tensor components are summed in each cell. For GG_kernel_norm, it selects the norm applied to each source kernel before those scalar norms are summed.

Bins source-position quantities or physical contributions into explicit three-dimensional cells and returns a native scalar, vector, or tensor field. Dynamic results retain all frequencies by default; frequency_hz selects one exact stored frequency. spatial_projection can sum along the omitted axis for an XY, XZ, or YZ projection.

gragra.plotting.source_field_result

source_field_result(
    data: object,
    quantity: str,
    *,
    target_id: str | None = None,
    grid: object,
    aggregation: str,
    frequency_hz: object | None = None,
    norm: str | None = None,
    projection: object | None = None,
    spatial_projection: str | None = None,
    softening_m: float | None = None,
) -> SourceFieldResult

Return a source-position field, validity mask, and immutable metadata.

Returns the source-position field together with a mask for empty means and undefined phase or interference values, plus immutable grid, target, frequency, and provenance metadata.

gragra.plotting.SourceContributionResult

Metadata and native-matrix access to source-resolved phasors.

Parameters:

Name Type Description Default
data SourceContributionData

A validated, immutable :class:SourceContributionData record.

required
Notes

Matrix rows identify targets, columns identify observable components, and the native frequency axis is in Hz. Array extraction is explicit because both frequency-first and target-first layouts are useful to downstream code and easy to confuse.

global_metadata property

global_metadata: Mapping[str, Any] | None

Return shared input metadata as its immutable, single snapshot.

metadata property

metadata: Mapping[str, Any]

Deeply immutable source, target, phase, and coordinate metadata.

total property

total

Return the total contribution as a fresh native frequency matrix.

iter_source_blocks

iter_source_blocks(
    block_size: int = 256,
    *,
    frequency_index: int | None = None,
) -> Iterator[tuple[int, int, np.ndarray]]

Delegate lazy source iteration without materializing all sources.

source

source(source_id: str | int | integer)

Return one source's native FrequencySeriesMatrix.

String selectors require source IDs that were present in the input. Integer selectors always mean the stable source index and are accepted whether or not source IDs were supplied.

group

group(group_id: Any)

Return one grouped contribution's native frequency matrix.

to_array

to_array(*, kind: str, layout: str) -> np.ndarray

Return a read-only array in a caller-selected axis layout.

kind is one of source, group, or total. The sample_first layout places frequency first; target_first moves target first and frequency after the optional item axis. Components, when present, remain the final axes. Totals have no source/group item axis.

Retains source and group phasors, target and source labels, physical metadata, and access to native frequency-series matrices or explicitly laid-out arrays.

gragra.plotting.source_contributions

source_contributions(
    phasors: DensityPhasors,
    observable: str,
    targets_m: object,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    group_labels: object | None = None,
    radial_edges_m: object | None = None,
) -> SourceContributionResult

Compute complex per-source gravity contributions from density phasors.

Targets are interpreted as SI coordinates in the phasors' own frame and origin. The returned source values are computed on demand from immutable snapshots. Physical source weights are density_kg_m3 * volumes_m3; group sums and totals are accumulated source-block by source-block. No automatic frame transform or phase adjustment is applied.

Computes complex source-resolved potential, acceleration, or gravity-gradient responses from DensityPhasors, accumulating groups and totals in bounded source blocks.

gragra.plotting.ContributionValidityMask

Labelled frequency-domain validity mask with explicit array layout.

Labels which frequency-resolved group statistics are defined for each target and component, with array extraction requiring an explicit layout.

gragra.plotting.ContributionFrequencyStatistic

Native frequency matrices and validity masks, one matrix per group.

Provides per-group native frequency matrices, validity masks, and explicit-layout extraction for a frequency-resolved statistic.

gragra.plotting.ContributionRMSStatistics dataclass

Labelled weighted spectral norms and same-frequency cross quantities.

group_rms stores sqrt(0.5 * sum_f(w_f * |a_j(f)|**2)) and total_rms applies the same norm after coherent group summation. The weights are used as supplied, with no frequency-spacing factor or normalization. This is a peak-phasor spectral quadratic norm; the long-time RMS interpretation assumes distinct positive-frequency tones are orthogonal. It is not a general finite-window time RMS or PSD integral. rms_share divides by the sum of group RMS values, while total_ratio divides by the RMS of the coherent total. group_total_cross is 0.5 * sum_f(w_f * Re(a_j * conj(a_total))).

Stores explicitly weighted peak-phasor spectral norms, RMS shares, total ratios, group-total cross terms, and their validity masks.

gragra.plotting.ContributionStatistics dataclass

Frequency-resolved component statistics and optional weighted RMS.

Amplitude shares use abs(a_j) / sum_k(abs(a_k)). Phase uses arg(a_j) under the input phasor convention. Interference shares use Re(a_j * conj(a_total)) / abs(a_total)**2 and may be negative or greater than one. Undefined phase and ratios use zero placeholders with independent validity masks.

Groups the frequency-resolved amplitude shares, phases, cumulative complex contributions, interference shares, and optional weighted RMS results.

gragra.plotting.contribution_statistics

contribution_statistics(
    result: SourceContributionResult,
    *,
    frequency_weights: object | None = None,
) -> ContributionStatistics

Return componentwise phasor shares, phase, interference, and optional RMS.

With no frequency_weights, all frequency-integrated quantities are None. Supplied weights are finite, non-negative, dimensionless, and used without normalization or an automatic frequency-spacing factor.

Computes componentwise group statistics; exact-zero phase and interference denominators are reported with validity masks.

gragra.plotting.DirectionalContributionStatistics dataclass

Direction-ensemble cross contributions and optional weighted RMS.

directional_cross is the direction-weighted group/total cross term, directional_power is the corresponding total power, and interference_share divides those ensemble means. Ratios are therefore formed after the direction average, not averaged from per-direction ratios. Directional RMS quantities use averaged power, not a complex sum of responses from distinct directions.

metadata property

metadata: Mapping[str, Any]

Return immutable provenance in the same order as the directions.

Stores direction-ensemble cross terms, powers, interference shares, optional weighted RMS results, and per-direction provenance.

gragra.plotting.directional_contribution_statistics

directional_contribution_statistics(
    results: Sequence[SourceContributionResult],
    *,
    direction_weights: object,
    frequency_weights: object | None = None,
) -> DirectionalContributionStatistics

Compute second-order contribution statistics for uncorrelated directions.

Direction weights are normalized to sum to one. Complex source responses are crossed before division, so this reports a direction ensemble rather than the coherent field obtained by summing different directions.

Computes compatible direction-ensemble cross and power averages before taking interference ratios, for directions treated as statistically independent.

Gen1 temperature fields

These immutable inputs describe one prescribed temperature perturbation. The analytic model applies the isobaric ideal-gas relation δρ = -rho0 * δT / T0; finite shapes describe bounded anomalies in a homogeneous background, while TemperaturePerturbationGrid is converted through the existing volume-element and point_sum route. It does not replace a continuum analytic field with an implicit grid approximation.

gragra.fields.TemperatureFourierMode dataclass

Spatial Fourier-mode temperature profile in a fixed Cartesian frame.

Without frequency, a real plane-wave amplitude gives a Static cosine. Supplying frequency selects Phasor output for either real or complex amplitude, with a positive spatial exponential and the shared negative-time reconstruction convention.

gragra.fields.TemperatureGaussian dataclass

All-space isotropic Gaussian temperature profile.

An all-space isotropic Gaussian temperature anomaly with finite center limits and a zero-at-infinity potential reference.

gragra.fields.TemperaturePerturbationGrid dataclass

Rectilinear real Kelvin anomaly grid with explicit fixed support.

The generic static-source route can be composed without importing private model helpers::

source = grid.as_volume_element_source(rho0=rho0, T0=T0)
model = point_sum(
    source, frame=grid.frame, field_definition=grid.field_definition,
    provenance=grid.point_sum_provenance(rho0=rho0, T0=T0),
)

point_sum_provenance

point_sum_provenance(
    *, rho0: Quantity, T0: Quantity
) -> dict[str, object]

Return finite provenance accepted by the existing point-sum route.

as_volume_element_source

as_volume_element_source(
    *, rho0: Quantity, T0: Quantity
) -> VolumeElementSource

Convert cell centers to signed density-times-volume point masses.

A real Kelvin array on explicit increasing length edges. Cells use their centers and product edge widths, with C-order flattening and z varying fastest. Its public field_definition and point_sum_provenance() provide the metadata for the existing point_sum route.

gragra.fields.UnstructuredDisplacementField dataclass

Helper for bulk displacement fields on unstructured linear tetra meshes.

This helper calculates density perturbations from displacement vectors defined at the nodes of an unstructured linear tetrahedron mesh.

Supported: - Linear tetrahedron nodal displacement. - Uniform scalar background density (rho0) or background density model rho0(centroids) (supporting optional spatial gradient). - Bulk term (-rho0 * div(u)) and advection term (-u . grad(rho0)) for spatially varying density (when include_rho0_gradient_term=True). - Real or complex harmonic amplitude representation.

Not supported: - Hexahedron or other non-tetrahedral elements. - Surface/interface perturbation terms or density jumps at interfaces (these are handled by SurfaceDisplacementField). - Solver native importer (HDF5, SPECFEM, etc.).

Parameters:

Name Type Description Default
vertices_m array - like

Coordinate table of mesh nodes (vertices) in meters, shape (Nv, 3).

required
tetra array - like

Element connectivity table of shape (Nc, 4), where each row contains the indices of the four vertices forming a linear tetrahedron.

required
displacement_m array - like

Displacement vectors defined at the mesh nodes (vertices), shape (Nv, 3). Can be real-valued (float64) or complex-valued (complex128 for harmonic amplitude).

required

as_density_perturbation_source

as_density_perturbation_source(
    rho0_kg_m3: float | BackgroundDensityModel,
    include_rho0_gradient_term: bool = False,
) -> VolumeElementSource

Compute the density perturbation and return a VolumeElementSource.

Calculated via delta_density = -rho0 * div(u) - u_centroid . grad(rho0).

Parameters:

Name Type Description Default
rho0_kg_m3 float or BackgroundDensityModel

float: uniform background density. BackgroundDensityModel: background density evaluated at centroids.

required
include_rho0_gradient_term bool

If True, include the advection term -u . grad(rho0). Requires rho0_kg_m3 to support the gradient() method.

False

Returns:

Type Description
VolumeElementSource

The volume element source representing the perturbed density.

as_dipole_source

as_dipole_source(
    rho0_kg_m3: float,
) -> tuple[
    FloatArray, FloatArray, FloatArray | ComplexArray
]

Return (positions_m, mass_kg, displacement_m) at tetra centroids for the dipole/total (vector-weight) path (kernels.inverse_square.dipole_contract, via integrators.direct_point_dipole_sum).

mass_kg = rho0 * vols at each tetra centroid -- real, finite, non-negative (matches dipole_contract's mass_kg contract, kernel_contract.md Section 2.1.1; non-negativity follows automatically here since rho0_kg_m3 is validated non-negative and vols are always strictly positive per post_init's degenerate- tetra rejection). displacement_m = centroid-averaged nodal displacement (u0+u1+u2+u3)/4, real or complex (follows self.displacement_m's dtype). Complex outputs represent linear complex amplitudes or transfer-function-like responses, not directly real-valued time-domain gravitational fields.

Unlike as_density_perturbation_source, this method does not support a callable / BackgroundDensityModel rho0_kg_m3 -- only a uniform scalar background density.

Parameters:

Name Type Description Default
rho0_kg_m3 float

Uniform background density in kg/m^3. Real, finite, non-negative (bool rejected).

required

Returns:

Type Description
tuple of (FloatArray, FloatArray, FloatArray or ComplexArray)

positions_m (nc, 3), mass_kg (nc,), displacement_m (nc, 3). All read-only.

The unstructured-mesh analogue of DisplacementGrid: a bulk displacement field on a linear tetrahedral mesh, from which the bulk mass-element weights are computed per element rather than per grid cell.

gragra.fields.SurfaceDisplacementField dataclass

Helper for displacement fields on unstructured triangular surface meshes.

Computes an effective surface mass-density perturbation from displacement vectors defined at the nodes of a triangle surface mesh. A surface displacement u across an interface with unit normal n_hat and density jump delta_rho generates delta_sigma = delta_rho * (u . n_hat).

Sign / orientation convention

The unit normal of each triangle follows the triangle winding (right-hand rule on v0 -> v1 -> v2); it is not guaranteed to point outward, so a consistent winding is the caller's responsibility (use :meth:check_orientation to diagnose it). The density jump is defined relative to that normal as delta_rho = rho(-n_hat side) - rho(+n_hat side) (for an outward normal this is rho_inside - rho_outside). With that convention delta_sigma = +delta_rho * (u . n_hat) (no extra sign). delta_rho is a signed real density difference and may be negative (e.g. a lighter medium over a heavier one); it is not constrained to be non-negative, unlike the absolute background density rho0 of the bulk helpers.

The per-triangle normal displacement uses the face-mean displacement u_face = (u0 + u1 + u2) / 3 (which equals the area average for a linear P1 element), dotted with the unit normal via a raw (non-conjugate) inner product so that complex harmonic amplitudes are preserved linearly.

Supported: - Linear triangle nodal displacement. - Uniform scalar density jump (delta_rho), surface/interface term only. - Real or complex harmonic amplitude representation.

Not supported: - Quadrilateral or higher-order surface elements. - Position-dependent density jump models. - Solver native importer (HDF5, SPECFEM, etc.).

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

The resulting SurfaceMassSheetSource.as_weighted_source() weights are mass elements only (delta_m = delta_sigma * dS in kg); transfer factors or coherent phase terms belong to a separate (P4) abstraction.

Parameters:

Name Type Description Default
vertices_m array - like

Coordinate table of mesh nodes (vertices) in meters, shape (Nv, 3).

required
triangles array - like

Triangle connectivity table of shape (Nt, 3) of vertex indices.

required
displacement_m array - like

Displacement vectors defined at the mesh nodes (vertices), shape (Nv, 3). Can be real-valued (float64) or complex-valued (complex128 for harmonic amplitude). Component axis is trailing, per the array conventions.

required

as_surface_mass_source

as_surface_mass_source(
    delta_rho_kg_m3: float,
) -> SurfaceMassSheetSource

Compute the surface mass perturbation and return a sheet source.

delta_sigma = delta_rho * (u_face . n_hat) is folded per triangle into a :class:~gragra.gravity_sources.surface.SurfaceMassSheetSource, whose as_weighted_source() yields the mass elements delta_m = delta_sigma * area.

Parameters:

Name Type Description Default
delta_rho_kg_m3 float

Density jump across the interface in kg/m^3 (real, finite, signed; int/numpy real scalars are accepted). See the class docstring for the sign convention relative to the triangle normal.

required

Returns:

Type Description
SurfaceMassSheetSource

Centroids, unit normals, areas, and normal displacements per triangle.

check_orientation

check_orientation() -> OrientationReport

Diagnose the winding consistency and closedness of this mesh.

A consistent winding is the caller's responsibility; this method only reports the diagnosis (it does not modify the mesh). See :func:gragra.fields.surface_orientation.check_triangle_orientation.

Returns:

Type Description
OrientationReport

Diagnostic flags and counts for the mesh winding/topology.

with_consistent_orientation

with_consistent_orientation() -> SurfaceDisplacementField

Return a new field with consistently reoriented triangles.

This method attempts to resolve winding inconsistencies in the mesh topologically and returns a new field instance. Since displacement vectors are node-based, flipping triangle winding does not affect them.

.. note:: Asymmetry with Diagnostics: Unlike :meth:check_orientation, which acts as a non-blocking diagnostic by returning an OrientationReport without raising errors even if the mesh is topologically invalid, this method acts as a strict guard. If winding consistency cannot be resolved (due to non-manifold edges or non-orientable topology like a Mobius strip), it raises a ValueError.

Returns:

Type Description
SurfaceDisplacementField

A new field instance with reoriented triangles.

A displacement field sampled on an unstructured triangular surface mesh, used to build the surface term — the mass redistributed as an interface moves — independently of any bulk contribution.

gragra.fields.TetraLinearizedSources dataclass

Auditable source terms for a piecewise-constant-density tetra body.

Stores read-only mass-displacement, bulk, and interface source terms for a finite, piecewise-constant-density P1 tetra body. The bulk and interface terms form one representation; the mass-displacement term is an alternative for comparison.

gragra.fields.TetraRepresentationReport dataclass

Read-only G-free comparison of two linearized representations.

Records G-free responses for the separate bulk and interface terms, their sum, and the alternative mass-displacement response with residuals per target.

gragra.fields.piecewise_tetra_linear_sources

piecewise_tetra_linear_sources(
    field: UnstructuredDisplacementField,
    density_kg_m3: float | ndarray,
) -> TetraLinearizedSources

Build mass-displacement and bulk/interface sources for one finite body.

Faces are matched by shared vertex IDs only. Geometric vertex merging and global self-intersection detection are outside this bounded contract. Exterior density is fixed at vacuum (zero).

Builds the two finite-body representations from a conforming tetra field and cell densities. It matches faces by vertex ID, treats the exterior as vacuum, and rejects duplicate or non-manifold face ownership.

gragra.fields.compare_tetra_linearized_representations

compare_tetra_linearized_representations(
    sources: TetraLinearizedSources,
    targets,
    *,
    observable: str = "acceleration",
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> TetraRepresentationReport

Compare G-free bulk/interface and mass-displacement quadratures.

Computes G-free potential, acceleration, or gradient responses. It sums bulk and interface responses, then compares that result with the mass-displacement response; it never adds the two representations together.

gragra.fields.TetraP1DensityLinearizedSources dataclass

Builder-validated source terms for cell-local affine tetra density.

Stores read-only degree-2 tetra and face-quadrature source terms for a finite body with cell-local P1 density. It is separate from the existing P0 result so the old face-metadata contract remains unchanged.

gragra.fields.piecewise_tetra_p1_density_sources

piecewise_tetra_p1_density_sources(
    field: UnstructuredDisplacementField,
    cell_density_nodes_kg_m3: ndarray,
    *,
    quadrature_order: int | ndarray | None = None,
) -> TetraP1DensityLinearizedSources

Build P1-density mass-displacement and bulk/interface quadratures.

quadrature_order selects the tetra/face quadrature rule:

  • None (default): the fixed classical degree-2 rule (4-point tetra, 3-point face) -- bit-identical to every call from before this option existed.
  • a scalar int >= 2: every cell (and every face) uses a Gauss-Legendre Duffy rule (gragra.geometry.tetra_quadrature) with that many Gauss points per axis, uniformly.
  • an (Nc,) int array (each entry >= 2): a per-cell Gauss order, i.e. local higher-order refinement without changing subcell count or geometry. A shared interface face takes the higher (max) of its two owning cells' orders; a boundary face takes its single owner's order.

Complex outputs represent linear complex amplitudes or transfer-function-like responses, not directly real-valued time-domain gravitational fields; mass_kg stays real (mass-element weight only, see source-types.md) regardless of quadrature_order.

Builds the P1-density representation from each tetra's local-node density values. Adjacent cells may have discontinuous traces; the exterior remains vacuum and the displacement field remains conforming P1.

gragra.fields.compare_tetra_p1_density_representations

compare_tetra_p1_density_representations(
    sources: TetraP1DensityLinearizedSources,
    targets,
    *,
    observable: str = "acceleration",
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> TetraRepresentationReport

Compare G-free bulk/interface and mass-displacement quadratures.

Compares, without adding, the G-free bulk-plus-interface response and the mass-displacement response for the same cell-local P1-density finite body.

gragra.fields.BackgroundDensityModel

Bases: Protocol

Protocol for background density models.

Evaluates the background density rho0 at the given coordinates.

A Protocol describing anything that can supply a background density ρ₀ at arbitrary points: the minimal interface DisplacementGrid needs to compute ∇·(ρ₀ξ).

gragra.fields.DifferentiableBackgroundDensityModel

Bases: BackgroundDensityModel, Protocol

Protocol for differentiable background density models.

Extends BackgroundDensityModel to provide the spatial gradient (nabla rho0).

gradient

gradient(
    points_m: NDArray[float64],
) -> npt.NDArray[np.float64]

Evaluate the spatial gradient of background density.

Parameters:

Name Type Description Default
points_m (Nc, 3) float64 array

Coordinates where the gradient is evaluated.

required

Returns:

Type Description
(Nc, 3) float64 array

The spatial gradient (d_rho0/dx, d_rho0/dy, d_rho0/dz) at each point.

The stricter Protocol variant that can also supply ∇ρ₀ analytically, avoiding the finite-difference approximation BackgroundDensityModel alone would require for the density-gradient term.

gragra.fields.OrientationReport dataclass

Diagnostic result for triangle surface mesh orientation.

All fields are read-only; inconsistent_triangle_indices is stored as a defensive read-only copy. Inspect the boolean flags explicitly (no truthiness is defined on the report itself).

Attributes:

Name Type Description
is_consistent bool

True when every edge shared by exactly two triangles is traversed in opposite directions (a consistent manifold winding). Note that winding consistency and manifold-ness are independent: a non-manifold mesh (an edge shared by three or more triangles) can still report is_consistent=True because such edges are excluded from the opposite-direction check.

is_closed bool

True when the mesh has no boundary edges and no non-manifold edges (every edge is shared by exactly two triangles).

is_outward bool | None

Only meaningful when is_closed and is_consistent; otherwise None. True when the signed volume is strictly positive, i.e. the per-triangle normals (v1-v0) x (v2-v0) point outward. A degenerate closed mesh with signed_volume_m3 == 0.0 reports False (0 > 0 is False).

Limitation: a single boolean cannot certify outward orientation for a multi-component closed mesh. Two disjoint closed surfaces, one wound outward and one inward, satisfy is_consistent and is_closed yet the signed volume is V_a - V_b, whose sign does not guarantee that every component is outward. Connected-component decomposition is out of scope for this diagnostic.

signed_volume_m3 float

Signed volume (1/6) * sum_t a_t . (b_t x c_t) over triangles in connectivity order. Physically meaningful (the enclosed volume) only for a closed and consistently wound surface; for an open surface it is origin-dependent, and for a closed but inconsistently wound surface it is neither the enclosed volume nor origin-independent (hence is_outward is None in that case).

inconsistent_edge_count int

Number of edges shared by exactly two co-directed triangles.

boundary_edge_count int

Number of edges belonging to exactly one triangle (open boundary).

nonmanifold_edge_count int

Number of edges shared by three or more triangles.

inconsistent_triangle_indices ndarray

Sorted, de-duplicated np.intp indices of triangles participating in an inconsistent edge. Both triangles sharing an inconsistent directed edge are included (the diagnostic does not decide which one is "wrong").

The diagnostic result of check_triangle_orientation: whether a mesh's winding is internally consistent and whether it forms a closed manifold, plus which facets disagree if not.

gragra.fields.check_triangle_orientation

check_triangle_orientation(
    vertices_m: list | tuple | ndarray,
    triangles: list | tuple | ndarray,
) -> OrientationReport

Diagnose the winding consistency and closedness of a triangle mesh.

This is a pure function operating on raw arrays. It validates dtype/shape only; it does not enforce non-degenerate (non-zero-area) triangles, since a zero-area triangle is topologically harmless and contributes ~0 to the signed volume. Repeated-index triangles (e.g. [0, 1, 1]) are rejected with ValueError because the self-loop edge would pollute the topology counts.

Parameters:

Name Type Description Default
vertices_m array - like

Vertex coordinate table of shape (Nv, 3) in meters (float64).

required
triangles array - like

Triangle connectivity table of shape (Nt, 3) of vertex indices. Integer indices in [0, Nv), normalized to np.intp via :func:gragra._arrays.as_index_table (input integer dtype independent).

required

Returns:

Type Description
OrientationReport

Diagnostic flags and counts. See :class:OrientationReport.

Diagnoses the winding consistency and closedness of a triangle mesh before it is used as a surface source — a mesh with inconsistent winding produces a surface term whose contributions partially cancel instead of summing.

gragra.fields.reorient_triangles

reorient_triangles(
    triangles: list | tuple | ndarray,
) -> np.ndarray

Consistently reorient triangle winding.

This function attempts to resolve winding inconsistencies (i.e. ensure that for every pair of triangles sharing an edge, the edge is traversed in opposite directions).

Topology-Only & Coordinate-Free:

The algorithm is purely topological and does not utilize vertex coordinates (it is coordinate-free). Consequently, it does not force an outward orientation (which would require coordinates and closedness).

Seed Winding Rule:

For each connected component, the algorithm selects a starting triangle as a "seed" and preserves its original winding direction. The winding of all other triangles in the same component is flipped or kept as necessary to be consistent with the seed triangle.

Asymmetry with Diagnostics:
  • Diagnostics (:func:check_triangle_orientation): Reports topological defects (e.g., non-manifold edges, open boundary edges, or winding inconsistencies) by setting properties in the returned OrientationReport without raising any exceptions.
  • Correction (:func:reorient_triangles): Behaves as a strict guard. If it is impossible to achieve winding consistency (due to non-manifold edges shared by 3 or more triangles, or non-orientable topologies such as a Mobius strip), it raises a ValueError.

This is a pure function. It validates and returns a new read-only np.intp array of shape (Nt, 3) without modifying the input array.

Parameters:

Name Type Description Default
triangles array - like

Triangle connectivity table of shape (Nt, 3) of vertex indices. Integer indices in [0, N_max), independent of input integer dtype.

required

Returns:

Type Description
ndarray

A read-only np.intp array of shape (Nt, 3) representing the reoriented connectivity table.

Consistently reorients a triangle mesh's winding, typically applied after check_triangle_orientation reports an inconsistency.

gragra.fields.DipoleConsistencyReport dataclass

G-free comparison between the divergence (bulk+surface) and dipole/total (vector-weight) paths.

See kernel_contract.md Section 2.2 for the six equivalence preconditions (closed volume, consistent winding, outward normal, delta_rho sign convention, geometric boundary match, vacuum truncation) -- a nonzero residual for a mesh/config that violates any precondition is EXPECTED, not a bug (this is the diagnostic's purpose, see :func:dipole_consistency_check).

Complex outputs (when the volume field's displacement is complex) represent linear complex amplitudes or transfer-function-like responses, not directly real-valued time-domain gravitational fields.

Attributes:

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

G-free acceleration from the divergence (bulk [+ surface]) path.

acceleration_dipole (FloatArray or ComplexArray, shape(M, 3))

G-free acceleration from the dipole/total path.

abs_residual (FloatArray, shape(M))

norm(acceleration_bulk_surface - acceleration_dipole, axis=-1).

rel_residual (FloatArray, shape(M))

abs_residual / norm(acceleration_dipole, axis=-1), with an explicit rule at targets where acceleration_dipole is exactly zero (a fixed-epsilon floor is deliberately NOT used there: gragra spans many magnitude scales with no canonical unit, so any fixed floor either fails to guard the zero or overflows to +inf for realistic abs_residual magnitudes -- see numerical.md's zero-division guard rule): 0.0 if abs_residual is also (numerically) zero (perfect agreement), otherwise +inf (a clean, well-defined signal of total disagreement). Always inspect abs_residual directly to interpret this degenerate case.

All fields are read-only (``flags.writeable is False``) and shape-checked
against each other (matching leading (M,) length) in ``__post_init__``.

The diagnostic result of dipole_consistency_check: a G-free comparison between the divergence-based (bulk + surface) path and the direct dipole-contraction path for the same displacement field, which should agree under the six equivalence conditions in kernel_contract.md §2.2.

gragra.fields.dipole_consistency_check

dipole_consistency_check(
    volume_field: UnstructuredDisplacementField,
    surface_field: SurfaceDisplacementField | None,
    rho0_kg_m3: float,
    delta_rho_kg_m3: float | None,
    targets_xyz: list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
) -> DipoleConsistencyReport

Cross-check the divergence path against the dipole/total path.

Path A (divergence, existing): volume_field.as_density_perturbation_source(rho0_kg_m3) -> direct_point_sum(..., observable="acceleration") (scalar weight, mass elements) + (if surface_field is not None) surface_field.as_surface_mass_source(delta_rho_kg_m3) -> direct_point_sum(..., observable="acceleration"), summed into the volume contribution. Path B (dipole): volume_field.as_dipole_source(rho0_kg_m3) (background mass elements mass_n = rho0 * vol_n at undisturbed tetra centroids) -> direct_point_dipole_sum. No surface term -- the dipole/total formula is a pure volume integral (ANNA eq. 15/17); it is not summed with any surface contribution.

surface_field=None (with delta_rho_kg_m3=None) is a valid, intentional "bulk-only" diagnostic mode for a volume mesh with no modeled interface -- it is not merely a device for constructing a deliberate non-equivalence probe.

CALLER RESPONSIBILITY (kernel_contract.md Section 2.2): equivalence between Path A and Path B requires a closed volume mesh, consistent triangle winding, outward-pointing surface normals, delta_rho_kg_m3 following fields/surface.py's sign convention, geometric coincidence of the volume boundary and surface mesh, and vacuum truncation outside the boundary. This function does NOT verify these preconditions (no automatic winding/outward check is run) -- callers must confirm them independently, e.g. via SurfaceDisplacementField.check_orientation() / OrientationReport before calling this function on data expected to satisfy equivalence. Note that OrientationReport.is_outward is only a reliable outward-orientation certificate for a single connected component -- for a multi-component closed mesh a single boolean cannot certify every component is outward (see fields/surface_orientation.py's OrientationReport docstring). Calling this function on an open sub-volume is valid and expected to show a large, non-vanishing residual -- that is the diagnostic's purpose, not a bug.

Output is G-free (G_SI is not applied) -- this is a kernel-layer diagnostic, not a public observable; the residual between the two G-free paths is unaffected by G_SI (a common multiplicative factor), so the comparison need not multiply by it.

Parameters:

Name Type Description Default
volume_field UnstructuredDisplacementField

Bulk displacement field supplying both Path A's bulk term (as_density_perturbation_source) and Path B's dipole source (as_dipole_source).

required
surface_field SurfaceDisplacementField or None

Optional interface displacement field supplying Path A's surface term. If None, Path A is bulk-only (a valid diagnostic mode, not merely a non-equivalence probe); delta_rho_kg_m3 must also be None in that case.

required
rho0_kg_m3 float

Uniform background density in kg/m^3, forwarded to both as_density_perturbation_source and as_dipole_source (each validates it independently: real, finite, non-negative).

required
delta_rho_kg_m3 float or None

Density jump across the interface in kg/m^3, forwarded to surface_field.as_surface_mass_source. Must be provided (not None) exactly when surface_field is not None -- specifying only one of the pair raises ValueError (a silent ignore of the caller's intended surface term is avoided).

required
targets_xyz (array - like, shape(M, 3))

Target coordinates in meters. Validated independently by the underlying direct_point_sum / direct_point_dipole_sum calls.

required
softening_m float

Plummer softening in meters, forwarded to all kernel calls. Defaults to 0.0.

0.0
chunk_size int

Chunk size forwarded to all kernel calls. Defaults to None.

None

Returns:

Type Description
DipoleConsistencyReport

Cross-checks the divergence path (bulk mass elements + surface mass sheet) against the dipole/total path (displacement_transfer_acceleration) for the same field; a non-trivial residual signals a broken equivalence condition, not necessarily a bug — see guide/fields.md.

gragra.fields.batched_displacement_grid_weights

batched_displacement_grid_weights(
    x_m, y_m, z_m, displacement_m, rho0_kg_m3
) -> tuple[np.ndarray, np.ndarray]

Compute batched weights from structured grid displacements.

Parameters:

Name Type Description Default
x_m array - like

1D grid coordinate axes.

required
y_m array - like

1D grid coordinate axes.

required
z_m array - like

1D grid coordinate axes.

required
displacement_m (P, Nx, Ny, Nz, 3) array-like or sequence of (Nx, Ny, Nz, 3)

arrays. Batched displacement field.

required
rho0_kg_m3 float or (Nx, Ny, Nz) ndarray

Background density.

required

Returns:

Name Type Description
positions_m (N, 3) ndarray

Read-only grid cell center positions.

weights (N, P) ndarray

Read-only computed batched density perturbation weights.

Computes batched bulk mass-element weights from a batch of structured-grid displacement snapshots in one call, for time- or parameter-batched fields.

gragra.fields.batched_unstructured_weights

batched_unstructured_weights(
    vertices_m,
    tetra,
    displacement_m,
    rho0_kg_m3,
    *,
    include_rho0_gradient_term: bool = False,
) -> tuple[np.ndarray, np.ndarray]

Compute batched weights from unstructured tetrahedral mesh displacements.

Parameters:

Name Type Description Default
vertices_m (Nv, 3) array-like

Mesh node coordinates.

required
tetra (Nc, 4) array-like

Tetrahedron connectivity indices.

required
displacement_m (P, Nv, 3) array-like or sequence of (Nv, 3) arrays.

Batched displacement field.

required
rho0_kg_m3 float or BackgroundDensityModel

Background density.

required
include_rho0_gradient_term bool

Whether to include background density gradient term.

False

Returns:

Name Type Description
positions_m (Nc, 3) ndarray

Read-only cell centroid positions.

weights (Nc, P) ndarray

Read-only computed batched density perturbation weights.

The unstructured-mesh analogue of batched_displacement_grid_weights: batched bulk weights from a batch of tetrahedral-mesh displacement snapshots.

gragra.fields.batched_surface_weights

batched_surface_weights(
    vertices_m,
    triangles,
    displacement_m,
    delta_rho_kg_m3: float,
) -> tuple[np.ndarray, np.ndarray]

Compute batched weights from surface mesh displacements.

Parameters:

Name Type Description Default
vertices_m (Nv, 3) array-like

Mesh node coordinates.

required
triangles (Nt, 3) array-like

Triangle connectivity indices.

required
displacement_m (P, Nv, 3) array-like or sequence of (Nv, 3) arrays.

Batched displacement field.

required
delta_rho_kg_m3 float

Density jump across the interface.

required

Returns:

Name Type Description
positions_m (Nt, 3) ndarray

Read-only surface facet centroid positions.

weights (Nt, P) ndarray

Read-only computed batched density perturbation weights.

Batched surface-term weights from a batch of surface-mesh displacement snapshots, the surface-term counterpart to the two bulk batching helpers above.

gragra.fields.adiabatic_pressure_density_perturbation

adiabatic_pressure_density_perturbation(
    delta_pressure_pa: object, sound_speed_m_s: object
)

Return delta_p/c_s**2 for a physical pressure perturbation in Pa.

Sound speed is positive finite and real. Pressure perturbations may be real or complex. Scalars may scale an array, but non-scalar inputs must have exactly matching shapes.

Converts a physical pressure perturbation to its adiabatic density perturbation using δρ = δp/c_s², with explicit SI pressure and sound speed.

gragra.fields.isobaric_temperature_density_perturbation

isobaric_temperature_density_perturbation(
    rho0_kg_m3: object,
    delta_temperature_k: object,
    temperature0_k: object,
)

Return the ideal-gas isobaric linearization -rho0*delta_T/T0.

Background density and absolute temperature are positive finite real scalars or arrays. The temperature perturbation may be real or complex. Scalars may scale an array, but all non-scalar inputs must have exactly the same shape; general NumPy broadcasting is intentionally rejected.

Converts a temperature perturbation to its ideal-gas isobaric density perturbation using δρ = −ρ₀δT/T₀.

gragra.fields.FixedMeshDisplacementSources dataclass

One fixed mesh's SI background mass and sampled displacement field.

mass_source and volume_source are alternative views of the same background mass. They are not meant to be summed with one another or with a surface representation.

volume_source property

volume_source: VolumeElementSource

Return the existing density-times-volume source representation.

mass_source property

mass_source: WeightedPointSource

Return the existing background-mass point representation.

as_frequency_series

as_frequency_series(
    frequency_hz: float, *, t_ref_s: float = 0.0
) -> FixedMeshDisplacementSeries

Wrap this one sampled field in the existing one-sample series API.

Stores fixed-mesh displacement field source terms for time or frequency evaluations.

gragra.fields.FixedMeshSurfaceSources dataclass

One fixed triangle mesh's SI surface sheet plus shared metadata.

Stores fixed-mesh surface density and normal source terms for boundary interfaces.

gragra.fields.Hex8DisplacementField dataclass

Isoparametric Q1 displacement on hex8 cells with VTK node order.

Jacobians are checked at 27 reference lattice points and at every selected quadrature point. Coordinates and displacement use metres.

sources

sources(materials, *, quadrature_order=3, cell_ids=None)

Build Gaussian mass-motion and bulk-density views (G-free).

Represents an 8-node hexahedral (Hex8) finite-element displacement field.

gragra.fields.Hex8Sources dataclass

Q1 Gaussian volume source views, built only by a validated hex field.

bulk_source omits interfaces. mass_kg, displacement_m represents complete linearized finite-body mass motion, including those interfaces, through the existing displacement integrator. Do not add the two views.

Stores mass-element sources derived from a Hex8 displacement field.

gragra.fields.MaterialRegions dataclass

Finite cell-constant background with explicit cell/region identities.

region_ids is in cell_ids order. The density map must contain exactly the used integer region IDs. Zero-density cells represent cavities.

check_mesh

check_mesh(cell_ids, coordinate_frame, unit_system='SI')

Reject reordered, missing, duplicate IDs or mixed frame/units.

tetra_sources

tetra_sources(
    field,
    *,
    cell_ids,
    coordinate_frame="world",
    unit_system="SI",
    quadrature_order=None,
)

Reuse P1 bulk/interface topology: jump=rho_negative-rho_positive.

Defines piecewise-continuous material density and elastic parameter regions.

gragra.fields.build_fixed_mesh_displacement_sources

build_fixed_mesh_displacement_sources(
    positions_m,
    volumes_m3,
    density_kg_m3,
    displacement_m,
    *,
    source_ids,
    coordinate_frame: str = "world",
    coordinate_origin_m=(0.0, 0.0, 0.0),
    phase_origin_m=(0.0, 0.0, 0.0),
    phase0_rad: float = 0.0,
) -> FixedMeshDisplacementSources

Build fixed-volume mass and displacement sources without interpolation.

Builds mass displacement sources from a fixed mesh and nodal displacement vectors.

gragra.fields.build_fixed_mesh_surface_sources

build_fixed_mesh_surface_sources(
    vertices_m,
    triangles,
    displacement_m,
    density_jump_kg_m3: float,
    *,
    source_ids,
    coordinate_frame: str = "world",
    coordinate_origin_m=(0.0, 0.0, 0.0),
    phase_origin_m=(0.0, 0.0, 0.0),
    phase0_rad: float = 0.0,
) -> FixedMeshSurfaceSources

Build surface density-times-area sources from one sampled triangle field.

Builds interface mass sheet sources from a fixed surface mesh.

gragra.fields.build_plane_wave_fixed_mesh_sources

build_plane_wave_fixed_mesh_sources(
    positions_m,
    volumes_m3,
    density_kg_m3,
    *,
    k_hat,
    wavenumber_rad_m: float,
    wave_type: str,
    amplitude_m: float = 1.0,
    phase0: float = 0.0,
    phase_origin_m=(0.0, 0.0, 0.0),
    source_ids,
    coordinate_frame: str = "world",
    coordinate_origin_m=(0.0, 0.0, 0.0),
) -> FixedMeshDisplacementSources

Sample an existing P/S plane-wave constructor on a fixed mesh once.

Builds fixed-mesh mass sources excited by a propagating plane wave.

Waves

gragra.waves supplies closed-form kinematic field constructors — plane waves, Rayleigh eigenfunctions, stochastic P/S realizations — that you can feed into gragra.coherent or gragra.fields as input. It does not solve a dynamical PDE for you beyond the Rayleigh secular equation itself. See guide/waves.md for the physics and the confirmed-zero cases (pure S wave, rigid translation).

gragra.waves.plane_wave_phase

plane_wave_phase(
    positions_m: list | tuple | ndarray,
    k_hat: list | tuple | ndarray,
    wavenumber_rad_m: float | int | list | tuple | ndarray,
    phase0: float | int = 0.0,
) -> np.ndarray

Calculate plane wave phase: k * (k_hat . position) + phase0.

Output shape is (N, Ndir, Nf), squeeze is disabled.

The scalar plane-wave phase k·(k̂·r) + phase0, the argument that every other plane-wave helper on this page builds a complex factor or displacement from.

gragra.waves.plane_wave_complex_factor

plane_wave_complex_factor(
    positions_m: list | tuple | ndarray,
    k_hat: list | tuple | ndarray,
    wavenumber_rad_m: float | int | list | tuple | ndarray,
    phase0: float | int = 0.0,
    *,
    sign: int = 1,
) -> np.ndarray

Calculate plane wave complex factor: exp(i * sign * phase).

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

Output shape is (N, Ndir, Nf) and complex128, squeeze is disabled.

The complex factor exp(i·sign·phase) for a plane wave, with sign fixing the time-convention (e^{+iωt} vs e^{-iωt}) a caller commits to.

gragra.waves.plane_wave_displacement

plane_wave_displacement(
    positions_m,
    k_hat,
    wavenumber_rad_m,
    wave_type: str,
    *,
    amplitude_m: float = 1.0,
    phase0: float = 0.0,
    vertical_unit=(0.0, 0.0, 1.0),
    polarization=None,
    orthogonality_tol: float = 1e-05,
) -> np.ndarray

Calculate the displacement field of a plane wave.

Formula: amplitude_m * displacement_direction * plane_wave_complex_factor

Parameters:

Name Type Description Default
positions_m array_like

Target positions where displacement is evaluated, shape (N, 3).

required
k_hat array_like

Wave propagation direction vectors, shape (Ndir, 3).

required
wavenumber_rad_m float or array_like

Wavenumber values, shape (Nf,).

required
wave_type str

Wave polarization type. Must be "P", "S1", "S2", "SH", "SV", or "custom".

required
amplitude_m float

Wave amplitude. Must be a finite real number. Negative values are allowed and are equivalent to adding a phase shift of pi. Default is 1.0.

1.0
phase0 float

Initial phase offset. Default is 0.0.

0.0
vertical_unit array_like

Vertical unit vector defining SV/SH orientations, shape (3,). Default is (0.0, 0.0, 1.0).

(0.0, 0.0, 1.0)
polarization array_like

Custom polarization vector, only used if wave_type is "custom". Default is None.

None
orthogonality_tol float

Orthogonality tolerance for custom polarization. Default is 1e-5.

1e-05

Returns:

Type Description
ndarray

Displacement field array of shape (N, Ndir, Nf, 3) and dtype complex128. It is read-only.

Notes
  • This function is placed in gragra.waves because it represents a purely kinematic quantity and is independent of the gravitational constant G (G-free).
  • The phase follows the e^{i(k.x - omega*t)} time factor convention. The sign of the phase is fixed to +1 internally, meaning there is no sign argument in this API. This ensures consistency with the source-side mass weights (plane_wave_bulk_mass_weights) and prevents phase conjugation mismatches in cross statistics.
  • When coupling this displacement with source mass weights to calculate cross-statistics (like gravitoelastic tensors c_ij), the source and witness displacement MUST share the same wave propagation parameters (k_hat, wavenumber_rad_m, phase0).
  • For surface-wave displacement calculations like Rayleigh waves, the phase convention alignment (such as defining which component is real and positive at the phase origin) is shared, but the API signatures are not unified.
  • Complex outputs represent linear complex amplitudes or transfer-function-like responses, not directly real-valued time-domain fields.

The complex displacement field of a plane wave: amplitude times polarization times plane_wave_complex_factor, for the wave type (P/S1/S2/SH/SV) requested.

gragra.waves.evanescent_complex_factor

evanescent_complex_factor(
    positions_m: list | tuple | ndarray,
    k_hat_horizontal: list | tuple | ndarray,
    wavenumber_rad_m: float | int | list | tuple | ndarray,
    decay_rad_m: float | int,
    *,
    phase0: float | int = 0.0,
    sign: int = 1,
) -> np.ndarray

Calculate evanescent wave complex factor.

e^{i * sign * (k * (k_hat_h . r_xy) + phase0)} * e^{-decay * h} where h = -z >= 0.

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

Output shape is (N, Ndir, Nf) and complex128, squeeze is disabled.

Positions above surface (z > 0) are rejected (ValueError). Negative decay values are rejected (ValueError). Non-horizontal propagation directions are rejected (ValueError).

The complex factor for an evanescent (exponentially decaying with depth) wave component, used where a wave is inhomogeneous rather than uniformly propagating.

gragra.waves.normalize_directions

normalize_directions(
    directions: list | tuple | ndarray,
) -> np.ndarray

Normalize direction vectors.

Expects shape (3,) or (Ndir, 3). Returns a read-only float64 array of shape (Ndir, 3). Raises ValueError if any vector is zero or non-finite.

Normalizes an array of direction vectors to unit length, guarding against zero/non-finite input rather than dividing silently.

gragra.waves.orthonormal_basis_from_direction

orthonormal_basis_from_direction(
    k_hat: list | tuple | ndarray,
    reference_axis: list | tuple | ndarray | None = None,
) -> tuple[np.ndarray, np.ndarray]

Build orthonormal basis (e1, e2) orthogonal to k_hat.

k_hat is expected to be a single 3D vector of shape (3,) or (1, 3). If reference_axis is provided and not parallel (absolute dot product <= 0.99) to k_hat, e1 is defined by projecting reference_axis onto the plane orthogonal to k_hat. Otherwise, a stable deterministic reference axis is chosen. e2 is defined as k_hat_norm x e1 to complete a right-handed system.

Returns tuple (e1, e2) of shape (3,).

Builds an orthonormal basis (e1, e2) orthogonal to a given propagation direction k̂, the basis the S-wave polarizations are expressed in.

gragra.waves.p_wave_polarization

p_wave_polarization(
    k_hat: list | tuple | ndarray,
) -> np.ndarray

P-wave polarization direction (same as normalized k_hat).

The P-wave polarization direction, which is simply the normalized propagation direction k̂ (longitudinal motion).

gragra.waves.s_wave_basis

s_wave_basis(
    k_hat: list | tuple | ndarray,
    *,
    vertical_unit: list | tuple | ndarray | None = None,
    degeneracy_tol: float = 1e-08,
) -> tuple[np.ndarray, np.ndarray]

S-wave polarization basis (e1, e2) orthogonal to k_hat.

If vertical_unit is None, a generic orthonormal basis is returned. If vertical_unit is provided, the physical vertical-anchored (e_SH, e_SV) basis matching the seismic convention is returned.

The S-wave polarization basis (e1, e2) orthogonal to k̂, from which S1, S2, SH and SV polarizations are constructed.

gragra.waves.displacement_direction

displacement_direction(
    wave_type: Literal[
        "P", "S1", "S2", "SH", "SV", "custom"
    ],
    k_hat: list | tuple | ndarray,
    *,
    vertical_unit: list | tuple | ndarray = (0.0, 0.0, 1.0),
    polarization: list | tuple | ndarray | None = None,
    orthogonality_tol: float = 1e-05,
) -> np.ndarray

Displacement direction units according to wave type.

The unit displacement direction for a requested wave type (P, S1, S2, SH, SV), dispatching to p_wave_polarization or s_wave_basis as appropriate.

gragra.waves.rayleigh_secular

rayleigh_secular(c_m_s, v_p_m_s, v_s_m_s) -> np.ndarray

Rayleigh secular function R(c) (Aki & Richards standard form).

R(c) = (2 - c^2/v_S^2)^2 - 4 sqrt(1 - c^2/v_P^2) sqrt(1 - c^2/v_S^2)

The Rayleigh phase speed c_R is the root R(c_R) = 0 on 0 < c < v_S. No extra c^2/v_S^2 factor multiplies the second term (a historically common misprint — see halfspace_conventions.md §3).

Parameters:

Name Type Description Default
c_m_s float or array - like

Trial phase speed(s) in m/s. Must lie strictly inside (0, v_S) — the real-branch domain of the secular function; values outside raise ValueError.

required
v_p_m_s float

P- and S-wave speeds in m/s (0 < v_s < v_p).

required
v_s_m_s float

P- and S-wave speeds in m/s (0 < v_s < v_p).

required

Returns:

Type Description
ndarray

R(c), dimensionless, float64, same shape as c_m_s (read-only).

The Rayleigh secular function R(c) in the standard Aki & Richards form, whose root in phase speed c is the Rayleigh wave speed for a homogeneous elastic half-space.

gragra.waves.rayleigh_speed

rayleigh_speed(v_p_m_s, v_s_m_s) -> float

Rayleigh phase speed c_R from the secular equation (numpy bisection).

Solves R(c_R) = 0 on the primary bracket [0.5 v_S, (1 - 1e-9) v_S] (physical media give c_R/v_S in ~0.87–0.96; 0.5 is a safety margin). If the primary bracket shows no sign change, scans c/v_S in [0.01, 0.999999] for the first sign-change interval; if none exists, raises ValueError carrying v_P/v_S and the sampled extrema of R (fail-closed with diagnostics). Converges to a width of 1e-13 v_S (an order of magnitude below the 1e-12 secular-residual test gate).

For a Poisson solid (v_P/v_S = sqrt(3)) the exact closed form is c_R/v_S = sqrt(2 - 2/sqrt(3)) = 0.9194016868.

Returns:

Type Description
float

c_R in m/s, guaranteed 0 < c_R < v_S.

The Rayleigh phase speed c_R, found as the root of rayleigh_secular via NumPy-based bisection.

gragra.waves.rayleigh_displacement

rayleigh_displacement(
    positions_m: list | tuple | ndarray,
    direction: list | tuple | ndarray,
    wavenumber_rad_m: float | int,
    v_p_m_s: float | int,
    v_s_m_s: float | int,
    *,
    amplitude_m: float | int = 1.0,
) -> np.ndarray

Complex Rayleigh-wave displacement field u(r) in the half-space.

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

Normalization and phase reference: the vertical surface displacement at the horizontal phase origin (k_hat . r_xy = 0, z = 0) is +amplitude_m (real). The horizontal component then carries the 90-degree quadrature phase (factor i) required by the eigenfunction, giving retrograde particle motion at the surface — Im(u_x conj(u_z)) < 0 there, with a sign flip below the horizontal-displacement node at k h = 1.209 (Poisson solid; see halfspace_conventions.md §3.2). The overall particle- motion sense is normalization-independent.

G-free pure kinematics (no G_SI). Evaluation points with z > 0 (above the free surface) raise ValueError — the exponential growth direction is structurally rejected (overflow guard).

Parameters:

Name Type Description Default
positions_m array-like of shape (N, 3)

Evaluation points in meters, z-up, free surface at z = 0, medium z <= 0.

required
direction array-like of shape (3,)

Horizontal propagation direction (must lie in the xy plane; the z component must vanish). Normalized internally.

required
wavenumber_rad_m float

Horizontal wavenumber k > 0 in rad/m.

required
v_p_m_s float

Elastic wave speeds in m/s (0 < v_s < v_p).

required
v_s_m_s float

Elastic wave speeds in m/s (0 < v_s < v_p).

required
amplitude_m float

Vertical surface displacement amplitude in meters (positive finite).

1.0

Returns:

Type Description
ndarray

Complex displacement of shape (N, 3), complex128, component axis trailing, read-only.

The complex Rayleigh-wave displacement field u(r) in the half-space, combining the horizontal and vertical eigenfunctions with their fixed relative phase (see guide/waves.md for the phase convention).

gragra.waves.rayleigh_ellipticity

rayleigh_ellipticity(
    depth_m, wavenumber_rad_m, v_p_m_s, v_s_m_s
) -> np.ndarray

Depth-dependent Rayleigh H/V ellipticity |u_x(h)| / |u_z(h)|.

Derived from the two-exponential eigenfunctions (not a fixed surface value): H/V = |f_x(k h)| / (q |f_z(k h)|). The denominator never vanishes (f_z < 0 for all depths); the ratio crosses zero at the horizontal- displacement node (k h = 1.209 for a Poisson solid, where the surface value is H/V = 0.68125). Evaluated with the slower-decaying exp(-s k h) factored out, so the ratio stays finite at arbitrarily large depths (both raw profiles underflow beyond k h ~ 700/s and would give 0/0 = NaN); the deep limit is H/V -> s.

G-free, dimensionless. depth_m is depth below the surface (h >= 0; negative depths raise ValueError).

Returns:

Type Description
ndarray

H/V, float64, same shape as depth_m (read-only).

The depth-dependent Rayleigh wave H/V ellipticity |u_x(h)| / |u_z(h)|, a diagnostic quantity independent of absolute amplitude.

gragra.waves.free_surface_reflection_vertical

free_surface_reflection_vertical(
    wave_type: Literal["P", "SH", "SV"],
) -> dict[str, float]

Calculate free-surface displacement reflection coefficients.

Calculation is for vertical incidence.

Parameters:

Name Type Description Default
wave_type (P, SH, SV)

The type of the incident wave.

"P"

Returns:

Type Description
dict[str, float]

Real displacement reflection coefficients. - For "P" and "SV": {"R_PP": 1.0, "R_PS": 0.0, "R_SP": 0.0, "R_SS": 1.0} - For "SH": {"R_SH": 1.0}

Raises:

Type Description
ValueError

If wave_type is not one of "P", "SH", "SV".

The free-surface displacement reflection coefficients for vertical incidence, needed to combine an incident and reflected body wave into the correct free-surface displacement.

gragra.waves.surface_displacement_factor_vertical

surface_displacement_factor_vertical() -> float

Free-surface displacement-doubling factor at vertical incidence.

Returns:

Type Description
float

The displacement doubling factor, which is 2.0.

The free-surface displacement-doubling factor at vertical incidence — the scalar consequence of free_surface_reflection_vertical for the common vertically-incident case.

gragra.waves.StochasticPSParameters dataclass

The parameter container for stochastic_ps_realization: propagation direction, vertical unit, wave types, amplitudes, wavenumbers and phase offsets for a correlated P/S wave pair.

gragra.waves.stochastic_ps_realization

stochastic_ps_realization(
    rng: Generator,
    n_realizations: int,
    positions_m,
    wavenumber_p_rad_m: float,
    velocity_ratio_s_over_p: float,
    s_wave_type: Literal["S1", "S2", "SH", "SV"] = "SV",
    *,
    amplitude_p_m: float = 1.0,
    amplitude_s_m: float = 1.0,
    vertical_unit=(0.0, 0.0, 1.0),
    fixed_direction=None,
    correlated_phase: bool = True,
) -> tuple[np.ndarray, np.ndarray, StochasticPSParameters]

Generate a stochastic P/S correlation-preserving plane wave ensemble realization.

This function generates stochastic realizations of coupled P-wave and S-wave displacement fields. The P/S correlation is modeled by sharing a common propagation direction k_hat (either isotropically drawn or fixed) and phase0 (if correlated_phase is True).

Parameters:

Name Type Description Default
rng Generator

Random number generator used to draw stochastic directions and phases.

required
n_realizations int

Number of realizations (R) to generate. Must be a positive integer.

required
positions_m array_like

Target positions where displacement is evaluated, shape (N, 3).

required
wavenumber_p_rad_m float

P-wave wavenumber. Must be positive.

required
velocity_ratio_s_over_p float

Ratio of S-wave to P-wave velocity (C_s/C_p). Must satisfy 0 < ratio < 1.

required
s_wave_type Literal['S1', 'S2', 'SH', 'SV']

S-wave polarization type. Default is "SV".

'SV'
amplitude_p_m float

P-wave amplitude. Default is 1.0.

1.0
amplitude_s_m float

S-wave amplitude. Default is 1.0.

1.0
vertical_unit array_like

Vertical unit vector defining SV/SH orientations, shape (3,). Default is (0.0, 0.0, 1.0).

(0.0, 0.0, 1.0)
fixed_direction array_like or None

Fixed propagation direction, shape (3,). If None, directions are drawn isotropically. Default is None.

None
correlated_phase bool

If True, P and S waves share the same phase0_p = phase0_s (physical model). If False, phase0_p and phase0_s are drawn independently. Default is True.

True

Returns:

Name Type Description
u_p ndarray

P-wave displacement field array of shape (N, R, 3) and dtype complex128. Read-only.

u_s ndarray

S-wave displacement field array of shape (N, R, 3) and dtype complex128. Read-only.

drawn_params StochasticPSParameters

A frozen typed object containing all generated parameters.

Raises:

Type Description
TypeError

If rng is not a np.random.Generator, or if float/integer parameters are boolean or not numeric.

ValueError

If shapes are invalid, non-finite values are encountered, n_realizations <= 0, wavenumber_p_rad_m <= 0, velocity_ratio_s_over_p is outside (0, 1), or a zero vector is supplied for direction.

Notes
  • This function is placed in gragra.waves because it represents a purely kinematic quantity and is independent of the gravitational constant G (G-free).
  • Complex outputs represent linear complex amplitudes or transfer-function-like responses, not directly real-valued time-domain fields.
  • When coupling this displacement with source mass weights, the source and witness must share the exact same propagation parameters (k_hat, wavenumber, phase0).
  • This function uses sign=+1 internally, preventing silent phase conjugation.
  • "P/S correlation" refers to the correlation between P and S waves propagating in the same direction, which is orthogonal to the "direction-uncorrelated" models.
  • correlated_phase=False is for uncorrelated comparison cases only.

Generates a stochastic P/S correlation-preserving plane-wave ensemble realization from a StochasticPSParameters set — a randomized field for Monte Carlo style studies rather than a single deterministic wave.

gragra.waves.PlaneWave dataclass

Harmonic plane wave description.

evaluate_on

evaluate_on(
    sources, *, coordinate_frame: str = "world"
) -> PlaneWaveSources

Sample plane wave displacement on a point cloud or volume mesh.

Kinematic plane wave container with propagation direction, frequency, phase velocity, and amplitude.

gragra.waves.PlanePWave

PlanePWave(
    directions,
    frequencies_hz,
    wavenumbers_rad_m,
    *,
    amplitudes_m=1.0,
    phase_origin_m=(0.0, 0.0, 0.0),
    phase0_rad: float = 0.0,
    t_ref_s: float = 0.0,
) -> PlaneWave

Convenience constructor for a compressional (P) plane wave.

Compressional plane P-wave with longitudinal polarization along the propagation vector.

gragra.waves.PlaneWaveSources dataclass

Evaluated plane-wave mass and displacement perturbation bundle.

Carries sampled background masses and multi-direction/multi-frequency displacement fields for exact linearized gravitational perturbation evaluation.

evaluate

evaluate(
    targets_m: list | tuple | ndarray,
    *,
    observable: Literal[
        "potential", "acceleration", "gradient"
    ] = "acceleration",
    softening_m: float = 0.0,
    chunk_size: int | None = None,
) -> np.ndarray

Calculate complex response for the chosen gravitational observable.

Parameters:

Name Type Description Default
targets_m array_like of shape (M, 3)

Evaluation points in meters.

required
observable ('potential', 'acceleration', 'gradient')

Observable quantity to compute.

"potential"
softening_m float

Plummer softening length.

0.0
chunk_size int

Target chunk size for memory control.

None

Returns:

Type Description
ndarray
  • "potential": shape (M, D, F), complex128
  • "acceleration": shape (M, D, F, 3), complex128
  • "gradient": shape (M, D, F, 3, 3), complex128

Mass-element source representation excited by a kinematic plane wave.

Coherent

gragra.coherent turns a kinematic wave field into mass-element weights and computes cross-statistics between per-direction or per-realization responses. See Coherent responses and cross statistics for the G⁰ witness vs. G¹ vs. G² distinction and the element-wise, conjugate-second- argument convention that the cross-average functions below follow.

gragra.coherent.plane_wave_mass_weights

plane_wave_mass_weights(
    base_weights_kg: list | tuple | ndarray,
    positions_m: list | tuple | ndarray,
    directions: list | tuple | ndarray,
    wavenumber_rad_m: float | int | list | tuple | ndarray,
    phase0: float | int = 0.0,
    sign: int = 1,
    *,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> np.ndarray

Calculate plane-wave coherent mass weights: base_weights * complex_factor.

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

backend selects the implementation ("numpy" default, "numba", "cpp", or "cupy"). Raises ImportError if the selected compiled backend ("numba", "cpp", or "cupy") is not installed or available. The "cupy" backend estimates peak memory and enforces a VRAM safety limit before allocating device memory.

Returns a complex128 array of shape (N, Ndir, Nf) which is read-only.

The plane-wave coherent mass weights: base (real) mass weights modulated by plane_wave_complex_factor, giving each source element a complex, direction- and phase-dependent weight.

gragra.coherent.plane_wave_bulk_mass_weights

plane_wave_bulk_mass_weights(
    volumes_m3: list | tuple | ndarray,
    positions_m: list | tuple | ndarray,
    density_kg_m3: float,
    directions: list | tuple | ndarray,
    wavenumber_rad_m: float | list | tuple | ndarray,
    *,
    wave_type: Literal[
        "P", "S1", "S2", "SH", "SV", "custom"
    ] = "P",
    polarization: list | tuple | ndarray | None = None,
    displacement_m: float = 1.0,
    phase0: float = 0.0,
) -> ComplexArray

Calculate the polarization-projected bulk mass weights for a plane wave.

Calculates the mass perturbation weights: δm_j = −ρ₀ * (i k) * (k̂ · ê_pol) * ξ * V_j * e^{i k k̂ · r_j + iφ₀}

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

G-free convention: The output is the mass perturbation δm_j [kg] under the G-free (G_SI = 1) convention. Complex-output disclaimer: The output is a complex (np.complex128) array of linear complex amplitudes -- see the paragraph above. Formulation distinction: Corresponds to the discretized weights of the volume-integral term (δm = δρ * dV) in the pure-bulk formulation.

Parameters:

Name Type Description Default
volumes_m3 array - like

Shape (N,) volume of each mass element in m^3 (must be positive).

required
positions_m array - like

Shape (N, 3) coordinates of each mass element in meters.

required
density_kg_m3 float

Medium background mass density in kg/m^3 (positive).

required
directions array - like

Shape (Ndir, 3) propagation directions (wavenumber vectors).

required
wavenumber_rad_m float or array - like

Shape (Nf,) wavenumbers in rad/m (non-negative).

required
wave_type str

Wave type (e.g. "P", "SH", "SV", "custom", defaults to "P"). For a pure shear wave the projection k̂ · ê_pol vanishes identically, so the returned weights are exactly zero -- that is the physically correct answer for a bulk term, not a failure.

'P'
polarization array - like

Custom polarization direction of shape (Ndir, 3) if wave_type="custom".

None
displacement_m float

Displacement amplitude of the plane wave in meters (positive).

1.0
phase0 float

Initial phase of the plane wave in radians.

0.0

Returns:

Type Description
ComplexArray

Mass weight array of shape (N, Ndir, Nf) (read-only).

The polarization-projected bulk mass weights δm = −iρ₀k(k̂·ê)ξV·e^{ik·r} for a plane wave — identically zero for a pure S wave (k̂·ê = 0), which is a physically correct null result, not a bug.

gragra.coherent.directional_power_average

directional_power_average(
    response: list | tuple | ndarray,
    direction_weights: list | tuple | ndarray,
    direction_axis: int = 1,
) -> np.ndarray

Calculate the directional power average of a response.

Formula: sum(w_d * |response|^2) along direction_axis.

The directional power average of a response: ⟨|response|²⟩ averaged over a set of directions (e.g. a Lebedev grid), under the "directions are uncorrelated" ensemble model.

gragra.coherent.directional_cross_average

directional_cross_average(
    response_a,
    response_b,
    direction_weights,
    direction_axis: int = 1,
) -> np.ndarray

Calculate the directional cross average between two responses.

Formula: sum(w_d * A_d * conj(B_d)) along direction_axis, where the multiplication is element-wise, not a dot product.

This implements the second-order cross statistics convention. Reference: - coherent_statistics_conventions.md §1/§2/§4

Parameters:

Name Type Description Default
response_a array_like

First response array (A).

required
response_b array_like

Second response array (B). Must have the exact same shape as response_a.

required
direction_weights array_like

Direction weights (w). Must be real-valued. Negative weights are allowed. It is the user's responsibility to normalize the weights; this function performs a raw weighted sum without dividing by the sum of weights.

required
direction_axis int

Axis along which the direction average is computed. Default is 1.

1

Returns:

Type Description
ndarray

Cross average array of dtype complex128. It is read-only. The axis corresponding to direction_axis is removed.

Notes
  • Conjugation is applied to the second argument (response_b).
  • Under a directional ensemble model where fields from different directions are uncorrelated, this average corresponds to the ensemble expectation ⟨A·B*⟩.
  • Since negative weights are allowed, cross(A, A, w) may yield a negative value, and the Hermiticity/positive semi-definiteness (PSD) of the cross tensor is not guaranteed.
  • Complex outputs are second-order cross statistics (cross-spectral quantities such as ⟨A·B*⟩), not time-domain fields; the phase encodes the relative propagation delay or coherence between the two inputs, not an absolute field phase.

The directional cross average between two responses, element-wise with the second argument conjugated (not a dot product) — the primitive the gravitoelastic and CSD observables are built from.

gragra.coherent.directional_outer_cross_average

directional_outer_cross_average(
    response_a, response_b, direction_weights
) -> np.ndarray

Calculate the direction-averaged component-outer cross tensor of two responses.

Formula: c_ij(r_a, r_b) = Σ_d w_d · response_a_i,d · conj(response_b_j,d)

This is a thin wrapper around directional_cross_average (coherent/average.py): it inserts singleton axes so the component axes of the two inputs are broadcast against each other (outer product over components) rather than aligned element-wise, then delegates the direction-axis contraction and conjugate-second-argument convention to that function without reimplementing it (see docs/architecture/coherent_statistics_conventions.md §1/§4).

This helper is G-agnostic: it performs a pure statistical contraction and never multiplies by G_SI. It is the (A)-type (G-free helper) API in the G-order table of coherent_statistics_conventions.md §5; callers (e.g. observables.gravitoelastic) are responsible for computing any G-included response before passing it in.

Parameters:

Name Type Description Default
response_a array_like

First response array, shape (Ma, Ndir, Nf, 3) (component axis trailing). This is the unconjugated argument (index i).

required
response_b array_like

Second response array, shape (Mb, Ndir, Nf, 3). This is the conjugated argument (index j) -- conjugation is applied internally by directional_cross_average; do not pre-conjugate.

required
direction_weights array_like

Real-valued direction weights, shape (Ndir,). Negative values are allowed (see coherent_statistics_conventions.md §2). Normalization is the caller's responsibility: this is a raw weighted sum, not divided by the sum of weights.

required

Returns:

Type Description
ndarray

Cross tensor of shape (Ma, Mb, Nf, 3, 3) and dtype complex128. It is read-only.

Notes
  • Under a directional ensemble model where waves from different directions are mutually uncorrelated, this average corresponds to the ensemble expectation <response_a_i * conj(response_b_j)>. It does not apply to a coherent superposition of directionally correlated waves.
  • Since negative weights are allowed, the resulting 3x3 tensor is not guaranteed to be Hermitian positive semi-definite (PSD); callers must not assume PSD when treating it as a covariance-like quantity.
  • Complex outputs are second-order cross statistics (cross-spectral quantities such as ), not time-domain fields; the phase encodes relative propagation delay/coherence, not an absolute field phase.

The direction-averaged component-outer cross tensor of two vector responses, the tensor-valued generalization of directional_cross_average.

gragra.coherent.ensemble_outer_cross_average

ensemble_outer_cross_average(
    realizations_a, realizations_b
) -> np.ndarray

Calculate the ensemble outer cross average over realizations.

Formula: c_ij(x) = (1/R) sum_{r=1}^R A_i(x, r) * conj(B_j(x, r)) where the component axes form an outer product (3, 3) tensor.

Parameters:

Name Type Description Default
realizations_a array_like

First realization field array (A) of shape (N, R, 3) and numeric type.

required
realizations_b array_like

Second realization field array (B) of shape (N, R, 3) and numeric type. N and R axes must be identical in shape to realizations_a.

required

Returns:

Type Description
ndarray

Outer cross average array of shape (N, 3, 3) and dtype complex128. It is read-only.

Raises:

Type Description
TypeError

If inputs cannot be converted to complex128 or contain booleans.

ValueError

If shapes are invalid, non-finite values are encountered, R = 0, or shape of N and R axes mismatch.

Notes
  • Conjugation is applied to the second argument (realizations_b).
  • The output represents second-order cross statistics (cross-spectral quantities such as ⟨A·B*⟩), not time-domain fields; the phase encodes the relative propagation delay or coherence between the two inputs, not an absolute field phase.
  • This function computes the equal-weight average over realizations (w = 1/R), which has a different statistical meaning from the direction-uncorrelated models (which allow arbitrary real and possibly negative weights).
  • Although the underlying directional_cross_average performs a raw weighted sum without dividing by the sum of weights, w = 1/R makes the result an ensemble average.
  • The component axes are treated as an outer product (yielding a (3, 3) tensor), unlike the element-wise component product used in directional_cross_average.
  • This function is G-agnostic: if the inputs are G-free (like witness displacements), the output is G⁰. If the inputs include G, the output preserves the product of G orders. No additional gravitational constant G_SI is multiplied internally.

The ensemble outer cross average over a set of realizations (rather than directions), used with stochastic_ps_realization-style Monte Carlo ensembles.

gragra.observables.coherent_point_potential

coherent_point_potential(
    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 potential at target points.

Returns negative gravitational potential Phi = -G * sum(w_j / r_j). Output shape is (M, *P), dtype follows weights (real -> float64, complex -> complex128).

Computes the coherent gravitational potential from a point mass excitation.

Analytic

gragra.analytic supplies the closed-form benchmarks this project treats as its primary verification strategy (analytic tests over finite-difference checks). Every function here is G-free — multiply by G_SI before comparing to a public observable. See Analytic benchmarks.

General free-surface P/SV waves

The uniform, lossless half-space at z<0 supports incident P or SV and both reflected modes, including converted evanescent P. Potential, acceleration and gradient are analytic on either side of z=0. Exact surface and grazing points are excluded, as is the nonunique zero-Lame-lambda SV critical point.

gragra.analytic.HalfspacePSVReflection dataclass

Dimensionless reflection data in the Helmholtz potential convention.

u = grad(phi) + curl(psi * e_transverse); upward incident SV has displacement direction cos(theta)*h - sin(theta)*e_z. The two potential ratios divide the reflected scalar potentials by the incident scalar potential (P: phi; SV: psi), not by displacement in meters. p_over_ks has nonnegative imaginary part; reflected P uses kz=-p. Propagating reflected displacement ratios are also supplied, with polarizations (q*h-p*e_z)/kP and (s*h+q*e_z)/kS respectively. For evanescent P that polarization is complex, not a unit vector under the Hermitian norm, so its coefficient is not a displacement magnitude. incident_plus_reflected_potential_ratio is the stable evaluation of one plus the same-mode potential ratio, used to avoid cancellation.

Stores the wave-number ratios and potential/displacement reflection ratios with explicit polarization conventions.

gragra.analytic.halfspace_psv_reflection

halfspace_psv_reflection(
    *,
    wave_type: Literal["P", "SV"],
    v_p_m_s: float,
    v_s_m_s: float,
    incidence_angle_rad: float,
) -> HalfspacePSVReflection

Return lossless free-surface P/SV reflection and conversion ratios.

Angles use the incident mode's speed, measured from +z, in [0, pi/2). Normal and ordinary critical incidence are supported analytically. Exact grazing is excluded. At zero Lame lambda and exact SV critical incidence the traction system loses rank: a horizontal P mode is undetermined. This isolated degenerate configuration raises ValueError.

Evaluates traction-free reflection coefficients without a matrix solve. The evanescent branch decays into the medium.

gragra.analytic.halfspace_psv_observables_g_free

halfspace_psv_observables_g_free(
    targets_m,
    *,
    wave_type: Literal["P", "SV"],
    density_kg_m3: float,
    v_p_m_s: float,
    v_s_m_s: float,
    frequency_hz,
    incidence_angle_rad: float,
    azimuth_rad: float,
    incident_displacement_m,
    phase_origin_m=(0.0, 0.0, 0.0),
) -> GFreeGravityValues

Ground/underground potential, acceleration and gradient, G-free.

Incident P polarization is sin(theta)h+cos(theta)e_z; incident SV polarization is cos(theta)h-sin(theta)e_z. Complex displacement is referenced at the fixed phase origin, using exp(ik.x-iomega*t). Reflection coefficients refer all legs to the surface once. The surface remains z=0 for every origin. Converted evanescent P decays as z -> -inf.

targets_m is (M,3), z != 0. Positive frequency_hz is scalar or (K,); displacement is scalar or matching (K,). Outputs have shapes (M,), (M,3), (M,3,3), or (K,M), (K,M,3), (K,M,3,3), respectively. Units are kg/m, kg/m^2, kg/m^3; arrays are read-only complex128. Stable isotropic speeds and nonnegative density are required. At q=0 the continuous-q gauge sets the upper constant potential to zero. The lower oscillating potential is retained. Exact grazing and the isolated zero-lambda SV critical configuration are excluded.

Returns G-free ground/underground potential, acceleration and gradient for the same physical displacement field, with frequency-first arrays.

gragra.observables.halfspace_psv_observables

halfspace_psv_observables(
    targets_m,
    *,
    wave_type,
    density_kg_m3,
    v_p_m_s,
    v_s_m_s,
    frequency_hz,
    incidence_angle_rad,
    azimuth_rad,
    incident_displacement_m,
    phase_origin_m=(0.0, 0.0, 0.0),
) -> GravityObservables

Return SI potential (m²/s²), acceleration (m/s²), gradient (s⁻²).

Parameters and shapes follow :func:gragra.analytic.halfspace_psv.halfspace_psv_observables_g_free. The shared conversion multiplies by G exactly once at this boundary.

Converts the general P/SV result to SI at the observable boundary. Its complex incident amplitude is referenced at the fixed phase origin.

Static and other wave benchmarks

The high-level object factory binds a pure sphere geometry and density to an analytic model whose .at() request returns validated, unit-bearing results.

gragra.analytic.objects.uniform_sphere

uniform_sphere(
    geometry: Sphere, density: Quantity
) -> UniformSphereModel

Create an analytic static model of a real, finite-density sphere.

gragra.analytic.uniform_sphere_potential

uniform_sphere_potential(
    center_m: list | tuple | ndarray,
    radius_m: float,
    density_kg_m3: float | complex,
    targets_m: list | tuple | ndarray,
) -> FloatArray | ComplexArray

Calculate G-free gravitational potential contraction of a uniform sphere.

Parameters:

Name Type Description Default
center_m array - like

Shape (3,) coordinates of the sphere center in meters.

required
radius_m float

Radius of the sphere in meters (must be positive).

required
density_kg_m3 float or complex

Mass density in kg/m^3 (real or complex).

required
targets_m array - like

Shape (M, 3) coordinates of the target points in meters.

required

Returns:

Type Description
FloatArray or ComplexArray

Calculated G-free potential of shape (M,).

The G-free gravitational potential contraction of a uniform sphere, the standard closed-form target for the Sphere discretization's convergence test.

gragra.analytic.uniform_sphere_acceleration

uniform_sphere_acceleration(
    center_m: list | tuple | ndarray,
    radius_m: float,
    density_kg_m3: float | complex,
    targets_m: list | tuple | ndarray,
) -> FloatArray | ComplexArray

Calculate G-free gravitational acceleration contraction of a uniform sphere.

Parameters:

Name Type Description Default
center_m array - like

Shape (3,) coordinates of the sphere center in meters.

required
radius_m float

Radius of the sphere in meters (must be positive).

required
density_kg_m3 float or complex

Mass density in kg/m^3 (real or complex).

required
targets_m array - like

Shape (M, 3) coordinates of the target points in meters.

required

Returns:

Type Description
FloatArray or ComplexArray

Calculated G-free acceleration vector of shape (M, 3).

The G-free gravitational acceleration contraction of a uniform sphere, exact both inside and outside the sphere.

gragra.analytic.uniform_sphere_gradient

uniform_sphere_gradient(
    center_m: list | tuple | ndarray,
    radius_m: float,
    density_kg_m3: float | complex,
    targets_m: list | tuple | ndarray,
) -> FloatArray | ComplexArray

Calculate G-free gravity gradient tensor contraction of a uniform sphere.

Parameters:

Name Type Description Default
center_m array - like

Shape (3,) coordinates of the sphere center in meters.

required
radius_m float

Radius of the sphere in meters (must be positive).

required
density_kg_m3 float or complex

Mass density in kg/m^3 (real or complex).

required
targets_m array - like

Shape (M, 3) coordinates of the target points in meters.

required

Returns:

Type Description
FloatArray or ComplexArray

Calculated G-free gravity gradient tensor of shape (M, 3, 3).

The G-free gravity-gradient tensor contraction of a uniform sphere, completing the potential/acceleration/gradient triple for the sphere benchmark.

gragra.analytic.spherical_cavity_bulk_p

spherical_cavity_bulk_p(
    radius_m: float,
    wavenumber_rad_m: float | list | tuple | ndarray,
    density_kg_m3: float,
    displacement_m: float,
) -> np.ndarray

Calculate the G-free Newtonian acceleration amplitude of the P-wave bulk term.

G-free convention: The output is G-free (G_SI = 1); its physical unit is kg/m^2 (acceleration divided by G). Complex-output disclaimer: The output is the real-valued magnitude scale of a linear complex amplitude, not a real-valued time-domain gravitational field. Formulation distinction: Computes the bulk component of the pure-bulk formulation only. Formula: bulk(P) = 4*pi * rho0 * xi * j0(k_P * R)

Parameters:

Name Type Description Default
radius_m float

Radius of the spherical cavity in meters (positive).

required
wavenumber_rad_m float or array - like

Wavenumber of the P-wave in rad/m (non-negative).

required
density_kg_m3 float

Medium background mass density in kg/m^3 (positive).

required
displacement_m float

Displacement amplitude of the P-wave in meters (positive).

required

Returns:

Type Description
ndarray

P-wave bulk acceleration amplitude array of shape matching wavenumber_rad_m.

The G-free Newtonian acceleration amplitude of the P-wave bulk term for a spherical cavity, one term of the small-cavern approximation.

gragra.analytic.spherical_cavity_total_p

spherical_cavity_total_p(
    radius_m: float,
    wavenumber_rad_m: float | list | tuple | ndarray,
    density_kg_m3: float,
    displacement_m: float,
) -> np.ndarray

Calculate the G-free Newtonian acceleration amplitude of the P-wave total term.

G-free convention: The output is G-free (G_SI = 1); its physical unit is kg/m^2 (acceleration divided by G). Complex-output disclaimer: The output is the real-valued magnitude scale of a linear complex amplitude, not a real-valued time-domain gravitational field. Formulation distinction: Corresponds to the dipole/total formulation, and equals the sum of the bulk and wall terms. Formula: total(P) = bulk(P) + wall(P) = 8*pi * rho0 * xi * j1(x)/x

Parameters:

Name Type Description Default
radius_m float

Radius of the spherical cavity in meters (positive).

required
wavenumber_rad_m float or array - like

Wavenumber of the P-wave in rad/m (non-negative).

required
density_kg_m3 float

Medium background mass density in kg/m^3 (positive).

required
displacement_m float

Displacement amplitude of the P-wave in meters (positive).

required

Returns:

Type Description
ndarray

P-wave total acceleration amplitude array of shape matching wavenumber_rad_m.

The fixed spherical cavity series evaluates bulk, wall, and total potential, acceleration, and gradient at general interior and material-side targets. It uses analytic solid harmonics and preserves the center-only functions above.

gragra.analytic.spherical_cavity_observables_g_free

spherical_cavity_observables_g_free(
    targets_m,
    *,
    radius_m: float,
    density_kg_m3: float,
    wavenumber_rad_m: float | ndarray,
    displacement_m: complex | ndarray,
    propagation_direction,
    polarization,
    wave_type: str,
    center_m=(0.0, 0.0, 0.0),
    phase_origin_m=(0.0, 0.0, 0.0),
    rtol: float = 1e-12,
    atol: tuple[float, float, float] | None = None,
    max_degree: int = 128,
) -> dict[str, GFreeGravityValues]

Return bulk, wall, total potential/acceleration/gradient at (M,3) targets.

Positive scalar or (K,) wavenumber, scalar radius; nonnegative density; finite complex displacement; normalized real parallel (P) or transverse (S) polarization. The exact wall is excluded (eight floating-point epsilons on r/a). atol has G-free units (kg/m, kg/m², kg/m³). Its default is 1e-13 times 4πρ|ξ|(a,1,1/a). Each target, term and observable must pass four consecutive degree tests after degree ka+4, with a factor-eight margin. This is an a posteriori truncation estimate, not a rigorous tail bound. Reaching max_degree without it raises ValueError naming the target. No spatial quadrature or finite differences are used.

The corresponding SI entry point converts each of the three component fields through the existing gravitational-observable conversion boundary.

gragra.observables.spherical_cavity_observables

spherical_cavity_observables(
    targets_m, **kwargs
) -> dict[str, GravityObservables]

SI bulk/wall/total analytic series; tolerances are specified in G-free units.

Parameters follow spherical_cavity_observables_g_free exactly.

The G-free Newtonian acceleration amplitude of the P-wave total term (bulk + wall) for a spherical cavity.

gragra.analytic.spherical_cavity_wall

spherical_cavity_wall(
    radius_m: float,
    wavenumber_rad_m: float | list | tuple | ndarray,
    density_kg_m3: float,
    displacement_m: float,
    *,
    wave_type: Literal["P", "S"] = "P",
) -> np.ndarray

Calculate the G-free Newtonian acceleration amplitude of the cavity wall term.

G-free convention: The output is G-free (G_SI = 1); its physical unit is kg/m^2 (acceleration divided by G). Complex-output disclaimer: The output is the real-valued magnitude scale of a linear complex amplitude, not a real-valued time-domain gravitational field. Formulation distinction: Computes the wall (surface mass sheet) component of the pure-bulk formulation. P wave: wall(P) = -4pi * rho0 * xi * (j0(x) - 2j1(x)/x) S wave: wall(S) = -4*pi * rho0 * xi * j1(x)/x (Note: for an S wave bulk(S) = 0, so wall(S) is itself the total.)

Parameters:

Name Type Description Default
radius_m float

Radius of the spherical cavity in meters (positive).

required
wavenumber_rad_m float or array - like

Wavenumber of the wave in rad/m (non-negative).

required
density_kg_m3 float

Medium background mass density in kg/m^3 (positive).

required
displacement_m float

Displacement amplitude of the wave in meters (positive).

required
wave_type str

Wave type, either "P" or "S" (defaults to "P").

'P'

Returns:

Type Description
ndarray

Cavity wall acceleration amplitude array of shape matching wavenumber_rad_m.

The G-free Newtonian acceleration amplitude of the cavity-wall term alone for a spherical cavity.

gragra.analytic.spherical_shell_dipole_factor

spherical_shell_dipole_factor(
    k_r: float | list | tuple | ndarray,
) -> np.ndarray

Calculate the dimensionless spherical shell dipole factor, -j1(x)/x.

G-free convention: The output is dimensionless. Complex-output disclaimer: The output is a real-valued dimensionless coefficient. Formulation distinction: Geometric factor of the spherical-shell dipole/total formulation. Relation: total(P) = -8*pi * rho0 * xi * shell_dipole_factor(k * R)

Parameters:

Name Type Description Default
k_r float or array - like

Dimensionless wavenumber * radius product (non-negative).

required

Returns:

Type Description
ndarray

The dipole factor values of shape matching k_r.

The dimensionless spherical-shell dipole factor −j₁(x)/x (a spherical Bessel function ratio), a building block of the cavity closed forms above.

gragra.analytic.halfspace_transfer_bulk

halfspace_transfer_bulk(k_h) -> np.ndarray

Dimensionless bulk transfer T_bulk(kH) = 1 - 2 cos(kH).

Bulk density-perturbation contribution only (no surface mass sheet), for a vertically incident P wave in a homogeneous half-space, observed at depth H below the free surface; kH = omega H / v_P >= 0. The physical (G-carrying) relation is delta_a_z(H) = -4 pi G rho_0 xi_inc T_bulk(kH) with xi_inc the incident amplitude before surface doubling (halfspace_conventions.md §5) — this function is G-free and returns T only.

Fixed points: T_bulk(0) = -1; null at kH = pi/3 (f = v_P / 6H).

Returns:

Type Description
ndarray

T_bulk, dimensionless float64, same shape as k_h (read-only).

The dimensionless bulk transfer function T_bulk(kH) = 1 − 2cos(kH) for a half-space at depth H, one term of the full vertical-incidence transfer.

gragra.analytic.halfspace_transfer_full

halfspace_transfer_full(k_h) -> np.ndarray

Dimensionless full transfer T_full(kH) = -2 cos(kH) = T_bulk + T_sheet.

Adds the free-surface mass-sheet term T_sheet = -1 to the bulk term, so T_full - T_bulk = -1 identically. Same definition relation and G-free convention as :func:halfspace_transfer_bulk.

Fixed points: T_full(0) = -2; null at kH = pi/2 (f = v_P / 4H). Note that T_full(0) = -2 is the limit approached from inside the medium (H -> 0+); for an observer above the surface the sheet term flips sign, so this value does not apply to surface-mounted detectors.

Returns:

Type Description
ndarray

T_full, dimensionless float64, same shape as k_h (read-only).

The dimensionless full transfer function T_full(kH) = −2cos(kH) = T_bulk + T_sheet for a half-space at depth H.

gragra.analytic.rayleigh_depth_reduction

rayleigh_depth_reduction(
    depth_m, wavenumber_rad_m, v_p_m_s, v_s_m_s
) -> np.ndarray

Kinematic Rayleigh displacement-magnitude depth reduction R(h).

R(h) = |u(h)| / |u(0)| with |u| = sqrt(|u_x|^2 + |u_z|^2) evaluated from the exact two-exponential eigenfunctions (gragra.waves.rayleigh). R(0) = 1, and it is NOT a single exponential — for a Poisson solid R(kh=1) = 0.8374, far above e^{-1} = 0.3679, which is what a naive exp(-kh) model would give.

Monotonic decrease with depth holds only for v_P/v_S below ~2.7 (it covers the Poisson solid and most hard-rock sites). For larger ratios the vertical eigenfunction develops a subsurface maximum and R can exceed 1 (e.g. v_P/v_S = 5 gives max R = 1.031 near kh = 0.81) — real physics, relevant for water-saturated sediments where v_P/v_S reaches 3-15, so "reduction" must not be read as R <= 1 unconditionally.

This is a G-free, dimensionless kinematic benchmark of the displacement field only; the depth dependence of the Newtonian-noise acceleration couples the whole field and must be computed via field integrals (it is not this ratio).

Parameters:

Name Type Description Default
depth_m float or array - like

Depth(s) below the free surface in meters (h >= 0).

required
wavenumber_rad_m float

Horizontal Rayleigh wavenumber k > 0 in rad/m.

required
v_p_m_s float

Elastic wave speeds in m/s (0 < v_s < v_p).

required
v_s_m_s float

Elastic wave speeds in m/s (0 < v_s < v_p).

required

Returns:

Type Description
ndarray

R(h), dimensionless float64, same shape as depth_m (read-only).

The kinematic Rayleigh displacement-magnitude depth-reduction factor R(h), used to scale a surface-referenced Rayleigh amplitude to depth h.

gragra.analytic.sca_wall_coupling_factor

sca_wall_coupling_factor(
    cavern_shape: CavernShape,
    test_mass_location: TestMassLocation,
) -> float

Look up the dimensionless SCA cavern-wall coupling factor (Harms Table 1).

G-free convention: The output is dimensionless. Complex-output disclaimer: The output is real. The return value is a plain Python float, not an np.ndarray -- see the module docstring's "Return type" note. Formulation distinction: A coefficient of the wall term, matching spherical_cavity_wall; it does not correspond to total (bulk + wall). See the module docstring.

Parameters:

Name Type Description Default
cavern_shape (sphere, cube, half_sphere, elongated_cuboid_2to1to1)

Cavern shape per Harms et al. 2022 Table 1. "elongated_cuboid_2to1to1" is a finite cuboid with side-length ratio 2:1:1 (elongated along the horizontal) -- not a non-finite/tunnel-like geometry.

"sphere"
test_mass_location (arbitrary, center_3d, floor_center_2d)

Table 1 location label. "arbitrary" is retained verbatim for the sphere and is not a synonym for its center. "center_3d" labels the cube row. "floor_center_2d" is a bounded source lookup only; Table 1 alone does not define its boundary condition, tensor interpretation, direction, or one-sided limit.

"arbitrary"

Returns:

Type Description
float

Dimensionless coupling factor from Table 1.

Raises:

Type Description
ValueError

If (cavern_shape, test_mass_location) is not one of the five combinations tabulated in Harms et al. 2022 Table 1.

Looks up the dimensionless small-cavern-approximation (SCA) cavern-wall coupling factor from Harms et al. 2022 Table 1 — a plain Python float, not an array, because the underlying formula has no wavenumber or component axis (see the array-conventions exception this function is documented under).

gragra.analytic.sca_wall_acceleration

sca_wall_acceleration(
    cavern_shape: CavernShape,
    test_mass_location: TestMassLocation,
    density_kg_m3: float,
    displacement_m: float,
) -> float

Calculate the G-free small-cavern-limit cavern-wall acceleration amplitude.

G-free convention: The output is G-free (G_SI = 1); its physical unit is kg/m^2 (acceleration divided by G). Complex-output disclaimer: The output is real (the small-cavern approximation has no wavenumber dependence). The return value is a plain Python float, not an np.ndarray -- see the module docstring's "Return type" note. Formulation distinction: The cavern-wall term of Harms et al. 2022 Eq. (7) (wall only; the bulk term is deliberately excluded -- see the module docstring): a = -coupling_factor * density_kg_m3 * displacement_m The spherical case ("sphere"/"arbitrary") agrees exactly with the x = k*R -> 0 limit of spherical_cavity_wall (-4*pi/3 * rho * xi == cavity_wall_geometric(0) * -4*pi * rho * xi), as verified in tests/test_analytic_cavity_coupling.py.

Parameters:

Name Type Description Default
cavern_shape (sphere, cube, half_sphere, elongated_cuboid_2to1to1)

Cavern shape per Harms et al. 2022 Table 1 (see sca_wall_coupling_factor).

"sphere"
test_mass_location (arbitrary, center_3d, floor_center_2d)

Test-mass location per Harms et al. 2022 Table 1 (see sca_wall_coupling_factor).

"arbitrary"
density_kg_m3 float

Medium background mass density in kg/m^3 (positive).

required
displacement_m float

Ground displacement amplitude in meters (positive). It is the scalar amplitude for this Table 1 lookup, not a statement that a general non-spherical tensor response is parallel to displacement.

required

Returns:

Type Description
float

G-free cavern-wall acceleration amplitude.

The G-free small-cavern-limit cavern-wall acceleration amplitude, built from sca_wall_coupling_factor; also returns a plain float.

gragra.analytic.sphere_sca_wall_coupling_tensor_g_free

sphere_sca_wall_coupling_tensor_g_free(
    center_m: list | tuple | ndarray,
    radius_m: float,
    targets_m: list | tuple | ndarray,
    *,
    quadrature_order: int | None = None,
) -> np.ndarray

Return the dimensionless SCA wall tensor for a sphere.

targets_m may contain general interior or exterior points, but points on the spherical wall are rejected because the integral is singular. By default the tensor is evaluated from the exact filled-sphere gradient inversion C = -Gamma_filled/rho. Passing quadrature_order opts in to the surface-integral reference; its result is returned only when every target passes the target-wise order-convergence check. The result has shape (M, 3, 3) and is read-only.

Evaluates the dimensionless sphere wall-coupling tensor from an independent surface quadrature for general interior or exterior targets; physical wall points are rejected.

gragra.analytic.cuboid_sca_wall_coupling_tensor_g_free

cuboid_sca_wall_coupling_tensor_g_free(
    center_m: list | tuple | ndarray,
    lengths_m: list | tuple | ndarray,
    targets_m: list | tuple | ndarray,
    *,
    rotation_matrix: list | tuple | ndarray | None = None,
    quadrature_order: int | None = None,
) -> np.ndarray

Return the dimensionless SCA wall tensor for a cuboid.

rotation_matrix is a local-to-world proper rotation. The cuboid boundary is integrated in local coordinates and the resulting rank-two tensor is rotated as Q @ C_local @ Q.T. By default the tensor is evaluated from the exact filled-cuboid gradient inversion C = -Gamma_filled/rho. Passing quadrature_order opts in to the surface-integral reference; its result is returned only when every target passes the target-wise order-convergence check. Interior and exterior targets are supported; physical boundary targets are rejected.

Evaluates the dimensionless cuboid wall-coupling tensor, including an explicit proper local-to-world rotation when requested.

gragra.analytic.sca_wall_acceleration_from_tensor_g_free

sca_wall_acceleration_from_tensor_g_free(
    coupling_tensor: list | tuple | ndarray,
    density_kg_m3: float,
    displacement_m: list | tuple | ndarray,
) -> np.ndarray

Apply delta_a/G = -rho * C @ displacement in G-free units.

Applies the SCA wall convention delta_a/G = -rho * C @ displacement to a tensor and returns the G-free acceleration amplitude.

gragra.analytic.cuboid_filled_internal_field

cuboid_filled_internal_field(
    lengths_m: list | tuple | ndarray,
    points_m: list | tuple | ndarray,
    density_kg_m3: float,
) -> FloatArray

Calculate the G-free static gravitational field of a filled uniform prism.

G-free convention: The output is G-free (G_SI = 1); its physical unit is kg/m^2 (acceleration divided by G). Real output (a static field): There is no wavenumber or displacement-amplitude here, so the complex-amplitude disclaimer does not apply. Formulation distinction: The filled term -- the internal field of the notionally filled body, which is the input to the inversion principle (see the module docstring). It differs from both cavity_sphere.py's bulk and its wall.

Parameters:

Name Type Description Default
lengths_m (array - like, shape(3))

Full side lengths (Lx, Ly, Lz) of the prism in meters, all positive. The prism is centered at the origin of the coordinate system used by points_m (caller's responsibility to translate observation points relative to the prism center).

required
points_m (array - like, shape(M, 3))

Observation point coordinates in meters, relative to the prism center. May be negative or zero (interior/boundary/exterior points are all valid -- the closed form is finite everywhere, including on faces, edges, and at vertices; see the corner-term guards in _corner_term). Points strictly near (but not exactly on) a face, edge, or vertex are not specially guarded -- the guards only cover the exact-zero degenerate case -- so, as with any log/atan-based closed form, expect gradual precision loss (not a discontinuity) within a few floating-point ULPs of the boundary, well below the rtol used by this module's tests.

required
density_kg_m3 float

Mass density of the filled prism in kg/m^3 (positive).

required

Returns:

Type Description
FloatArray

G-free gravitational acceleration field of shape (M, 3), float64, read-only.

The G-free static gravitational field of a filled uniform rectangular prism, evaluated at points that may lie inside the prism (unlike a point-mass sum, which is undefined at r=0).

gragra.analytic.cylinder_filled_axis_field

cylinder_filled_axis_field(
    radius_m: float,
    height_m: float,
    z_m: float | list | tuple | ndarray,
    density_kg_m3: float,
) -> FloatArray

Calculate the G-free static on-axis gravitational field of a filled cylinder.

G-free convention: The output is G-free (G_SI = 1); its physical unit is kg/m^2 (acceleration divided by G). Real output (a static field): There is no wavenumber or displacement amplitude here, so the complex-amplitude disclaimer does not apply. Formulation distinction: The filled term -- the same formulation as cavity_cuboid.cuboid_filled_internal_field (see the module docstring). Numerical defence: Unlike cavity_cuboid.py's _corner_term, this function carries no guards for removable singularities on faces, edges or vertices: sqrt(r^2+u^2) is identically positive as long as r > 0 (a valid radius), so neither a division by zero nor a 0/0 indeterminate form of a log/arctan can arise in principle (restricting to the axis removes the multi-variable cancellation singularities that the cuboid's 8-corner sum has). In the far field (|u| >> r), however, evaluating f(u) = |u| - sqrt(r^2+u^2) naively loses precision by subtracting two nearly equal large values, so the algebraically equivalent rationalized form f(u) = -r^2 / (|u| + sqrt(r^2+u^2)) is used instead (its denominator |u| + sqrt(r^2+u^2) is identically positive, so there is no division by zero). Beyond 64 times the enclosing sphere radius, a degree-8 solid-harmonic expansion avoids endpoint subtraction and is evaluated with scaled products.

Parameters:

Name Type Description Default
radius_m float

Cylinder radius in meters (positive).

required
height_m float

Cylinder height in meters (positive). The cylinder is centered at the origin, spanning z in [-height_m/2, height_m/2].

required
z_m (float or array - like, shape(M))

On-axis observation point z-coordinates in meters, relative to the cylinder center. May be negative, zero, or exceed the cylinder extent (interior/boundary/exterior all valid).

required
density_kg_m3 float

Mass density of the filled cylinder in kg/m^3 (positive).

required

Returns:

Type Description
FloatArray

G-free on-axis acceleration z-component, shape matching z_m (scalar input -> shape (), array input -> matching shape), float64, read-only.

The G-free filled cylinder's scalar on-axis gravitational field.

gragra.analytic.cylinder_sca_wall_coupling_tensor_g_free

cylinder_sca_wall_coupling_tensor_g_free(
    center_m: list | tuple | ndarray,
    radius_m: float,
    height_m: float,
    targets_m: list | tuple | ndarray,
    *,
    rotation_matrix: list | tuple | ndarray | None = None,
) -> np.ndarray

Return the dimensionless cylinder SCA wall tensor C=-Gamma(rho=1).

The outward normal points from the cavity into the surrounding material: C_ij = integral_wall((s_i-x_i)*n_j / |s-x|**3 dS). Uniform wall displacement gives delta_a_wall/G = -rho * C @ u. This is the wall term only, with no bulk, wavelength or elastic-scattering contribution.

Parameters follow the existing analytic cylinder field: center (3,), positive radius and full height in meters, targets (M,3), and optional proper local-to-world rotation (3,3). Internal and external targets are supported; physical side/cap/rim targets are rejected. Interior trace is 4*pi; exterior trace is zero. Rotation validation and analytic field evaluation delegate to the existing cylinder implementation without projection or any spatial quadrature.

Returns a read-only float64 array of shape (M,3,3). Density and complex displacement do not enter this geometry-only API. Apply the established SCA tensor contraction after this step; do not multiply the tensor by G.

The dimensionless cylinder SCA wall tensor is minus the unit-density filled cylinder gradient. It supports general interior/exterior points and proper rotation, and excludes the physical wall. Density and displacement are applied by the separate SCA contraction; this function does not multiply by G.

The G-free static on-axis gravitational field of a filled uniform cylinder; restricted to the axis because no general off-axis closed form is implemented.

gragra.analytic.GFreeGravityValues dataclass

Potential, acceleration, and gradient in G-free units.

Physical units: - potential: kg / m - acceleration: kg / m^2 - gradient: kg / m^3

Shapes: - Static targets: potential: (M,), acceleration: (M, 3), gradient: (M, 3, 3) - Series targets: potential: (S, M), acceleration: (S, M, 3), gradient: (S, M, 3, 3)

Frozen container holding G-free potential, acceleration, and gradient arrays evaluated from an analytic source.

gragra.analytic.GFreeSphericalShellPComponents dataclass

Component decomposition of spherical shell P-wave acceleration in G-free units (kg / m^2).

Fields: - bulk: Volume compression contribution of the shell. - inner_wall: Surface mass sheet contribution of the inner cavity wall. - outer_boundary: Surface mass sheet contribution of the outer boundary. - total: Total acceleration, equal to bulk + inner_wall + outer_boundary. - unit_system: Fixed identifier string "g_free".

Shapes: - Scalar wavenumber: each field is (1, 3) (1 center point, 3 spatial components). - 1D wavenumber array of length K: each field is (K, 1, 3).

Frozen container holding G-free acceleration components (bulk, inner_wall, outer_boundary, total) for a spherical shell cavity under P-wave excitation.

gragra.analytic.GFreeSphericalShellSComponents dataclass

Component decomposition of spherical shell S-wave acceleration in G-free units (kg / m^2).

Fields: - bulk: Always identically zero. An S wave (shear wave) has zero divergence (div(u) = 0), so it produces no volumetric density perturbation and therefore no bulk contribution. This field is kept only so the S-wave container has the same 4-field structure as GFreeSphericalShellPComponents, letting the same total == bulk + inner_wall + outer_boundary identity apply uniformly to both wave types. - inner_wall: Surface mass sheet contribution of the inner cavity wall. - outer_boundary: Surface mass sheet contribution of the outer boundary. - total: Total acceleration, equal to inner_wall + outer_boundary (since bulk is always zero). - unit_system: Fixed identifier string "g_free".

Shapes: - Scalar wavenumber: each field is (1, 3) (1 center point, 3 spatial components). - 1D wavenumber array of length K: each field is (K, 1, 3).

Frozen container holding G-free acceleration components (bulk, inner_wall, outer_boundary, total) for a spherical shell cavity under S-wave excitation. bulk is always identically zero because S waves are divergence-free.

gragra.analytic.uniform_sphere_observables_g_free

uniform_sphere_observables_g_free(
    center_m: list | tuple | ndarray,
    radius_m: float,
    density_kg_m3: float | complex,
    targets_m: list | tuple | ndarray,
) -> GFreeGravityValues

Calculate G-free potential, acceleration, and gradient of a uniform sphere.

Parameters:

Name Type Description Default
center_m (array - like, shape(3))

Coordinates of the sphere center in meters.

required
radius_m float

Radius of the sphere in meters (must be positive).

required
density_kg_m3 float or complex

Mass density in kg/m^3 (real or complex).

required
targets_m (array - like, shape(M, 3))

Coordinates of the target points in meters.

required

Returns:

Type Description
GFreeGravityValues

Immutable container holding potential (M,), acceleration (M, 3), and gradient (M, 3, 3) in G-free units.

Bundles the G-free potential, acceleration, and gradient tensor of a uniform sphere into a GFreeGravityValues container.

gragra.analytic.cuboid_potential_g_free

cuboid_potential_g_free(
    center_m: list | tuple | ndarray,
    lengths_m: list | tuple | ndarray,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
) -> FloatArray

Calculate G-free gravitational potential of a uniform cuboid (rectangular prism).

Physical unit: kg / m.

Evaluates the G-free gravitational potential of a uniform rectangular prism using 3D closed-form vertex antiderivatives.

gragra.analytic.cuboid_acceleration_g_free

cuboid_acceleration_g_free(
    center_m: list | tuple | ndarray,
    lengths_m: list | tuple | ndarray,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
) -> FloatArray

Calculate G-free gravitational acceleration vector of a uniform cuboid.

Physical unit: kg / m^2.

Evaluates the G-free gravitational acceleration vector of a uniform rectangular prism using 3D closed-form vertex antiderivatives.

gragra.analytic.cuboid_gradient_g_free

cuboid_gradient_g_free(
    center_m: list | tuple | ndarray,
    lengths_m: list | tuple | ndarray,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
) -> FloatArray

Calculate G-free gravity gradient tensor of a uniform cuboid.

Physical unit: kg / m^3. Rejects points on the material boundary of the cuboid.

Evaluates the G-free symmetric 3x3 gravity-gradient tensor of a uniform rectangular prism using 3D closed-form vertex antiderivatives.

gragra.analytic.cuboid_observables_g_free

cuboid_observables_g_free(
    center_m: list | tuple | ndarray,
    lengths_m: list | tuple | ndarray,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
) -> GFreeGravityValues

Calculate G-free potential, acceleration, and gradient of a uniform cuboid.

Parameters:

Name Type Description Default
center_m (array - like, shape(3))

Center of the cuboid in meters.

required
lengths_m (array - like, shape(3))

Full side lengths (Lx, Ly, Lz) in meters, all positive.

required
density_kg_m3 float

Uniform mass density in kg/m^3 (positive).

required
targets_m (array - like, shape(M, 3))

Observation target points in meters. Points lying on the cuboid material boundary are rejected.

required

Returns:

Type Description
GFreeGravityValues

Immutable container holding potential (M,), acceleration (M, 3), and gradient (M, 3, 3) in G-free units.

Bundles the G-free potential, acceleration, and 3x3 gradient tensor of a uniform rectangular prism into a GFreeGravityValues container.

gragra.analytic.oriented_cuboid_observables_g_free

oriented_cuboid_observables_g_free(
    center_m: list | tuple | ndarray,
    lengths_m: list | tuple | ndarray,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
    *,
    rotation_matrix: list | tuple | ndarray,
) -> GFreeGravityValues

Evaluate a uniformly dense cuboid in an arbitrary proper orientation.

Parameters:

Name Type Description Default
center_m (array - like, shape(3))

World-coordinate cuboid center in meters.

required
lengths_m (array - like, shape(3))

Full local-coordinate side lengths in meters.

required
density_kg_m3 float

Non-negative uniform density in kg/m^3.

required
targets_m (array - like, shape(M, 3))

World-coordinate targets. Material-boundary targets are rejected by the local cuboid closed form.

required
rotation_matrix (array - like, shape(3, 3), keyword - only)

Proper orthogonal local-to-world matrix Q. Invalid matrices are rejected; they are not projected or normalized.

required

Returns:

Type Description
GFreeGravityValues

G-free potential, acceleration, and 3x3 gradient in world coordinates. Potential is invariant under the rigid transform; vector and tensor components are rotated covariantly.

Evaluates the same cuboid closed form after an explicit proper local-to-world rotation. The potential is invariant, while acceleration and the 3x3 gradient are transported with Q and Q @ gradient @ Q.T; invalid rotation matrices are rejected rather than projected onto SO(3).

gragra.analytic.cylinder_potential_axis_g_free

cylinder_potential_axis_g_free(
    center_m: list | tuple | ndarray,
    radius_m: float,
    height_m: float,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
) -> FloatArray

Calculate G-free on-axis gravitational potential of a uniform cylinder.

Physical unit: kg / m.

Evaluates the G-free gravitational potential on the symmetry axis of a uniform cylinder using closed-form antiderivatives.

gragra.analytic.cylinder_gradient_axis_g_free

cylinder_gradient_axis_g_free(
    center_m: list | tuple | ndarray,
    radius_m: float,
    height_m: float,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
) -> FloatArray

Calculate G-free on-axis 3x3 gravity gradient tensor of a uniform cylinder.

Physical unit: kg / m^3. Rejects end face points z = ±h/2.

Evaluates the G-free 3x3 gravity-gradient tensor on the symmetry axis of a uniform cylinder using longitudinal derivatives and Poisson constraints.

gragra.analytic.cylinder_axis_observables_g_free

cylinder_axis_observables_g_free(
    center_m: list | tuple | ndarray,
    radius_m: float,
    height_m: float,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
) -> GFreeGravityValues

Calculate G-free on-axis potential, acceleration, and gradient.

The source is a uniform cylinder.

Parameters:

Name Type Description Default
center_m (array - like, shape(3))

Center of the cylinder in meters.

required
radius_m float

Radius in meters (positive).

required
height_m float

Height in meters (positive).

required
density_kg_m3 float

Uniform mass density in kg/m^3 (positive).

required
targets_m (array - like, shape(M, 3))

On-axis observation target points. Off-axis points and points on the end faces z = ±h/2 are rejected.

required

Returns:

Type Description
GFreeGravityValues

Immutable container holding potential (M,), acceleration (M, 3), and gradient (M, 3, 3) in G-free units.

Bundles the G-free on-axis potential, acceleration, and gradient tensor of a uniform cylinder into a GFreeGravityValues container.

gragra.analytic.cylinder_observables_g_free

cylinder_observables_g_free(
    center_m: list | tuple | ndarray,
    radius_m: float,
    height_m: float,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
    *,
    quadrature_order: int = 32,
) -> GFreeGravityValues

Calculate G-free observables of a finite z-aligned solid cylinder.

This opt-in general-point path numerically evaluates the divergence-theorem boundary representation, except beyond 64 times the enclosing sphere radius where it uses a degree-8 solid-harmonic expansion to avoid far-field cancellation. It is a numerical semi-analytic implementation, not Conway's closed elliptic-integral formula: quadrature_order controls the Gauss--Legendre order and the periodic azimuthal order is four times larger. The existing axis entry point is reused for axis targets.

Targets on the physical cylindrical boundary are rejected because the boundary integrands are singular there and the gradient has distinct one-sided limits. Acceleration is continuous. With Delta = s - x, the evaluated formulas are Phi = -rho/2 * integral(Delta dot n / |Delta|) and a_i = -rho * integral(n_i / |Delta|). The gradient is Gamma_ij = -rho * integral(Delta_i*n_j / |Delta|**3). The trace therefore follows from the enclosed-target version of the divergence theorem; no local term is added to this boundary expression.

This path remains a numerical diagnostic/reference implementation until Conway's elliptic formula is transcribed and independently verified. Its far-field branch uses the documented degree-10 tail bound.

Parameters:

Name Type Description Default
center_m (array - like, shape(3))

Cylinder center in meters; its axis is parallel to world z.

required
radius_m float

Positive radius and height in meters. The cylinder spans center_z +/- height_m/2.

required
height_m float

Positive radius and height in meters. The cylinder spans center_z +/- height_m/2.

required
density_kg_m3 float

Non-negative uniform density in kg/m^3.

required
targets_m (array - like, shape(M, 3))

World-coordinate observation points, excluding the material boundary.

required
quadrature_order (int, keyword - only)

Gauss--Legendre order in [4, 128] for the side height and cap radius coordinates.

32

Returns:

Type Description
GFreeGravityValues

Potential, acceleration, and gravity gradient in G-free units with shapes (M,), (M,3), and (M,3,3).

Evaluates a z-aligned uniform cylinder at general target points with an opt-in cylindrical Gauss-quadrature path. This is a numerical semi-analytic reference/exploratory API, not the Conway closed elliptic-integral formula; quadrature_order controls the radial and axial orders. The exact on-axis closed form is reused, and physical side/end-boundary targets are rejected.

gragra.analytic.cylinder_acceleration_gradient_g_free

cylinder_acceleration_gradient_g_free(
    center_m: list | tuple | ndarray,
    radius_m: float,
    height_m: float,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
    *,
    rotation_matrix: list | tuple | ndarray | None = None,
) -> tuple[FloatArray, FloatArray]

Analytic acceleration and full gradient of a uniform finite cylinder.

Returns read-only float64 arrays (M,3) and (M,3,3) in kg/m² and kg/m³. Uses real complete elliptic integrals, no spatial quadrature or finite differences. Material-boundary targets are rejected. Numerical potential remains available from cylinder_observables_g_free.

Returns analytic acceleration and the full gradient as a pair of read-only arrays. Real complete elliptic integrals are supplemented by analytic near-axis and far-field series. rotation_matrix maps local to world coordinates and must be a proper rotation; the physical boundary is rejected. The separate bundled API above retains the numerical potential diagnostic.

gragra.analytic.cylinder_analytic_observables_g_free

cylinder_analytic_observables_g_free(
    center_m: list | tuple | ndarray,
    radius_m: float,
    height_m: float,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
    *,
    rotation_matrix: list | tuple | ndarray | None = None,
) -> GFreeGravityValues

Analytic potential, acceleration, and gradient of a finite cylinder.

Potential has the infinity-zero gauge. All outputs are read-only, G-free float64 arrays; units are kg/m, kg/m², and kg/m³. The cylinder's local axis is z and rotation_matrix maps local vectors to world. Material-boundary targets are rejected, matching the gradient contract. Uses elliptic functions and convergent analytic series, not numerical spatial integration. The existing cylinder_observables_g_free remains the separately named numerical boundary-quadrature diagnostic.

Returns the analytic finite-cylinder potential, acceleration, and gradient in one read-only container. The infinity-zero potential uses convergent analytic elliptic/logarithmic series, not spatial quadrature or a claimed finite closed form. Proper rotation and material-boundary exclusions match the analytic acceleration/gradient pair; the numerical API stays separate.

gragra.analytic.rayleigh_halfspace_allspace_observables_g_free

rayleigh_halfspace_allspace_observables_g_free(
    targets_m: ArrayLike,
    *,
    density_kg_m3: float,
    v_p_m_s: float,
    v_s_m_s: float,
    frequency_hz: float | ArrayLike,
    vertical_surface_amplitude_m: float
    | complex
    | ArrayLike,
    direction: ArrayLike = (1.0, 0.0, 0.0),
    phase_origin_m: ArrayLike = (0.0, 0.0, 0.0),
) -> GFreeGravityValues

G-free Rayleigh-wave gravity above and below a homogeneous half-space.

Implements H19 Eq. (96) (z > 0) and Eq. (97) (z < 0), with the amplitude A from Eq. (98) expressed via the fixed-phase-origin, t = 0 complex vertical surface displacement amplitude vertical_surface_amplitude_m. Acceleration and gradient are this module's own analytic derivative of those closed forms (evidence B; see the module docstring and docs/design/literature-r.md).

Parameters:

Name Type Description Default
targets_m array-like of shape (M, 3)

Evaluation points in meters (z-up; free surface at z = 0; medium occupies z < 0). Points with z == 0 are rejected: the potential and the tangential acceleration components are continuous across the free surface, but the normal acceleration and the gradient are not (see "Surface behavior, precisely stated" in docs/design/literature-r.md), so the ground and underground closed forms are only defined on their respective open half-spaces.

required
density_kg_m3 float

Background mass density in kg/m^3 (non-negative; a zero density is accepted and does not skip any other geometry validation).

required
v_p_m_s float

P- and S-wave speeds in m/s. Requires 0 < v_s_m_s < v_p_m_s and v_p_m_s**2 > (4/3) * v_s_m_s**2 (stable isotropic half-space, Poisson ratio < 0.5) -- the condition under which the Rayleigh secular equation has a root with 0 < q, s < 1.

required
v_s_m_s float

P- and S-wave speeds in m/s. Requires 0 < v_s_m_s < v_p_m_s and v_p_m_s**2 > (4/3) * v_s_m_s**2 (stable isotropic half-space, Poisson ratio < 0.5) -- the condition under which the Rayleigh secular equation has a root with 0 < q, s < 1.

required
frequency_hz float or array-like of shape (K,)

Positive frequency/frequencies in Hz. A scalar gives potential: (M,), acceleration: (M, 3), gradient: (M, 3, 3); a 1D array of length K gives potential: (K, M), acceleration: (K, M, 3), gradient: (K, M, 3, 3).

required
vertical_surface_amplitude_m float, complex, or array-like of shape (K,)

Fixed-phase-origin, t = 0 complex vertical surface displacement amplitude in meters (Eq. 98's xi_z(0, 0)). Zero is accepted. A 1D array of length K (one amplitude per frequency) is only accepted together with a 1D frequency_hz of the same length K; no other implicit broadcast between the two is allowed.

required
direction array-like of shape (3,)

Horizontal Rayleigh propagation direction (z component must vanish). Normalized scale-safely (dividing by the largest-magnitude component first), so (1e-200, 0, 0) and (1e200, 0, 0) both normalize to the same direction as (1, 0, 0) rather than underflowing to "zero" or overflowing the norm to inf. Default (1, 0, 0).

(1.0, 0.0, 0.0)
phase_origin_m array-like of shape (3,)

Fixed horizontal phase-reference point in meters (not moved per target). Default the coordinate origin.

(0.0, 0.0, 0.0)

Returns:

Type Description
GFreeGravityValues

G-free potential (kg/m), acceleration (kg/m^2), and gradient (kg/m^3), complex128, read-only.

G-free Rayleigh-wave gravity above (H19 Eq. 96) and below (H19 Eq. 97) a homogeneous elastic half-space, with acceleration and gradient from this module's own analytic derivative of those closed forms. A separate entry point from the legacy ground-only rayleigh_halfspace_observables_g_free (see the Wave 4-6 reference page); see docs/design/literature-r.md for the full literature mapping.

gragra.analytic.halfspace_single_bodywave_observables_g_free

halfspace_single_bodywave_observables_g_free(
    targets_m: ArrayLike,
    *,
    wave_type: Literal["P", "SV"],
    density_kg_m3: float,
    v_p_m_s: float,
    v_s_m_s: float,
    frequency_hz: float | ArrayLike,
    incidence_angle_rad: float,
    azimuth_rad: float,
    displacement_m: float | complex | ArrayLike,
    phase_origin_m: ArrayLike = (0.0, 0.0, 0.0),
) -> GFreeGravityValues

G-free gravity of a single upward-propagating plane P or SV wave.

Implements H19 Eq. (86) (P, z>0), Eq. (87) (P, z<0), and Eq. (88) (SV, one formula valid on both sides), without compositing a free-surface reflection (that is :func:halfspace_reflected_p_above_observables_g_free). Acceleration and gradient are this module's own analytic derivative of those closed forms (evidence B; see docs/design/literature-b.md).

Parameters:

Name Type Description Default
targets_m array-like of shape (M, 3)

Evaluation points in meters (z-up; free surface at z=0). Points with z == 0 are rejected; z > 0 and z < 0 targets may be mixed in one call.

required
wave_type ('P', 'SV')

Which single mode to evaluate.

"P"
density_kg_m3 float

Background mass density in kg/m^3 (non-negative; zero accepted).

required
v_p_m_s float

P- and S-wave speeds in m/s. Requires 0 < v_s_m_s < v_p_m_s and v_p_m_s**2 > (4/3) * v_s_m_s**2 (stable isotropic half-space).

required
v_s_m_s float

P- and S-wave speeds in m/s. Requires 0 < v_s_m_s < v_p_m_s and v_p_m_s**2 > (4/3) * v_s_m_s**2 (stable isotropic half-space).

required
frequency_hz float or array-like of shape (K,)

Positive frequency/frequencies in Hz.

required
incidence_angle_rad float

Incidence angle theta measured from the surface normal, against this mode's own speed (v_p_m_s for "P", v_s_m_s for "SV"). Must satisfy 0 <= theta < pi/2 (exact grazing rejected). One scalar per call -- no per-frequency angle array.

required
azimuth_rad float

Horizontal propagation azimuth in radians. One scalar per call.

required
displacement_m float, complex, or array-like of shape (K,)

Complex incident-wave displacement amplitude along its own polarization direction (H19's xi_0^P / xi_0^SV; P polarization sin(theta) h + cos(theta) e_z, SV polarization cos(theta) h - sin(theta) e_z, both for the upward-propagating convention -- the polarization vector itself does not enter the potential formulas, which already reduce to this scalar amplitude). Zero accepted. A 1D array of length K (one amplitude per frequency) is only accepted together with a 1D frequency_hz of the same length K.

required
phase_origin_m array-like of shape (3,)

Fixed 3D phase-reference point in meters. displacement_m is the incident wave's own complex amplitude evaluated AT this point, not necessarily at z=0; a nonzero phase_origin_m[2] re-references that amplitude to z=0 via the incident wave's own vertical wavenumber (exp(-i*k_z*z0)) without moving the free surface itself. Default the coordinate origin.

(0.0, 0.0, 0.0)

Returns:

Type Description
GFreeGravityValues

G-free potential (kg/m), acceleration (kg/m^2), and gradient (kg/m^3), complex128, read-only.

G-free gravity of a single upward-propagating plane P or SV wave, without compositing a free-surface reflection (H19 Eq. 86-88), with acceleration and gradient from this module's own analytic derivative of those closed forms. wave_type="P" targets may mix z>0 and z<0; see docs/design/literature-b.md for the full literature mapping.

gragra.analytic.halfspace_reflected_p_above_observables_g_free

halfspace_reflected_p_above_observables_g_free(
    targets_m: ArrayLike,
    *,
    density_kg_m3: float,
    v_p_m_s: float,
    v_s_m_s: float,
    frequency_hz: float | ArrayLike,
    incidence_angle_rad: float,
    azimuth_rad: float,
    incident_displacement_m: float | complex | ArrayLike,
    phase_origin_m: ArrayLike = (0.0, 0.0, 0.0),
) -> GFreeGravityValues

G-free gravity above ground of an incident P + reflected P + converted SV.

Uses the coefficient consistent with the independently solved traction-free displacement field and its actual surface mass sheet. The literal H19 Eq. (90) coefficient, including its -1j term, remains available through the private _harms2019_reflected_p_delta helper; production deliberately uses the separate physical +1j coefficient rather than relabeling it as Eq. (90). This distinction and the full potential/acceleration/gradient reconstruction are checked in docs/design/literature-b.md and tests/test_bodywave_literature_oracle.py. Acceleration and gradient are this module's own analytic derivative (evidence B).

Only the ground side (z > 0) is defined by this entry point -- the paper only gives the above-surface composite (Eq. 89/90); the underground field of the full reflected/converted composite is out of scope for this PR (docs/design/literature-b.md).

Parameters:

Name Type Description Default
targets_m array-like of shape (M, 3)

Evaluation points in meters (z-up). z <= 0 is rejected.

required
density_kg_m3 float

Background mass density in kg/m^3 (non-negative; zero accepted).

required
v_p_m_s float

P- and S-wave speeds in m/s. Requires 0 < v_s_m_s < v_p_m_s and v_p_m_s**2 > (4/3) * v_s_m_s**2.

required
v_s_m_s float

P- and S-wave speeds in m/s. Requires 0 < v_s_m_s < v_p_m_s and v_p_m_s**2 > (4/3) * v_s_m_s**2.

required
frequency_hz float or array-like of shape (K,)

Positive frequency/frequencies in Hz.

required
incidence_angle_rad float

Incident P-wave angle from the surface normal, against v_p_m_s. Must satisfy 0 <= theta < pi/2. At theta=0 the closed form evaluates to exactly zero (every term of Eq. (90)'s numerator carries a k_rho factor that vanishes there), matching H19's "vanishes for vertically propagating incident P-waves" -- this is not special-cased, it falls out of evaluating Eq. (90) literally.

required
azimuth_rad float

Horizontal propagation azimuth in radians.

required
incident_displacement_m float, complex, or array-like of shape (K,)

Complex incident P-wave displacement amplitude (H19's xi_0^P). Zero accepted. A 1D array of length K only with a matching 1D frequency_hz.

required
phase_origin_m array-like of shape (3,)

Fixed 3D phase-reference point in meters. incident_displacement_m is the incident P wave's own complex amplitude evaluated AT this point; a nonzero phase_origin_m[2] re-references it to z=0 via the incident leg's own vertical wavenumber k_zp (exp(-i*k_zp*z0)), applied once and shared by the reflected/converted legs rather than separately per leg (see docs/design/literature-b.md).

(0.0, 0.0, 0.0)

Returns:

Type Description
GFreeGravityValues

G-free potential (kg/m), acceleration (kg/m^2), and gradient (kg/m^3), complex128, read-only.

G-free gravity above ground of an incident P + reflected P + converted SV composite. The production observable uses the coefficient reconstructed from the same traction-free displacement field and its actual surface mass sheet; the literal H19 Eq. (90) coefficient is retained separately in the private _harms2019_reflected_p_delta helper. Acceleration and gradient come from this module's own analytic derivative. Ground only (z>0); see docs/design/literature-b.md.

gragra.analytic.spherical_shell_p_acceleration_components_g_free

spherical_shell_p_acceleration_components_g_free(
    inner_radius_m: float,
    outer_radius_m: float,
    wavenumber_rad_m: float | list | tuple | ndarray,
    density_kg_m3: float,
    displacement_m: float | complex,
    direction: list | tuple | ndarray,
) -> GFreeSphericalShellPComponents

Calculate G-free P-wave acceleration component decomposition in a finite spherical shell.

The model considers an isotropic, homogeneous medium in a spherical shell a < r < R with background density rho. A plane harmonic P-wave propagates in the given direction with center displacement amplitude xi. The observation point is fixed at the cavity center.

Formulation: ANNA v4 (arXiv:2603.15157v4, §4.1, Eqs. 47-53): bulk = 4pi * rho * [j0(ka) - j0(kR)] * xi * e_hat inner_wall = 4pi * rho * [2f(ka) - j0(ka)] * xi * e_hat outer_boundary = 4pi * rho * [j0(kR) - 2f(kR)] * xi * e_hat total = 8pi * rho * [f(ka) - f(kR)] * xi * e_hat where f(x) = j1(x) / x.

Parameters:

Name Type Description Default
inner_radius_m float

Inner cavity radius a in meters (positive).

required
outer_radius_m float

Outer boundary radius R in meters (strictly greater than a, finite).

required
wavenumber_rad_m float or array - like

P-wave wavenumber k in rad/m (non-negative, scalar or 1D array).

required
density_kg_m3 float

Background mass density in kg/m^3 (non-negative, >= 0).

required
displacement_m float or complex

Center displacement amplitude in meters (real or complex phasor).

required
direction (array - like, shape(3))

P-wave propagation and displacement direction (non-zero 3-vector). Normalized internally to a unit vector.

required

Returns:

Type Description
GFreeSphericalShellPComponents

Container with bulk, inner_wall, outer_boundary, and total acceleration vectors in G-free units (kg / m^2). Shapes: (1, 3) for scalar k, or (K, 1, 3) for 1D k array of length K.

Calculates the G-free 4-component acceleration decomposition (bulk, inner wall, outer boundary, total) at the center of a spherical shell cavity under a P-wave.

gragra.analytic.spherical_shell_p_infinite_difference_g_free

spherical_shell_p_infinite_difference_g_free(
    inner_radius_m: float,
    outer_radius_m: float,
    wavenumber_rad_m: float | list | tuple | ndarray,
    density_kg_m3: float,
    displacement_m: float | complex,
    direction: list | tuple | ndarray,
) -> np.ndarray

Calculate the G-free difference (infinite_total - finite_total) for k > 0.

Formula: infinite_total - finite_total = 8*pi * rho * (j1(kR) / (kR)) * xi * e_hat

Parameters:

Name Type Description Default
inner_radius_m float

Inner cavity radius a in meters (positive).

required
outer_radius_m float

Outer boundary radius R in meters (strictly greater than a, finite).

required
wavenumber_rad_m float or array - like

P-wave wavenumber k in rad/m (strictly positive k > 0, scalar or 1D array).

required
density_kg_m3 float

Background mass density in kg/m^3 (positive).

required
displacement_m float or complex

Center displacement amplitude in meters.

required
direction (array - like, shape(3))

P-wave direction (non-zero 3-vector).

required

Returns:

Type Description
ndarray

Difference vector in G-free units (kg / m^2). Shape: (1, 3) for scalar k, or (K, 1, 3) for 1D k array.

Calculates the G-free acceleration difference between an infinite medium and a finite spherical shell cavity under P-wave excitation.

gragra.analytic.spherical_shell_s_acceleration_components_g_free

spherical_shell_s_acceleration_components_g_free(
    inner_radius_m: float,
    outer_radius_m: float,
    wavenumber_rad_m: float | list | tuple | ndarray,
    density_kg_m3: float,
    displacement_m: float | complex,
    propagation_direction: list | tuple | ndarray,
    polarization_direction: list | tuple | ndarray,
    *,
    orthogonality_tol: float = 1e-05,
) -> GFreeSphericalShellSComponents

Calculate G-free S-wave acceleration component decomposition in a finite spherical shell.

The model considers an isotropic, homogeneous medium in a spherical shell a < r < R with background density rho. A plane harmonic S-wave (shear wave) propagates in propagation_direction with polarization (displacement direction) polarization_direction, orthogonal to the propagation direction (S-wave transversality), and center displacement amplitude xi. The observation point is fixed at the cavity center.

Formulation: ANNA v4 (arXiv:2603.15157v4): Eq. (71) gives the finite-shell total: total(S)/G = -4pi * rho * (f(ka) - f(kR)) * xi * e_hat_S where f(x) = j1(x) / x. The inner/outer decomposition is derived from the general surface-integral form, Eq. (22), evaluated with the outward normal of the material region at each boundary (n_inner = -r_hat at r=a, n_outer = +r_hat at r=R): bulk = 0 inner_wall = -4pi * rho * f(ka) * xi * e_hat_S outer_boundary = +4*pi * rho * f(kR) * xi * e_hat_S so that total = inner_wall + outer_boundary, consistent with Eq. (71). S waves are divergence-free (div(u) = 0), so they produce no volumetric density perturbation and bulk is identically zero.

Numerical stability of total: total is computed via a direct stable difference (see gragra.analytic._bessel._j1_over_x_diff), not by independently rounding inner_wall/outer_boundary to float64 and then adding them. At small wavenumber and/or a thin shell (R close to a), f(ka) and f(kR) each round to ~1/3 in float64, and their naive difference loses essentially all significant digits (up to 100% relative error at extreme k -> 0), while the fully-cancelled total those two individual roundings imply is not recoverable from the returned inner_wall/outer_boundary values themselves. Consequently, in that regime, total and bulk + inner_wall + outer_boundary (reconstructed from the returned fields) can differ at the level of float64's resolution around inner_wall/outer_boundary's own magnitude; use total directly rather than reconstructing it by addition when that level of precision matters.

Direction normalization: propagation_direction and polarization_direction are normalized with a scale-safe unit-vector routine (divide by the largest-magnitude component first) so that direction vectors with very large or very small (but finite, non-zero) components are not mishandled by squared-norm overflow/underflow.

Rotational-symmetry note: Because the observation point is fixed at the common center of concentric spherical boundaries, the closed-form output above depends only on the wavenumber magnitude k = |k_vec| and the polarization direction e_hat_S; it has no explicit dependence on the propagation direction n_hat. propagation_direction is required only to validate S-wave transversality (n_hat . e_hat_S == 0, within orthogonality_tol); it does not otherwise enter the returned values. See test_shell_s_propagation_direction_invariance for a direct regression check of this invariance.

Complex-output disclaimer: The output is a linear complex amplitude / transfer-function-like response, not directly a real-valued time-domain gravitational field.

Parameters:

Name Type Description Default
inner_radius_m float

Inner cavity radius a in meters (positive).

required
outer_radius_m float

Outer boundary radius R in meters (strictly greater than a, finite).

required
wavenumber_rad_m float or array - like

S-wave wavenumber k in rad/m (non-negative, scalar or 1D array).

required
density_kg_m3 float

Background mass density in kg/m^3 (non-negative, >= 0).

required
displacement_m float or complex

Center displacement amplitude in meters (real or complex phasor).

required
propagation_direction (array - like, shape(3))

S-wave propagation direction (non-zero 3-vector). Normalized internally; validated to be orthogonal to polarization_direction.

required
polarization_direction (array - like, shape(3))

S-wave polarization (displacement) direction (non-zero 3-vector). Normalized internally to a unit vector; this is the direction that appears in the returned acceleration vectors.

required
orthogonality_tol float

Tolerance on abs(dot(n_hat, e_hat)) for the transversality check (default 1e-5, matching gragra.waves.polarization's convention for custom-polarization orthogonality checks). Must be in (0, 1.0) (the upper bound is strict, unlike gragra.waves.polarization's (0, 1.0]); this closed form assumes exact S-wave transversality, and a nonzero orthogonality_tol only accepts a caller's direction vectors as an approximately transverse input, not a redefinition of what transversality means. Independently of this parameter, a propagation/polarization pair whose normalized dot product exceeds 1.0 - 1e-9 (i.e. an exactly, or numerically indistinguishably, parallel or antiparallel pair) is always rejected, regardless of how permissive a requested tolerance is -- this guards against the case where a very permissive orthogonality_tol close to 1.0 happens to sit above the actual (float64-normalization-rounded) dot product of a truly parallel pair, which need not be exactly 1.0 (e.g. normalizing [1, 1, 0] against itself gives 0.9999999999999998, not 1.0).

1e-05

Returns:

Type Description
GFreeSphericalShellSComponents

Container with bulk (always zero), inner_wall, outer_boundary, and total acceleration vectors in G-free units (kg / m^2). Shapes: (1, 3) for scalar k, or (K, 1, 3) for 1D k array of length K.

Calculates the G-free 4-component acceleration decomposition (bulk, inner wall, outer boundary, total) at the center of a spherical shell cavity under an S-wave. Requires separate propagation and polarization directions, validated to be orthogonal (S-wave transversality); the closed form itself does not depend on the propagation direction.

gragra.analytic.spherical_shell_s_infinite_difference_g_free

spherical_shell_s_infinite_difference_g_free(
    inner_radius_m: float,
    outer_radius_m: float,
    wavenumber_rad_m: float | list | tuple | ndarray,
    density_kg_m3: float,
    displacement_m: float | complex,
    propagation_direction: list | tuple | ndarray,
    polarization_direction: list | tuple | ndarray,
    *,
    orthogonality_tol: float = 1e-05,
) -> np.ndarray

Calculate the G-free difference (infinite_total - finite_total) for k > 0.

ANNA v4 Eq. (71) (finite-shell total) and Eq. (72) (R -> infinity limit, fixed k > 0) imply the algebraic difference (this is not Eq. (72) itself, but a consequence of subtracting Eq. (71) from Eq. (72)):

infinite_total (Eq. 72) - finite_total (Eq. 71)
    = -4*pi * rho * f(kR) * xi * e_hat_S

See spherical_shell_s_acceleration_components_g_free for the rotational-symmetry note on why propagation_direction does not appear in the output despite being a required, validated input.

Parameters:

Name Type Description Default
inner_radius_m float

Inner cavity radius a in meters (positive).

required
outer_radius_m float

Outer boundary radius R in meters (strictly greater than a, finite).

required
wavenumber_rad_m float or array - like

S-wave wavenumber k in rad/m (strictly positive k > 0, scalar or 1D array).

required
density_kg_m3 float

Background mass density in kg/m^3 (non-negative, >= 0).

required
displacement_m float or complex

Center displacement amplitude in meters (real or complex phasor).

required
propagation_direction (array - like, shape(3))

S-wave propagation direction (non-zero 3-vector), validated to be orthogonal to polarization_direction.

required
polarization_direction (array - like, shape(3))

S-wave polarization (displacement) direction (non-zero 3-vector).

required
orthogonality_tol float

Tolerance for the transversality check (default 1e-5). Must be in (0, 1.0); see spherical_shell_s_acceleration_components_g_free's docstring for why the upper bound is strict and for the additional hard, tolerance-independent parallel/antiparallel rejection.

1e-05

Returns:

Type Description
ndarray

Difference vector in G-free units (kg / m^2). Shape: (1, 3) for scalar k, or (K, 1, 3) for 1D k array.

Calculates the G-free acceleration difference between an infinite medium and a finite spherical shell cavity under S-wave excitation.

Observables

The seventeen gragra.observables symbols — point_potential, point_acceleration, point_gravity_gradient, coherent_point_acceleration, coherent_point_gravity_gradient, coherent_gravitoelastic_tensor, coherent_acceleration_csd, displacement_transfer_acceleration, displacement_transfer_potential, displacement_transfer_gravity_gradient, trajectory_potential, trajectory_acceleration, trajectory_gravity_gradient, rigid_transform_potential, rigid_transform_acceleration, rigid_transform_gravity_gradient and displacement_field_acceleration — are the layer that multiplies by G_SI and are documented in full on Sources, targets and geometry's sibling page, Top-level API, and their dedicated guide pages (Point sources, Observables, Coherent responses and cross statistics). They are not repeated here to avoid two ::: directives rendering the same symbol, except for the two subpackage-only displacement observables below.

gragra.observables.displacement_transfer_potential

displacement_transfer_potential(
    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 potential perturbation linearized in source displacement.

Parameters follow :func:displacement_transfer_acceleration: background masses are finite, real, and non-negative; displacement vectors have shape (N, 3) and may be complex amplitudes. The result has shape (M,) and is read-only.

The NumPy and Numba backends implement this derivative. The G-free kernel is multiplied by G_SI exactly once here.

Returns the first-order potential perturbation of discrete, non-negative mass elements under real or complex displacement vectors. Its NumPy implementation uses the G-free displacement kernel and returns a read-only (M,) array.

gragra.observables.displacement_transfer_gravity_gradient

displacement_transfer_gravity_gradient(
    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 gravity-gradient perturbation linearized in displacement.

Parameters follow :func:displacement_transfer_acceleration: background masses are finite, real, and non-negative; displacement vectors have shape (N, 3) and may be complex amplitudes. The result has shape (M, 3, 3) and is read-only.

The NumPy and Numba backends implement this derivative. The G-free kernel is multiplied by G_SI exactly once here. With Plummer softening, its trace is generally nonzero as documented in kernel_contract.md.

Returns the first-order gravity-gradient perturbation for the same discrete mass-element model as displacement_transfer_potential. Its read-only (M, 3, 3) result is symmetric, and Plummer softening can give it nonzero trace.

gragra.observables.trajectory_potential

trajectory_potential(
    trajectory: PrescribedPointTrajectory,
    targets,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> np.ndarray

Return potential (P, M) for a prescribed point trajectory.

Returns read-only potential samples shaped (P, M) for a prescribed positive point trajectory.

gragra.observables.trajectory_acceleration

trajectory_acceleration(
    trajectory: PrescribedPointTrajectory,
    targets,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> np.ndarray

Return acceleration (P, M, 3) for a prescribed point trajectory.

Returns read-only acceleration samples shaped (P, M, 3) for a prescribed positive point trajectory.

gragra.observables.trajectory_gravity_gradient

trajectory_gravity_gradient(
    trajectory: PrescribedPointTrajectory,
    targets,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> np.ndarray

Return gravity gradient (P, M, 3, 3) for a point trajectory.

Returns read-only gravity-gradient samples shaped (P, M, 3, 3) for a prescribed positive point trajectory.

gragra.observables.rigid_transform_potential

rigid_transform_potential(
    source: PointMassCloud,
    transform: PrescribedRigidTransform,
    targets,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> np.ndarray

Return potential (P, M) for a transformed point-mass cloud.

Returns read-only potential samples shaped (P, M) for a PointMassCloud under a prescribed rigid transform.

gragra.observables.rigid_transform_acceleration

rigid_transform_acceleration(
    source: PointMassCloud,
    transform: PrescribedRigidTransform,
    targets,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> np.ndarray

Return acceleration (P, M, 3) for a transformed point cloud.

Returns read-only acceleration samples shaped (P, M, 3) for a PointMassCloud under a prescribed rigid transform.

gragra.observables.rigid_transform_gravity_gradient

rigid_transform_gravity_gradient(
    source: PointMassCloud,
    transform: PrescribedRigidTransform,
    targets,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
    backend: str = "numpy",
) -> np.ndarray

Return gradient (P, M, 3, 3) for a transformed point cloud.

Returns read-only gravity-gradient samples shaped (P, M, 3, 3) for a PointMassCloud under a prescribed rigid transform.

Analytic SI Observables

gragra.observables.GravityObservables dataclass

Potential, acceleration, and gradient in SI units.

Physical units: - potential: m^2 / s^2 - acceleration: m / s^2 - gradient: s^-2

Shapes: - Static targets: potential (M,), acceleration (M, 3), gradient (M, 3, 3). - Series targets: potential (S, M), acceleration (S, M, 3), gradient (S, M, 3, 3).

Frozen container holding potential, acceleration, and gradient arrays in standard physical SI units (m^2/s^2, m/s^2, s^-2).

gragra.observables.to_gravity_observables

to_gravity_observables(
    values: GFreeGravityValues,
) -> GravityObservables

Convert G-free gravitational values to SI gravitational observables.

Multiplies potential, acceleration, and gradient by G_SI exactly once. Rejects values already in SI units or legacy structures without clear units.

Parameters:

Name Type Description Default
values GFreeGravityValues

G-free potential, acceleration, and gradient.

required

Returns:

Type Description
GravityObservables

SI observables (m^2/s^2, m/s^2, s^-2).

Converts a GFreeGravityValues bundle to physical SI GravityObservables by multiplying every component by the gravitational constant G_SI exactly once.

gragra.observables.SphericalShellPComponents dataclass

Component decomposition of spherical-shell P-wave acceleration in SI units.

Fields: - bulk: Volume compression contribution of the shell (m / s^2). - inner_wall: Surface mass-sheet contribution of the inner cavity wall. - outer_boundary: Surface mass-sheet contribution of the outer boundary. - total: bulk + inner_wall + outer_boundary. - unit_system: Fixed identifier string "si".

Shapes: - Scalar wavenumber: each field is (1, 3) (one center, three components). - 1D wavenumber array of length K: each field is (K, 1, 3).

Frozen container holding physical SI acceleration components (bulk, inner_wall, outer_boundary, total) in m/s^2 for a spherical shell cavity under P-wave excitation.

gragra.observables.to_spherical_shell_p_components

to_spherical_shell_p_components(
    values: GFreeSphericalShellPComponents,
) -> SphericalShellPComponents

Convert G-free spherical-shell P-wave acceleration components to SI units.

Multiplies bulk, inner_wall, outer_boundary, and total by G_SI exactly once. Rejects values already in SI units or incompatible structures.

Converts a GFreeSphericalShellPComponents bundle to physical SI SphericalShellPComponents by multiplying every component by G_SI exactly once.

gragra.observables.SphericalShellSComponents dataclass

Component decomposition of spherical-shell S-wave acceleration in SI units.

Fields: - bulk: Always identically zero (S waves are divergence-free). - inner_wall: Surface mass-sheet contribution of the inner cavity wall. - outer_boundary: Surface mass-sheet contribution of the outer boundary. - total: inner_wall + outer_boundary. - unit_system: Fixed identifier string "si".

Shapes: - Scalar wavenumber: each field is (1, 3) (one center, three components). - 1D wavenumber array of length K: each field is (K, 1, 3).

Frozen container holding physical SI acceleration components (bulk, inner_wall, outer_boundary, total) in m/s^2 for a spherical shell cavity under S-wave excitation. bulk is always identically zero.

gragra.observables.to_spherical_shell_s_components

to_spherical_shell_s_components(
    values: GFreeSphericalShellSComponents,
) -> SphericalShellSComponents

Convert G-free spherical-shell S-wave acceleration components to SI units.

Multiplies bulk, inner_wall, outer_boundary, and total by G_SI exactly once. Rejects values already in SI units or incompatible structures.

Converts a GFreeSphericalShellSComponents bundle to physical SI SphericalShellSComponents by multiplying every component by G_SI exactly once.

gragra.observables.uniform_sphere_observables

uniform_sphere_observables(
    center_m: list | tuple | ndarray,
    radius_m: float,
    density_kg_m3: float | complex,
    targets_m: list | tuple | ndarray,
) -> GravityObservables

Calculate SI potential, acceleration, and gradient of a uniform sphere.

Parameters:

Name Type Description Default
center_m (array - like, shape(3))

Coordinates of the sphere center in meters.

required
radius_m float

Radius of the sphere in meters (must be positive).

required
density_kg_m3 float or complex

Mass density in kg/m^3 (real or complex).

required
targets_m (array - like, shape(M, 3))

Coordinates of the target points in meters.

required

Returns:

Type Description
GravityObservables

SI observables bundle (potential, acceleration, gradient).

Evaluates the gravitational potential, acceleration, and gradient tensor of a uniform sphere in physical SI units.

gragra.observables.cuboid_observables

cuboid_observables(
    center_m: list | tuple | ndarray,
    lengths_m: list | tuple | ndarray,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
) -> GravityObservables

Calculate SI potential, acceleration, and gradient of a uniform cuboid.

Parameters:

Name Type Description Default
center_m (array - like, shape(3))

Center coordinates of the cuboid in meters.

required
lengths_m (array - like, shape(3))

Side lengths (Lx, Ly, Lz) in meters (all positive).

required
density_kg_m3 float

Uniform mass density in kg/m^3 (positive).

required
targets_m (array - like, shape(M, 3))

Observation target points in meters. Target points lying on the material boundary of the cuboid are rejected.

required

Returns:

Type Description
GravityObservables

SI observables bundle (potential in m^2/s^2, acceleration in m/s^2, gradient in s^-2).

Evaluates the closed-form potential, acceleration, and 3x3 gravity-gradient tensor of a uniform cuboid in physical SI units.

gragra.observables.oriented_cuboid_observables

oriented_cuboid_observables(
    center_m: list | tuple | ndarray,
    lengths_m: list | tuple | ndarray,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
    *,
    rotation_matrix: list | tuple | ndarray,
) -> GravityObservables

Evaluate a rotated uniform cuboid in physical SI units.

rotation_matrix is the explicit local-to-world proper rotation. The G-free local cuboid closed form is evaluated first and multiplied by G_SI exactly once through :func:to_gravity_observables.

Evaluates an arbitrarily translated and properly rotated uniform cuboid in physical SI units by scaling the G-free oriented wrapper exactly once.

gragra.observables.sca_wall_acceleration_from_tensor

sca_wall_acceleration_from_tensor(
    coupling_tensor: list | tuple | ndarray,
    density_kg_m3: float,
    displacement_m: list | tuple | ndarray,
) -> np.ndarray

Apply an SCA wall tensor and return the SI acceleration amplitude.

The G-free operation is -rho * C @ displacement; this wrapper applies G_SI exactly once. The displacement may be a shared vector (3,) or one vector per tensor row (M,3).

Applies an SCA wall-coupling tensor and multiplies the resulting G-free acceleration by G_SI exactly once.

gragra.observables.cylinder_axis_observables

cylinder_axis_observables(
    center_m: list | tuple | ndarray,
    radius_m: float,
    height_m: float,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
) -> GravityObservables

Calculate SI on-axis potential, acceleration, and gradient of a uniform cylinder.

Parameters:

Name Type Description Default
center_m (array - like, shape(3))

Center of the cylinder in meters.

required
radius_m float

Radius in meters (positive).

required
height_m float

Height in meters (positive).

required
density_kg_m3 float

Uniform mass density in kg/m^3 (positive).

required
targets_m (array - like, shape(M, 3))

Observation target points in meters. Off-axis points and points on the end faces z = ±h/2 are rejected.

required

Returns:

Type Description
GravityObservables

SI observables bundle on the cylinder axis.

Evaluates the closed-form on-axis potential, acceleration, and 3x3 gradient tensor of a uniform cylinder in physical SI units.

gragra.observables.cylinder_observables

cylinder_observables(
    center_m: list | tuple | ndarray,
    radius_m: float,
    height_m: float,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
    *,
    quadrature_order: int = 32,
) -> GravityObservables

Calculate SI general-point observables of a z-aligned solid cylinder.

This is the SI wrapper for the opt-in cylindrical quadrature path in :func:gragra.analytic.cylinder_observables_g_free.

Evaluates the general-point z-aligned uniform-cylinder observables in SI units by scaling gragra.analytic.cylinder_observables_g_free by G_SI. The general-point implementation is an opt-in numerical semi-analytic path; it is not a claim of Conway's closed elliptic-integral solution.

gragra.observables.cylinder_acceleration_gradient

cylinder_acceleration_gradient(
    center_m: list | tuple | ndarray,
    radius_m: float,
    height_m: float,
    density_kg_m3: float,
    targets_m: list | tuple | ndarray,
    *,
    rotation_matrix: list | tuple | ndarray | None = None,
) -> tuple[np.ndarray, np.ndarray]

Analytic finite-cylinder acceleration (m/s²) and gradient (1/s²).

rotation_matrix is the proper local-to-world rotation. Returns read-only arrays (M,3), (M,3,3); rejects the physical material boundary. See cylinder_acceleration_gradient_g_free for the analytic method.

SI acceleration and gradient from the analytic cylinder route, multiplied by G_SI once. Returns (acceleration, gradient) with shapes (M,3), (M,3,3).

gragra.observables.cylinder_analytic_observables

cylinder_analytic_observables(
    center_m: ArrayLike,
    radius_m: float,
    height_m: float,
    density_kg_m3: float,
    targets_m: ArrayLike,
    *,
    rotation_matrix: ArrayLike | None = None,
) -> GravityObservables

Analytic finite-cylinder triple in SI units, with infinity-zero potential.

See cylinder_analytic_observables_g_free for the real elliptic/series method and material-boundary exclusions. Rotation maps local to world. The existing cylinder_observables is the numerical diagnostic route.

SI potential, acceleration, and gradient from the analytic cylinder triple, scaled by G_SI once at the observable boundary. Supports proper rotations and returns read-only arrays with shapes (M,), (M,3), and (M,3,3).

gragra.observables.rayleigh_halfspace_allspace_observables

rayleigh_halfspace_allspace_observables(
    targets_m: ArrayLike,
    *,
    density_kg_m3: float,
    v_p_m_s: float,
    v_s_m_s: float,
    frequency_hz: float | ArrayLike,
    vertical_surface_amplitude_m: float
    | complex
    | ArrayLike,
    direction: ArrayLike = (1.0, 0.0, 0.0),
    phase_origin_m: ArrayLike = (0.0, 0.0, 0.0),
) -> GravityObservables

SI potential/acceleration/gradient of a Rayleigh wave above and below ground.

Multiplies :func:gragra.analytic.rayleigh_literature.rayleigh_halfspace_allspace_observables_g_free by G_SI exactly once via :func:gragra.observables.analytic.to_gravity_observables. See that G-free function's docstring for the literature mapping (H19 Eq. 96-98), evidence classification, and parameter/shape contract.

Returns:

Type Description
GravityObservables

SI observables (potential m^2/s^2, acceleration m/s^2, gradient s^-2).

SI potential/acceleration/gradient of a Rayleigh wave above and below a homogeneous elastic half-space (H19 Eq. 96-98), multiplying the G-free gragra.analytic.rayleigh_halfspace_allspace_observables_g_free by G_SI exactly once. A separate entry point from the legacy ground-only rayleigh_halfspace_observables.

The high-level seismic namespace accepts a HalfSpace, material quantities, and an explicit complex phasor contract, then evaluates potential, acceleration, and gradient together as frequency matrices.

gragra.analytic.seismic.rayleigh_halfspace

rayleigh_halfspace(
    geometry: HalfSpace,
    density: Quantity,
    vp: Quantity,
    vs: Quantity,
    vertical_displacement: FrequencySeries,
    representation: PhasorRepresentation,
    reference_time: object,
    phase_origin: Quantity,
    direction: object,
) -> _RayleighModel

Create a Rayleigh half-space model from an explicit phasor contract.

rayleigh_response builds a reusable Newtonian transfer from vertical surface displacement to potential, acceleration, and gradient. The setup computes its coefficients from a one-metre phasor and can apply later phasor inputs without running the Rayleigh observable again.

gragra.analytic.seismic.rayleigh_response

rayleigh_response(
    geometry: HalfSpace,
    *,
    density: Quantity,
    vp: Quantity,
    vs: Quantity,
    frequencies: Quantity,
    direction: object,
    phase_origin: Quantity,
) -> _RayleighResponseModel

Create a setup for reusable Rayleigh-to-gravity response coefficients.

Parameters:

Name Type Description Default
geometry HalfSpace

The elastic half-space and its surface frame.

required
density Quantity

Half-space density, with units convertible to kg/m³.

required
vp Quantity

Compressional-wave speed, with units convertible to m/s.

required
vs Quantity

Shear-wave speed, with units convertible to m/s.

required
frequencies Quantity

Positive, strictly increasing frequency bins, with units convertible to Hz.

required
direction object

Nonzero horizontal propagation direction in the surface frame; it is normalized internally.

required
phase_origin Quantity

Surface location where the complex displacement phasor is defined, with units convertible to m.

required

Returns:

Type Description
Rayleigh response setup

A deferred model description. Call at(targets).run() to calculate a GravityResponse with coefficients for potential, acceleration, and gradient.

Notes

This setup contains no displacement amplitude or reference time. The response uses a one-metre basis displacement to calculate coefficients. Applying a vertical-displacement frequency series reuses those coefficients. The resulting values are complex phasor quantities, not directly real-valued time-domain gravitational fields.

gragra.observables.halfspace_single_bodywave_observables

halfspace_single_bodywave_observables(
    targets_m: ArrayLike,
    *,
    wave_type: Literal["P", "SV"],
    density_kg_m3: float,
    v_p_m_s: float,
    v_s_m_s: float,
    frequency_hz: float | ArrayLike,
    incidence_angle_rad: float,
    azimuth_rad: float,
    displacement_m: float | complex | ArrayLike,
    phase_origin_m: ArrayLike = (0.0, 0.0, 0.0),
) -> GravityObservables

SI potential/acceleration/gradient of a single upward-propagating P or SV wave.

Multiplies :func:gragra.analytic.bodywave_literature.halfspace_single_bodywave_observables_g_free by G_SI exactly once via :func:gragra.observables.analytic.to_gravity_observables. See that G-free function's docstring for the literature mapping (H19 Eq. 86-88), evidence classification, and parameter/shape contract.

Returns:

Type Description
GravityObservables

SI observables (potential m^2/s^2, acceleration m/s^2, gradient s^-2).

SI potential/acceleration/gradient of a single upward-propagating P or SV wave, without a free-surface reflection composite (H19 Eq. 86-88), multiplying the G-free gragra.analytic.halfspace_single_bodywave_observables_g_free by G_SI exactly once.

gragra.observables.halfspace_reflected_p_above_observables

halfspace_reflected_p_above_observables(
    targets_m: ArrayLike,
    *,
    density_kg_m3: float,
    v_p_m_s: float,
    v_s_m_s: float,
    frequency_hz: float | ArrayLike,
    incidence_angle_rad: float,
    azimuth_rad: float,
    incident_displacement_m: float | complex | ArrayLike,
    phase_origin_m: ArrayLike = (0.0, 0.0, 0.0),
) -> GravityObservables

SI potential/acceleration/gradient of incident + reflected P + converted SV.

Multiplies :func:gragra.analytic.bodywave_literature.halfspace_reflected_p_above_observables_g_free by G_SI exactly once via :func:gragra.observables.analytic.to_gravity_observables. See that G-free function's docstring for the literature mapping (H19 Eq. 89/90), evidence classification, and parameter/shape contract.

Returns:

Type Description
GravityObservables

SI observables (potential m^2/s^2, acceleration m/s^2, gradient s^-2).

SI potential/acceleration/gradient above ground of an incident P + reflected P + converted SV composite (H19 Eq. 90), multiplying the G-free gragra.analytic.halfspace_reflected_p_above_observables_g_free by G_SI exactly once.

gragra.observables.spherical_shell_p_acceleration_components

spherical_shell_p_acceleration_components(
    inner_radius_m: float,
    outer_radius_m: float,
    wavenumber_rad_m: float | list | tuple | ndarray,
    density_kg_m3: float,
    displacement_m: float | complex,
    direction: list | tuple | ndarray,
) -> SphericalShellPComponents

Calculate SI P-wave acceleration component decomposition in a spherical shell.

Evaluates the bulk, inner cavity wall, outer boundary, and total acceleration components at the center of a spherical cavity in a finite shell a < r < R, multiplying by G_SI exactly once.

Parameters:

Name Type Description Default
inner_radius_m float

Inner cavity radius a in meters (positive).

required
outer_radius_m float

Outer boundary radius R in meters (strictly greater than a, finite).

required
wavenumber_rad_m float or array - like

P-wave wavenumber k in rad/m (non-negative, scalar or 1D array).

required
density_kg_m3 float

Background mass density in kg/m^3 (positive).

required
displacement_m float or complex

Center displacement amplitude in meters (real or complex phasor).

required
direction (array - like, shape(3))

P-wave propagation and displacement direction (non-zero 3-vector).

required

Returns:

Type Description
SphericalShellPComponents

Container with bulk, inner_wall, outer_boundary, and total acceleration vectors in SI units (m / s^2). Shapes: (1, 3) for scalar k, or (K, 1, 3) for 1D k array of length K.

Calculates the 4-component P-wave cavity acceleration decomposition (bulk, inner wall, outer boundary, total) in physical SI units.

gragra.observables.spherical_shell_p_infinite_difference

spherical_shell_p_infinite_difference(
    inner_radius_m: float,
    outer_radius_m: float,
    wavenumber_rad_m: float | list | tuple | ndarray,
    density_kg_m3: float,
    displacement_m: float | complex,
    direction: list | tuple | ndarray,
) -> np.ndarray

Calculate SI difference (infinite_total - finite_total) for k > 0.

Formula: infinite_total - finite_total = 8*pi * G_SI * rho * (j1(kR) / (kR)) * xi * e_hat

Parameters:

Name Type Description Default
inner_radius_m float

Inner cavity radius a in meters (positive).

required
outer_radius_m float

Outer boundary radius R in meters (strictly greater than a, finite).

required
wavenumber_rad_m float or array - like

P-wave wavenumber k in rad/m (strictly positive k > 0, scalar or 1D array).

required
density_kg_m3 float

Background mass density in kg/m^3 (positive).

required
displacement_m float or complex

Center displacement amplitude in meters.

required
direction (array - like, shape(3))

P-wave direction (non-zero 3-vector).

required

Returns:

Type Description
ndarray

Difference vector in SI units (m / s^2). Shape: (1, 3) for scalar k, or (K, 1, 3) for 1D k array.

Calculates the physical SI acceleration difference between an infinite medium and a finite spherical shell cavity under P-wave excitation.

gragra.observables.spherical_shell_s_acceleration_components

spherical_shell_s_acceleration_components(
    inner_radius_m: float,
    outer_radius_m: float,
    wavenumber_rad_m: float | list | tuple | ndarray,
    density_kg_m3: float,
    displacement_m: float | complex,
    propagation_direction: list | tuple | ndarray,
    polarization_direction: list | tuple | ndarray,
    *,
    orthogonality_tol: float = 1e-05,
) -> SphericalShellSComponents

Calculate SI S-wave acceleration component decomposition in a spherical shell.

Evaluates the (always-zero) bulk, inner cavity wall, outer boundary, and total acceleration components at the center of a spherical cavity in a finite shell a < r < R, multiplying by G_SI exactly once. See gragra.analytic.spherical_shell_s_acceleration_components_g_free for the closed-form derivation, primary-source equation references (ANNA v4 Eq. 71/72/22), and the rotational-symmetry note explaining why propagation_direction does not appear in the output.

Parameters:

Name Type Description Default
inner_radius_m float

Inner cavity radius a in meters (positive).

required
outer_radius_m float

Outer boundary radius R in meters (strictly greater than a, finite).

required
wavenumber_rad_m float or array - like

S-wave wavenumber k in rad/m (non-negative, scalar or 1D array).

required
density_kg_m3 float

Background mass density in kg/m^3 (non-negative, >= 0).

required
displacement_m float or complex

Center displacement amplitude in meters (real or complex phasor).

required
propagation_direction (array - like, shape(3))

S-wave propagation direction (non-zero 3-vector), validated to be orthogonal to polarization_direction.

required
polarization_direction (array - like, shape(3))

S-wave polarization (displacement) direction (non-zero 3-vector).

required
orthogonality_tol float

Tolerance for the transversality check (default 1e-5). Must be in (0, 1.0); see gragra.analytic.spherical_shell_s_acceleration_components_g_free's docstring for why the upper bound is strict and for the additional hard, tolerance-independent parallel/antiparallel rejection.

1e-05

Returns:

Type Description
SphericalShellSComponents

Container with bulk (always zero), inner_wall, outer_boundary, and total acceleration vectors in SI units (m / s^2). Shapes: (1, 3) for scalar k, or (K, 1, 3) for 1D k array of length K.

Calculates the 4-component S-wave cavity acceleration decomposition (bulk, inner wall, outer boundary, total) in physical SI units.

gragra.observables.spherical_shell_s_infinite_difference

spherical_shell_s_infinite_difference(
    inner_radius_m: float,
    outer_radius_m: float,
    wavenumber_rad_m: float | list | tuple | ndarray,
    density_kg_m3: float,
    displacement_m: float | complex,
    propagation_direction: list | tuple | ndarray,
    polarization_direction: list | tuple | ndarray,
    *,
    orthogonality_tol: float = 1e-05,
) -> np.ndarray

Calculate SI difference (infinite_total - finite_total) for k > 0.

Formula (ANNA v4 Eq. 71 and Eq. 72 imply this algebraic difference): infinite_total - finite_total = -4*pi * G_SI * rho * (j1(kR) / (kR)) * xi * e_hat_S

See gragra.analytic.spherical_shell_s_acceleration_components_g_free's "Rotational-symmetry note" for why propagation_direction is a required, validated input but does not itself appear in the formula above.

Parameters:

Name Type Description Default
inner_radius_m float

Inner cavity radius a in meters (positive).

required
outer_radius_m float

Outer boundary radius R in meters (strictly greater than a, finite).

required
wavenumber_rad_m float or array - like

S-wave wavenumber k in rad/m (strictly positive k > 0, scalar or 1D array).

required
density_kg_m3 float

Background mass density in kg/m^3 (non-negative, >= 0).

required
displacement_m float or complex

Center displacement amplitude in meters.

required
propagation_direction (array - like, shape(3))

S-wave propagation direction (non-zero 3-vector), validated to be orthogonal to polarization_direction.

required
polarization_direction (array - like, shape(3))

S-wave polarization (displacement) direction (non-zero 3-vector).

required
orthogonality_tol float

Tolerance for the transversality check (default 1e-5). Must be in (0, 1.0); see gragra.analytic.spherical_shell_s_acceleration_components_g_free's docstring for why the upper bound is strict and for the additional hard, tolerance-independent parallel/antiparallel rejection.

1e-05

Returns:

Type Description
ndarray

Difference vector in SI units (m / s^2). Shape: (1, 3) for scalar k, or (K, 1, 3) for 1D k array.

Calculates the physical SI acceleration difference between an infinite medium and a finite spherical shell cavity under S-wave excitation.