Skip to main content

omnibias.fields.torch.ops.vector

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

Vector ops: curl, vorticity, strain_rate, deformation_gradient.

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

curl​

omnibias.fields.torch.ops.curlSource ↗
curl(state: FieldState, names: tuple[str, ...]) -> Tensor

nabla x u of a 3D vector field, shape (B, 3).

For 2D this returns the *scalar* curl omega = du2/dx1 - du1/dx2 of shape (B, 1). For 1D it raises (curl is not defined).

The vector names length must equal the number of spatial axes.

Parameters

NameType & defaultContract
statepositional-or-keywordFieldStateRequiredSee the operation contract and implementation below.
namespositional-or-keywordtuple[str, ...]RequiredSee the operation contract and implementation below.
ReturnsTensor
Explicit validation & failure cases
  • When len(names) != len(sa), raises ValueError(f'curl: vector length {len(names)} must equal n_spatial {len(sa)} ({sa!r})').
  • When len(sa) == 1, raises ValueError('curl is not defined for 1D vector fields; use derivative instead').

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

Executed regression · div rot aliases

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_div_rot_aliases():
    nodes = _nodes(3)
    st = _state("torch", "3d", nodes)
    assert np.allclose(
        _np(st.ops.div(st, ("u", "v", "w"))),
        _np(st.ops.divergence(st, ("u", "v", "w"))),
        rtol=1e-12, atol=1e-12,
    )
    assert np.allclose(
        _np(st.ops.rot(st, ("u", "v", "w"))),
        _np(st.ops.curl(st, ("u", "v", "w"))),
        rtol=1e-12, atol=1e-12,
    )
python -m pytest "packages/omnibias-fields/tests/test_vector_calculus.py::test_div_rot_aliases" -q
Read the implementation
def curl(state: FieldState, names: tuple[str, ...]) -> Tensor:
    """``nabla x u`` of a 3D vector field, shape ``(B, 3)``.

    For 2D this returns the *scalar* curl ``omega = du2/dx1 - du1/dx2``
    of shape ``(B, 1)``. For 1D it raises (curl is not defined).

    The vector ``names`` length must equal the number of spatial axes.
    """
    sa = state.coordinate_spec.spatial_axes
    if len(names) != len(sa):
        raise ValueError(
            f"curl: vector length {len(names)} must equal n_spatial {len(sa)} "
            f"({sa!r})"
        )
    if len(sa) == 1:
        raise ValueError(
            "curl is not defined for 1D vector fields; use derivative instead"
        )
    if len(sa) == 2:
        u, v = names
        x_axis, y_axis = sa[0], sa[1]
        cz = derivative(state, v, axis=x_axis) - derivative(state, u, axis=y_axis)
        return cz.unsqueeze(-1)                            # (B, 1)
    if len(sa) == 3:
        u, v, w = names
        x_axis, y_axis, z_axis = sa[0], sa[1], sa[2]
        cx = derivative(state, w, axis=y_axis) - derivative(state, v, axis=z_axis)
        cy = derivative(state, u, axis=z_axis) - derivative(state, w, axis=x_axis)
        cz = derivative(state, v, axis=x_axis) - derivative(state, u, axis=y_axis)
        return torch.stack([cx, cy, cz], dim=-1)            # (B, 3)
    raise ValueError(
        f"curl supported for 2D / 3D vector fields, got {len(sa)} spatial axes"
    )
Other public import paths
  • omnibias.fields.torch.ops.curl
  • omnibias.fields.torch.ops.vector.curl
FUNCTION

curl_of_curl​

omnibias.fields.torch.ops.curl_of_curlSource ↗
curl_of_curl(state: FieldState, names: tuple[str, ...]) -> Tensor

\nabla\times(\nabla\times u) for 2D / 3D vector fields.

Expanded directly from second partials (not via the identity), so a test can independently assert curl_of_curl == gradient_of_divergence - vector_laplacian.

Parameters

NameType & defaultContract
statepositional-or-keywordFieldStateRequiredSee the operation contract and implementation below.
namespositional-or-keywordtuple[str, ...]RequiredSee the operation contract and implementation below.
ReturnsTensor
Explicit validation & failure cases
  • When len(names) != len(sa), raises ValueError(f'curl_of_curl: vector length {len(names)} must equal n_spatial {len(sa)} ({sa!r})').

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

Executed regression · cross backend bit parity

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_cross_backend_bit_parity(which, opfn):
    nodes = _nodes(2 if which == "2d" else 3, seed=7)
    ts = _state("torch", which, nodes)
    js = _state("jax", which, nodes)
    t = _np(opfn(ts.ops, ts))
    j = _np(opfn(js.ops, js))
    assert np.allclose(t, j, rtol=1e-12, atol=1e-12)
