Skip to content

Sources, targets and geometry

This page covers the input side of a calculation and the two layers beneath the observables. It is organised the way a calculation flows: you describe mass (gragra.gravity_sources), you say where you want the answer (gragra.targets), you turn a shape into mass elements (gragra.geometry), and — if you are building something new — you reach the integrator and kernel layers that the observables are made of.

The layering is strict and worth stating once: an observable calls an integrator, the integrator dispatches to a kernel, and the kernel returns a purely geometric factor. Only the observable multiplies by G_SI. Anything you build on top of gragra.kernels is G-free and stays that way until you multiply it yourself.

Sources

WeightedPointSource, PointMass, and PointMassCloud are re-exported at the top level and documented on the Top-level API page. The remaining subpackage source types are documented below. The volume and surface types carry a discretization and density; the prescribed-motion types carry externally supplied time samples.

gragra.gravity_sources.VolumeElementSource dataclass

Volume element source representing discretized 3D volumes.

Note that weights_kg returned by as_weighted_source() are mass elements only (e.g., δm = δρ * dV) in kilograms. Transfer factors or coherent phase terms must be handled by a separate abstraction.

Parameters:

Name Type Description Default
positions_m array - like

Coordinates of shape (N, 3) in meters.

required
volumes_m3 array - like

Volume elements of shape (N,) in cubic meters. Must be positive and finite.

required
density_kg_m3 float, complex, or array-like

Mass density in kg/m^3. Can be a scalar or a vector of shape (N,).

required

as_weighted_source

as_weighted_source() -> WeightedPointSource

Convert to the canonical WeightedPointSource format.

weights = density * volume.

A set of volume elements — centroid positions, per-element volumes and a density — which as_weighted_source() collapses into mass elements δm = ρ·dV. This is what a discretized solid, a voxelised density field or a tetrahedral mesh becomes on its way into an observable, and keeping the volume separate from the density until that point is what lets you change one without re-deriving the other.

For a uniform sphere, discretize accepts pure geometry, a density Quantity and a spacing Quantity, then returns the fixed point source used by evaluation. The same source model also accepts caller-provided real static point sources and volume elements. Density grids and volume meshes can be converted to VolumeElementSource values and evaluated with an explicit Frame and field definition; the static-source guide documents those input routes and their evidence.

gragra.gravity_sources.discretize

discretize(
    geometry: Sphere,
    density: Quantity,
    spacing: Quantity,
    max_points: int | None = 1000000,
) -> DiscreteSource

Eagerly create one immutable Cartesian midpoint source for a sphere.

The existing geometry.primitives.Sphere implementation supplies the midpoint locations, cell volume, inclusion rule, and closest-point fallback. max_points limits its bounding-box grid before inclusion. No boundary-cell correction or mass renormalization is applied.

point_sum binds a static source to the numerical point-sum model. A DiscreteSource from discretize carries its Sphere Frame and field meaning; bare point and volume sources require an explicit Frame, and general weighted or volume sources also require a GravityFieldDefinition. Calling .at() fixes the targets and observables before validation or calculation begins.

gragra.gravity_sources.point_sum

point_sum(
    source: StaticPointInput,
    *,
    frame: Frame | None = None,
    field_definition: GravityFieldDefinition | None = None,
    provenance: Mapping[str, object] | None = None,
) -> PointSumModel

Create a static point-sum model.

DiscreteSource supplies its geometry frame and Sphere field meaning. Bare sources require frame; generic signed weights and volume elements also require field_definition. PointMass and PointMassCloud default to a total source field with potential zero at infinity. Optional provenance is an immutable snapshot and never establishes frame identity.

rigid_motion builds a rigid-motion model of a point-mass cloud. A PrescribedRigidTransform with sampling= gives a time-series evaluation. A callable pose with epoch= gives continuous Fourier-series and Fourier-transform evaluations. The rigid-motion guide covers units, phase conventions, applicability and the memory budget.

gragra.gravity_sources.rigid_motion

rigid_motion(
    source: PointMassCloud,
    transform: PrescribedRigidTransform,
    *,
    frame: Frame,
    sampling: TimeSampling,
    field_definition: GravityFieldDefinition | None = None,
    provenance: Mapping[str, object] | None = None,
) -> RigidMotionModel
rigid_motion(
    source: PointMassCloud,
    transform: PoseFunction,
    *,
    frame: Frame,
    epoch: object,
    field_definition: GravityFieldDefinition | None = None,
    provenance: Mapping[str, object] | None = None,
) -> ContinuousFourierModel
rigid_motion(
    source: PointMassCloud,
    transform: PrescribedRigidTransform | PoseFunction,
    *,
    frame: Frame,
    sampling: TimeSampling | None = None,
    epoch: object | None = None,
    field_definition: GravityFieldDefinition | None = None,
    provenance: Mapping[str, object] | None = None,
) -> RigidMotionModel | ContinuousFourierModel

Create a rigid-motion model of a point-mass cloud.

The second argument selects one of two forms.

Sampled form. transform is a PrescribedRigidTransform. Pass sampling (a TimeSampling) and do not pass epoch. The model is evaluated with .at(targets).run(), which returns a time-series EvaluationResult.

Continuous form. transform is a callable pose. It takes a Quantity of times in seconds, relative to epoch, and returns (Rotation, Quantity[m] of shape (N, 3)), with one rotation per time. Pass epoch (a LIGOTimeGPS, an astropy Time, or a (seconds, nanoseconds) tuple of integers, giving the absolute GPS time of relative time zero) and do not pass sampling. The model is evaluated with .at(targets) and then .fourier_series(...) or .fourier_transform(...).

Any other combination of arguments raises TypeError.

Parameters:

Name Type Description Default
source PointMassCloud

Positive point masses. Their positions are body coordinates in metres.

