CodeSampleX

Пример

numba 0.67.0rc1: guvectorize

Проверенный пример — pypi numba 0.67.0rc1: guvectorize. Контракт выполнен на python 3.12 · linux debian/x64 · docker и пройден.

sha256:1b6a1fec598fd0115ab2be8b625156617399eff4ebbfb19e6f401139e2ffe906

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 pip

Среды запусков проверки

Окружение Контракт Этапы Запуск
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-02

Кейс

HOW
Цель
verify numba.guvectorize in pkg:pypi/numba@0.67.0rc1
Пакеты
Символы
  • numba.guvectorize
Создан
2026-09-02T13:14:27Z

Контракт

  1. assert guvectorize with explicit signatures performs 1D vector addition and broadcasts across 2D arrays
  2. assert guvectorize with reduction layout computes sum reduction over 1D and 2D arrays
  3. assert guvectorize with matrix-vector signature computes matrix-vector products
  4. assert guvectorize dynamically compiles layout function with explicit output buffer argument
  5. assert guvectorize with explicit signatures raises TypeError when called with incompatible argument types

Файлы

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • requirements.txt
  • spec.json
  • test/contract.py

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify numba.guvectorize in pkg:pypi/numba@0.67.0rc1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/numba@0.67.0rc1
Demonstrate these symbols/APIs:
  - numba.guvectorize
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:98bb5813a13ce793eed9cb59b23fc4cbd7f1f0a6a5c38ab2e3ae5826954f97aa","contract":["assert guvectorize with explicit signatures performs 1D vector addition and broadcasts across 2D arrays","assert guvectorize with reduction layout computes sum reduction over 1D and 2D arrays","assert guvectorize with matrix-vector signature computes matrix-vector products","assert guvectorize dynamically compiles layout function with explicit output buffer argument","assert guvectorize with explicit signatures raises TypeError when called with incompatible argument types"],"goal":"verify numba.guvectorize in pkg:pypi/numba@0.67.0rc1","kind":"HOW","packages":["pkg:pypi/numba@0.67.0rc1"],"schemaVersion":1,"symbols":["numba.guvectorize"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/numba@0.67.0rc1"],"schemaVersion":1,"subject":"pkg:pypi/numba@0.67.0rc1","symbols":["numba.guvectorize"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-numba-guvectorize"
version = "0.1.0"
dependencies = [
    "llvmlite==0.49.0",
    "numba==0.67.0rc1",
    "numpy==2.5.2",
]
requirements.txt
--pre
llvmlite==0.49.0
numba==0.67.0rc1
numpy==2.5.2
spec.json
{
  "schemaVersion": 1,
  "goal": "verify numba.guvectorize in pkg:pypi/numba@0.67.0rc1",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/numba@0.67.0rc1"
  ],
  "symbols": [
    "numba.guvectorize"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.py
import numpy as np
import numba
from numba import guvectorize, int64, float64


def test_guvectorize_explicit_signatures():
    @guvectorize([(int64[:], int64[:], int64[:]), (float64[:], float64[:], float64[:])], '(n),(n)->(n)')
    def gu_add(a, b, out):
        for i in range(a.shape[0]):
            out[i] = a[i] + b[i]

    # 1D vector addition
    a = np.array([1, 2, 3], dtype=np.int64)
    b = np.array([4, 5, 6], dtype=np.int64)
    res = gu_add(a, b)
    assert isinstance(res, np.ndarray)
    assert np.array_equal(res, np.array([5, 7, 9], dtype=np.int64))

    # Broadcasting over 2D array
    a_2d = np.array([[1, 2], [3, 4]], dtype=np.int64)
    b_2d = np.array([[10, 20], [30, 40]], dtype=np.int64)
    res_2d = gu_add(a_2d, b_2d)
    assert res_2d.shape == (2, 2)
    assert np.array_equal(res_2d, np.array([[11, 22], [33, 44]], dtype=np.int64))


def test_guvectorize_reduction_layout():
    @guvectorize([(float64[:], float64[:])], '(n)->()')
    def gu_sum(a, out):
        s = 0.0
        for i in range(a.shape[0]):
            s += a[i]
        out[0] = s

    # 1D array reduction to scalar
    arr_1d = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float64)
    res_1d = gu_sum(arr_1d)
    assert np.isclose(res_1d, 10.0)

    # 2D array reduction along axis
    arr_2d = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=np.float64)
    res_2d = gu_sum(arr_2d)
    assert res_2d.shape == (3,)
    assert np.allclose(res_2d, np.array([3.0, 7.0, 11.0]))


def test_guvectorize_matrix_vector():
    @guvectorize([(float64[:,:], float64[:], float64[:])], '(m,n),(n)->(m)')
    def gu_matvec(A, x, out):
        for i in range(A.shape[0]):
            s = 0.0
            for j in range(A.shape[1]):
                s += A[i, j] * x[j]
            out[i] = s

    mat = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float64)
    vec = np.array([5.0, 6.0], dtype=np.float64)
    res = gu_matvec(mat, vec)
    assert res.shape == (2,)
    assert np.allclose(res, np.array([17.0, 39.0]))


def test_guvectorize_dynamic_compilation():
    @guvectorize('(n)->()')
    def gu_mean(a, out):
        s = 0.0
        for i in range(a.shape[0]):
            s += a[i]
        out[0] = s / a.shape[0]

    arr = np.array([1.0, 2.0, 3.0, 4.0, 5.0], dtype=np.float64)
    out_scalar = np.zeros(())
    gu_mean(arr, out_scalar)
    assert np.isclose(out_scalar, 3.0)


def test_guvectorize_type_error():
    @guvectorize([(int64[:], int64[:], int64[:])], '(n),(n)->(n)')
    def gu_int_add(a, b, out):
        for i in range(a.shape[0]):
            out[i] = a[i] + b[i]

    try:
        gu_int_add("invalid", "string")
        assert False, "Should have raised TypeError"
    except TypeError as e:
        assert isinstance(e, TypeError)


def main():
    test_guvectorize_explicit_signatures()
    test_guvectorize_reduction_layout()
    test_guvectorize_matrix_vector()
    test_guvectorize_dynamic_compilation()
    test_guvectorize_type_error()
    print("All guvectorize contract assertions passed.")


if __name__ == "__main__":
    main()

Исходный сидер

аноним