Skip to content

Results and spectral representations

GravityResult is an Experimental envelope for grouping existing observable payloads under the gragra.results namespace. It does not alter the return types of numerical APIs, and it is not re-exported from the gragra root package.

EvaluationResult groups native payloads, their shared EvaluationContext, an evaluation object, and an execution record. The context owns the normalized targets, resolved frame, requested observables, field definition, interaction, and exactly one of a static axis, phasor axes, or a time-sampling axis. It remains available only from gragra.results.

EvaluationContext provides model-independent interpretation shared by all observable bindings in one result. result.context returns the same object as result.evaluation.context.

gragra.results.EvaluationContext dataclass

Owned coordinates and shared interpretation for all requested observables.

binding

binding(observable: str) -> ObservableBinding

Return the same binding for repeated requests on this context.

validate

validate() -> None

Detect replacement of the model's shared physical interpretation.

FieldEvaluation is the structural contract for the object returned by a model's .at() method. It exposes one context, model parameters, formulas, references, validation, and a run() method.

gragra.results.FieldEvaluation

Bases: Protocol

An evaluation that exposes one stable context and result.

ModelSpec supplies the field definition and interaction that identify a model's physical interpretation. The context reads both from this spec.

gragra.results.ModelSpec

Bases: Protocol

Physical interpretation supplied by a concrete model.

StaticRepresentation marks ordinary real Quantity payloads and keeps static interpretation distinct from spectral descriptors.

gragra.results.StaticRepresentation dataclass

Describe a static real field with ordinary Quantity payloads.

EvaluationRecord stores execution facts such as backend, dependency versions, and the single application of the gravitational constant.

gragra.results.EvaluationRecord dataclass

Execution facts only; physical assumptions stay in the model context.

TimeSampling is the immutable canonical axis for a uniform time series. It stores an integer GPS seconds/nanoseconds epoch, a positive dt in seconds, and a positive sample count; construction uses keyword-only arguments such as TimeSampling(epoch=..., dt=1e-6 * u.s, count=1). At large GPS epochs, floating-point display coordinates may not distinguish adjacent samples. Validation and comparison use the canonical epoch, dt, and count rather than subtracting rounded absolute time values.

gragra.results.TimeSampling dataclass

Expected epoch, positive sample interval, and sample count.

The epoch is stored as an integer GPS seconds/nanoseconds pair. Accessing epoch returns a fresh LIGOTimeGPS wrapper, so callers cannot mutate the coordinate retained by this immutable contract.

epoch property

epoch: LIGOTimeGPS

Return a new GPS wrapper for the canonical epoch.

dt property

dt: Quantity

Return the sample interval as a fresh seconds quantity.

TimeSeriesRepresentation marks real time-sampled payloads and requires one TimeSampling in the shared context. A context cannot combine time sampling with frequencies or a phasor reference time.

gragra.results.TimeSeriesRepresentation dataclass

Describe real observables sampled on one uniform GPS time axis.

NumericalDiagnostic is immutable per-target, per-observable numerical evidence in SI units. A quadrature/numerical error estimate and a rigorous integral-tail bound remain separate; runtime cavity convergence checks their sum against its fixed tolerance policy. The estimate is not a rigorous bound, and a successful diagnostic does not certify values edited after evaluation.

gragra.results.NumericalDiagnostic dataclass

One target/observable accuracy and termination record in SI units.

ConvergenceError reports a numerical evaluation failure and carries the immutable diagnostics for at least one failed target/observable. Inspect its diagnostics and the original exception cause to identify the failing term; changing a tolerance does not establish accuracy.

EvaluationResult validates high-level payloads against this shared context and exposes the model evaluation and execution record that produced them.

gragra.results.EvaluationResult dataclass

A validated view of payloads from one stable field evaluation.

Payloads are retained by identity and rechecked on result operations. The constructor reads evaluation.context once and never runs the producer.

validate

validate() -> None

Recheck the mutable payload against its fixed interpretation.

