Skip to content

Additional APIs and internal modules

Interface status

The adapters, field I/O helpers, and optional integrations are documented here. "Experimental" describes an interface that may change as research use exposes new requirements; it does not mean untested. The SPECFEM3D section describes the supported input profile and its scientific limitations. Compute backends and Verification describe the numerical checks; External data and HDF5 and SPECFEM3D Cartesian state each adapter's actual scope in full, and take precedence over any summary here.

Adapters

Meshes (meshio/trimesh, extras mesh / mesh-quality)

gragra.adapters.TriangleSurfaceMesh dataclass

Triangle surface mesh representation.

Parameters:

Name Type Description Default
vertices_m ndarray

Array of vertex coordinates of shape (Nv, 3) in meters.

required
triangles ndarray

Array of triangle vertex indices of shape (Nt, 3).

required

check_orientation

check_orientation() -> OrientationReport

Diagnose the winding consistency and closedness of this mesh.

Delegates to the numpy-only core diagnostic :func:gragra.fields.surface_orientation.check_triangle_orientation. A consistent winding is the caller's responsibility; this method only reports the diagnosis and does not modify the mesh.

Returns:

Type Description
OrientationReport

Diagnostic flags and counts for the mesh winding/topology.

with_consistent_orientation

with_consistent_orientation() -> TriangleSurfaceMesh

Return a new mesh with consistently reoriented triangles.

This method attempts to resolve winding inconsistencies in the mesh topologically and returns a new mesh instance.

.. 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
TriangleSurfaceMesh

A new mesh instance with reoriented triangles.

A triangle surface mesh — vertices, triangle connectivity, and (once computed) per-facet centroids, normals and areas — the container from_meshio and gragra.geometry.PrimitiveSurfaceMesh share a shape with.

gragra.adapters.VolumeMesh dataclass

Volume mesh representation.

Unlike TriangleSurfaceMesh, degenerate zero-volume cell validation is performed during volume calculation in cell_centroids_volumes(), rather than at class construction time, to avoid premature rejection of empty or complex intermediate meshes.

Parameters:

Name Type Description Default
vertices_m ndarray

Array of vertex coordinates of shape (Nv, 3) in meters.

required
cell_blocks tuple[tuple[str, ndarray], ...]

Tuple of (cell_type, connectivity) pairs.

required
cell_groups tuple[ndarray, ...] | None

Tuple of integer group tags for each cell in each block.

None
group_names Mapping[str, int] | None

Mapping from group name to integer tag.

None

A volume mesh — vertices, cell connectivity, and (once computed) per-cell centroids and volumes — the volume counterpart to TriangleSurfaceMesh.

gragra.adapters.from_meshio

from_meshio(
    path: str | Path, *, length_scale_m: float = 1.0
) -> TriangleSurfaceMesh

Read a mesh via meshio and extract triangle cells.

Meshio library is lazily imported.

Reads a mesh file via meshio and extracts its triangle cells into a TriangleSurfaceMesh, requiring the mesh extra.

gragra.adapters.from_meshio_volume

from_meshio_volume(
    path: str | Path,
    *,
    length_scale_m: float = 1.0,
    cell_types: tuple[str, ...] = ("tetra", "hexahedron"),
) -> VolumeMesh

Read a volume mesh via meshio and extract cells.

Meshio library is lazily imported.

Reads a mesh file via meshio and extracts its volume cells into a VolumeMesh.

gragra.adapters.centroids_normals_areas

centroids_normals_areas(
    mesh: TriangleSurfaceMesh,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]

Calculate centroids, unit normals, and areas of triangles.

Returns tuple (centroids, unit_normals, areas_m2) of read-only arrays.

Computes per-triangle centroids, unit normals and areas for a TriangleSurfaceMesh — the geometric data a surface source needs.

gragra.adapters.cell_centroids_volumes

cell_centroids_volumes(
    mesh: VolumeMesh,
) -> tuple[np.ndarray, np.ndarray]

Calculate centroids and volumes of volume cells.

Returns tuple (centroids, volumes) of read-only arrays.

Raises:

Type Description
ValueError

If the mesh contains degenerate zero-volume cells (volume <= 1e-15). Note that this degenerate cell check is intentionally performed here rather than during VolumeMesh construction.

