feat(pipekit-array): check_positive and check_count, the positivity and count checks five libraries write for themselves

Abierto Apto para principiantes
#296 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
78/100
Tipo de issue
Nueva funcionalidad
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
numpy, python
Área
backend, testing

Línea de trabajo

Empieza con packages/pipekit-array/src/pipekit_array/arrays/_checks.py y la implementación existente de check_values; después, lee sus exportaciones en arrays/__init__.py y las pruebas en packages/pipekit-array/tests/arrays/test_checks.py. Añade las dos comprobaciones públicas según los contratos propuestos, incluidas las comprobaciones de positividad con trazas y la validación de recuentos enteros. El trabajo estará terminado cuando la API esté exportada y pasen los casos indicados para valores concretos, con trazas y con límites mínimos.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

area:code layer:0-primitives priority:p2 type:feature

Problem / Request

Add two checks to pipekit_array.arrays, next to check_values.
check_positive refuses values that are not > 0 (or ≥ 0), and check_count refuses an integer argument below a minimum.
plumax, sesmax-core, argminax, integrix, functax and tracerax each have their own copy, and the copies disagree on what they accept and return.

User Story

As a GeoStack library author, I want one positivity check that works under jit and one count check, so that every library refuses arguments alike.

Motivation

The positivity copies differ under a trace: plumax's require_positive skips the check, so jax.jit lets −1.0 through silently, where check_values raises.

# verified: plumax .venv, x64, CPU, 26 Nov 2026 (plumax 20c923b, pipekit-array 0.2.0)
import jax, jax.numpy as jnp
from pipekit_array.arrays import check_values
from plumax._src.tracing import require_positive

def skipped(z):
    require_positive("z0", z)  # traced: the check is skipped
    return z

def checked(z):
    return check_values(z, ~jnp.all(z > 0.0), "'z0' must be > 0")  # traced: equinox.error_if

print("require_positive under jit:", jax.jit(skipped)(-1.0))
try:
    jax.jit(checked)(-1.0)
except Exception as error:
    print("check_values under jit:", type(error).__name__)
# require_positive under jit: -1.0
# check_values under jit: JaxRuntimeError

The count copies differ on NumPy integers, on the error class and on what they return:

# verified: plumax .venv (each library's main on PYTHONPATH), x64, CPU, 26 Nov 2026
import numpy as np
from argminax._src.curvature._matfree import _require_count
from functax._src.geometry._sphere_grids import _check_count
from integrix._src.adjoint._scan import positive_count
from tracerax._src._validate import check_count

checks = {
    "tracerax check_count": check_count,
    "integrix positive_count": positive_count,
    "functax _check_count": _check_count,
    "argminax _require_count": lambda v, n: _require_count(v, n, minimum=1),
}
for name, check in checks.items():
    row = []
    for value in (3, np.int64(3), True, 0, 2.0):
        try:
            row.append(repr(check(value, "n")))
        except Exception as error:
            row.append(type(error).__name__)
    print(f"{name:26s}", " | ".join(row))
Copy 3 np.int64(3) True 0 2.0
tracerax check_count None None ValidationError ValidationError ValidationError
integrix positive_count 3 3 ValidationError ValidationError ValidationError
functax _check_count 3 3 GeometryError GeometryError GeometryError
argminax _require_count None ValidationError ValidationError ValidationError ValidationError

Design Snapshot

The copies, at each repo's main:

Library Symbol File @ commit Calls Contract
plumax require_positive src/plumax/_src/tracing.py:27 @ 20c923b about 100 skips traced values; NaN fails; allow_zero, error=
sesmax-core require_positive packages/sesmax-core/src/sesmax_core/_src/_validation.py:14 @ e138224 20 eager floats only; keyword values; finite required
argminax require_positive src/argminax/_src/blr/_optax.py:40 @ 3a42cc7 7 eager; NaN fails
tracerax check_count src/tracerax/_src/_validate.py:45 @ b7a9ea9 11 Python or NumPy int; returns None
integrix positive_count src/integrix/_src/adjoint/_scan.py:14 @ f94228f 2 operator.index; returns the int
functax _check_count src/functax/_src/geometry/_sphere_grids.py:54 @ acb5e30 7 operator.index; returns the int; GeometryError
argminax _require_count src/argminax/_src/curvature/_matfree.py:43 @ 3a42cc7 3 Python int only; minimum=