required
transform PrescribedRigidTransform or callable pose

Rigid motion of the body. The body-to-frame map is x = R x_body + c.

required
frame Frame

Computation frame. The output is expressed in this frame, and the pose maps body coordinates into it.

required
sampling TimeSampling

Required for the sampled form only.

None
epoch LIGOTimeGPS, astropy Time, or (int, int)

Required for the continuous form only. It is the absolute GPS time of pose relative time zero.

None
field_definition GravityFieldDefinition

Field metadata. The default is the total field of the source.

None
provenance Mapping

Not supported. Passing a value raises TypeError.

None
Notes

Units and phase. Times are in seconds, positions in metres, and accelerations in m/s**2. Fourier coefficients use the convention exp[-2*pi*i*f*(t - tref)]. tref is an explicit argument of the Fourier methods and has no default, so the epoch is never used as an implicit phase reference.

Continuous-form Fourier methods. fourier_series covers periodic motion only (periodic integrator). Its amplitudes satisfy A_0 = C_0 and A_n = 2 C_n. fourier_transform integrates a finite window (finite-window integrator). Its coefficients are one-sided and not doubled. The result is limited by tau_min and by the finite sampling, which together control aliasing. For fourier_transform the phase range must satisfy f_max * |epoch - tref| <= 1e6 cycles. Place tref near the window.

Stability. The return type of the continuous form is provisional, and its signature may change in future.

Gravitational constant. G is applied exactly once, in the observable layer. The kernels are G-free.

Complex outputs. Complex Fourier coefficients are linear complex amplitudes or transfer-function-like responses. They are not real-valued time-domain gravitational fields.

Memory. memory_budget_bytes is a per-lane budget for the arrays managed by the library. It is not a process RSS limit, and it is not summed across lanes.

gragra.gravity_sources.SurfaceMassSheetSource dataclass

Surface mass sheet source representation.

Represents displacement-induced surface mass perturbations. Note that weights_kg returned by as_weighted_source() are mass elements only (e.g., δm = δρ * u_n * dS) in kilograms. Transfer factors or coherent phase terms must be handled by a separate abstraction.

Parameters:

Name Type Description Default
positions_m array - like

Coordinates of shape (N, 3) in meters.

required
normals array - like

Normal vectors of shape (N, 3) (will be unit normalized internally).

required
areas_m2 array - like

Area elements of shape (N,) in square meters. Must be positive and finite.

required
normal_displacement_m float, complex, or array-like

Normal displacement in meters. Can be a scalar or a vector of shape (N,).

required
density_kg_m3 float or complex

Mass density of the medium in kg/m^3 (must be a scalar).

required

as_weighted_source

as_weighted_source() -> WeightedPointSource

Convert to the canonical WeightedPointSource format.

weights = density * displacement * area.

A set of triangle facets — centroids, unit normals, areas, a normal displacement and a density jump — representing the mass redistributed when an interface moves. The sign follows the normal direction, so a mesh with inconsistent winding produces a sheet whose contributions partially cancel; Volume and surface sources explains how to check that before it silently reduces your answer.

gragra.gravity_sources.PrescribedPointTrajectory dataclass

A positive point mass sampled at prescribed times and positions.

A positive point mass at prescribed, strictly increasing time samples. The stored positions are read-only float64 coordinates, ready for the trajectory observables without interpolation or equation-of-motion solving.

gragra.gravity_sources.PrescribedRigidTransform dataclass

A sampled rigid transform x_world = R(t) x_body + c(t).

A prescribed sequence of translations and proper rotation matrices for a rigid point-mass cloud. It validates each R Rᵀ = I and det(R) = 1 frame without correcting supplied rotations.

gragra.gravity_sources.read_prescribed_point_trajectory_csv

read_prescribed_point_trajectory_csv(
    filepath_or_buffer,
    *,
    mass_kg: float | None = None,
    mass_column: str | None = None,
    time_column: str = "time_s",
    position_columns: tuple[str, str, str] = (
        "x_m",
        "y_m",
        "z_m",
    ),
    delimiter: str = ",",
) -> PrescribedPointTrajectory

Read measured or prescribed point trajectory from a CSV/TSV file.

Parameters:

Name Type Description Default
filepath_or_buffer str, Path, or file-like object

Path to CSV/TSV file or open buffer.

required
mass_kg float

Fixed point mass in kg. Mutually exclusive with mass_column.

None
mass_column str

Name of column containing mass values (must be identical and positive across all rows).

None
time_column str

Name of column containing sampling timestamps in seconds.

"time_s"
position_columns tuple[str, str, str]

Column names for 3D cartesian coordinates (x, y, z) in meters.

("x_m", "y_m", "z_m")
delimiter str

Field delimiter character.

","

Returns:

Type Description
PrescribedPointTrajectory

Validated trajectory with strictly increasing non-uniform time frames.

Read a prescribed single-particle trajectory from a CSV file into a PrescribedPointTrajectory.

gragra.gravity_sources.read_prescribed_rigid_transform_csv

read_prescribed_rigid_transform_csv(
    filepath_or_buffer,
    *,
    time_column: str = "time_s",
    translation_columns: tuple[str, str, str] = (
        "tx_m",
        "ty_m",
        "tz_m",
    ),
    rotation_columns: tuple[str, ...] | None = None,
    delimiter: str = ",",
) -> PrescribedRigidTransform

Read measured or prescribed rigid motion transforms from a CSV/TSV file.

Parameters:

Name Type Description Default
filepath_or_buffer str, Path, or file-like object

Path to CSV/TSV file or open buffer.

required
time_column str

Name of column containing sampling timestamps in seconds.

"time_s"
translation_columns tuple[str, str, str]

Column names for translation vector in meters.

("tx_m", "ty_m", "tz_m")
rotation_columns tuple[str, ...]