python -m pytest "packages/omnibias-fields/tests/test_vector_calculus.py::test_cross_backend_bit_parity[2d-<lambda>]" -q
Read the implementation
def curl_of_curl(state: FieldState, names: tuple[str, ...]) -> Tensor:
    r""":math:`\nabla\times(\nabla\times u)` for 2D / 3D vector fields.

    Expanded directly from second partials (not via the identity), so a test can
    independently assert ``curl_of_curl == gradient_of_divergence - vector_laplacian``.
    """
    sa = state.coordinate_spec.spatial_axes
    if len(names) != len(sa):
        raise ValueError(
            f"curl_of_curl: vector length {len(names)} must equal n_spatial "
            f"{len(sa)} ({sa!r})"
        )
    if len(sa) == 2:
        u, v = names
        x, y = sa
        s_y = mixed_partial(state, v, (x, y), (1, 1)) - derivative(state, u, axis=y, order=2)
        s_x = derivative(state, v, axis=x, order=2) - mixed_partial(state, u, (x, y), (1, 1))
        return torch.stack([s_y, -s_x], dim=-1)
    if len(sa) == 3:
        u, v, w = names
        x, y, z = sa
        ccx = (
            mixed_partial(state, v, (x, y), (1, 1)) + mixed_partial(state, w, (x, z), (1, 1))
            - derivative(state, u, axis=y, order=2) - derivative(state, u, axis=z, order=2)
        )
        ccy = (
            mixed_partial(state, w, (y, z), (1, 1)) + mixed_partial(state, u, (x, y), (1, 1))
            - derivative(state, v, axis=z, order=2) - derivative(state, v, axis=x, order=2)
        )
        ccz = (
            mixed_partial(state, u, (x, z), (1, 1)) + mixed_partial(state, v, (y, z), (1, 1))
            - derivative(state, w, axis=x, order=2) - derivative(state, w, axis=y, order=2)
        )
        return torch.stack([ccx, ccy, ccz], dim=-1)
    raise ValueError(
        f"curl_of_curl supported for 2D / 3D vector fields, got {len(sa)} spatial axes"
    )
Other public import paths
  • omnibias.fields.torch.ops.curl_of_curl
  • omnibias.fields.torch.ops.vector.curl_of_curl
FUNCTION

deformation_gradient​

omnibias.fields.torch.ops.deformation_gradientSource ↗
deformation_gradient(state: FieldState, names: tuple[str, ...]) -> Tensor

Spatial gradient tensor J[b,i,j] = du_i / dx_j of shape (B, C, n_spatial).

This is the standard "deformation gradient" used in continuum mechanics. For an incompressible flow the trace equals \nabla \cdot u = 0.

Parameters

NameType & defaultContract
statepositional-or-keywordFieldStateRequiredSee the operation contract and implementation below.
namespositional-or-keywordtuple[str, ...]RequiredSee the operation contract and implementation below.
ReturnsTensor
Explicit validation & failure cases
  • When len(names) != len(sa), raises ValueError(f'deformation_gradient: vector length {len(names)} must equal n_spatial {len(sa)} ({sa!r})').

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

Executed regression · cross backend bit parity

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_cross_backend_bit_parity(which, opfn):
    nodes = _nodes(2 if which == "2d" else 3, seed=7)
    ts = _state("torch", which, nodes)
    js = _state("jax", which, nodes)
    t = _np(opfn(ts.ops, ts))
    j = _np(opfn(js.ops, js))
    assert np.allclose(t, j, rtol=1e-12, atol=1e-12)
python -m pytest "packages/omnibias-fields/tests/test_vector_calculus.py::test_cross_backend_bit_parity[3d-<lambda>2]" -q
Read the implementation
def deformation_gradient(state: FieldState, names: tuple[str, ...]) -> Tensor:
    """Spatial gradient tensor ``J[b,i,j] = du_i / dx_j`` of shape ``(B, C, n_spatial)``.

    This is the standard "deformation gradient" used in continuum
    mechanics. For an incompressible flow the trace equals
    :math:`\\nabla \\cdot u = 0`.
    """
    sa = state.coordinate_spec.spatial_axes
    if len(names) != len(sa):
        raise ValueError(
            f"deformation_gradient: vector length {len(names)} must equal "
            f"n_spatial {len(sa)} ({sa!r})"
        )
    return spatial_jacobian(state, names)
Other public import paths
  • omnibias.fields.torch.ops.deformation_gradient
  • omnibias.fields.torch.ops.vector.deformation_gradient
FUNCTION

gradient_of_divergence​