select

select(*observables: str) -> EvaluationResult

Return a narrower view sharing evaluation, record, context and payloads.

fft

fft(*, tref: object) -> EvaluationResult

Discrete Fourier transform (C3 · ONE_SIDED · unit Q·s).

spectrum

spectrum(
    kind: str | FiniteRecordInterpretation, *, tref: object
) -> EvaluationResult

Complex amplitude spectrum (C3 · periodic or transient · unit Q).

Direct construction of EvaluationResult no longer accepts one separately created binding per observable. Pass the values, a FieldEvaluation (the object returned by .at()), and one execution record; the result reads its shared context from that evaluation and derives bindings from it.

# Previous construction
EvaluationResult(
    values=values,
    bindings=bindings,
    evaluation=evaluation,
    record=record,
)

# Current construction
result = EvaluationResult(
    values,
    evaluation=evaluation,
    record=record,
)
context = result.context
binding = context.binding("potential")

For .at().run() results, result.evaluation is the FieldEvaluation returned by .at(). For GravityResponse.apply() results, it is a private adapter for the applied input and context; its run() raises RuntimeError. Call response.apply() to reuse the stored coefficients. Read shared metadata such as targets, frame, representation, frequencies, and interaction from result.context; read model parameters, formulas, and references through result.evaluation or the corresponding result properties. result.record contains execution facts.

High-level results retain the original potential, acceleration, and gradient payload objects. Access revalidates shape, observable labels, unit compatibility, finite values, and exact canonical frequency or time axes. Finite payload edits remain visible when those declared contracts still hold; result validation does not recompute fields or certify that edited values satisfy the source physics. The result's context owns target and source interpretation, while each vector or tensor binding records the component Frame chosen with output_frame.

compare aligns compatible results by target ID and SI position, then returns candidate-minus-reference differences in SI units and a summary table. Static summaries have one row per target; phasor summaries add one row per target and frequency. TimeSeries summaries have one row per target and sample and include sample_index and time_offset; their epoch_gps is table metadata. Time axes must match exactly by epoch, interval, and count. Comparison never resamples, interpolates, rotates components, or rephases. Compatibility uses the result context and observable descriptors, so independent models can be compared through the same result contract.

gragra.results.compare

compare(
    *,
    reference: EvaluationResult,
    candidate: EvaluationResult,
) -> ComparisonResult

Compare compatible results after ID and SI-position alignment.

Static Quantity payloads are promoted to float64, converted to reference units, and subtracted. Phasor Matrix cells are converted to SI before complex subtraction; their difference matrices preserve the native target, component, and frequency axes. The operation never intersects observable sets, rotates output components, interpolates positions, or rephases data.

GravityResponse owns precomputed single-input transfer coefficients and the contract that explains their input, output, and gravity law. Its apply() method accepts a phasor input with an explicit GPS reference time and returns the usual EvaluationResult payload; coefficients() returns an independent frequency matrix with field-unit-per-input-unit metadata.

gragra.results.GravityResponse dataclass

Own the coefficients and interpretation of a single-input response.

Obtain a Rayleigh response from rayleigh_response(...).at(...).run(); direct construction is an internal factory operation. Its stored transfer coefficients are separate from fields produced by applying an input. Complex outputs represent linear complex amplitudes or transfer-function-like responses, not directly real-valued time-domain gravitational fields.

coefficients

coefficients(observable: str)

Return a fresh native FrequencySeriesMatrix of coefficients.

Values and metadata are independent of the response. Rows identify targets, columns identify components, and the frequency axis is last. Potential has one component, acceleration three, and gradient nine. Units are the field SI unit divided by contract.input_unit; for a Rayleigh metre input these are m s⁻², s⁻², and m⁻¹ s⁻², respectively. These coefficients are not applied fields.

apply

apply(
    *,
    representation: object,
    reference_time: object,
    **inputs: object,
)

Apply a phasor to the stored transfer and return an EvaluationResult.

