Skip to content

Checked against NumPy

shaperules does not need NumPy to run. Its tests do. In the tests NumPy is the oracle: the reference whose answer is taken as correct. Every claim a rule makes is compared with what a real NumPy call does.

This page says what is compared, how, and on which versions. It ends with two things the oracle found while the library was being written.

>>> import shaperules as sr

What each answer claims

The three answers claim different things, so they are checked differently.

Answer Claim Check
Known(shape) NumPy succeeds and returns exactly this shape, for every assignment. The real call must succeed and return that shape, for every assignment tried.
Refused NumPy raises the named exception, for every assignment. The real call must raise an exception of that class, for every assignment tried.
Unknown Nothing. Nothing, except for its likely reading. See below.

An ANY in a Known shape matches any size on that axis. The number of axes must still be right.

The shape rules

The shape rules are property-tested with Hypothesis, a library that generates test inputs. The machinery is in tests/oracle.py and the tests are in tests/test_shape_rules.py.

One test run goes like this:

  1. Hypothesis draws shapes whose sizes are formulas over three names, k, m and n. A size is an integer from 0 to 4, a name, or a small formula: n+2, n-1, 3*n, 2*n+1, (n+1)//2, n//3+1, n*m, n+m.
  2. The test asks the rule and keeps its answer.
  3. For every assignment of the sizes 0, 1, 2 and 3 to the names, the test turns the formulas into integers, builds real arrays of those shapes and makes the NumPy call.
  4. The rule's answer is held against each real result, as in the table above.

Sizes 0 to 3 are few, and they are the ones that matter. Shape rules have their special cases at 0 and 1, and with three names every pattern of equal and unequal names occurs. An assignment that makes a formula negative is skipped, since no array has that shape. So is one that makes a size larger than 12.

A drawn size can also be a hidden name. The rule is given ANY in its place, and the oracle gives the hidden name every size. This checks that a rule claims nothing about a size it was told nothing about.

When every size drawn is an integer, the test also requires that the answer is not Unknown. A rule has no excuse for doubt when it was told everything.

Each rule is checked against this call:

Rule NumPy call
broadcast np.broadcast_shapes(*shapes)
matmul np.matmul(a, b)
reduce np.sum(a, axis=axis, keepdims=keepdims)
reduce with needs_elements=True np.max(a, axis=axis, keepdims=keepdims)
arg_reduce np.argmax(a, axis=axis, keepdims=keepdims)
cumulative np.cumsum(a, axis=axis)
transpose np.transpose(a, axes)
swapaxes np.swapaxes(a, axis1, axis2)
moveaxis np.moveaxis(a, source, destination)
squeeze np.squeeze(a, axis=axis)
expand_dims np.expand_dims(a, axis)
reshape np.reshape(a, newshape), with no, one or two sizes of -1
concatenate np.concatenate(arrays, axis=axis)
stack np.stack(arrays, axis=axis)
index a[key], for keys of integers, slices, None and ...

Axes are drawn from a range wider than any shape drawn, so many of them are out of range. Axis arguments are drawn as None, as one integer and as a tuple, wherever NumPy takes all three. broadcast, matmul and index have a second test each on shapes of plain integers.

By default each test draws 400 examples, which keeps the suite to seconds. A long run draws more:

SHAPERULES_EXAMPLES=20000 uv run pytest

The likely reading

Unknown.likely is not a proof, so it cannot be checked for every assignment. It is checked where its assumptions hold: no name is 0 or 1, and no two names are equal. The test evaluates the shapes at k = 7, m = 8, n = 9 and makes the NumPy call. A likely refusal must be an exception of the named class. A likely shape must be the shape NumPy returns, when NumPy returns one.

Two cases are left out. The likely reading of a slice assumes the axis is longer than the bounds of the slice, whatever they are, so index is not checked this way. Shapes with a hidden name are not checked this way either.

The size algebra

Every rule rests on the arithmetic and the comparisons of sizes. These have their own property tests in tests/test_dims.py, checked for every assignment of the sizes 0 to 4 to the three names:

  • add, sub, mul and floordiv on formulas give the same number as the arithmetic on the values, unless they answer ANY.
  • The quotient of exact_div, times the divisor, is the dividend.
  • Where equal says yes, the values are equal for every assignment. Where unequal says yes, they differ for every assignment.
  • at_least, at_most and can_be hold for every assignment.
  • parse(fmt(size)) is the same size, and so is a form rebuilt from its repr.
  • substitute agrees with evaluating the formula.

The element types

There are few enough element types to try everything. tests/test_dtypes.py compares with NumPy exhaustively:

What Compared with How many
result_type of one operand, of two, and of three different ones, drawn from the fourteen types and the Python types int, float, complex, bool np.result_type 18, 324 and 4,896 calls
Promotion of four array types np.result_type 38,416 calls
can_cast np.can_cast(a, b, "safe") 196 pairs
ufunc_dtypes, every ufunc with every operand type, Python numbers included The ufunc, called on arrays of one element 13,702 calls on NumPy 2.5.5
reduce_dtype, every reduction with every element type The reduction, called on an array 224 calls

