Skip to main content

omnibias.fields.torch.ops.integral

0.2.0rc1Release candidatePython >=3.10Apache-2.0

Structured scalar, vector, and tensor fields with derivative caches, calculus operators, and coordinate conventions.

import omnibias.fields.torch.ops.integral
Module contract & mathematical conventions

Definite integration of a field component over a box domain (torch).

The integrate op contracts the component values *already evaluated at a quadrature rule's nodes* with that rule's weights. Evaluate the field at quadrature_nodes first::

rule = gauss_legendre([(0.0, 1.0)], 16) state = field(quadrature_nodes(rule, like=coords)) total = integrate(state, "u", rule=rule) # scalar tensor

This is a quadrature sum \sum_q w_q\,u(x_q); it is exact for polynomials up to the rule's degree and converges otherwise. The nodes and weights come from the shared numpy QuadratureSpec, so torch and jax produce bit-identical results.

Shared formulas do not imply universal floating-point identity. Verify dtype, shape, derivative-order support, and the stated numerical assumptions for the path you use.

FUNCTION

integrate​

omnibias.fields.torch.ops.integrateSource ↗
integrate(state: FieldState, name: str, *, rule: QuadratureSpec) -> Tensor

Definite integral \int_\Omega u\,dx via the quadrature rule.

state must have been evaluated at rule's nodes (so that state.coords.shape[0] == rule.n_nodes).

Parameters

state Field state evaluated at the quadrature nodes. name Scalar component name to integrate. rule The quadrature rule supplying the weights.

Returns

Tensor A scalar tensor (shape ()) holding the integral.

Parameters

NameType & defaultContract
statepositional-or-keywordFieldStateRequiredField state evaluated at the quadrature nodes.
namepositional-or-keywordstrRequiredScalar component name to integrate.
rulekeyword-onlyQuadratureSpecRequiredThe quadrature rule supplying the weights.
ReturnsTensor
Explicit validation & failure cases
  • When vals.shape[0] != rule.n_nodes, raises ValueError(f'integrate: state has {vals.shape[0]} points but rule has {rule.n_nodes} nodes; evaluate the field at quadrature_nodes(rule)').

These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.

Executed regression · integrate regression pin

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_integrate_regression_pin(make_torch_field):  # type: ignore[no-untyped-def]
    rule = _rule()
    state = make_torch_field()(torch.as_tensor(rule.nodes, dtype=torch.float64))
    # int_0^1 (1+2x+x^2) dx * int_-1^1 (1-y) dy = (1+1+1/3) * (2) = 14/3.
    assert np.isclose(float(_np(state.u.integrate(rule=rule))), 14.0 / 3.0,
                      rtol=1e-12, atol=1e-14)
python -m pytest "packages/omnibias-fields/tests/test_integration_norms.py::test_integrate_regression_pin" -q
Read the implementation
def integrate(state: FieldState, name: str, *, rule: QuadratureSpec) -> Tensor:
    r"""Definite integral :math:`\int_\Omega u\,dx` via the quadrature ``rule``.

    ``state`` must have been evaluated at ``rule``'s nodes (so that
    ``state.coords.shape[0] == rule.n_nodes``).

    Parameters
    ----------
    state
        Field state evaluated at the quadrature nodes.
    name
        Scalar component name to integrate.
    rule
        The quadrature rule supplying the weights.

    Returns
    -------
    Tensor
        A scalar tensor (shape ``()``) holding the integral.
    """
    vals = value(state, name)
    if vals.shape[0] != rule.n_nodes:
        raise ValueError(
            f"integrate: state has {vals.shape[0]} points but rule has "
            f"{rule.n_nodes} nodes; evaluate the field at quadrature_nodes(rule)"
        )
    w = _weights(rule, vals)
    return torch.tensordot(w, vals, dims=([0], [0]))
Other public import paths
  • omnibias.fields.torch.ops.integrate
  • omnibias.fields.torch.ops.integral.integrate
FUNCTION

line_integral​

omnibias.fields.torch.ops.line_integralSource ↗
line_integral(state: FieldState, name: str, curve: Callable[[Tensor], Tensor], *, rule: QuadratureSpec) -> Tensor

Gradient-theorem line integral \int_C \nabla u \cdot d\mathbf r.

Evaluates \int_{t_0}^{t_1} \nabla u(r(t))\cdot r'(t)\,dt for the scalar potential name along the curve r. By the multivariate Fundamental Theorem of Calculus (the gradient theorem) this equals u(r(t_1)) - u(r(t_0)) for any path.

state must hold name evaluated at the curve image points curve(quadrature_nodes(rule)) (the same pre-evaluation convention as the geometry surface integrals); curve is a bare callable mapping a (1,) parameter to an ambient point (n,) -- fields never import geometry, so the curve is not a ChartSpec. The gradient \nabla u is the closed-form field op and the tangent r'(t) is exact forward-mode autodiff; the integral itself is Gauss-Legendre quadrature over the 1-D parameter box.

Returns a scalar tensor.

Parameters

NameType & defaultContract
statepositional-or-keywordFieldStateRequiredSee the operation contract and implementation below.
namepositional-or-keywordstrRequiredSee the operation contract and implementation below.
curvepositional-or-keywordCallable[[Tensor], Tensor]RequiredSee the operation contract and implementation below.
rulekeyword-onlyQuadratureSpecRequiredSee the operation contract and implementation below.
ReturnsTensor
Explicit validation & failure cases
  • When g.shape[0] != rule.n_nodes, raises ValueError(f'line_integral: state has {g.shape[0]} points but rule has {rule.n_nodes} nodes; evaluate the field at curve(quadrature_nodes(rule))').
  • When x.shape[-1] != 1, raises ValueError(f'line_integral requires a 1-D parameter rule (a curve); got a {x.shape[-1]}-D rule').
  • When tangent.shape[-1] != g.shape[-1], raises ValueError(f"line_integral: curve maps to {tangent.shape[-1]} ambient dims but the field gradient spans {g.shape[-1]}; the curve must land in the field's gradient axes").

