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.
| 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, |
1.0
|
reduction
|
str
|
whether to reduce across the batch and channel dimensions by summing ('sum') or averaging ('mean') Warning
|
'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.
uniform_quadrature
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 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
|
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, |
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.
|
'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_y
|
bool
|
whether to use periodic boundary conditions in y-direction when computing finite differences:
|
True
|
Configure the H1 Sobolev loss. See the class docstring for parameters.
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 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 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
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 |
1.0
|
enforce_dirichlet
|
bool
|
whether to hard-constrain the boundary of the predicted field to
|
True
|
boundary_value
|
float, 0-d array, or dict[str, float]
|
the known Dirichlet value(s) enforced when |
0.0
|
diffusion_order
|
int
|
derivative order used for both the flux ( |
1
|
diffusion_scheme
|
str
|
finite-difference scheme used for both the flux and the divergence
step of the diffusion term, one of |
'central'
|
Configure the Darcy equation loss. See the class docstring for parameters.
prepare_eval_inputs
Prepare Trainer eval inputs for this loss's channel-last contract.
eval_batch_loss
Return unrooted sum(residual**2) for cross-batch eval aggregation.
finalize_eval_metric
Convert accumulated squared residuals to one global per-sample RMS.
residual
Pointwise Darcy PDE residual, -div(a * grad(u)) - f.
Args:
| Name | Type | Description |
|---|---|---|
y_pred
|
ndarray
|
predicted pressure field |
x
|
ndarray
|
permeability field |
Returns:
| Type | Description |
|---|---|
ndarray
|
residual, shape |
abs
Scalar PDE-residual norm: the (optionally root-ed) reduced squared residual.
Args:
| Name | Type | Description | Default |
|---|---|---|---|
y_pred
|
ndarray
|
predicted pressure field, shape |
|
x
|
ndarray
|
permeability field, shape |
|
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
|
|
'u'
|
coeff
|
str or float
|
|
1.0
|
order
|
int
|
derivative order applied at both the flux step ( |
1
|
scheme
|
str
|
finite-difference scheme applied at both the flux step and the
divergence step, one of |
'central'
|
SourceTerm
A constant or spatially-varying forcing term f.
Args:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str or float
|
|
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 -- |
|
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 |
True
|
spacing
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)).
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 |
|
order
|
int
|
derivative order, 1 or 2, by default 1 |
1
|
spacing
|
float
|
grid spacing Note For a periodic axis sampled at |
1.0
|
periodic
|
bool
|
whether
|
True
|
scheme
|
str
|
one of |
'central'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
derivative of |
Galerkin (weak-form) loss
Q4Galerkin
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-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
Physical coordinates of every quadrature point, every element,
shape (Q, T, 2).
element_gradient_at_quad
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).