Column names for 3x3 rotation matrix entries (9 columns: r00, r01, r02, r10, r11, r12, r20, r21, r22) or identity if None.

None
delimiter str

Field delimiter character.

","

Returns:

Type Description
PrescribedRigidTransform

Validated rigid transform series with strictly increasing time frames.

Read a prescribed rigid-body translation and rotation history from a CSV file into a PrescribedRigidTransform.

The trajectory observables evaluate only the supplied frames. They support the NumPy backend and have a direct NumPy/Numba comparison; interpolation and motion generation are outside this interface.

Causal force histories

ForceHistory describes a signed real force after a GPS onset by polynomial pieces in elapsed time. It is intended for the causal analytic analytic.seismic.point_force model; the class itself does not calculate a field. Knot values are elapsed seconds, each interval uses a normalized local coordinate, adjacent pieces must join in force and first derivative, and the final continuation is either zero or a held force.

gragra.gravity_sources.ForceHistory dataclass

Piecewise local-polynomial force history with causal zero before onset.

Coefficients are in ascending powers of each interval's normalized local coordinate. Every interval has the same coefficient width; lower-degree polynomials are represented by trailing zeros. Public Quantity properties return copies, so caller mutation cannot change this snapshot.

smooth_pulse builds a C1 force pulse that returns to zero at the final knot.

gragra.gravity_sources.smooth_pulse

smooth_pulse(
    *,
    amplitude: Quantity,
    duration: Quantity,
    onset: object,
) -> ForceHistory

Create a zero-ended pulse amplitude * 16 s² (1-s)².

smooth_ramp_to_hold builds a C1 ramp whose final force continues unchanged.

gragra.gravity_sources.smooth_ramp_to_hold

smooth_ramp_to_hold(
    *,
    amplitude: Quantity,
    duration: Quantity,
    onset: object,
) -> ForceHistory

Create the C1 ramp amplitude * (3 s² - 2 s³) followed by a hold.

Prescribed motion verification

Status & verification

Status Experimental
Verified against closed-form analytic solution; invariance property; backend equivalence
Agreement A point flyby matches its closed form, and rigid rotations preserve the documented covariance.
Test evidence tests/test_trajectory.py::test_trajectory_point_flyby_closed_form_and_readonly, tests/test_trajectory.py::test_rigid_rotation_covariance_for_all_observables, tests/test_trajectory.py::test_trajectory_superposition_and_chunk_size_invariance
Conditions Prescribed finite time samples, positive point masses, and proper rotation matrices
Not verified Interpolation or generated trajectories
Known limits The tested non-NumPy backend is Numba; cpp and cupy are not verified for this API
Scope Potential, acceleration, and gravity-gradient samples for point trajectories and rigid point-mass clouds

Targets

There is a single high-level target container, TargetPoints, and it is re-exported lazily at the top level, so its reference entry lives on the Top-level API page. It stores length quantities, unique IDs and a coordinate frame. Low-level numerical observables still accept bare coordinate arrays without this context.

The target object requires an explicit (M, 3) Quantity and one unique ID per row. Low-level functions such as point_acceleration continue to promote a bare (3,) array to one row and return shape (1, 3).

Geometry and numerical primitives

Frame defines a static Cartesian coordinate system. The public Sphere, Cuboid, Cylinder, and SphericalShell are pure, Quantity-backed shapes: their centers are expressed in their Frame, and they carry no density or discretization settings. Existing numerical Cuboid and Cylinder classes remain at gragra.geometry.primitives for volume-grid workflows. The shared short names identify different classes in those two namespaces; no compatibility wrapper is provided.

HalfSpace defines the flat surface geometry used by high-level Rayleigh, P/SV, and rigid-reflection acoustic models. Its frame's local z=0 plane is the interface. The seismic medium lies at local z<0; the acoustic model uses local z>0 for air and z<0 for ground. Density and wave properties remain model inputs.

gragra.geometry.HalfSpace dataclass

The local z=0 free surface; the elastic medium occupies local z<0.

Frame stores a Cartesian origin and orientation, letting geometry and targets use named local coordinates within one connected coordinate system.

gragra.geometry.Frame dataclass

Static right-handed Cartesian frame, relative to its explicit parent.

origin is a length Quantity in the parent's coordinates. Columns of basis are this frame's unit axes expressed in the parent. A frame with no parent is a distinct root and has identity origin/basis. Equal names do not connect independent roots.

trace_point_m

trace_point_m(
    point_m: object, destination: Frame
) -> PointTrace

Convert one SI point through the shortest common-ancestor path.

transform_points_m

transform_points_m(
    points_m: object, destination: Frame
) -> np.ndarray

Convert one or N SI points to destination without using root detours.

rotation_to

rotation_to(destination: Frame) -> np.ndarray

Return the component rotation from this basis to destination.

gragra.geometry.Sphere dataclass

Static sphere with an owned center and positive radius in a Frame.

A solid sphere given by centre, radius and frame. It contains no density or grid settings; pass it to uniform_sphere or discretize to choose those independently. The midpoint point-sum model is the standard convergence test.

gragra.geometry.Cuboid dataclass

Cuboid centered in a Frame, with edges parallel to its local axes.

A pure box given by centre, three positive edge lengths, and Frame. Its edges follow the Frame's local x, y, and z axes; orient the Frame to place the box. This high-level shape does not carry a discretization grid.

gragra.geometry.Cylinder dataclass

Cylinder centered in a Frame and aligned with its local z axis.

A pure solid cylinder given by centre, positive radius and height, and Frame. Its axis follows the Frame's local z direction. The older numerical cylinder retains its axis-label interface under gragra.geometry.primitives.

gragra.geometry.SphericalShell dataclass

Spherical shell centered in a Frame, with ordered positive radii.