These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.

Executed regression · dispatch matches view torch

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_dispatch_matches_view_torch(make_torch_field):  # type: ignore[no-untyped-def]
    field = make_torch_field()
    curve = _torch_linear(_P0, _P1)
    rule = gauss_legendre([(0.0, 1.0)], 8)
    state = _torch_curve_points(field, curve, rule)
    via_view = _np(state.u.line_integral(curve, rule=rule))
    via_ops = _np(state.ops.line_integral(state, "u", curve, rule=rule))
    assert np.array_equal(via_view, via_ops)
python -m pytest "packages/omnibias-fields/tests/test_line_integral.py::test_dispatch_matches_view_torch" -q
Read the implementation
def line_integral(
    state: FieldState,
    name: str,
    curve: Callable[[Tensor], Tensor],
    *,
    rule: QuadratureSpec,
) -> Tensor:
    r"""Gradient-theorem line integral :math:`\int_C \nabla u \cdot d\mathbf r`.

    Evaluates :math:`\int_{t_0}^{t_1} \nabla u(r(t))\cdot r'(t)\,dt` for the scalar
    potential ``name`` along the curve ``r``. By the multivariate Fundamental
    Theorem of Calculus (the gradient theorem) this equals ``u(r(t_1)) -
    u(r(t_0))`` for any path.

    ``state`` must hold ``name`` evaluated at the curve image points
    ``curve(quadrature_nodes(rule))`` (the same pre-evaluation convention as the
    geometry surface integrals); ``curve`` is a bare callable mapping a ``(1,)``
    parameter to an ambient point ``(n,)`` -- fields never import geometry, so the
    curve is not a ``ChartSpec``. The gradient :math:`\nabla u` is the closed-form
    field op and the tangent ``r'(t)`` is exact forward-mode autodiff; the integral
    itself is Gauss-Legendre quadrature over the 1-D parameter box.

    Returns a scalar tensor.
    """
    g = gradient(state, name)  # (Q, dim)
    if g.shape[0] != rule.n_nodes:
        raise ValueError(
            f"line_integral: state has {g.shape[0]} points but rule has "
            f"{rule.n_nodes} nodes; evaluate the field at "
            "curve(quadrature_nodes(rule))"
        )
    x = quadrature_nodes(rule, like=g)  # (Q, param_dim) parameter nodes
    if x.shape[-1] != 1:
        raise ValueError(
            "line_integral requires a 1-D parameter rule (a curve); got a "
            f"{x.shape[-1]}-D rule"
        )
    tangent = _tangent(curve, x)  # (Q, dim)
    if tangent.shape[-1] != g.shape[-1]:
        raise ValueError(
            f"line_integral: curve maps to {tangent.shape[-1]} ambient dims but "
            f"the field gradient spans {g.shape[-1]}; the curve must land in the "
            "field's gradient axes"
        )
    integrand = (g * tangent).sum(dim=-1)  # (Q,)
    w = _weights(rule, integrand)
    return torch.tensordot(w, integrand, dims=([0], [0]))
Other public import paths
  • omnibias.fields.torch.ops.line_integral
  • omnibias.fields.torch.ops.integral.line_integral
FUNCTION

quadrature_nodes​

omnibias.fields.torch.ops.quadrature_nodesSource ↗
quadrature_nodes(rule: QuadratureSpec, *, like: Tensor) -> Tensor

Return the rule's nodes as a (n_nodes, dim) tensor matching like.

Parameters

rule The quadrature rule whose nodes to materialise. like A tensor whose dtype and device the nodes should match.

Parameters

NameType & defaultContract
rulepositional-or-keywordQuadratureSpecRequiredThe quadrature rule whose nodes to materialise.
likekeyword-onlyTensorRequiredA tensor whose dtype and device the nodes should match.
ReturnsTensor
Executed regression · dispatch matches view torch

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_dispatch_matches_view_torch(make_torch_field):  # type: ignore[no-untyped-def]
    field = make_torch_field()
    curve = _torch_linear(_P0, _P1)
    rule = gauss_legendre([(0.0, 1.0)], 8)
    state = _torch_curve_points(field, curve, rule)
    via_view = _np(state.u.line_integral(curve, rule=rule))
    via_ops = _np(state.ops.line_integral(state, "u", curve, rule=rule))
    assert np.array_equal(via_view, via_ops)
python -m pytest "packages/omnibias-fields/tests/test_line_integral.py::test_dispatch_matches_view_torch" -q
Read the implementation
def quadrature_nodes(rule: QuadratureSpec, *, like: Tensor) -> Tensor:
    """Return the rule's nodes as a ``(n_nodes, dim)`` tensor matching ``like``.

    Parameters
    ----------
    rule
        The quadrature rule whose nodes to materialise.
    like
        A tensor whose dtype and device the nodes should match.
    """
    return torch.as_tensor(rule.nodes, dtype=like.dtype, device=like.device)
Other public import paths
  • omnibias.fields.torch.ops.quadrature_nodes
  • omnibias.fields.torch.ops.integral.quadrature_nodes