Computes per-cell centroids and volumes for a VolumeMesh — the geometric data a volume source needs.

gragra.adapters.select_group

select_group(mesh: VolumeMesh, name: str) -> VolumeMesh

Filter mesh cells belonging to a specific group by name.

Filters mesh cells belonging to a named group (as recorded by the source mesh format), for meshes with multiple named regions.

gragra.adapters.select_group_tag

select_group_tag(mesh: VolumeMesh, tag: int) -> VolumeMesh

Filter mesh cells belonging to a specific group by integer tag.

Unlike :func:select_group, this does not require group_names; it matches the integer cell_groups tags directly. Raises ValueError if no cell carries tag.

Filters mesh cells by an integer group tag, the numeric-tag counterpart to select_group.

gragra.adapters.to_surface_mass_sheet

to_surface_mass_sheet(
    mesh: TriangleSurfaceMesh,
    surface_density_kg_m2: float | complex,
) -> SurfaceMassSheetSource

Convert TriangleSurfaceMesh to SurfaceMassSheetSource.

Note that the surface mass density (kg/m^2) is mapped to density_kg_m3 (kg/m^3) in SurfaceMassSheetSource with normal_displacement_m = 1.0 m internally. This preserves the total physical mass (weights_kg = density * displacement * area = surface_density * area) while matching the volumetric mass density API.

Converts a TriangleSurfaceMesh into a SurfaceMassSheetSource, the step that hands mesh geometry to the source layer described on Sources, targets and geometry.

gragra.adapters.to_volume_element_source

to_volume_element_source(
    mesh: VolumeMesh,
    density_kg_m3: float | complex | ndarray,
) -> VolumeElementSource

Convert VolumeMesh to VolumeElementSource.

Converts a VolumeMesh into a VolumeElementSource, the volume-mesh counterpart to to_surface_mass_sheet.

gragra.adapters.to_unstructured_displacement_field

to_unstructured_displacement_field(
    mesh: VolumeMesh, displacement_m
) -> UnstructuredDisplacementField

Concatenate tetra blocks in input order and attach nodal displacement.

Builds an UnstructuredDisplacementField from the tetra blocks of a VolumeMesh, preserving their input order and rejecting nonempty hex blocks.

gragra.adapters.cell_density_from_group_tags

cell_density_from_group_tags(
    mesh: VolumeMesh,
    density_by_tag_kg_m3: Mapping[int, float],
) -> np.ndarray

Map every volume cell group tag to density without changing cell order.

Supports both tetra and hexahedron cell blocks in the order defined by mesh.

Maps every tetra cell-group tag to one finite, non-negative density while requiring the supplied mapping to cover exactly the tags that the mesh uses.

OpenFOAM density snapshots (mesh extra)

The supported profile is Foundation OpenFOAM 14 patch 20260724, reconstructed single-region legacy ASCII UNSTRUCTURED_GRID VTK. It accepts native cell data C, Vc, cellID, and a caller-selected density field. A file may contain both rho and delta_rho; field_name selects exactly one of them.

gragra.adapters.OpenFOAMDensitySnapshot dataclass

Immutable native-centre density snapshot in declared world coordinates.

An immutable loader-created snapshot retaining native cell centres, volumes, IDs, units, time assertion, frame origin, and frozen producer provenance.

gragra.adapters.load_openfoam_density

load_openfoam_density(
    path,
    *,
    field_name,
    time_s,
    time_name,
    coordinate_frame,
    coordinate_origin_m,
    density_unit,
    coordinate_unit,
    volume_unit,
    time_unit,
    provenance,
)

Load rho or delta_rho from the bounded legacy-ASCII profile.

Loads one bounded VTK snapshot after validating caller-supplied units and producer profile assertions. World coordinates equal case coordinates plus the declared origin; no CFD solver is run and pressure or temperature is not read.

gragra.adapters.check_mesh_quality

check_mesh_quality(
    mesh_or_path,
    *,
    expected_volume_m3: float | None = None,
    duplicate_vertex_rounding: float = 1e-08,
) -> dict[str, bool | float | int | None]

Compute geometric quality metrics for a surface mesh.

Returns a dict with both the raw metric values and an overall pass flag, so that callers can record the numbers (not just pass/fail).

Parameters:

Name Type Description Default
mesh_or_path str, os.PathLike, or meshio-like Mesh

Forwarded to :func:load_trimesh.

required
expected_volume_m3 float

Analytic reference volume in m^3 (must be positive and finite). When given, volume_rel_error is reported and folded into pass (relative error < 5%).

None
duplicate_vertex_rounding float

Rounding used to treat near-coincident vertices as duplicates, relative to the bounding-box extent floored at 1 m (i.e. sub-metre meshes use an absolute rounding metres key). Default 1e-8; must be positive and finite.

1e-08

Returns:

Name Type Description
dict

Metric values keyed as follows.

is_watertight, is_winding_consistent : bool
volume_m3 float

abs of the signed divergence-theorem volume |(1/3) oint r.n dS|.

area_m2 float
max_edge_length_m, edge_length_p99_m, min_edge_length_m : float

Edge-length statistics in metres (drive phase-sampling gates downstream).

n_faces, n_vertices, n_duplicate_vertices : int

Counted on the raw (unmerged) mesh — STL-style per-face storage reports n_vertices = 3 * n_faces. Topology keys below are evaluated after merging coincident vertices.

euler_number int
volume_rel_error float or None

|volume - expected| / expected when expected_volume_m3 is given.

pass bool

is_watertight and is_winding_consistent (and volume within 5% when an expected volume is provided). This is a screen, not a proof — see the module docstring for known blind spots (self-intersection, global normal flip).

Computes geometric quality metrics for a surface mesh (degenerate-element and aspect-ratio checks), requiring the mesh-quality extra.

gragra.adapters.load_trimesh

load_trimesh(
    mesh_or_path, *, process: bool = False
) -> trimesh.Trimesh

Load a trimesh.Trimesh from a file path or a meshio-like Mesh.

trimesh is imported lazily (optional mesh-quality extra).

Parameters:

Name Type Description Default
mesh_or_path str, os.PathLike, or meshio-like Mesh

Source geometry. A path is read directly by trimesh. A Mesh object is accepted by duck typing (.points and .cells with per-block .type/.data, as in meshio.Mesh) so meshio itself is never imported here; quad cells are split into two triangles.

required
process bool

Forwarded to trimesh. Defaults to False so that duplicate vertices and degenerate faces are not silently merged away — otherwise quality metrics such as n_duplicate_vertices would always read zero.

False

Returns:

Type Description
Trimesh

Loads a trimesh.Trimesh from a file path or a meshio-like mesh object, requiring the mesh-quality extra.

Directional quadrature (scipy, extra lebedev)

gragra.adapters.lebedev_grid

lebedev_grid(order: int) -> tuple[FloatArray, FloatArray]

Generate a Lebedev spherical-quadrature grid (directions + normalized weights).

Thin wrapper over scipy.integrate.lebedev_rule (scipy >= 1.15). Returns unit directions and normalized quadrature weights. Lebedev integration itself is outside this adapter.

Some supported orders (13/25/27) carry negative quadrature weights; the returned wnorm can contain negatives (sum is still 1).

Generates a Lebedev spherical-quadrature grid (directions and normalized weights) for the directional averages in guide/coherent.md, requiring the lebedev extra (scipy>=1.15.0, where lebedev_rule was added).

External field data (h5py, extra field-io)

External field HDF5 I/O is documented narratively in External field data and HDF5; this is the symbol-level reference.

gragra.adapters.DiscreteBackgroundDensity dataclass

Discrete background density model for unstructured fields.

Parameters:

Name Type Description Default
centroids_m FloatArray

Centroids of the mesh cells, shape (Nc, 3).

required
rho0_kg_m3 FloatArray

Background density values at the centroids, shape (Nc,).

required

A background density model (implementing the BackgroundDensityModel protocol from gragra.fields) backed by discrete, imported density samples rather than an analytic function.

gragra.adapters.DifferentiableDiscreteBackgroundDensity dataclass

Differentiable discrete background density model for unstructured fields.

Parameters:

Name Type Description Default
centroids_m FloatArray

Centroids of the mesh cells, shape (Nc, 3).

required
rho0_kg_m3 FloatArray

Background density values at the centroids, shape (Nc,).

required
grad_rho0_kg_m4 FloatArray

Spatial gradient of background density at the centroids, shape (Nc, 3).

