Skip to content

scirex.losses

Data losses, and the finite-element building blocks (Q4Galerkin) behind the Ritz-energy loss of the Darcy physics-only benchmark. The residual losses of the Darcy equation are listed below for completeness; no released benchmark uses them.

from scirex.losses import LpLoss
Group Names
Data losses LpLoss, H1Loss
Darcy residual DarcyEqnLoss, DiffusionTerm, SourceTerm
Derivatives AxisSpec, FiniteDiff
Weak form Q4Galerkin

The other physics losses are in scirex.experimental.losses. For how to choose among them, read Physics-informed losses.

Data losses

LpLoss

LpLoss(
    d: int = 1,
    p: int = 2,
    measure: float | Sequence[float] = 1.0,
    reduction: str = "sum",
    eps: float = 1e-08,
)

LpLoss provides the Lp norm between two discretized d-dimensional functions.

Note that LpLoss always averages over the spatial dimensions.

Note

In function space, the Lp norm is an integral over the entire domain. To ensure the norm converges to the integral, we scale the matrix norm by quadrature weights along each spatial dimension.

If no quadrature is passed at a call to LpLoss, we assume a regular discretization and take 1 / measure as the quadrature weights.

Args:

Name Type Description Default
d int

dimension of data on which to compute, by default 1

1
p int

order of L-norm, by default 2 L-p norm: \(\left[\sum_{i=0}^{n} \lvert x_i - y_i\rvert^p\right]^{1/p}\)

2
measure float or list

measure of the domain, by default 1.0 either single scalar for each dim, or one per dim

Note

To perform quadrature, LpLoss scales measure by the size of each spatial dimension of x, and multiplies them with ||x-y||, such that the final norm is a scaled average over the spatial dimensions of x.

1.0
reduction str

whether to reduce across the batch and channel dimensions by summing ('sum') or averaging ('mean')

Warning

LpLoss always reduces over the spatial dimensions according to self.measure. reduction only applies to the batch and channel dimensions.

'sum'
eps float

small number added to the denominator for numerical stability when using the relative loss

1e-08

Examples:

>>> import jax.numpy as jnp
>>> from scirex.losses import LpLoss
>>> y = jnp.ones((2, 1, 8, 8))  # (batch, channels, height, width)
>>> loss = LpLoss(d=2, p=2, reduction="mean")
>>> round(float(loss.rel(1.1 * y, y)), 3)  # relative L2 error
0.1

Configure the Lp loss. See the class docstring for parameter details.

name property

name: str

str: Human-readable identifier, e.g. "L2_1Dloss".

uniform_quadrature

uniform_quadrature(x: ndarray) -> list[float]

uniform_quadrature creates quadrature weights scaled by the spatial size of x to ensure that LpLoss computes the average over spatial dims.

Args:

Name Type Description
x ndarray

input data

Returns:

Name Type Description
quadrature list

list of quadrature weights per-dim

reduce_all

reduce_all(x: ndarray) -> jnp.ndarray

reduce x across the batch according to self.reduction

Args:

Name Type Description
x ndarray

inputs

abs

abs(
    x: ndarray,
    y: ndarray,
    quadrature: float | Sequence[float] | None = None,
    take_root: bool = True,
) -> jnp.ndarray

Absolute Lp-norm

Args:

Name Type Description Default
x ndarray

inputs

y ndarray

targets

quadrature float or list

quadrature weights for integral either single scalar or one per dimension

None
take_root bool

whether to take the p-th root of the norm, by default True

True

rel

rel(
    x: ndarray, y: ndarray, take_root: bool = True
) -> jnp.ndarray

rel: relative LpLoss computes ||x-y||/(||y|| + eps)

Args:

Name Type Description Default
x ndarray

inputs

y ndarray

targets

take_root bool

whether to take the p-th root of the norm, by default True

True

H1Loss

H1Loss(
    d: int = 1,
    measure: float | Sequence[float] = 1.0,
    reduction: str = "sum",
    eps: float = 1e-08,
    periodic_in_x: bool = True,
    periodic_in_y: bool = True,
    periodic_in_z: bool = True,
)

H1 Sobolev norm between two d-dimensional discretized functions.