For the current Rayleigh response, provide vertical_displacement as a GWexpy FrequencySeries with a length unit. Values are converted to metres. Only PhasorRepresentation is supported, and an explicit GPS reference_time is required; the series epoch is not a fallback. Frequencies are converted to hertz and must match the stored strictly increasing axis exactly. No interpolation or reordering is performed.

Application multiplies the stored coefficients by the finite SI input amplitudes without rerunning the kernel or applying G again. The result retains the actual input and its reference time. The Rayleigh output is a first-order field change at fixed observation points, with no reference field added; linearization applicability is not_assessed.

ResponseContract records the physical input, basis amplitude, mapping, coefficient storage, varied source, fixed target position, and gravity law. The Rayleigh response reports its linearization applicability as not_assessed. Gravity response contracts are documented in the package API reference and concept pages for this release.

gragra.results.ResponseContract dataclass

Describe the physical input, mapping, gravity law, and applicability.

The Rayleigh contract identifies vertical surface displacement in input_frame at input_location_m and records its normalization and basis amplitude. mapping_kind describes the physical map independently of the output definition's C2 change form. A concrete response currently supports per_frequency action, precomputed storage, Newton gravity with no law parameters, a varied source, fixed targets, one input channel and component, and not_assessed applicability. Both exact_linear and local_linearization are valid mapping kinds. Future action, storage, law, or assessment vocabulary does not imply execution support.

Mutable constructor inputs are copied; the descriptor is immutable.

input_location_m property

input_location_m: Quantity

Return an independent position in metres in input_frame.

basis_amplitude property

basis_amplitude: Quantity

Return an independent amplitude in the declared input unit.

GravityResult accepts potential, acceleration, and gradient payloads by reference. At least one observable must be present; None marks an observable that was not supplied. Validation checks name first: it must be a string or None, and the empty string is accepted. Another name type raises TypeError; if the name is valid but all observables are None, construction raises ValueError, even when a name is given. The wrapper does not inspect payload types, units, shapes, axes, compatibility, or physical validity, and it does not copy or coerce values.

name is an optional human-readable label. It is not a physical identity and is not propagated into a payload's name or channel metadata. The caller is responsible for grouping payloads that belong to the same evaluation; multiple results can be kept in dict[str, GravityResult]. GravityResult has no parts or term field, and does not implement arithmetic because target and frame alignment and the connection of spectral descriptors to results remain unspecified; this avoids implicitly combining potentially incompatible data. It also has no time or FFT operations, I/O, or display. Coupling and other model metadata remain separate.

The dataclass freezes its field bindings and uses identity equality and hashing. Reassigning or deleting a field raises FrozenInstanceError. Payloads can remain mutable, and changes through either reference are visible through the other. This does not provide a fully immutable scientific snapshot.

For high-level time and frequency representations, GWexpy Matrix payloads use rows for targets and columns for components; the matrix type and labels carry axis information. TimeSeries payloads have shape (Ntarget, Ncomponent, Ntime) and use TimeSampling as their canonical expected axis. The example also uses sample-last internal storage as provided by these Matrix types. A frequency-indexed example makes no claim about any particular spectral meaning; the descriptors below state those meanings independently of the payload. This layout rule does not apply to CSD matrices, whose row and column semantics remain unspecified.

The example wraps an existing uniform-sphere SI result and native GWexpy matrices. Its U11 case calls a lower-level SI implementation to demonstrate wrapping. That import path is not in gragra.observables.__all__ and is not a new recommended public entry point. The complete cases are in examples/gravity_result.py.

GravityResult and the spectral names below are public from this subpackage.

gragra.results.GravityResult dataclass

Group optional observable payloads produced by one evaluation.

Only the field bindings are frozen. Payload objects are retained by identity and may remain mutable; this class does not create a snapshot. At least one observable must be provided. name is a container label and is not copied into payload metadata.

Gravity field definition