omnibias.fields.torch.ops.gradient_of_divergenceSource ↗
gradient_of_divergence(state: FieldState, names: tuple[str, ...]) -> Tensor

\nabla(\nabla\cdot u), shape (B, d).

Component i is \sum_j \partial^2_{ij} u_j.

Parameters

NameType & defaultContract
statepositional-or-keywordFieldStateRequiredSee the operation contract and implementation below.
namespositional-or-keywordtuple[str, ...]RequiredSee the operation contract and implementation below.
ReturnsTensor
Explicit validation & failure cases
  • When len(names) != len(sa), raises ValueError(f'gradient_of_divergence: vector length {len(names)} must equal n_spatial {len(sa)} ({sa!r})').

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

Executed regression · cross backend bit parity

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_cross_backend_bit_parity(which, opfn):
    nodes = _nodes(2 if which == "2d" else 3, seed=7)
    ts = _state("torch", which, nodes)
    js = _state("jax", which, nodes)
    t = _np(opfn(ts.ops, ts))
    j = _np(opfn(js.ops, js))
    assert np.allclose(t, j, rtol=1e-12, atol=1e-12)
python -m pytest "packages/omnibias-fields/tests/test_vector_calculus.py::test_cross_backend_bit_parity[3d-<lambda>0]" -q
Read the implementation
def gradient_of_divergence(state: FieldState, names: tuple[str, ...]) -> Tensor:
    r""":math:`\nabla(\nabla\cdot u)`, shape ``(B, d)``.

    Component ``i`` is :math:`\sum_j \partial^2_{ij} u_j`.
    """
    sa = state.coordinate_spec.spatial_axes
    if len(names) != len(sa):
        raise ValueError(
            f"gradient_of_divergence: vector length {len(names)} must equal "
            f"n_spatial {len(sa)} ({sa!r})"
        )
    cols = []
    for i in sa:
        acc = None
        for n, j in zip(names, sa, strict=False):
            term = mixed_partial(state, n, (i, j), (1, 1))
            acc = term if acc is None else acc + term
        cols.append(acc)
    return torch.stack(cols, dim=-1)
Other public import paths
  • omnibias.fields.torch.ops.gradient_of_divergence
  • omnibias.fields.torch.ops.vector.gradient_of_divergence
FUNCTION

rate_of_rotation_tensor​

omnibias.fields.torch.ops.rate_of_rotation_tensorSource ↗
rate_of_rotation_tensor(state: FieldState, names: tuple[str, ...]) -> Tensor

Antisymmetric velocity-gradient (spin) tensor W = \tfrac12(J - J^T).

Complement of strain_rate; together J = strain_rate + rate_of_rotation_tensor.

Parameters

NameType & defaultContract
statepositional-or-keywordFieldStateRequiredSee the operation contract and implementation below.
namespositional-or-keywordtuple[str, ...]RequiredSee the operation contract and implementation below.
ReturnsTensor
Explicit validation & failure cases
  • When J.shape[-2] != J.shape[-1], raises ValueError(f'rate_of_rotation_tensor requires square Jacobian; got shape {tuple(J.shape)}').

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

Executed regression · cross backend bit parity

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_cross_backend_bit_parity(which, opfn):
    nodes = _nodes(2 if which == "2d" else 3, seed=7)
    ts = _state("torch", which, nodes)
    js = _state("jax", which, nodes)
    t = _np(opfn(ts.ops, ts))
    j = _np(opfn(js.ops, js))
    assert np.allclose(t, j, rtol=1e-12, atol=1e-12)
python -m pytest "packages/omnibias-fields/tests/test_vector_calculus.py::test_cross_backend_bit_parity[3d-<lambda>2]" -q
Read the implementation
def rate_of_rotation_tensor(state: FieldState, names: tuple[str, ...]) -> Tensor:
    r"""Antisymmetric velocity-gradient (spin) tensor :math:`W = \tfrac12(J - J^T)`.

    Complement of :func:`strain_rate`; together ``J = strain_rate + rate_of_rotation_tensor``.
    """
    J = deformation_gradient(state, names)
    if J.shape[-2] != J.shape[-1]:
        raise ValueError(
            f"rate_of_rotation_tensor requires square Jacobian; got shape {tuple(J.shape)}"
        )
    return 0.5 * (J - J.transpose(-1, -2))
Other public import paths
  • omnibias.fields.torch.ops.rate_of_rotation_tensor
  • omnibias.fields.torch.ops.vector.rate_of_rotation_tensor
FUNCTION

spatial_jacobian​

omnibias.fields.torch.ops.spatial_jacobianSource ↗
spatial_jacobian(state: FieldState, names: tuple[str, ...]) -> Tensor