Note

In function space, the Sobolev norm is an integral over the entire domain. To ensure the norm converges to the integral, we scale the matrix norm by quadrature weights along each spatial dimension.

If no quadrature is passed at a call to H1Loss, we assume a regular discretization and take 1 / measure as the quadrature weights.

Args:

Name Type Description Default
d int

dimension of input functions, by default 1

1
measure float or list

measure of the domain, by default 1.0 either single scalar for each dim, or one per dim

Note

To perform quadrature, H1Loss scales measure by the size of each spatial dimension of x, and multiplies them with ||x-y||, such that the final norm is a scaled average over the spatial dimensions of x.

1.0
reduction str

whether to reduce across the batch and channel dimension by summing ('sum') or averaging ('mean')

Warning

H1Loss always averages over the spatial dimensions. reduction only applies to the batch and channel dimensions.

'sum'
eps float

small number added to the denominator for numerical stability when using the relative loss

1e-08
periodic_in_x bool

whether to use periodic boundary conditions in x-direction when computing finite differences:

  • True: periodic in x (default)
  • False: non-periodic in x with forward/backward differences at boundaries by default True
True
periodic_in_y bool

whether to use periodic boundary conditions in y-direction when computing finite differences:

  • True: periodic in y (default)
  • False: non-periodic in y with forward/backward differences at boundaries by default True
True

Configure the H1 Sobolev loss. See the class docstring for parameters.

name property

name: str

str: Human-readable identifier, e.g. "H1_1DLoss".

compute_terms

compute_terms(
    x: ndarray, y: ndarray, quadrature: Sequence[float]
) -> tuple[dict[int, jnp.ndarray], dict[int, jnp.ndarray]]

compute_terms computes the necessary finite-difference derivative terms for computing the H1 norm

Args:

Name Type Description
x ndarray

inputs

y ndarray

targets

quadrature int or list

quadrature weights

uniform_quadrature

uniform_quadrature(x: ndarray) -> list[float]

uniform_quadrature creates quadrature weights scaled by the spatial size of x to ensure that LpLoss computes the average over spatial dims.

Args:

Name Type Description
x ndarray

input data

Returns:

Name Type Description
quadrature list

list of quadrature weights per-dim

reduce_all

reduce_all(x: ndarray) -> jnp.ndarray

reduce x across the batch according to self.reduction

Args:

Name Type Description
x ndarray

inputs

abs

abs(
    x: ndarray,
    y: ndarray,
    quadrature: float | Sequence[float] | None = None,
    take_root: bool = True,
) -> jnp.ndarray

Absolute H1 norm

Args:

Name Type Description Default
x ndarray

inputs

y ndarray

targets

quadrature float or list

quadrature constant for reduction along each dim, by default None

None
take_root bool

whether to take the square root of the norm, by default True

True
Notes

The root is taken per sample, before reduce_all reduces across the batch, so take_root=True with reduction="sum" gives the sum of the per-sample norms rather than the norm of the batch. As a consequence abs(take_root=False) equals abs(take_root=True) ** 2 only when the batch holds a single sample.

rel

rel(
    x: ndarray,
    y: ndarray,
    quadrature: float | Sequence[float] | None = None,
    take_root: bool = True,
) -> jnp.ndarray

Relative H1-norm

Args:

Name Type Description Default
x ndarray

inputs

y ndarray

targets

quadrature float or list

quadrature constant for reduction along each dim, by default None

None
take_root bool

whether to take the square root of the norm, by default True

True
Notes

The root is taken per sample, before reduce_all reduces across the batch. take_root=True with reduction="sum" therefore gives the sum of the per-sample norms, not the norm of the batch. As a consequence rel(take_root=False) equals rel(take_root=True) ** 2 only when the batch holds a single sample.

Darcy residual loss

Finite-difference residual of the 2D Darcy equation, built from these terms.

DarcyEqnLoss

DarcyEqnLoss(
    measure: float | ndarray | Sequence[float] = 1.0,
    reduction: str = "mean",
    forcing: float = 1.0,
    enforce_dirichlet: bool = True,
    boundary_value: float
    | ndarray
    | dict[str, float] = 0.0,
    diffusion_order: int = 1,
    diffusion_scheme: str = "central",
)