A pure spherical shell given by centre, positive inner radius, greater outer radius, and Frame. It describes geometry only; pass it with density and phasor inputs to spherical_shell for the finite-shell wave evaluation.

gragra.geometry.Appearance dataclass

Optional color, opacity, and display label metadata.

Values are retained for a drawing backend to interpret. They do not participate in shape dimensions, placement, or physics.

Optional color, opacity, and display label metadata for a high-level shape. It does not affect geometry checks or physics. For each field, an explicit drawing-call value wins, followed by shape metadata and the plotter default.

gragra.geometry.HalfSphere dataclass

Hemispherical dome geometry primitive with uniform density.

Floor at z = 0 relative to center, dome occupying z >= center_z.

Parameters:

Name Type Description Default
center_m array - like

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

required
radius_m float

Radius of the hemisphere in meters.

required
density_kg_m3 float or complex

Mass density in kg/m^3. Real densities yield float64 weights; complex densities yield complex128 weights.

required
spacing_m float

Grid spacing (maximum cell width) in meters.

required
max_points int or None

Maximum allowed grid cells in the bounding box (default: 1,000,000).

1000000

analytic_area_m2 property

analytic_area_m2: float

Exact surface area of the half-sphere in square meters.

analytic_volume_m3 property

analytic_volume_m3: float

Exact enclosed volume of the half-sphere in cubic meters.

to_weighted_points

to_weighted_points() -> WeightedPointSource

Discretize the half-sphere into a WeightedPointSource of mass elements.

Uses cell-center inclusion, representing a mass approximation (does not account for partial cell volumes at boundaries). This geometry discretization is G-free (does not import or multiply by G_SI). Weights are mass elements (δm = δρ * dV) in kg only (not P4 coherent transfer weights). Complex density produces complex weights representing linear complex amplitude.

Returns:

Type Description
WeightedPointSource

The discretized representation with coordinates in float64 and weights in float64 or complex128.

contains

contains(
    points_m: list | tuple | ndarray, *, tol_m: float = 0.0
) -> np.ndarray

Check if target points lie inside or on the boundary of the half-sphere.

.. note:: This method assumes a convex basic shape.

Parameters:

Name Type Description Default
points_m list | tuple | ndarray

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

required
tol_m float

Boundary expansion tolerance in meters. Must be non-negative and finite.

0.0

Returns:

Type Description
ndarray

Boolean array of shape (N,) indicating whether each point is inside.

surface_mesh

surface_mesh(
    resolution: MeshResolution | None = None,
) -> PrimitiveSurfaceMesh

Generate a PrimitiveSurfaceMesh representation of the half-sphere surface.

.. warning:: This method is experimental/provisional. API stability is not guaranteed. Triangle ordering is not guaranteed.

A hemispherical dome: the half of a sphere on one side of the plane through its centre. It exists because cavern end-caps are modelled this way, and it shares the sphere's spacing and mass-guard behaviour.

gragra.geometry.HalfCylinder dataclass

Kamaboko half-cylinder geometry primitive with uniform density.

Oriented with axis along x-axis and flat floor at z = 0 relative to center.

Parameters:

Name Type Description Default
center_m array - like

Shape (3,) coordinates of the half-cylinder center in meters (float64).

required
radius_m float

Radius of the semi-cylindrical arch in meters.

required
length_m float

Length of the half-cylinder along x-axis in meters.

required
density_kg_m3 float or complex

Mass density in kg/m^3. Real densities yield float64 weights; complex densities yield complex128 weights.

required
spacing_m float

Grid spacing (maximum cell width) in meters.

required
max_points int or None

Maximum allowed grid cells in the bounding box (default: 1,000,000).

1000000

analytic_area_m2 property

analytic_area_m2: float

Exact surface area of the half-cylinder in square meters.

analytic_volume_m3 property

analytic_volume_m3: float

Exact enclosed volume of the half-cylinder in cubic meters.

to_weighted_points

to_weighted_points() -> WeightedPointSource

Discretize the half-cylinder into a WeightedPointSource of mass elements.

Uses cell-center inclusion, representing a mass approximation (does not account for partial cell volumes at boundaries). This geometry discretization is G-free (does not import or multiply by G_SI). Weights are mass elements (δm = δρ * dV) in kg only (not P4 coherent transfer weights). Complex density produces complex weights representing linear complex amplitude.

Returns:

Type Description
WeightedPointSource

The discretized representation with coordinates in float64 and weights in float64 or complex128.

contains

contains(
    points_m: list | tuple | ndarray, *, tol_m: float = 0.0
) -> np.ndarray

Check if target points lie inside or on the boundary of the half-cylinder.

.. note:: This method assumes a convex basic shape.

Parameters:

Name Type Description Default
points_m list | tuple | ndarray

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

required
tol_m float

Boundary expansion tolerance in meters. Must be non-negative and finite.

0.0

Returns:

Type Description
ndarray

Boolean array of shape (N,) indicating whether each point is inside.

surface_mesh

surface_mesh(
    resolution: MeshResolution | None = None,
) -> PrimitiveSurfaceMesh

Generate a PrimitiveSurfaceMesh representation of the half-cylinder.

.. warning:: This method is experimental/provisional. API stability is not guaranteed. Triangle ordering is not guaranteed.

A half-cylinder with a flat floor — the "kamaboko" cross-section used for tunnel and cavern models. It is the primitive most often combined with HalfSphere end-caps to approximate an underground detector hall.

High-level analytic factories

These factories bind pure geometry and physical inputs to the shared EvaluationResult contract. Static cuboid and cylinder models use their analytic G-free native functions and apply G_SI once. The cylinder factory does not fall back to the numerical quadrature diagnostic. Seismic factories require explicit phasor reference time; a FrequencySeries epoch is retained as provenance and does not rephase the displacement. The approved Gen1 additions live in their analytic.objects, analytic.seismic, and analytic.atmospheric namespaces; they are not re-exported at the package root. Their assumptions and runnable examples are collected in the Gen1 analytic models guide.

