Metadata-Version: 2.5
Name: shaperules
Version: 0.1.0
Summary: NumPy's shape and dtype rules as a small library: symbolic sizes, three honest answers, no NumPy needed.
Project-URL: Homepage, https://sofeikov.github.io/shaperules/
Project-URL: Documentation, https://sofeikov.github.io/shaperules/
Project-URL: Repository, https://github.com/sofeikov/shaperules
Project-URL: Issues, https://github.com/sofeikov/shaperules/issues
Author: sofeikov
License-Expression: MIT
License-File: LICENSE
Keywords: broadcasting,dtype,numpy,shape,static-analysis,symbolic
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown

# shaperules

[![CI](https://github.com/sofeikov/shaperules/actions/workflows/ci.yml/badge.svg)](https://github.com/sofeikov/shaperules/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/shaperules)](https://pypi.org/project/shaperules/)
![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)
![MIT licence](https://img.shields.io/badge/license-MIT-green)

NumPy's shape and dtype rules as a pure-Python library with no dependencies. Give a rule the shapes of the operands and it answers with the shape of the result, without NumPy installed and without running anything.

A size is an integer, a formula over names such as `n` or `2*n+1`, or unknown. Every rule answers one of three things:

- `Known(value)`: the result, proven for every value the names can take.
- `Refused(refusal)`: NumPy raises, for every value the names can take.
- `Unknown(reason, likely)`: it depends on sizes the rule was not told. `likely` is a best reading for a caller that wants one, and is not a proof.

```python
>>> import shaperules as sr

>>> sr.broadcast((8, 1, 3), (5, 3))
Known(value=(8, 5, 3))

>>> product = sr.matmul(("batch", "n", 64), (64, 10))
>>> sr.fmt_shape(product.value)
'(batch, n, 10)'

>>> refused = sr.matmul((2, 3), (4, 5))
>>> refused.refusal.kind, refused.refusal.raises
('matmul-core', 'ValueError')

>>> doubt = sr.broadcast(("n",), (3,))
>>> doubt.reason
'sizes at axis -1 must be equal or 1: n and 3'
>>> doubt.likely
Known(value=(3,))

```

The last call is valid when `n` is 3 or 1 and raises in NumPy otherwise, so nothing is proven. A caller that must agree with NumPy exactly acts on `Known` and `Refused` and asks NumPy for the rest. A caller such as a type checker can carry on with `likely`.

Element types (dtypes) work the same way:

```python
>>> sr.result_type("int8", "uint8").value
'int16'
>>> sr.result_type("float32", float).value
'float32'
>>> sr.ufunc_dtype("true_divide", "int32", "int32").value
'float64'
>>> sr.ufunc_dtype("subtract", "bool", "bool").refusal.raises
'TypeError'

```

Documentation: [sofeikov.github.io/shaperules](https://sofeikov.github.io/shaperules/)

## Install

```sh
pip install shaperules
```

```sh
uv add shaperules
```

It needs Python 3.11 or later and installs nothing else.

## What is covered

Version 0.1 covers these rules. Each one takes shapes or element types and answers with a shape, a size or an element type.

| Area | Rules | NumPy calls they stand for |
|---|---|---|
| Broadcasting | `broadcast`, `broadcast_pair`, `match_pair` | `np.broadcast_shapes`, and so the shape of any element-wise operation |
| Matrix product | `matmul` | `a @ b`, `np.matmul` |
| Reductions | `reduce`, `arg_reduce`, `cumulative` | `np.sum`, `np.prod`, `np.any`, `np.max`, `np.min`, `np.argmax`, `np.cumsum` and the like |
| Reordering axes | `transpose`, `swapaxes`, `moveaxis` | `a.T`, `np.transpose`, `np.swapaxes`, `np.moveaxis` |
| Adding and removing axes | `squeeze`, `expand_dims` | `np.squeeze`, `np.expand_dims` |
| Regrouping elements | `reshape` (with `-1`), `concatenate`, `stack` | `np.reshape`, `np.concatenate`, `np.stack` |
| Basic indexing | `index`, `slice_length` | `a[key]` where the key holds integers, slices, `None` and `...` |
| Element types | `result_type`, `can_cast`, `ufunc_dtype`, `ufunc_dtypes`, `reduce_dtype` | `np.result_type`, `np.can_cast`, the result type of every element-wise ufunc of one or two inputs, and of sixteen reductions |

Fourteen element types are covered: `bool`, `int8` to `int64`, `uint8` to `uint64`, `float16` to `float64`, `complex64` and `complex128`. A Python `int`, `float` or `complex` among the operands is promoted the way NumPy 2 promotes a Python number (NEP 50).

Each rule is described with examples in the [guide to the shape rules](https://sofeikov.github.io/shaperules/guide/shape-rules/) and the [guide to element types](https://sofeikov.github.io/shaperules/guide/dtypes/).

## How it is checked

NumPy is not needed to use shaperules. It is used by the tests, where it is the reference every answer is held against.

- **Shape rules.** [Hypothesis](https://hypothesis.readthedocs.io/) draws shapes whose sizes are formulas over a few names. The test asks the rule, then makes the real NumPy call for every assignment of the sizes 0 to 3 to those names. A `Known` answer must be NumPy's shape every time. A `Refused` answer must be an exception of the named class every time.
- **Element types.** Promotion is compared with `np.result_type` for every single operand, every pair, every triple of different operands, and every combination of four array types. Every cell of every ufunc table and every reduction is compared with the NumPy call it stands for.
- **The tables.** What a ufunc returns for each pair of element types is read from tables generated from NumPy by `tools/generate_tables.py`. A test generates them again on the NumPy under test and fails on any difference.
- **Versions.** CI runs the suite on NumPy 2.1, the oldest version modelled, and on the latest, and installs the wheel into an environment with no NumPy to check that it answers there.
- **The examples.** Every example in this README and in the documentation is run by the test suite.

The full account is in [Checked against NumPy](https://sofeikov.github.io/shaperules/internals/checked-against-numpy/).

## Status and limits

Version 0.1.0 is the first version. The following are not modelled:

- A Python integer that does not fit the array's type. `np.uint8(1) + 300` raises `OverflowError` in NumPy. That depends on a value, and shaperules sees types only.
- Shapes of unknown rank. A shape is a tuple with one size per axis, so the number of axes is always known.
- Indexing by arrays or boolean masks.
- `einsum`, `numpy.linalg`, `numpy.fft` and the functions that build arrays.
- Sums of products in the formula algebra. `n*m + 1` has no form there and is read as an unknown size.
- Element types outside the fourteen, such as `datetime64`, `longdouble` and `object`. A rule given one answers `Unknown`.

A refusal's message is written by shaperules and is not NumPy's message. The list with details is in [Limitations and roadmap](https://sofeikov.github.io/shaperules/internals/limitations/).

## Where it comes from

The rules were extracted from [numty](https://github.com/sofeikov/numty), a mypy plugin that checks NumPy shapes statically, so that clients other than a type checker can use them. numty imports its size algebra and its dtype promotion from shaperules. A second intended client is the lazy layer of [hotkernels](https://github.com/sofeikov/hotkernels), which needs the shape and element type of a NumPy call at run time without computing it. hotkernels does not use shaperules yet.

## Documentation

- [Get started](https://sofeikov.github.io/shaperules/get-started/)
- [Sizes](https://sofeikov.github.io/shaperules/guide/sizes/): integers, names, formulas and the unknown size
- [The three answers](https://sofeikov.github.io/shaperules/guide/answers/)
- [Writing a client](https://sofeikov.github.io/shaperules/guide/clients/): a run-time client and a static one
- [API reference](https://sofeikov.github.io/shaperules/reference/api/) and [the list of refusals](https://sofeikov.github.io/shaperules/reference/refusals/)
- [Design](https://sofeikov.github.io/shaperules/internals/design/)
- [Development](https://sofeikov.github.io/shaperules/contributing/)

## Licence

MIT. See [LICENSE](LICENSE).