GravityFieldDefinition is an immutable typed contract that connects physical meaning to an existing gravity result. During one evaluation, the model spec, binding, and result share the same definition object. The field-definition contract for this release is described in the results API reference and concept pages.

FieldKind distinguishes a source field from a field change. A source field has no change definition, while a field change requires one.

gragra.results.FieldKind

Bases: StrEnum

Distinguish a source field from a field change.

ReferenceStatus states whether the reference is defined, unknown, or explicitly zero. Defined and explicit-zero references require both a temporal kind and a nonempty state kind.

gragra.results.ReferenceStatus

Bases: StrEnum

Describe whether a field reference is defined, unknown, or zero.

ReferenceTemporalKind distinguishes a reference state from a reference history.

gragra.results.ReferenceTemporalKind

Bases: StrEnum

Temporal interpretation of a field reference.

ChangeForm separates a finite state difference from a first-order linearized response. The latter is not a numerical finite-difference method.

gragra.results.ChangeForm

Bases: StrEnum

Mathematical form used to define a field change.

PotentialReference identifies the convention used to define the potential reference level.

gragra.results.PotentialReference

Bases: StrEnum

Reference convention for a potential field.

ReferenceDefinition records reference status and the temporal and state categories needed to compare field meanings. A defined reference does not store the concrete reference state.

gragra.results.ReferenceDefinition dataclass

Describe the reference state or history used for a field.

ChangeDefinition records the changed input, reference, mathematical form, order, and fixed conditions for a field change.

gragra.results.ChangeDefinition dataclass

Describe how a source field was varied and under which conditions.

Contribution declares either all contributions or a selected, nonempty set of contribution components. Components are normalized to a sorted tuple.

gragra.results.Contribution dataclass

Describe whether a field contains total or selected contributions.

GravityFieldDefinition combines field kind, source kind, contribution coverage, potential convention, and an optional change definition.

gragra.results.GravityFieldDefinition dataclass

Describe the source kind, contribution, and reference for a field.

source_field classmethod

source_field(
    source_kind: str,
    contribution: Contribution,
    potential_reference: PotentialReference,
) -> GravityFieldDefinition

Create a descriptor for a source field.

field_change classmethod

field_change(
    source_kind: str,
    contribution: Contribution,
    potential_reference: PotentialReference,
    change: ChangeDefinition,
) -> GravityFieldDefinition

Create a descriptor for a field change.

Spectral representation descriptors

The descriptors are Experimental APIs and immutable tags for spectral meaning. They do not store payload values or estimator settings and do not calculate spectra. This interface provides spectral distinctions independently of GravityResult. The entries below summarize each representation and the conditions attached to it.

There are nine public spectral names: two enums, six descriptor classes, and the SpectralRepresentation union.

Frequency sidedness

Use Sidedness to distinguish storage of positive frequencies alone from storage of both frequency signs. Because Sidedness is a StrEnum, Sidedness.ONE_SIDED == "one_sided" is true. Descriptor validation still requires the enum member: passing the bare string as sidedness="one_sided" raises TypeError.

gragra.results.Sidedness

Bases: StrEnum

Frequency storage convention for a Fourier transform.

As a StrEnum, a member compares equal to its string value. The descriptor constructor still requires a Sidedness member, so pass Sidedness.ONE_SIDED rather than the bare string "one_sided".

Finite-record interpretation

FiniteRecordInterpretation states whether an amplitude spectrum interprets the finite record as periodic or as a zero-extended transient.

gragra.results.FiniteRecordInterpretation

Bases: StrEnum

Interpretation of a finite amplitude-spectrum record.

As a StrEnum, a member compares equal to its string value. The descriptor constructor still requires a FiniteRecordInterpretation member, so pass FiniteRecordInterpretation.PERIODIC rather than the bare string "periodic".

Fourier transform

FourierTransformRepresentation describes the transform sign convention, physical unit, and whether negative-frequency coefficients are stored.

gragra.results.FourierTransformRepresentation dataclass

Describe a Fourier transform with physical quantity unit Q·s.