required

The differentiable variant of DiscreteBackgroundDensity, additionally supplying ∇ρ₀ from the imported samples.

gragra.adapters.from_hdf5_field

from_hdf5_field(
    path: str, *, length_scale_m: float = 1.0
) -> UnstructuredDisplacementField | DisplacementGrid

Import a displacement field (unstructured or structured) from HDF5.

The mesh_type attribute in the HDF5 file determines the concrete return type.

Note: This only reads the displacement field geometry/data. Background density is read separately via read_hdf5_background_density().

Parameters:

Name Type Description Default
path str

Path to the HDF5 file.

required
length_scale_m float

Length scale conversion factor to convert coordinates to meters.

1.0

Returns:

Type Description
UnstructuredDisplacementField or DisplacementGrid

The imported field helper.

Imports a displacement field — unstructured or structured, dispatched on the file's recorded layout — from an HDF5 file conforming to gragra's external field schema.

gragra.adapters.from_hdf5_displacement_grid

from_hdf5_displacement_grid(
    path: str, *, length_scale_m: float = 1.0
) -> DisplacementGrid

Import a DisplacementGrid from an HDF5 file.

Parameters:

Name Type Description Default
path str

Path to the HDF5 file.

required
length_scale_m float

Length scale conversion factor to convert coordinates to meters.

1.0

Returns:

Type Description
DisplacementGrid

The imported displacement grid helper.

Imports a gragra.fields.DisplacementGrid from an HDF5 file, the structured-grid-specific form of from_hdf5_field.

gragra.adapters.from_hdf5_unstructured_field

from_hdf5_unstructured_field(
    path: str, *, length_scale_m: float = 1.0
) -> UnstructuredDisplacementField

Import an UnstructuredDisplacementField from an HDF5 file.

Parameters:

Name Type Description Default
path str

Path to the HDF5 file.

required
length_scale_m float

Length scale conversion factor to convert coordinates to meters.

1.0

Returns:

Type Description
UnstructuredDisplacementField

The imported unstructured field helper.

Imports a gragra.fields.UnstructuredDisplacementField from an HDF5 file, the unstructured-mesh-specific form of from_hdf5_field.

gragra.adapters.read_hdf5_background_density

read_hdf5_background_density(
    path: str, *, length_scale_m: float = 1.0
) -> (
    None
    | float
    | DiscreteBackgroundDensity
    | DifferentiableDiscreteBackgroundDensity
    | np.ndarray
)

Read background density data from an HDF5 file.

Parameters:

Name Type Description Default
path str

Path to the HDF5 file.

required
length_scale_m float

Length scale conversion factor (must match the scale factor used to import the field).

1.0

Returns:

Type Description
(None, float, DiscreteBackgroundDensity)
DifferentiableDiscreteBackgroundDensity, or np.ndarray

For unstructured meshes: - None: if rho0_kg_m3 is missing. - float: if rho0_kg_m3 is a scalar. - DiscreteBackgroundDensity: if rho0_kg_m3 is cell-wise. - DifferentiableDiscreteBackgroundDensity: if grad_rho0_kg_m4 is also present. For structured meshes: - None: if rho0_kg_m3 is missing. - float: if rho0_kg_m3 is a scalar. - np.ndarray: raw (Nx, Ny, Nz) array representing spatially varying density.

Reads background density data from an HDF5 file, for pairing with an imported displacement field via a BackgroundDensityModel.

gragra.adapters.iter_hdf5_field_snapshots

iter_hdf5_field_snapshots(
    path: str,
    *,
    length_scale_m: float = 1.0,
    snapshots: Sequence[int] | None = None,
) -> Iterator[
    DisplacementGrid | UnstructuredDisplacementField
]

Iterate over batched HDF5 field snapshots.

Opens the HDF5 file, reads the mesh metadata once, and yields each snapshot as a DisplacementGrid or UnstructuredDisplacementField helper.

Memory Strategy:

To avoid materializing the entire (P, ...) displacement dataset in memory, this generator reads the displacement slice-by-slice from the HDF5 dataset.

Disclaimer on Complex Outputs (Linear Harmonic Amplitudes):

If the stored displacement dataset contains complex values, the yielded field helpers will contain complex-valued displacement_m. These represent linear complex amplitudes rather than real-time fields.