plumax's copy, the one with the traced behaviour:

# today (plumax), tracing.py:60-69
if _is_traced(value):
    return
array = np.asarray(value)
ok = np.all(array >= 0.0) if allow_zero else np.all(array > 0.0)
if bool(ok):
    return
bound = "≥ 0" if allow_zero else "> 0"
prefix = f"{caller}: " if caller else ""
raise error(f"{prefix}`{name}` must be {bound} (got {value!r})")

Proposed API

# proposed (pipekit_array.arrays)
def check_positive(
    array: Any,
    name: str,
    *,
    allow_zero: bool = False,
    error: type[Exception] = ValueError,
) -> Any:
    """``array``, or an error unless every element is > 0 (≥ 0 with ``allow_zero``).

    NaN fails. On concrete arrays (NumPy, JAX, Python numbers, nested sequences)
    it raises ``error`` at once; on traced ones it is `check_values`, so the
    check rides on the returned array under ``jax.jit``.
    """

def check_count(
    value: Any,
    name: str,
    *,
    minimum: int = 1,
    error: type[Exception] = ValueError,
) -> int:
    """``value`` as a Python int, or ``error`` unless it is an integer ≥ ``minimum``.

    Python and NumPy integers pass (``operator.index``); bools, floats and
    traced values fail.
    """
# usage
# proposed (pipekit_array): z₀ > 0, under jit too
roughness = check_positive(roughness, "z0", error=ParameterError)
# proposed (pipekit_array): N ≥ 1
n_particles = check_count(n_particles, "n_particles", error=ValidationError)

Recommended: check_count returns the int (as integrix and functax do), so callers can use the cast value; NumPy integers pass, as in three of the four copies.
Alternative: return None, as tracerax and argminax do; callers then keep the value they passed.

Mathematical Notes

None: both checks are comparisons.
The one invariant is that check_positive(x, ...) under jax.jit returns x unchanged when every element is > 0, and raises at run time otherwise.

References & Existing Code

  • Design doc / spec: check_values in packages/pipekit-array/src/pipekit_array/arrays/_checks.py:24 @ 94c766d (jejjohnson/pipekit#278), whose traced path this reuses
  • Reference impl: plumax require_positive (above), integrix positive_count
  • Related prior art: the open pipekit issues have no issue about these checks (searched 26 Nov 2026)

Implementation Steps

  • Add check_positive and check_count in packages/pipekit-array/src/pipekit_array/arrays/_checks.py
  • Export them from packages/pipekit-array/src/pipekit_array/arrays/__init__.py and list them under "Checks" in its docstring
  • Tests in packages/pipekit-array/tests/arrays/test_checks.py

Definition of Done

  • Code lands at the intended path
  • Public API exported via pipekit_array.arrays
  • Tests pass: make test
  • Lint + typecheck pass: make lint && make typecheck
  • Docstrings (Google-style) on all public symbols

Testing

  • Unit test: check_positive raises error on 0, −1 and NaN, passes 0 with allow_zero, and accepts a tuple of numbers
  • Unit test: under jax.jit, check_positive raises at run time on −1 and returns the array on 1
  • Unit test: check_count gives the row 3 | 3 | error | error | error for the five inputs of the table, and honours minimum

Documentation

  • API reference page / section
  • Notebook or recipe (if user-facing flow): N/A
  • Docstrings (covered by Definition of Done)

Relationships

  • Parent (theme epic): jejjohnson/geostack#326
  • Blocked by: none
  • Blocks: the adoption in each library (plumax jejjohnson/plumax#424 and jejjohnson/plumax#427 take the traced half today; plumax, sesmax-core, argminax, integrix, functax and tracerax switch once this is released)
  • Related: jejjohnson/pipekit#278 (check_values)
Lenguaje dominante
Python
Estrellas
0
Forks
0
Merge medio
3 h 50 min
PR fusionados (30 d)
143

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de jejjohnson/pipekit

Todos los issues de jejjohnson/pipekit

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.