PDE-residual loss for the 2D Darcy-flow equation.

Measures how well a predicted pressure field u satisfies

\[ -\nabla \cdot (a \nabla u) = f, \quad x \in (0, 1)^2, \quad u = 0 \text{ on } \partial(0,1)^2, \]

the standard Darcy-flow benchmark (Li et al., Fourier Neural Operator for Parametric Partial Differential Equations), where a is the (possibly rough/discontinuous) permeability field and f is a constant forcing term (f = 1 by convention).

The divergence is computed in flux form: flux = a * grad(u) is computed first (one FiniteDiff call per spatial axis), and only flux -- not a itself -- is differentiated again to get the divergence. This avoids ever taking a finite difference of the rough coefficient field a directly, which would be numerically poor for a non-smooth field.

Note

Dirichlet boundary handling. By default (enforce_dirichlet=True), the boundary rows/columns of the predicted field are overwritten with the known exact value (u=0 on every edge, the standard Darcy-flow convention) before differentiating, rather than trusting the model's own (as-yet-unconstrained) boundary output. This makes the PDE residual numerically correct near the boundary, but it also means no gradient flows back to the model's boundary predictions through this loss (the overwritten values are constants, not a function of the model's output). This is only safe when some other loss in the training objective (e.g. LpLoss / H1Loss against paired ground-truth data, which already encodes the true boundary values) supervises the boundary directly. If this loss is ever used without such a data loss (e.g. training data-free), set enforce_dirichlet=False, or the model will never learn the boundary condition.

If the exact boundary value isn't 0 (a non-standard Darcy variant, or a manufactured-solution test with a nonzero boundary), set boundary_value -- either one constant applied to all four edges, or a per-edge dict (see below) if the edges genuinely differ.

Args:

Name Type Description Default
measure float, 0-d array, or Sequence[float]

physical domain length per spatial dimension, by default 1.0 (the standard unit-square Darcy domain), either a single (scalar or 0-d array) value applied to both spatial dims, or a length-2 sequence with one value per dim

1.0
reduction str

whether to reduce the squared residual across the batch and spatial dims by summing ("sum") or averaging ("mean"), by default "mean"

'mean'
forcing float

the (constant) forcing term f, by default 1.0 (the standard Darcy-flow benchmark convention)

1.0
enforce_dirichlet bool

whether to hard-constrain the boundary of the predicted field to boundary_value before differentiating, by default True. See the note above.

True
boundary_value float, 0-d array, or dict[str, float]

the known Dirichlet value(s) enforced when enforce_dirichlet=True, by default 0.0 (the standard Darcy-flow convention). Either a single (scalar or 0-d array) constant applied to all four edges, or a dict giving a separate constant per edge with exactly the keys "x_min", "x_max", "y_min", "y_max" (u's axis 1 is x, axis 2 is y, matching the AxisSpec convention used elsewhere in this class). At the four corners, where an x-edge and a y-edge overlap, the y-edge value is the one that ends up applied.

0.0
diffusion_order int

derivative order used for both the flux (grad(u)) and the divergence step of the diffusion term, by default 1 -- together giving the standard 2nd-order-overall Darcy diffusion operator div(a * grad(u)). Forwarded straight to DiffusionTerm; only change this for a non-standard, higher-order flux variant of the equation.

1
diffusion_scheme str

finite-difference scheme used for both the flux and the divergence step of the diffusion term, one of "central", "forward", "backward", by default "central" (2nd-order accurate, the standard choice for a diffusion term, which has no preferred direction to bias toward). Forwarded straight to DiffusionTerm. "forward"/"backward" only combine with diffusion_order=1.

'central'

Configure the Darcy equation loss. See the class docstring for parameters.

name property

name: str

str: Human-readable identifier.

prepare_eval_inputs

prepare_eval_inputs(
    y_pred: ndarray, sample: dict
) -> tuple[jnp.ndarray, dict]

Prepare Trainer eval inputs for this loss's channel-last contract.

eval_batch_loss

eval_batch_loss(
    y_pred: ndarray,
    x: ndarray | None = None,
    **kwargs: object,
) -> jnp.ndarray

Return unrooted sum(residual**2) for cross-batch eval aggregation.

finalize_eval_metric

finalize_eval_metric(
    accumulated_loss: float | ndarray, n_samples: int
) -> float

Convert accumulated squared residuals to one global per-sample RMS.

residual

residual(y_pred: ndarray, x: ndarray) -> jnp.ndarray

Pointwise Darcy PDE residual, -div(a * grad(u)) - f.

Args:

Name Type Description
y_pred ndarray

predicted pressure field u, shape (batch, n_x, n_y, 1)

x ndarray

permeability field a (the model's own input), shape (batch, n_x, n_y, 1)

Returns:

Type Description
ndarray

residual, shape (batch, n_x, n_y)

abs

abs(
    y_pred: ndarray, x: ndarray, take_root: bool = True
) -> jnp.ndarray

Scalar PDE-residual norm: the (optionally root-ed) reduced squared residual.

Args:

Name Type Description Default
y_pred ndarray

predicted pressure field, shape (batch, n_x, n_y, 1)

x ndarray

permeability field, shape (batch, n_x, n_y, 1)

take_root bool

whether to take the square root of the reduced squared residual, by default True

True

DiffusionTerm

DiffusionTerm(
    axes: Sequence[AxisSpec],
    field: str = "u",
    coeff: str | float = 1.0,
    order: int = 1,
    scheme: str = "central",
)

div(coeff * grad(field)), in flux form.

flux = coeff * grad(field) is computed first (one derivative per axis), and only flux -- not coeff -- is differentiated again to get the divergence. This avoids ever taking a finite difference of coeff directly, which is important when coeff is a rough or discontinuous field (e.g. Darcy's permeability).

Args:

Name Type Description Default
axes Sequence[AxisSpec]

one entry per spatial axis to include in the divergence, must be non-empty

field str

ctx key of the field being diffused, by default "u"

'u'
coeff str or float

ctx key of the (possibly spatially-varying) diffusion coefficient, or a constant, by default 1.0

1.0
order int

derivative order applied at both the flux step (grad(field)) and the divergence step, by default 1 -- together giving the usual 2nd-order-overall diffusion operator. Passed straight through to each axis's derivative call, so any order the configured differentiator supports works here too -- e.g. order=2 with a FourierDiff axis gives, per axis, d^2(coeff * d^2 field / d(axis)^2) / d(axis)^2, summed over axes. This is a per-axis higher-order damping term, not the standard isotropic biharmonic/hyperdiffusion operator -- it has no cross-axis terms (e.g. no d^4/dx^2dy^2), so it's directionally anisotropic whenever more than one axis is included.

1
scheme str

finite-difference scheme applied at both the flux step and the divergence step, one of "central", "forward", "backward", by default "central". Passed straight through to each axis's derivative call -- "forward"/"backward" only combine with order=1, since FiniteDiff itself rejects a directional scheme at any other order, and a FourierDiff axis only accepts "central" (see AxisSpec).

'central'

SourceTerm

SourceTerm(value: str | float = 0.0)

A constant or spatially-varying forcing term f.

Args:

Name Type Description Default
value str or float

ctx key of the (possibly spatially-varying) source field, or a constant, by default 0.0

0.0

Derivative operators

AxisSpec dataclass

AxisSpec(
    axis: int,
    differentiator: FiniteDiff | FourierDiff,
    measure: float = 1.0,
    periodic: bool = True,
)

Everything a term needs to differentiate along one axis of a field.

Args:

Name Type Description Default
axis int

axis of the field to differentiate along

differentiator FiniteDiff or FourierDiff

which differentiation primitive to use for this axis -- FiniteDiff for non-periodic and/or non-smooth axes (e.g. Darcy's spatial axes), FourierDiff for periodic, smooth axes (e.g. Burgers'/Navier-Stokes' spatial axis)

measure float

physical domain length along this axis, by default 1.0, must be > 0

1.0
periodic bool

whether this axis is periodic, by default True. Only meaningful for a FiniteDiff axis (FourierDiff always assumes periodic).

True

spacing

spacing(u: ndarray) -> float

Grid spacing along this axis, given a field sampled on it.

A periodic axis with n points spans its full measure without a duplicated endpoint (h = measure / n); a non-periodic axis samples both endpoints (h = measure / (n - 1)).

derivative

derivative(
    u: ndarray, order: int = 1, scheme: str = "central"
) -> jnp.ndarray

Differentiate u along this axis, dispatching to the configured differentiator with this axis's spacing/periodicity.

FiniteDiff

Central-difference derivatives of a field sampled on a regular grid.

Note

axis, order, and periodic must be static (plain Python values, not traced arrays) since they select which code path runs at trace time -- this matches how d/p/reduction are used as static configuration in LpLoss. If used inside jax.jit, mark them as static_argnames.

derivative

derivative(
    u: ndarray,
    axis: int,
    order: int = 1,
    spacing: float = 1.0,
    periodic: bool = True,
    scheme: str = "central",
) -> jnp.ndarray

Differentiate u along axis.

Args:

Name Type Description Default
u ndarray

field values on a regular grid, arbitrary rank

axis int

axis of u to differentiate along

order int

derivative order, 1 or 2, by default 1

1
spacing float

grid spacing h along axis, by default 1.0

Note

For a periodic axis sampled at n points over a domain of length L (no duplicated endpoint), use h = L / n. For a non-periodic axis sampled at n points including both endpoints, use h = L / (n - 1).

1.0
periodic bool

whether axis is periodic, by default True

  • periodic=True uses a jnp.roll-based stencil at every point (wrapping around the boundary).
  • periodic=False uses the interior stencil in the interior and a matched-order one-sided stencil at the two boundary points along axis.
True
scheme str

one of "central", "forward", "backward", by default "central". Only "central" is supported for order=2 (diffusion-type terms don't need directional biasing). "forward"/"backward" are 1st-order-accurate directional derivatives -- the building blocks for an upwind advection scheme (pick "backward" where the advecting velocity is positive, "forward" where it's negative), which trades central differencing's 2nd-order accuracy for stability on advection-dominated terms. At a non-periodic domain boundary, the direction that would need an out-of-domain neighbor falls back to the other one-sided difference instead (there is no other choice at the edge).

'central'

Returns:

Type Description
ndarray

derivative of u along axis, same shape as u

Galerkin (weak-form) loss

Q4Galerkin

Q4Galerkin(xy: ndarray, quad: ndarray)

Generic bilinear (Q4) quadrilateral-element Galerkin machinery, precomputed once for a fixed mesh and shared by every instance in a training batch -- the Q4 analogue of T6Galerkin.

Args:

Name Type Description
xy (array, shape(N, 2))

Node coordinates.

quad (array, shape(T, 4), int)

Quadrilateral connectivity, 0-indexed, CCW node order (see module docstring).

physical_grad_and_jacobian

physical_grad_and_jacobian() -> tuple[
    jnp.ndarray, jnp.ndarray, jnp.ndarray
]

Physical-space shape-function gradients and the Jacobian determinant at every quadrature point, for every element.

Returns:

Name Type Description
dN_dx, dN_dy : array, shape (Q, T, 4)
det_j (array, shape(Q, T))

quadrature_points_physical

quadrature_points_physical() -> jnp.ndarray

Physical coordinates of every quadrature point, every element, shape (Q, T, 2).

element_gradient_at_quad

element_gradient_at_quad(
    u: ndarray,
) -> tuple[jnp.ndarray, jnp.ndarray]

u, shape (N,) -> (du_dx, du_dy), each shape (Q, T): the gradient of u's Q4 (bilinear) interpolant, evaluated at every quadrature point of every element (linear within an element, not constant).

grad_energy

grad_energy(
    u: ndarray,
    kappa_fn: Callable[[ndarray, ndarray], ndarray],
    params: ndarray,
) -> jnp.ndarray

Scalar int kappa * |grad(u)|^2 dOmega, the Q4 analogue of T6Galerkin.grad_energy.

scatter_to_nodes

scatter_to_nodes(elem_contrib: ndarray) -> jnp.ndarray

elem_contrib, shape (T, 4) -- one value per element per local node (0..3) -- scattered/accumulated into a nodal array, shape (N,).