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

オープン 初心者向け
#296 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
78/100
issue の種類
機能追加
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
numpy, python
領域
backend, testing

調査の方向性

まず packages/pipekit-array/src/pipekit_array/arrays/_checks.py と既存の check_values の実装を確認し、次に arrays/__init__.py のエクスポートと packages/pipekit-array/tests/arrays/test_checks.py のテストを読みます。提案された契約に従って、2つの公開チェックを追加します。トレース付きの正値チェックと整数個数の検証も含めます。APIがエクスポートされ、記載された具体値、トレース付き、最小境界の各ケースが通れば完了です。

索引モデルが issue の本文から書いたものです。

説明

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)
主要言語
Python
スター
0
フォーク
0
平均マージ
3時間 50分
マージ済み PR(30日)
143

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

jejjohnson/pipekit のほかの issue

jejjohnson/pipekit の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。