gragra.analytic.objects.uniform_cuboid

uniform_cuboid(
    geometry: Cuboid, density: Quantity
) -> UniformCuboidModel

Create an analytic static model of a finite-density uniform cuboid.

Use this factory for a uniformly dense cuboid evaluated through its analytic G-free field calculation.

gragra.analytic.objects.uniform_cylinder

uniform_cylinder(
    geometry: Cylinder, density: Quantity
) -> UniformCylinderModel

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

Use this factory for a uniformly dense cylinder; evaluation stays on the analytic native path and does not invoke the quadrature diagnostic.

gragra.analytic.objects.constant_velocity

constant_velocity(
    point_mass: PointMass,
    velocity: Quantity,
    *,
    frame: Frame,
    motion_epoch: object,
    sampling: TimeSampling,
) -> _MotionModel

Create an exact constant-velocity point-mass model.

Moves one positive point mass at constant velocity, sampled on an explicit TimeSampling axis. The source position is defined at motion_epoch.

gragra.analytic.objects.translational_oscillation

translational_oscillation(
    point_mass_or_cloud: PointMass | PointMassCloud,
    displacement: Quantity,
    *,
    frame: Frame,
    frequency: Quantity,
    reference_time: object,
) -> _MotionModel

Create a first-order uniform-translation phasor model.

Evaluates a first-order uniform-translation peak phasor for a point mass or cloud, with one positive frequency and explicit reference_time.

gragra.analytic.objects.fixed_axis_rotation

fixed_axis_rotation(
    cloud: PointMassCloud,
    axis: object,
    angular_velocity: Quantity,
    *,
    frame: Frame,
    origin: Quantity,
    angle0: Quantity,
    angle_epoch: object,
    sampling: TimeSampling,
) -> _MotionModel

Create an exact fixed-axis, constant-angular-velocity cloud model.

Rotates a positive point-mass cloud exactly at constant angular velocity about a fixed axis and origin. The input cloud is the zero-angle geometry.

gragra.analytic.seismic.small_cavity_wall

small_cavity_wall(
    geometry: Sphere | Cuboid | Cylinder,
    displacement: Quantity,
    *,
    density: Quantity,
    frequency: Quantity | None = None,
    reference_time: object | None = None,
) -> SCAWallModel

Create a static or single-frequency SCA wall field-change model.

Displacement is a three-vector in geometry.frame. Without frequency it is a real static displacement. Supplying frequency and reference_time interprets its real or complex vector as a peak phasor.

Evaluates only the selected first-order SCA cavern-wall contribution for a Sphere, Cuboid, or Cylinder and one displacement input.

gragra.analytic.seismic.point_force

point_force(
    position: Quantity,
    direction: object,
    history: ForceHistory,
    *,
    frame: Frame,
    vp: Quantity,
    sampling: TimeSampling,
) -> PointForceModel

Create a causal point-force model in a homogeneous elastic medium.

Evaluates a causal point force in an infinite homogeneous elastic medium from a piecewise C1 force history and a positive P-wave speed.

gragra.analytic.atmospheric.acoustic_halfspace

acoustic_halfspace(
    halfspace: HalfSpace,
    surface_pressure: Quantity,
    *,
    sound_speed: Quantity,
    frequency: Quantity,
    incidence_angle: Quantity,
    azimuth: Quantity,
    phase_origin: Quantity,
    reference_time: object,
) -> AcousticHalfspaceModel

Create a single-frequency total-surface-pressure acoustic model.

Evaluates the rigid-reflection acoustic halfspace for a total surface-pressure phasor, oblique incidence, and targets away from the interface.

gragra.analytic.atmospheric.isobaric_temperature

isobaric_temperature(
    profile: _Profile,
    delta_temperature: Quantity,
    *,
    rho0: Quantity,
    T0: Quantity,
    frequency: Quantity | None = None,
    reference_time: object | None = None,
) -> TemperatureModel

Create a static or single-frequency isobaric temperature model.

profile is a TemperatureFourierMode, TemperatureGaussian, Sphere, Cuboid, or Cylinder. TemperaturePerturbationGrid is intentionally evaluated via the existing point_sum route and is not an analytic profile.

Evaluates a prescribed isobaric temperature perturbation for a plane wave, all-space Gaussian, or bounded uniform Sphere, Cuboid, or Cylinder anomaly.

gragra.analytic.atmospheric.acoustic_cavity_mode

acoustic_cavity_mode(
    geometry: _CavityGeometry,
    mode: _CavityMode,
    pressure_amplitude: Quantity,
    *,
    sound_speed: Quantity,
    reference_time: object,
    numerics: AcousticCavityNumerics = AcousticCavityNumerics(),
) -> (
    SphereAcousticCavityModel
    | CuboidAcousticCavityModel
    | CylinderAcousticCavityModel
)

Build a cavity gravity model by dispatching on its geometry.

Sphere geometry uses the in-module evaluator. Cuboid and Cylinder geometry use their lazily imported shape-specific builders. Each geometry requires its matching acoustic mode descriptor.

Builds a single-frequency rigid-cavity pressure-mode gravity response for a Sphere, Cuboid, or Cylinder and the matching geometry-specific mode type.

gragra.analytic.atmospheric.SphereAcousticMode dataclass

Real spherical Neumann mode indices (l, m, n).

Real spherical Neumann mode indices (l, m, n); n selects a strictly positive radial derivative root.

gragra.analytic.atmospheric.CuboidAcousticMode dataclass

Nonnegative cuboid Neumann indices, excluding the constant mode.