Iterates over batched HDF5 field snapshots one at a time, for files using the schema's leading batch axis (see External field data and HDF5 for why on-disk batch layout differs from the in-memory API shape convention).

gragra.adapters.from_hdf5_batched_weights

from_hdf5_batched_weights(
    path: str,
    rho0_kg_m3=None,
    *,
    length_scale_m: float = 1.0,
    include_rho0_gradient_term: bool = False,
    snapshots: Sequence[int] | None = None,
) -> tuple[np.ndarray, np.ndarray]

Compute batched weights directly from a batched HDF5 file.

Parameters:

Name Type Description Default
path str

Path to the batched HDF5 file.

required
rho0_kg_m3 float, ndarray, BackgroundDensityModel, or None

Precedence: 1. If provided (non-None), this density is used and file datasets are ignored. 2. If None, falls back to the 'rho0_kg_m3' dataset inside the HDF5 file. 3. If None and no dataset exists in the file, raises ValueError.

None
length_scale_m float

Length scale conversion factor to convert coordinates to meters.

1.0
include_rho0_gradient_term bool

Whether to include background density gradient term. Only valid for unstructured meshes.

False
snapshots Sequence[int]

Sequence of snapshot indices to import. Defaults to all snapshots.

None

Returns:

Name Type Description
positions_m (N, 3) ndarray

Read-only source positions.

weights (N, P) ndarray

Read-only computed batched weights.

Computes batched mass-element weights directly from a batched HDF5 file, combining iter_hdf5_field_snapshots with the weight-computation helpers on Fields in one call.

SPECFEM3D Cartesian GLL path (extra field-io)

Scope, supported input profile, and known limitations are the subject of SPECFEM3D Cartesian — read that page before using either symbol below; this entry states only what each one does mechanically.

gragra.adapters.ExportConfig dataclass

Configuration for one SPECFEM3D Cartesian GLL export.

Only specfem_dir/output_path/output_sampling_kind have no generic default -- everything else is either mechanically derivable (nproc is auto-detected from proc*_Database files; LOCAL_PATH is auto-resolved from DATA/Par_file unless local_path overrides it) or a scientific/build-identity input this module deliberately refuses to fabricate (cadence, t0, f_resolved_estimate when no matching solver log file exists -- raising ValueError instead of guessing rather than fabricating a plausible-looking default).

Attributes:

Name Type Description
specfem_dir Path

Root of the SPECFEM3D run tree (contains DATA/Par_file, and -- via LOCAL_PATH -- the decompose_mesh output tree).

output_path Path

Destination canonical HDF5 path.

output_sampling_kind 'static' | 'time_sampled'

"static" writes a mesh-only artifact (no /field/displacement dataset); "time_sampled" additionally writes movie-volume displacement snapshots under the configured sampling cadence.

ngll_shape tuple[int, int, int]

(NGLLX, NGLLY, NGLLZ), default schema.EXPECTED_NGLL.

local_path Path | None

Override for the decompose_mesh output directory (proc*_Database etc.); when None, resolved from Par_file's LOCAL_PATH (which xdecompose_mesh treats as the write target, not a CLI argument).

par_file_relpath str

Path to Par_file relative to specfem_dir.

density_source, solver_kind, solver_version, float_precision, field_units