The forward transform uses the negative exponential and the inverse uses the positive exponential. ONE_SIDED omits negative frequencies for real input without doubling stored coefficients. For a transformed array y_j with interval dt, length M, DFT coefficients X_k = Σ_j y_j exp(−2πi k j/M), and f_k = k/(M dt), the finite transform convention is x̃_d(f_k) = dt exp[−2πi f_k(t₀−t_ref)] X_k. Here t₀ is the time of index zero in the array actually transformed, after cropping or padding; t_ref is the caller's absolute phase reference. This descriptor stores neither time and performs no transform computation.

Amplitude spectrum

AmplitudeSpectrumRepresentation identifies the one-sided coefficient normalization and its finite-record interpretation.

gragra.results.AmplitudeSpectrumRepresentation dataclass

Describe a one-sided complex amplitude spectrum with unit Q.

For DFT coefficients X_k of the array actually transformed, the coefficient is A_k = (c_k/M) exp[−2πi f_k(t₀−t_ref)] X_k. Here M is the transform length, t₀ is the time of index zero in that array after cropping or padding, t_ref is the caller's absolute phase reference, and c_k is one at DC and even-length Nyquist and two at interior bins. Positive-exponential synthesis reconstructs the transformed array. PERIODIC means periodic extension of the finite record; TRANSIENT means zero extension. A coefficient is a peak amplitude only for an unpadded, bin-centered component. The descriptor stores none of these record conditions or times.

Phasor

PhasorRepresentation describes a complex peak amplitude under the stated negative-exponential time convention.

gragra.results.PhasorRepresentation dataclass

Describe complex peak phasors P in x(t)=Re[P exp(-2πif(t-t_ref))].

The physical unit is Q. At an internal Fourier bin, P is the conjugate of the amplitude-spectrum coefficient. Phasors generally describe positive frequencies; a DC phasor, if used, is real. No reference time is stored.

Power spectral density

PSDRepresentation denotes a one-sided power density for a real signal, with endpoint and conversion conditions stated in its docstring.

gragra.results.PSDRepresentation dataclass

Describe a nonnegative one-sided power spectral density, unit Q²/Hz.

This density is for real signals; DC and even-length Nyquist bins are not doubled. Its conversion to squared amplitude requires a boxcar record, detrending disabled, no zero padding (M=N), and matching frequency grid. The descriptor does not define an estimator or store its conditions.

Amplitude spectral density

ASDRepresentation denotes the square root of a one-sided power density for a real signal.

gragra.results.ASDRepresentation dataclass

Describe the nonnegative square root of a one-sided PSD, unit Q/√Hz.

It applies to real signals and retains undoubled DC and even-length Nyquist endpoints. It represents density, not the square root of a spectrum-scaled estimate; estimator settings are not stored here.

Cross spectral density

CSDRepresentation states the cross-spectrum conjugation direction and the conditions for interpreting coefficients as a one-sided density.

gragra.results.CSDRepresentation dataclass

Describe one-sided cross spectral density, unit Q_x Q_y/Hz.

For real signals, the Fourier-coefficient convention conjugates the left transform: conj(FT(x)) · FT(y). The corresponding phasor product is P_x · conj(P_y), with unit Q_x Q_y; it is not itself a density. For internal bins, density conversion divides that product by 2Δf. DC and even-length Nyquist bins are not doubled and use conj(A_x) · A_y / Δf. Conversion requires boxcar, no detrending, M=N, and a common sample grid and phase reference. This descriptor stores no signals or estimator conditions.

Descriptor union

SpectralRepresentation is the type alias union of the six representation descriptor classes above. It is not a runtime wrapper or an additional descriptor kind.

gragra.results.SpectralRepresentation module-attribute

SpectralRepresentation: TypeAlias = (
    FourierTransformRepresentation
    | AmplitudeSpectrumRepresentation
    | PhasorRepresentation
    | PSDRepresentation
    | ASDRepresentation
    | CSDRepresentation
)