Nonnegative cosine-mode indices (nx, ny, nz) for a cuboid Neumann mode; the all-zero constant mode is excluded.

gragra.analytic.atmospheric.CylinderAcousticMode dataclass

Real cylindrical Neumann mode indices and azimuthal convention.

Real cylindrical Neumann mode indices, including a cosine or sine azimuthal choice when the order is nonzero.

gragra.analytic.atmospheric.AcousticCavityNumerics dataclass

Owned resource limits for cavity kernels that require integration.

Positive resource ceilings for evaluation count and refinement count. They do not set a physical error tolerance or replace the fixed convergence policy.

gragra.analytic.seismic.spherical_cavity

spherical_cavity(
    geometry: Sphere,
    density: Quantity,
    phase_speed: Quantity | FrequencySeries,
    displacement: FrequencySeries,
    representation: PhasorRepresentation,
    reference_time: object,
    wave_type: str,
    propagation_direction: object,
    polarization: object,
    phase_origin: Quantity,
    part: str = "total",
) -> SphericalCavityModel

Create a spherical-cavity phasor model with an explicit phase reference.

displacement is a GWexpy FrequencySeries interpreted as a complex peak phasor under representation. reference_time is mandatory and supplies its GPS phase reference; a series epoch is retained only as provenance and does not trigger rephasing. A frequency-series phase_speed must have the exact displacement frequency axis.

phase_origin is a position in geometry.frame. The components of propagation_direction and polarization are also expressed in that frame. part selects "bulk", "wall", or the native "total".

Use this factory for the selected P or S displacement contribution of a spherical cavity, with the documented potential reference attached per part.

gragra.analytic.seismic.spherical_shell

spherical_shell(
    geometry: SphericalShell,
    density: Quantity,
    phase_speed: Quantity | FrequencySeries,
    displacement: FrequencySeries,
    representation: PhasorRepresentation,
    reference_time: object,
    phase_origin: Quantity,
    propagation_direction: object,
    polarization: object,
    wave_type: str,
    contribution: str = "total",
) -> _SphericalShellModel

Create an explicitly referenced P/S displacement perturbation model.

Use this factory for P or S displacement contributions from the inner and outer boundaries of a spherical shell.

gragra.analytic.seismic.halfspace_psv

halfspace_psv(
    geometry: HalfSpace,
    density: Quantity,
    vp: Quantity,
    vs: Quantity,
    displacement: FrequencySeries,
    representation: PhasorRepresentation,
    reference_time: object,
    wave_type: Literal["P", "SV"],
    incidence_angle_rad: float,
    azimuth_rad: float,
    phase_origin: Quantity,
) -> _HalfspacePSVModel

Create a P/SV half-space phasor model with explicit phase reference.

displacement is an incident displacement FrequencySeries in meters (or any length unit). reference_time is required and defines temporal phasor interpretation; displacement.epoch is retained as provenance and never triggers an implicit rephase. phase_origin is a position in geometry.frame. Incidence and polarization use that same local basis, with azimuth measured from local +x toward local +y.

Use this factory for supported P/SV plane-wave displacement families in a half-space, including only the documented limited zero-horizontal-wavenumber cases.

Surface meshes

The surface of a primitive is a separate object from its volume filling, because the two are used for different terms: the volume gives the bulk density perturbation, the surface gives the interface term. These two types describe the surface side.

gragra.geometry.MeshResolution dataclass

Resolution parameters for surface mesh generation.

.. warning:: This class is experimental/provisional. API stability is not guaranteed.

Parameters:

Name Type Description Default
n_u int

Number of divisions in the azimuthal / primary direction.

50
n_v int

Number of divisions in the meridional / secondary direction.

50
n_cap int

Number of radial divisions for disc / end-cap meshes.

25

How finely surface_mesh() subdivides a primitive, as counts along the two surface parameters plus a cap count. It is a small explicit container rather than three loose integers so that the same resolution can be handed to several primitives and be recognisably the same choice.

gragra.geometry.PrimitiveSurfaceMesh dataclass

Container for discretized primitive cavity surface mesh cells.

.. warning:: This class is experimental/provisional. API stability is not guaranteed. Triangle ordering is not guaranteed by the API (only centroids, normals, areas shape, units, outward normals direction, and read-only flags are stable).

Attributes:

Name Type Description
vertices_m FloatArray

Shape (V, 3) coordinates of the mesh vertices in meters (read-only).

triangles ndarray

Shape (T, 3) vertex indices for triangular cells (int64, read-only).

centroids_m FloatArray

Shape (T, 3) cell centroids in meters (read-only).

normals FloatArray

Shape (T, 3) unit-length outward-facing normal vectors (read-only).

areas_m2 FloatArray

Shape (T,) cell surface areas in square meters (read-only).

concatenate classmethod

concatenate(
    *meshes: PrimitiveSurfaceMesh,
) -> PrimitiveSurfaceMesh

Concatenate multiple PrimitiveSurfaceMesh objects into a single mesh.

The result: vertices, triangles, and the per-facet centroids, unit normals and areas that a surface source needs. concatenate() joins the meshes of several primitives into one, which is how a compound cavern — a hall with domed ends — is assembled while keeping every facet's winding as generated.

Integrators

The integrator layer normalises inputs, picks the kernel that matches the requested observable, and applies the chunking strategy. It is public because it is the right place to stand if you are adding an observable, and because it is G-free: everything it returns still needs the gravitational constant applied.

gragra.integrators.direct_point_sum

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

Execute G-free integration by dispatching to the appropriate kernel contract.

This function is internal to the package.

Parameters:

Name Type Description Default
source WeightedPointSource, PointMass, or PointMassCloud

The source of gravitational perturbation.

required
targets TargetPoints or array - like

The target observation points.

required
observable str

The observable type: 'potential', 'acceleration', or 'gradient'.

