Skip to main content

omnibias.fields.weak.torch

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.weak.torch
Module contract & mathematical conventions

Weak-form VPINN assembly (torch; theory 02-04).

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.

CLASS

ResidualTerm​

omnibias.fields.weak.torch.ResidualTermSource ↗
class ResidualTerm

Dataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.

One assembled weak-form contribution, with the path recorded.

Parameters

NameType & defaultContract
namedataclass fieldstrRequiredSee the operation contract and implementation below.
pathdataclass fieldPathNameRequiredSee the operation contract and implementation below.
valuedataclass fieldTensorRequiredSee the operation contract and implementation below.

Fields & methods

namefield
name: str

Declared str field on ResidualTerm. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
pathfield
path: PathName

Declared PathName field on ResidualTerm. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
valuefield
value: Tensor

Declared Tensor field on ResidualTerm. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
Read the implementation
class ResidualTerm:
    """One assembled weak-form contribution, with the path recorded."""

    name: str
    path: PathName
    value: Tensor
FUNCTION

weak_loss​

omnibias.fields.weak.torch.weak_lossSource ↗
weak_loss(field: Callable[[Tensor], Tensor] | tuple[float, ...], space: TestFunctionSpace, *, operator: WeakForm, source: Callable[[Tensor], Tensor] | tuple[float, ...] | None=None, quadrature: QuadratureSpec | None=None, include_boundary_bound: bool=True, deriv_bound: float=1.0) -> Tensor

Sum of squared weak residuals; boundary bound on by default.

Parameters

NameType & defaultContract
fieldpositional-or-keywordCallable[[Tensor], Tensor] | tuple[float, ...]RequiredSee the operation contract and implementation below.
spacepositional-or-keywordTestFunctionSpaceRequiredSee the operation contract and implementation below.
operatorkeyword-onlyWeakFormRequiredSee the operation contract and implementation below.
sourcekeyword-onlyCallable[[Tensor], Tensor] | tuple[float, ...] | NoneDefault: NoneSee the operation contract and implementation below.
quadraturekeyword-onlyQuadratureSpec | NoneDefault: NoneSee the operation contract and implementation below.
include_boundary_boundkeyword-onlyboolDefault: TrueSee the operation contract and implementation below.
deriv_boundkeyword-onlyfloatDefault: 1.0See the operation contract and implementation below.
ReturnsTensor
Executed regression · g2 boundary bound changes loss

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_g2_boundary_bound_changes_loss() -> None:
    torch.set_default_dtype(torch.float64)
    space = _space()
    op = WeakForm(diffusion=(1.0,), source=(2.0,))
    field = (0.0, 1.0, -1.0)  # x - x^2
    on = float(weak_loss(field, space, operator=op, include_boundary_bound=True))
    off = float(weak_loss(field, space, operator=op, include_boundary_bound=False))
    assert on != off
    bound = boundary_bound(space, deriv_bound=1.0)
    assert bound.hi > 0.0
python -m pytest "packages/omnibias-fields/tests/test_weak.py::test_g2_boundary_bound_changes_loss" -q
Read the implementation
def weak_loss(
    field: Callable[[Tensor], Tensor] | tuple[float, ...],
    space: TestFunctionSpace,
    *,
    operator: WeakForm,
    source: Callable[[Tensor], Tensor] | tuple[float, ...] | None = None,
    quadrature: QuadratureSpec | None = None,
    include_boundary_bound: bool = True,
    deriv_bound: float = 1.0,
) -> Tensor:
    """Sum of squared weak residuals; boundary bound on by default."""
    residual, _terms = weak_residual(
        field, space, operator=operator, source=source, quadrature=quadrature
    )
    loss = (residual * residual).sum()
    if include_boundary_bound:
        bound = boundary_bound(space, deriv_bound=deriv_bound)
        loss = loss + torch.tensor(float(bound.hi), dtype=loss.dtype, device=loss.device)
    return loss
FUNCTION

weak_residual​

omnibias.fields.weak.torch.weak_residualSource ↗
weak_residual(field: Callable[[Tensor], Tensor] | tuple[float, ...], space: TestFunctionSpace, *, operator: WeakForm, source: Callable[[Tensor], Tensor] | tuple[float, ...] | None=None, quadrature: QuadratureSpec | None=None) -> tuple[Tensor, tuple[ResidualTerm, ...]]