A refusal is checked like an answer: where the rule says Refused, NumPy must raise TypeError, and where NumPy raises TypeError, the rule must say Refused.

The tables

What a ufunc returns for its operand types is not computed by shaperules. It is read from src/shaperules/_tables.py, a file generated by tools/generate_tables.py. The generator asks the installed NumPy for every ufunc and every combination of operand types and writes the answers down. Design explains the choice.

A generated file can go stale. Two tests in tests/test_tables.py prevent that:

  • The generator is run again on the NumPy under test, and every ufunc and reduction that both the fresh tables and the shipped ones know must agree cell for cell. A ufunc that only one side knows is skipped, which lets the same file be tested on an older NumPy that lacks a newer ufunc.
  • On the NumPy version that produced the shipped tables, the shipped tables must cover exactly the ufuncs the generator finds.

So the tables cannot differ from a supported NumPy without a failing test.

Versions

CI runs the whole suite on these combinations:

Python NumPy
3.11 2.1
3.12 2.1
3.13 2.1
3.11 latest
3.13 latest
3.14 latest

NumPy 2.1 is the oldest version the tables describe, and the same tables have to agree with every version after it. NumPy 2.0 is left out for one difference the table test found on its first run in CI: there np.floor, np.ceil and np.trunc of an integer or boolean array return a float array, and from 2.1 on they return the array's own type.

A separate job builds the wheel, installs it into an environment with no NumPy, and asks it two questions. That is the check behind "no dependencies".

CI also runs ruff and mypy --strict on the package.

The examples

Every Python example in the README and on these pages is a doctest: a session of >>> lines with the expected output under them. pytest collects the Markdown files and runs them with the unit tests, so an example that stops being true fails the build.

What the oracle found

Two of the rules exist in their present form because the comparison with NumPy failed on the obvious version.

Promotion is not a pairwise fold

The obvious way to promote several element types is to promote the first two, then the result with the third, and so on. For two types the rule is well known. Folding it over a list looks safe.

The exhaustive comparison over triples says it is not. np.result_type of int8, uint8 and float16 is float16. Folding gives float32:

>>> from shaperules import dtypes

>>> dtypes.promote("int8", "uint8")
'int16'
>>> dtypes.promote("int16", "float16")
'float32'
>>> sr.result_type("int8", "uint8", "float16").value
'float16'

int8 and uint8 both fit in float16, so float16 holds all three. The fold loses that. It first widens the two integers to int16, and int16 does not fit in float16. The fold even depends on the order of the operands:

>>> dtypes.promote(dtypes.promote("int8", "float16"), "uint8")
'float16'

NumPy works the answer out over all the operands at once, and so does shaperules.dtypes.promote_all, which result_type uses. Of the 2,744 ordered triples of array types, the fold is wrong for 14:

>>> from itertools import product

>>> wrong = [
...     (a, b, c)
...     for a, b, c in product(sr.DTYPES, repeat=3)
...     if dtypes.promote(dtypes.promote(a, b), c) != dtypes.promote_all([a, b, c])
... ]
>>> len(wrong)
14
>>> wrong[0]
('int8', 'uint8', 'float16')

Fourteen in 2,744 is rare enough to survive a test that tries a handful of cases by hand. It does not survive a test that tries all of them.

Axis 0 of an array with no axes

An array with no axes has no axis 0. So axis=0 should be out of range for it, and that is what the axis check said at first.

The oracle disagreed. NumPy accepts a single axis=0 or axis=-1 for an array with no axes in np.sum, np.max, np.squeeze and np.argmax. The axis names nothing and the call succeeds. The same axis inside a tuple is out of range:

>>> import numpy as np

>>> scalar = np.zeros(())
>>> np.sum(scalar, axis=0).shape
()
>>> np.sum(scalar, axis=(0,))
Traceback (most recent call last):
    ...
numpy.exceptions.AxisError: axis 0 is out of bounds for array of dimension 0

The rules follow NumPy on both:

>>> sr.reduce((), axis=0)
Known(value=())
>>> sr.reduce((), axis=(0,)).refusal.raises
'AxisError'
>>> sr.squeeze((), axis=-1)
Known(value=())
>>> sr.arg_reduce((), axis=0)
Known(value=())

This is not a case one thinks of testing by hand. It was found because the test draws shapes with no axes, and axes of every small value, as a matter of course.

What this does not show

The comparison covers the sizes 0 to 3 for three names, on the NumPy versions in the table, on 64-bit Linux. A claim that fails only at larger sizes, or with more names, or on another platform, would not be caught. The rules are written to be proofs, and the tests are evidence for that, not a second proof.

The NumPy functions in the table are the ones each rule is held against. A function with the same shape rule that is not in the table has not been compared. Limitations names one place where that matters.