required
softening_m float

Plummer softening parameter. Defaults to 0.0.

0.0
chunk_size int

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

None
backend str

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

'numpy'

Returns:

Type Description
FloatArray or ComplexArray

Calculated G-free observable result.

The direct O(N·M) sum over source elements for a scalar-weighted source, dispatching by observable name to the potential, acceleration or gradient kernel. It never materialises the full (M, N, ...) array — the sum is accumulated in chunks along the source axis — which is what makes a million-element source a memory question rather than an impossibility.

gragra.integrators.direct_point_dipole_sum

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

Execute G-free vector-weight (dipole/total) integration.

This compatibility entry point preserves the argument order, backend dispatch, and exception behavior that predate :func:direct_point_displacement_sum. It takes raw mass_kg and displacement_m arrays because the displacement vector is not a WeightedPointSource.weights_kg-compatible quantity.

Parameters:

Name Type Description Default
mass_kg array - like

Finite, real, non-negative background mass elements, shape (N,).

required
displacement_m array - like

Real or complex displacement vectors, shape (N, 3).

required
sources_xyz array - like

Source coordinates, shape (N, 3).

required
targets TargetPoints or array - like

Target coordinates.

required
softening_m float

Plummer softening length in meters.

0.0
chunk_size int

Source-axis chunk size.

None
backend str

'numpy', 'numba', 'cpp', or 'cupy'.

'numpy'

Returns:

Type Description
FloatArray or ComplexArray

G-free acceleration response with shape (M, 3).

The same direct sum for a vector-weighted source: mass elements plus a displacement each, contracted against the gravity-gradient kernel. This is the machinery under displacement_transfer_acceleration, and it is separate from the scalar path because the weight is a vector, not because the physics differs.

Kernels

A kernel returns the geometric factor K only, summed against the weights as Σⱼ wⱼ·K. Kernels do not import the gravitational constant and do not multiply by it; that boundary exists so that an alternative force law — Yukawa, modified gravity — can be introduced by substituting a kernel rather than by auditing every observable for a stray factor.

All seven take source positions, weights, target positions, a softening length and a chunk size. The four non-parametric forms take an (N,) weight column; the three _parametric forms take (N, ...) and carry the extra axes through to the result.

gragra.kernels.potential_contract

potential_contract(
    sources_xyz: list | tuple | ndarray,
    weights: list | tuple | ndarray,
    targets_xyz: list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
) -> FloatArray | ComplexArray

Calculate the G-free gravitational potential contraction.

K_Φ = -1 / sqrt(r^2 + ε^2)

Parameters:

Name Type Description Default
sources_xyz array - like

Source coordinates table of shape (N, 3) in meters.

required
weights array - like

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

required
targets_xyz array - like

Target coordinates table of shape (M, 3) in meters.

required
softening_m float

Plummer softening parameter in meters. Defaults to 0.0.

0.0
chunk_size int

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

None

Returns:

Type Description
FloatArray or ComplexArray

Calculated potential of shape (M,).

The potential kernel, K_Φ = −1/r_eff, contracted against scalar weights. The minus sign is part of the kernel and not applied later, which is why a positive mass gives a negative potential all the way through the stack.

gragra.kernels.acceleration_contract

acceleration_contract(
    sources_xyz: list | tuple | ndarray,
    weights: list | tuple | ndarray,
    targets_xyz: list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
) -> FloatArray | ComplexArray

Calculate the G-free gravitational acceleration contraction.

K_a = Δ / (r^2 + ε^2)^(3/2) where Δ = r'_j(source) - r_i(target)

Parameters:

Name Type Description Default
sources_xyz array - like

Source coordinates table of shape (N, 3) in meters.

required
weights array - like

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

required
targets_xyz array - like

Target coordinates table of shape (M, 3) in meters.

required
softening_m float

Plummer softening parameter in meters. Defaults to 0.0.

0.0
chunk_size int

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

None

Returns:

Type Description
FloatArray or ComplexArray

Calculated acceleration of shape (M, 3).

The acceleration kernel, K_a = Δ/r_eff³ with Δ = r_source − r_target, contracted against scalar weights. The direction convention is fixed by that subtraction order, and it is the single most useful thing to check first when a result comes out with the wrong sign.

gragra.kernels.gradient_contract

gradient_contract(
    sources_xyz: list | tuple | ndarray,
    weights: list | tuple | ndarray,
    targets_xyz: list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
) -> FloatArray | ComplexArray

Calculate the G-free gravity gradient tensor contraction.

K_T = 3 * ΔΔ / (r^2 + ε^2)^(5/2) - I / (r^2 + ε^2)^(3/2) where Δ = r'_j(source) - r_i(target) and I is the 3x3 identity matrix.

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

Parameters:

Name Type Description Default
sources_xyz array - like

Source coordinates table of shape (N, 3) in meters.

required
weights array - like

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

required
targets_xyz array - like

Target coordinates table of shape (M, 3) in meters.

required
softening_m float

Plummer softening parameter in meters. Defaults to 0.0.

0.0
chunk_size int

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

None

Returns:

Type Description
FloatArray or ComplexArray

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

The gravity-gradient kernel, K_T = 3ΔΔ/r_eff⁵ − I/r_eff³, differentiated with respect to the target coordinate. Its trace is identically zero only in the unsoftened case; with softening_m > 0 the kernel describes a smeared mass and its trace is a real, non-zero number rather than round-off.

gragra.kernels.dipole_contract

dipole_contract(
    sources_xyz: list | tuple | ndarray,
    mass_kg: list | tuple | ndarray,
    displacement_m: list | tuple | ndarray,
    targets_xyz: list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
) -> FloatArray | ComplexArray

Calculate the G-free displacement-transfer (dipole/total) contraction.