Recorded verbatim into provenance (density_source documents which quantity rho.bin actually holds -- see specfem_bin.read_rho's docstring; float_precision is a build-configuration fact this module has no independent way to verify from the binaries alone). The default, "proc_rho_bin_derived", is only a valid stand-in for the Newtonian-gravity background density rho0 under the documented profile's isotropic-elastic, self-consistent-material-parameters assumption -- do not reuse this default for a different material configuration without re-deriving that the equivalence still holds.

f_resolved_estimate float | None

If None, parsed from specfem_dir/output_generate_databases_relpath when that file exists; otherwise the export raises ValueError (this key is unconditionally required by the schema).

build_identity Mapping | None

If None, auto-collected via provenance.collect_build_identity (requires a real .git under specfem_dir). Callers without a git-tracked solver checkout (e.g. synthetic/test fixtures) must supply this explicitly.

exporter_code_ref str

Passed to provenance.collect_exporter_identity.

runtime_manifest_entries tuple[Mapping, ...]

Pre-captured executables[] entries (e.g. loaded from capture-run-produced runtime metadata JSON files for the mesher/ decompose/solver executables). The exporter's own identity entry is always appended automatically.

mesh_input_files tuple[str, ...]

External mesh input files (relative to specfem_dir, e.g. under MESH-default/) folded into mesh_input_hash alongside Par_file. Empty means "hash Par_file alone". This is a reduced input description and must not be confused with a full external-mesh hash.

t0, t0_source, t0_crosscheck, t0_crosscheck_max_deviation, cadence,
cadence_provenance str

time_sampled-only. t0/t0_source auto-parsed from OUTPUT_FILES/output_solver.txt when not given. cadence has no auto-fallback (scientific input -- see class docstring); only output_interval_steps (mechanically read from NTSTEP_BETWEEN_FRAMES) is filled in automatically.

material_id_source, domain_id_source, is_pml_source

Fixed documentation tags recorded into provenance (extra, non- schema-required keys) naming where each mask/label actually came from. This exporter version always reads material_id/ domain_id from the per-rank Database (generalizes the MVP single-material profile without a separate code path) and always writes is_pml as all-False (no CPML support in this exporter version -- the Database's boundary/CPML tail records are deliberately not parsed, per specfem_bin.parse_database's docstring).

chunk_element_size, gzip_level

Passed through to writer.write_gll_hdf5.

Configuration for one SPECFEM3D Cartesian GLL export: the supported profile or time-sampled exploratory mode and the output path to use.

gragra.adapters.export_specfem_gll_hdf5

export_specfem_gll_hdf5(config: ExportConfig) -> Path

Export one canonical mesh_type="gll" HDF5 file from a SPECFEM3D Cartesian decompose_mesh output tree, per config.

See the module docstring for the 6-step pipeline. Raises ValueError for any profile-input violation or structural inconsistency between the mesh/binary files (mismatched element counts, disagreeing record layouts across ranks, non-contiguous recovered element_id values, ...), or a missing required provenance input the config could not auto-resolve.

Exports one mesh_type="gll" HDF5 file from a SPECFEM3D Cartesian run's native binary output, for the single profile ExportConfig selects.

gragra.adapters.read_specfem_gll_hdf5

read_specfem_gll_hdf5(
    path: str | Path,
    *,
    profile_density_range: tuple[float, float] | None,
) -> SpecfemGLLDataset

Read an accepted canonical file into the historical eager data model.

Loads the 0.2.0 time-sampled schema-v1 profile into a closed immutable GLL dataset. PML, mixed material, and non-elastic input are rejected explicitly.

gragra.adapters.SpecfemGLLDataset dataclass

Closed immutable canonical GLL data, ordered by element then GLL.

mass_kg is reconstructed as density times quadrature volume. Unlike the context-managed streaming adapter, this historical API intentionally holds every accepted sample in memory after the HDF5 file is closed.

iter_blocks

iter_blocks(*, element_block_size: int | None = None)

Yield contiguous element-id blocks without merging shared GLL points.

Stores the immutable element-ordered GLL coordinates, source masses, displacement snapshots, time values, and source-file identity used by the acceleration observable.

GWexpy field bridge (base dependency, experimental)

gragra's component-axis convention is compatible with GWexpy's VectorField/TensorField axis convention, not shape-identical (GWexpy fields are 4D) — see the caveat on README.md. The numerical layer does not import GWexpy. GWexpy is a required runtime dependency, while the adapters import it only when conversion is called. The legacy converters, observable bridge, single-density-snapshot bridge, and fixed-mesh series bridges below are the public GWexpy surface.

to_gwexpy_observable and from_gwexpy_observable preserve a current native Field value with companion metadata for static, time-first, and frequency-target-first multi-target observables.

The fixed-mesh bridges below exchange density, displacement, and surface density series. They keep scalar weights distinct from mass-plus-vector displacement, store geometry and IDs in the immutable sidecar, and read the current native field values on reconstruction.

gragra.adapters.to_gwexpy_density_series

to_gwexpy_density_series(series)

Converts a fixed-volume density time series or phasor series to a native GWexpy scalar field with its complete immutable geometry and phase sidecar.

gragra.adapters.from_gwexpy_density_series

from_gwexpy_density_series(bundle)

Reconstructs either fixed-volume density series type after validating units, axis metadata, and the current native scalar field values.

gragra.adapters.to_gwexpy_density_time_series

to_gwexpy_density_time_series(series: DensityTimeSeries)

Convert only a real time-series density input to native GWexpy.

Converts only a real fixed-volume density time series, rejecting phasors at the typed entrypoint before native GWexpy conversion.

gragra.adapters.from_gwexpy_density_time_series

from_gwexpy_density_time_series(bundle)

Restore a real density time series after validating its native layout.

Restores only a real fixed-volume density time series and rejects a phasor bundle even when its scalar layout is otherwise valid.

gragra.adapters.to_gwexpy_density_phasors

to_gwexpy_density_phasors(series: DensityPhasors)

Convert only complex density phasors to native GWexpy.

Converts only complex fixed-volume density phasors while retaining their frequency, epoch, and spatial phase-origin metadata.

gragra.adapters.from_gwexpy_density_phasors

from_gwexpy_density_phasors(bundle)

Restore density phasors after validating their native layout.

Restores only complex fixed-volume density phasors after checking their frequency-specific phase metadata and current native scalar values.

gragra.adapters.to_gwexpy_displacement_series

to_gwexpy_displacement_series(series)

Converts a fixed-mesh displacement series to a native GWexpy vector field, with background mass remaining separately stored in the immutable sidecar.

gragra.adapters.from_gwexpy_displacement_series

from_gwexpy_displacement_series(bundle)

Restores a fixed-mesh displacement series from current native vector components while preserving component order, IDs, geometry, and axis data.

gragra.adapters.to_gwexpy_surface_density_series

to_gwexpy_surface_density_series(series)

Converts a fixed-quadrature surface-density series to a native scalar field, retaining areas, normals, and face metadata outside the scalar values.

gragra.adapters.from_gwexpy_surface_density_series

from_gwexpy_surface_density_series(bundle)

Restores a fixed-quadrature surface-density series after validating native units and its immutable surface geometry sidecar.

For frequency data, exp(-iwt) means u(t) = Re[C(f) exp(-i 2π f (t - t_ref_s))]; exp(+iwt) uses the corresponding plus sign. The bridge retains t_ref_s and phase_origin_m in companion metadata and infers neither conjugation nor an epoch conversion. phase_origin_m may be None only when no spatial phase origin applies.

gragra.adapters.GwexpyObservableBundle dataclass

A native GWexpy field plus immutable gragra sidecar metadata.

Pairs a native GWexpy Field with recursively immutable companion metadata for a gragra observable conversion.

gragra.adapters.ObservableArrayBundle dataclass

A read-only NumPy observable array plus immutable sidecar metadata.

Pairs a read-only NumPy observable array with the immutable companion metadata reconstructed from a GWexpy observable conversion.

gragra.adapters.to_gwexpy_observable

to_gwexpy_observable(
    values: ndarray,
    positions_m: ndarray,
    *,
    observable: str,
    layout: str,
    axis_values: ndarray,
    metadata: Mapping[str, object],
) -> GwexpyObservableBundle

Convert a gragra multi-target result into a native GWexpy field bundle.

Converts a static, time-first, or frequency-target-first gragra observable array and its positions, axis values, and metadata into a GWexpy Field bundle.

gragra.adapters.from_gwexpy_observable

from_gwexpy_observable(
    bundle: GwexpyObservableBundle,
) -> ObservableArrayBundle

Recover current native field values using the immutable companion.

Reads the current values from a GWexpy observable bundle and returns a read-only gragra array bundle after validating its companion metadata.

Single density snapshot bridge

This bridge accepts one real rho or delta_rho VolumeElementSource at one time. It keeps irregular positions, volumes, IDs, frame, origin, and metadata in an immutable sidecar; it is not a file reader or a time-series interface.

gragra.adapters.GwexpyDensitySnapshotBundle dataclass

A native ScalarField plus its immutable density sidecar.

The native scalar field plus sidecar for one density snapshot. A bare native field is deliberately insufficient for reconstruction because it has no irregular volume-element geometry.

gragra.adapters.DensitySnapshotArrayBundle dataclass

Restored volume source plus its immutable density sidecar.

The reconstructed volume-element source and validated sidecar. Its time_s property reads the single snapshot time from that sidecar.

gragra.adapters.to_gwexpy_density_snapshot

to_gwexpy_density_snapshot(
    source: VolumeElementSource,
    *,
    time_s: float,
    density_kind: Literal["rho", "delta_rho"],
    coordinate_frame: str,
    coordinate_origin_m: ndarray,
    source_ids: Sequence[str] | None = None,
    source_metadata: Mapping[str, object] | None = None,
) -> GwexpyDensitySnapshotBundle

Convert one current real density snapshot to a native GWexpy field.

Creates the native (1, N, 1, 1) scalar density field and frozen sidecar from one real density snapshot; conversion imports GWexpy only when called.

gragra.adapters.from_gwexpy_density_snapshot

from_gwexpy_density_snapshot(
    bundle: GwexpyDensitySnapshotBundle,
) -> DensitySnapshotArrayBundle

Restore a source from the field's current values and explicit sidecar.

Validates the field's current values, axes, units, and sidecar before reconstructing a read-only VolumeElementSource; it performs no file I/O.

Earlier bridge measurements against GWexpy 0.1.7 and 0.1.14 are historical. The current dependency range is gwexpy>=0.2.3,<0.3. Focused bridge, import, and policy checks passed locally with GWexpy 0.2.3; this does not establish scientific equivalence for every supported version or workflow.

GWexpy observable bridge verification

Status & verification

Status Experimental
Verified against invariance property
Agreement All three observables and accepted layouts round trip in the focused GWexpy 0.2.3 check.
Test evidence tests/test_gwexpy_observable.py::test_round_trip_all_observables_and_layouts, tests/test_gwexpy_observable.py::test_inverse_reads_current_native_component_values, tests/test_gwexpy_observable_missing.py::test_module_import_is_lazy_and_conversion_reports_missing_dependency
Conditions Focused local checks with GWexpy 0.2.3; adapter import remains lazy
Not verified Every version in the supported range and all scientific workflows
Known limits The bridge rejects implicit unit conversion and unsupported metadata values
Scope Static, time-first, and frequency-target-first multi-target observable bundles

gragra.adapters.to_gwexpy_scalar_field

to_gwexpy_scalar_field(
    data: ndarray,
    *,
    positions_m: ndarray | None = None,
    grid_shape: tuple[int, int, int] | None = None,
    unit=None,
    t_s: float = 0.0,
) -> gwexpy.fields.ScalarField

Convert gragra scalar data to a gwexpy ScalarField.

positions_m is currently validated only. It is not encoded into gwexpy axis metadata in flat point mode.

Converts gragra scalar output (e.g. point_potential) into a GWexpy ScalarField.

gragra.adapters.to_gwexpy_vector_field

to_gwexpy_vector_field(
    data: ndarray,
    *,
    positions_m: ndarray | None = None,
    grid_shape: tuple[int, int, int] | None = None,
    unit=None,
    t_s: float = 0.0,
) -> gwexpy.fields.VectorField

Convert gragra vector data to a gwexpy VectorField.

positions_m is currently validated only. It is not encoded into gwexpy axis metadata in flat point mode.

Converts gragra vector output (e.g. point_acceleration) into a GWexpy VectorField.

gragra.adapters.to_gwexpy_tensor_field

to_gwexpy_tensor_field(
    data: ndarray,
    *,
    positions_m: ndarray | None = None,
    grid_shape: tuple[int, int, int] | None = None,
    unit=None,
    t_s: float = 0.0,
) -> gwexpy.fields.TensorField

Convert gragra tensor data to a gwexpy TensorField.

positions_m is currently validated only. It is not encoded into gwexpy axis metadata in flat point mode.

Converts gragra tensor output (e.g. point_gravity_gradient) into a GWexpy TensorField.

Internal modules that are not part of the public contract

Anything under gragra.* not reachable from a package's __all__ — private helpers prefixed _, internal-only test fixtures, and backend-dispatch plumbing such as gragra.kernels._numba_* / gragra.kernels._cpp_* / gragra.kernels._cupy_* — is not part of the public API and can change or disappear without a deprecation notice. If you find yourself importing one of these directly, the public entry point you actually want is almost always one layer up: Top-level API, Sources, targets and geometry, or the Adapters section above.