Spatial Jacobian J[b,i,j] = d f_i / dx_j of shape (B, C, n_spatial).

Unlike deformation_gradient, this accepts any number of components; it is useful for multi-output scalar stacks as well as physical vector fields.

Parameters

NameType & defaultContract
statepositional-or-keywordFieldStateRequiredSee the operation contract and implementation below.
namespositional-or-keywordtuple[str, ...]RequiredSee the operation contract and implementation below.
ReturnsTensor
Executed regression · cross backend bit parity

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_cross_backend_bit_parity(which, opfn):
    nodes = _nodes(2 if which == "2d" else 3, seed=7)
    ts = _state("torch", which, nodes)
    js = _state("jax", which, nodes)
    t = _np(opfn(ts.ops, ts))
    j = _np(opfn(js.ops, js))
    assert np.allclose(t, j, rtol=1e-12, atol=1e-12)
python -m pytest "packages/omnibias-fields/tests/test_vector_calculus.py::test_cross_backend_bit_parity[3d-<lambda>2]" -q
Read the implementation
def spatial_jacobian(state: FieldState, names: tuple[str, ...]) -> Tensor:
    """Spatial Jacobian ``J[b,i,j] = d f_i / dx_j`` of shape ``(B, C, n_spatial)``.

    Unlike :func:`deformation_gradient`, this accepts any number of
    components; it is useful for multi-output scalar stacks as well as
    physical vector fields.
    """
    rows = [gradient(state, n) for n in names]
    return torch.stack(rows, dim=-2)
Other public import paths
  • omnibias.fields.torch.ops.spatial_jacobian
  • omnibias.fields.torch.ops.vector.spatial_jacobian
FUNCTION

strain_rate​

omnibias.fields.torch.ops.strain_rateSource ↗
strain_rate(state: FieldState, names: tuple[str, ...]) -> Tensor

Symmetric strain-rate S = 0.5 (J + J^T) of shape (B, C, C).

Requires len(names) == n_spatial. This is the symmetric part of the deformation gradient.

Parameters

NameType & defaultContract
statepositional-or-keywordFieldStateRequiredSee the operation contract and implementation below.
namespositional-or-keywordtuple[str, ...]RequiredSee the operation contract and implementation below.
ReturnsTensor
Explicit validation & failure cases
  • When J.shape[-2] != J.shape[-1], raises ValueError(f'strain_rate requires square Jacobian; got shape {tuple(J.shape)}').

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

Executed regression · tensor double dot value and dissipation sign

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_tensor_double_dot_value_and_dissipation_sign():
    nodes = _nodes(3)
    st = _state("torch", "3d", nodes)
    S = st.ops.strain_rate(st, ("u", "v", "w"))
    dd = _np(st.ops.tensor_double_dot(S, S))
    assert np.allclose(dd, (_np(S) ** 2).sum(axis=(-2, -1)), rtol=1e-12, atol=1e-12)
    assert np.all(dd >= 0.0)  # S:S is a sum of squares
python -m pytest "packages/omnibias-fields/tests/test_vector_calculus.py::test_tensor_double_dot_value_and_dissipation_sign" -q
Read the implementation
def strain_rate(state: FieldState, names: tuple[str, ...]) -> Tensor:
    """Symmetric strain-rate ``S = 0.5 (J + J^T)`` of shape ``(B, C, C)``.

    Requires ``len(names) == n_spatial``. This is the symmetric part of
    the deformation gradient.
    """
    J = deformation_gradient(state, names)                 # (B, C, n_spatial)
    if J.shape[-2] != J.shape[-1]:
        raise ValueError(
            f"strain_rate requires square Jacobian; got shape {tuple(J.shape)}"
        )
    return 0.5 * (J + J.transpose(-1, -2))
Other public import paths
  • omnibias.fields.torch.ops.strain_rate
  • omnibias.fields.torch.ops.vector.strain_rate
FUNCTION

vorticity​

omnibias.fields.torch.ops.vorticitySource ↗
vorticity(state: FieldState, names: tuple[str, ...]) -> Tensor

Alias for curl -- vorticity omega = nabla x velocity.

Parameters

NameType & defaultContract
statepositional-or-keywordFieldStateRequiredSee the operation contract and implementation below.
namespositional-or-keywordtuple[str, ...]RequiredSee the operation contract and implementation below.
ReturnsTensor
Read the implementation
def vorticity(state: FieldState, names: tuple[str, ...]) -> Tensor:
    """Alias for :func:`curl` -- vorticity ``omega = nabla x velocity``."""
    return curl(state, names)
Other public import paths
  • omnibias.fields.torch.ops.vorticity
  • omnibias.fields.torch.ops.vector.vorticity