Assemble r(v_i) for every test function.

Polynomial source / operator.diffusion on a box use the exact antiderivative path. A callable field falls back to quadrature on the coefficient factor only. Each term records exact or quadrature.

Parameters

NameType & defaultContract
fieldpositional-or-keywordCallable[[Tensor], Tensor] | tuple[float, ...]RequiredSee the operation contract and implementation below.
spacepositional-or-keywordTestFunctionSpaceRequiredSee the operation contract and implementation below.
operatorkeyword-onlyWeakFormRequiredSee the operation contract and implementation below.
sourcekeyword-onlyCallable[[Tensor], Tensor] | tuple[float, ...] | NoneDefault: NoneSee the operation contract and implementation below.
quadraturekeyword-onlyQuadratureSpec | NoneDefault: NoneSee the operation contract and implementation below.
Returnstuple[Tensor, tuple[ResidualTerm, ...]]
Explicit validation & failure cases
  • When space.window is None, raises ValueError('weak_residual needs a box window').

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

Executed regression · g2 boundary bound changes loss

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_g2_boundary_bound_changes_loss() -> None:
    torch.set_default_dtype(torch.float64)
    space = _space()
    op = WeakForm(diffusion=(1.0,), source=(2.0,))
    field = (0.0, 1.0, -1.0)  # x - x^2
    on = float(weak_loss(field, space, operator=op, include_boundary_bound=True))
    off = float(weak_loss(field, space, operator=op, include_boundary_bound=False))
    assert on != off
    bound = boundary_bound(space, deriv_bound=1.0)
    assert bound.hi > 0.0
python -m pytest "packages/omnibias-fields/tests/test_weak.py::test_g2_boundary_bound_changes_loss" -q
Regression example · path recording quadrature for callable source

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_path_recording_quadrature_for_callable_source() -> None:
    torch.set_default_dtype(torch.float64)
    space = _space()
    op = WeakForm(diffusion=(1.0,))
    quad = gauss_legendre(((0.0, 1.0),), 8)

    def source(x: torch.Tensor) -> torch.Tensor:
        return torch.sin(math.pi * x.reshape(-1)).reshape(x.shape)

    _res, terms = weak_residual(
        (0.0, 1.0, -1.0), space, operator=op, source=source, quadrature=quad
    )
    load_paths = {t.path for t in terms if t.name.startswith("load")}
    stiff_paths = {t.path for t in terms if t.name.startswith("stiffness")}
    assert "quadrature" in load_paths
    assert "exact" in stiff_paths
python -m pytest packages/omnibias-fields/tests/test_weak.py -k test_path_recording_quadrature_for_callable_source -q
Read the implementation
def weak_residual(
    field: Callable[[Tensor], Tensor] | tuple[float, ...],
    space: TestFunctionSpace,
    *,
    operator: WeakForm,
    source: Callable[[Tensor], Tensor] | tuple[float, ...] | None = None,
    quadrature: QuadratureSpec | None = None,
) -> tuple[Tensor, tuple[ResidualTerm, ...]]:
    """Assemble ``r(v_i)`` for every test function.

    Polynomial ``source`` / ``operator.diffusion`` on a box use the exact
    antiderivative path. A callable field falls back to quadrature on the
    coefficient factor only. Each term records ``exact`` or ``quadrature``.
    """
    if space.window is None:
        raise ValueError("weak_residual needs a box window")
    src = operator.source if source is None else source
    n = space.size
    values = []
    terms: list[ResidualTerm] = []
    sample = torch.zeros((), dtype=torch.get_default_dtype())
    dt = sample.dtype
    device = sample.device
    for i in range(n):
        stiffness, stiff_path = _stiffness_term(
            field, space, i, operator.diffusion, quadrature, dt, device
        )
        load, load_path = _load_term(src, space, i, quadrature, dt, device)
        r = stiffness - load
        values.append(r)
        terms.append(ResidualTerm(f"stiffness[{i}]", stiff_path, stiffness))
        terms.append(ResidualTerm(f"load[{i}]", load_path, load))
    stacked = torch.stack(values)
    return stacked, tuple(terms)