δa_i = -Σ_n mass_n * Σ_j K_T_ij(r_n) * displacement_n[j]

K_T is the same gravity gradient kernel as gradient_contract (K_T = 3ΔΔ/r_eff^5 - I/r_eff^3, Δ = source - target; see kernel_contract.md §3). Moving a mass element by a small displacement d produces a linear acceleration response at the target equal to -T·d: the sign follows from the source-derivative of the acceleration being the negation of the target-derivative K_T (kernel_contract.md §2.1/§2.2). This is verified independently by a finite-difference oracle in tests (source-shifted, not target-shifted): a source-shifted central difference of acceleration_contract converges directly to this function's output with no extra sign flip; a target-shifted difference would converge to the negation.

Equivalence to the bulk+surface divergence path (fields/ + gradient_contract/acceleration_contract on delta-rho mass elements) holds ONLY under the six conditions of kernel_contract.md §2.2 (closed volume, consistent triangle winding, outward-pointing surface normal, fields/surface.py delta_rho sign convention, geometric coincidence of the volume/surface boundary, vacuum truncation outside the boundary) — a sub-volume embedded in surrounding rock is NOT equivalent.

Parameters:

Name Type Description Default
sources_xyz array - like

Source (undisturbed / equilibrium) coordinates table of shape (N, 3) in meters.

required
mass_kg array - like

Background mass element at each source point, shape (N,) in kilograms. Real, finite, non-negative only (kernel_contract.md §2.1.1) — unlike the scalar weights of acceleration_contract / gradient_contract, signed or complex mass is rejected; complex harmonic amplitude belongs in displacement_m instead.

required
displacement_m array - like

Displacement vector at each source point, shape (N, 3) in meters (real or complex for harmonic amplitude). This is the "vector weight" of kernel_contract.md §2.1.

required
targets_xyz array - like

Target coordinates table of shape (M, 3) in meters.

required
softening_m float

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

0.0
chunk_size int

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

None

Returns:

Type Description
FloatArray or ComplexArray

Calculated displacement-transfer acceleration of shape (M, 3). dtype is complex128 if displacement_m is complex, else float64 (mass_kg is always real per §2.1.1, so only displacement_m drives the complex promotion).

The vector-weight contraction δaᵢ = −Σₙ mₙ K_T,ᵢⱼ dₙʲ, which turns a displacement field into an acceleration perturbation in one step. It uses the same K_T as gradient_contract; what differs is that the tensor is contracted against a per-element displacement instead of being returned.

gragra.kernels.potential_contract_parametric

potential_contract_parametric(
    sources_xyz: list | tuple | ndarray,
    weights: list | tuple | ndarray,
    targets_xyz: list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
) -> np.ndarray

Calculate the G-free potential contraction with parametric weights.

K_Φ = -1 / sqrt(r^2 + ε^2)

Parameters:

Name Type Description Default
sources_xyz array - like

Source coordinates table of shape (N, 3) in meters.

required
weights array - like

Weights vector of shape (N, *P) in kilograms (real or complex).

required
targets_xyz array - like

Target coordinates table of shape (M, 3) in meters.

required
softening_m float

Plummer softening parameter in meters. Defaults to 0.0.

0.0
chunk_size int

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

None

Returns:

Type Description
ndarray

Calculated potential of shape (M, *P).

The potential contraction with parametric weights, for weights that carry extra axes — direction, wavenumber, snapshot — beyond the source index. The parameter axes are broadcast through the sum and appear in the result before the (absent, for a scalar) component axis.

gragra.kernels.acceleration_contract_parametric

acceleration_contract_parametric(
    sources_xyz: list | tuple | ndarray,
    weights: list | tuple | ndarray,
    targets_xyz: list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
) -> np.ndarray

Calculate G-free acceleration contraction with parametric weights.

K_a = Δ / (r^2 + ε^2)^(3/2) where Δ = r'_j(source) - r_i(target)

Parameters:

Name Type Description Default
sources_xyz array - like

Source coordinates table of shape (N, 3) in meters.

required
weights array - like

Weights vector of shape (N, *P) in kilograms (real or complex).

required
targets_xyz array - like

Target coordinates table of shape (M, 3) in meters.

required
softening_m float

Plummer softening parameter in meters. Defaults to 0.0.

0.0
chunk_size int

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

None

Returns:

Type Description
ndarray

Calculated acceleration of shape (M, *P, 3).

The acceleration contraction with parametric weights, returning (M, ..., 3). This is the kernel behind coherent_point_acceleration, and the reason coherent responses cost no more per parameter value than a plain sum does per source.

gragra.kernels.gradient_contract_parametric

gradient_contract_parametric(
    sources_xyz: list | tuple | ndarray,
    weights: list | tuple | ndarray,
    targets_xyz: list | tuple | ndarray,
    *,
    softening_m: float = 0.0,
    chunk_size: int | None = None,
) -> np.ndarray

Calculate G-free gravity gradient contraction with parametric weights.

K_T = 3 * ΔΔ / (r^2 + ε^2)^(5/2) - I / (r^2 + ε^2)^(3/2) where Δ = r'_j(source) - r_i(target) and I is the 3x3 identity matrix.

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

Parameters:

Name Type Description Default
sources_xyz array - like

Source coordinates table of shape (N, 3) in meters.

required
weights array - like

Weights vector of shape (N, *P) in kilograms (real or complex).

required
targets_xyz array - like

Target coordinates table of shape (M, 3) in meters.

required
softening_m float

Plummer softening parameter in meters. Defaults to 0.0.

0.0
chunk_size int

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

None

Returns:

Type Description
ndarray

Calculated gravity gradient tensor of shape (M, *P, 3, 3).

The gravity-gradient contraction with parametric weights, returning (M, ..., 3, 3). The same softening caveat as the non-parametric form applies to every slice along the parameter axes.