Skip to content

API reference

This page is generated from the docstrings in the source. It is grouped by module. Most names are also importable from the top-level package, so shaperules.broadcast is shaperules.elementwise.broadcast. Each section lists the names that are.

The package is typed and ships a py.typed marker. Its version is shaperules.__version__.

Answers

Module shaperules.outcome. At the top level: Known, Refused, Unknown, Outcome, Refusal, RuleError, ShapeRefused, ShapeUnknown.

Described in The three answers.

The three answers a rule can give.

Every rule answers with one of:

  • Known(value): the result, for every assignment of the names involved.
  • Refused(refusal): NumPy raises, for every assignment.
  • Unknown(reason, likely): it depends on sizes the rule was not told.

Known and Refused are proofs. A caller that must agree with NumPy exactly acts on those two and treats Unknown as "ask NumPy".

Unknown.likely is for a caller that wants a best reading all the same, a type checker for one. It is what holds once the doubt is set aside: the call is assumed to be valid, and no name is assumed to be 0 or 1 or equal to another name. It is a Known, a Refused, or None when there is no single best reading.

Outcome module-attribute

Outcome: TypeAlias = Known[T] | Refused | Unknown[T]

What a rule returns.

Refusal dataclass

Refusal(
    kind: str,
    message: str,
    raises: str = "ValueError",
    axis: int | None = None,
)

Why NumPy refuses a call.

Attributes:

Name Type Description
kind str

A stable identifier of the check that failed, such as "broadcast", "matmul-core", "axis-out-of-range". Listed in the reference; safe to branch on.

message str

The reason in words. These are this library's words, not NumPy's: to show NumPy's own message, make the call.

raises str

The name of the exception NumPy raises: "ValueError", "IndexError", "AxisError", "TypeError". AxisError is numpy.exceptions.AxisError, a ValueError and an IndexError both.

axis int | None

The axis at fault, for a refusal about one axis, else None. For "axis-out-of-range" and "axis-repeated" it is the axis as the caller wrote it (-5, not a normalised index). For "squeeze-size" it is the index of the axis whose size is not 1. A caller that writes its own message reads it here.

RuleError

Bases: Exception

Base of the two exceptions unwrap raises.

ShapeRefused

ShapeRefused(refusal: Refusal)

Bases: RuleError

Raised by unwrap on a Refused answer.

Attributes:

Name Type Description
refusal

Why NumPy refuses the call.

ShapeUnknown

ShapeUnknown(reason: str)

Bases: RuleError

Raised by unwrap on an Unknown answer.

Attributes:

Name Type Description
reason

What the answer depends on.

Known dataclass

Known(value: T_co)

Bases: Generic[T_co]

The result of a call, proven for every assignment of the names.

Attributes:

Name Type Description
value T_co

The result: a shape, a size, or a dtype name, by the rule.

unwrap

unwrap() -> T_co

The result.

Returns:

Type Description
T_co

value.

best

best() -> T_co | None

The result.

Returns:

Type Description
T_co | None

value.

Refused dataclass

Refused(refusal: Refusal)

NumPy raises, for every assignment of the names.

Attributes:

Name Type Description
refusal Refusal

Why.

unwrap

unwrap() -> None

Raise the refusal.

Raises:

Type Description
ShapeRefused

Always.

best

best() -> None

No result.

Returns:

Type Description
None

None.

Unknown dataclass

Unknown(
    reason: str, likely: Known[T_co] | Refused | None = None
)

Bases: Generic[T_co]

The answer depends on sizes the rule was not told.

Attributes:

Name Type Description
reason str

What it depends on, in words.

likely Known[T_co] | Refused | None

The best reading once the doubt is set aside, or None. Not a proof: see the module's description.

unwrap

unwrap() -> None

Raise, since nothing is proven.

Raises:

Type Description
ShapeUnknown

Always.

best

best() -> T_co | None

The likely result, when there is one.

Returns:

Type Description
T_co | None

The value of likely when it is a Known, else None.

refused

refused(
    kind: str,
    message: str,
    raises: str = "ValueError",
    *,
    axis: int | None = None,
) -> Refused

Build a Refused answer.

Parameters:

Name Type Description Default
kind str

The identifier of the check that failed.

required
message str

The reason in words.

required
raises str

The name of the exception NumPy raises.

'ValueError'
axis int | None

The axis at fault, for a refusal about one axis.

None

Returns:

Type Description
Refused

The answer.

Sizes

Module shaperules.dims. The module itself is exported, so it is sr.dims after import shaperules as sr. At the top level: ANY, AnyDim, Dim, DimLike, Shape, ShapeLike, dim, shape, as_shape, sym, fresh, parse, fmt, fmt_shape, is_known, substitute, substitute_shape. The arithmetic and the comparisons are reached through the module: shaperules.dims.add, shaperules.dims.equal and the rest.

Described in Sizes.

Sizes: plain integers, formulas over names, and the size nothing is known about.

A Dim is the size of one axis:

  • an int when it is known;
  • a canonical form (shaperules.forms) when it is a formula over names, n, 2*n + 1, (n + 1) // 2, h*w;
  • ANY when nothing is known about it.

A name stands for one non-negative integer, the same one wherever it appears. So n equals n, and n + 1 never equals n. ANY is the opposite: two ANY sizes are not known to be equal, even to each other.

Arithmetic keeps sizes canonical, so a constant is always an int and two equal formulas compare equal with ==. Where a result has no canonical form (n*m + 1), the answer is ANY: no formula is ever approximated.

ANY module-attribute

ANY: Final = AnyDim()

A size nothing is known about, not even that it equals itself.

Dim module-attribute

Dim: TypeAlias = int | LinForm | DivForm | MonoForm | AnyDim

The size of one axis: an integer, a formula over names, or ANY.

DimLike module-attribute

DimLike: TypeAlias = (
    int | str | LinForm | DivForm | MonoForm | AnyDim
)

What the functions of this library accept for a size.

A string is a formula, read by parse: "n", "2*n+1", "(n+1)//2", "h*w", and "?" for ANY.

Shape module-attribute

Shape: TypeAlias = tuple[Dim, ...]

The shape of an array of known rank.

ShapeLike module-attribute

ShapeLike: TypeAlias = Iterable[DimLike]

What the functions of this library accept for a shape.

AnyDim

The size nothing is known about. Use the one instance, ANY.

normalize

normalize(value: Form | int | AnyDim) -> Dim

Bring a size to its one spelling.

Parameters:

Name Type Description Default
value Form | int | AnyDim

An integer, a form, or ANY.

required

Returns:

Type Description
Dim

An int for a constant, else the form itself.

sym

sym(name: str) -> Dim

A named size: one non-negative integer, the same wherever the name appears.

Parameters:

Name Type Description Default
name str

The name. Any non-empty text without spaces; a dotted name (pkg.mod.N) is fine.

required

Returns:

Type Description
Dim

The size name.

Raises:

Type Description
ValueError

When the name is empty or holds whitespace.

fresh

fresh(label: str = 'd') -> Dim

A named size no other call returns.

For a length that is fixed but not known yet, such as how many elements a mask selects: it equals itself and is not known to equal anything else.

Parameters:

Name Type Description Default
label str

A prefix for the generated name, to make it readable.

'd'

Returns:

Type Description
Dim

A new named size, label#1, label#2, and so on.

dim

dim(value: DimLike) -> Dim

Read a size from what a caller wrote.

Parameters:

Name Type Description Default
value DimLike

An integer, a formula as text, a form, or ANY.

required

Returns:

Type Description
Dim

The size, in its one spelling.

Raises:

Type Description
ValueError

When an integer is negative or a text is not a formula.

TypeError

When the value is none of the accepted kinds.

shape

shape(*dims: DimLike) -> Shape

Build a shape from its sizes.

Parameters:

Name Type Description Default
*dims DimLike

The size of each axis, as dim reads it.

()

Returns:

Type Description
Shape

The shape.

as_shape

as_shape(value: ShapeLike | str) -> Shape

Read a shape from what a caller wrote.

Parameters:

Name Type Description Default
value ShapeLike | str

The sizes, in order, or one text that lists them: "batch, n, 3" is ("batch", "n", 3).

required

Returns:

Type Description
Shape

The shape.

is_known

is_known(value: Dim) -> bool

Whether a size is a plain integer.

Parameters:

Name Type Description Default
value Dim

The size.

required

Returns:

Type Description
bool

True for an int.

names

names(value: Dim | Shape) -> tuple[str, ...]

The names a size or a shape mentions, each once, sorted.

Parameters:

Name Type Description Default
value Dim | Shape

A size or a shape.

required

Returns:

Type Description
tuple[str, ...]

The names.

add

add(a: DimLike, b: DimLike) -> Dim

The sum of two sizes.

Parameters:

Name Type Description Default
a DimLike

The first size.

required
b DimLike

The second size.

required

Returns:

Type Description
Dim

The sum, or ANY when it has no canonical form.

neg

neg(a: DimLike) -> Dim | int

The negation of a size, for use inside a sum.

Parameters:

Name Type Description Default
a DimLike

The size.

required

Returns:

Type Description
Dim | int

The negated formula (not a size by itself), or ANY.

sub

sub(a: DimLike, b: DimLike) -> Dim

The difference of two sizes.

The result is a formula: sub("n", 1) is n - 1, which is -1 when n is 0. A rule that subtracts checks the bounds itself.

Parameters:

Name Type Description Default
a DimLike

The size to subtract from.

required
b DimLike

The size to subtract.

required

Returns:

Type Description
Dim

The difference, or ANY when it has no canonical form.

mul

mul(a: DimLike, b: DimLike) -> Dim

The product of two sizes.

Parameters:

Name Type Description Default
a DimLike

The first size.

required
b DimLike

The second size.

required

Returns:

Type Description
Dim

The product, or ANY when it has no canonical form. A product with a known 0 is 0 whatever the other size is.

prod

prod(dims: Iterable[DimLike]) -> Dim

The product of sizes: the number of elements of a shape.

Parameters:

Name Type Description Default
dims Iterable[DimLike]

The sizes.

required

Returns:

Type Description
Dim

The product, 1 for no sizes, ANY when it has no canonical form.

floordiv

floordiv(a: DimLike, b: int) -> Dim

A size divided by a positive integer, rounded down.

Parameters:

Name Type Description Default
a DimLike

The size.

required
b int

The divisor.

required

Returns:

Type Description
The quotient

exact where every term divides (4*n // 2 is 2*n), a DivForm otherwise, ANY when it has no canonical form.

Raises:

Type Description
ValueError

When the divisor is not positive.

exact_div

exact_div(a: DimLike, b: DimLike) -> Dim | None

A size divided by another when the division leaves no remainder.

The quotient holds wherever the divisor is not 0: n*k / n is k, and at n = 0 there is no quotient to speak of. A caller that needs the division to exist checks the divisor with at_least(b, 1).

Parameters:

Name Type Description Default
a DimLike

The dividend.

required
b DimLike

The divisor.

required

Returns:

Type Description
Dim | None

The quotient, or None when the division may leave a remainder, the divisor is a known 0, or either side has no product form.

dim_or_int

dim_or_int(value: DimLike | int) -> Dim | int

Like dim, but a negative integer is let through.

For the terms of a sum, where -1 is a legal operand.

Parameters:

Name Type Description Default
value DimLike | int

An integer of either sign, a formula as text, a form, or ANY.

required

Returns:

Type Description
Dim | int

The integer or the size.

equal

equal(a: Dim, b: Dim) -> bool

Whether two sizes are equal for every assignment of their names.

Parameters:

Name Type Description Default
a Dim

The first size.

required
b Dim

The second size.

required

Returns:

Type Description
True when they are provably equal. False means "not proven"

n and m may be equal, and ANY is not known to equal anything.

unequal

unequal(a: Dim, b: Dim) -> bool

Whether two sizes differ for every assignment of their names.

Parameters:

Name Type Description Default
a Dim

The first size.

required
b Dim

The second size.

required

Returns:

Type Description
True when no assignment makes them equal

3 and 4, n and n + 1, 2*n and 2*n + 1. False means "not proven".

can_be

can_be(value: Dim, target: int) -> bool

Whether a size may equal an integer for some assignment of its names.

Parameters:

Name Type Description Default
value Dim

The size.

required
target int

The integer.

required

Returns:

Type Description
bool

False only when the size provably never has this value. ANY may be anything.

at_least

at_least(value: Dim, bound: int) -> bool

Whether a size is provably no smaller than an integer.

Every size is at least 0. Beyond that, the proof is the form's own lower bound: n + 2 is at least 2, n is not known to be at least 1.

Parameters:

Name Type Description Default
value Dim

The size.

required
bound int

The integer to compare with.

required

Returns:

Type Description
bool

True when the size is at least bound for every assignment.

at_most

at_most(value: Dim, bound: int) -> bool

Whether a size is provably no larger than an integer.

Parameters:

Name Type Description Default
value Dim

The size.

required
bound int

The integer to compare with.

required

Returns:

Type Description
bool

True when the size is at most bound for every assignment.

substitute

substitute(value: Dim, sizes: Mapping[str, int]) -> Dim

Replace names by integers.

Parameters:

Name Type Description Default
value Dim

The size.

required
sizes Mapping[str, int]

A size for some or all of the names.

required

Returns:

Type Description
The size with those names replaced

an int once every name has a value, a smaller formula otherwise. ANY stays ANY.

Raises:

Type Description
ValueError

When the names given make the size negative.

substitute_shape

substitute_shape(
    value: Shape, sizes: Mapping[str, int]
) -> Shape

Replace names by integers in every size of a shape.

Parameters:

Name Type Description Default
value Shape

The shape.

required
sizes Mapping[str, int]

A size for some or all of the names.

required

Returns:

Type Description
Shape

The shape with those names replaced.

fmt

fmt(
    value: Dim, display: Callable[[str], str] | None = None
) -> str

A size as text: 3, n, 2*n+1, (n+1)//2, h*w, ?.

Parameters:

Name Type Description Default
value Dim

The size.

required
display Callable[[str], str] | None

Maps a name to the text shown for it. None shows names as they are.

None

Returns:

Type Description
str

The text. parse reads it back to the same size when every name is a dotted identifier and display is None; a name from fresh is deliberately not one.

fmt_shape

fmt_shape(
    value: Shape,
    display: Callable[[str], str] | None = None,
) -> str

A shape as text, the way NumPy prints one: (3, n, 2*n+1), (n,), ().

Parameters:

Name Type Description Default
value Shape

The shape.

required
display Callable[[str], str] | None

Maps a name to the text shown for it.

None

Returns:

Type Description
str

The text.

parse

parse(text: str) -> Dim

Read a size from a formula.

The formula is integers, names, +, -, *, // by a positive integer, and parentheses. ? alone is ANY. A name is a Python identifier, optionally dotted.

Parameters:

Name Type Description Default
text str

The formula, such as "n", "2*n+1", "(n+1)//2", "h*w".

required

Returns:

Type Description
Dim

The size. A formula with no canonical form ("n*m+1") is ANY.

Raises:

Type Description
ValueError

When the text is not such a formula, or is negative whatever its names are ("-3", "-n-1").

Broadcasting and the matrix product

Module shaperules.elementwise. At the top level: broadcast, broadcast_pair, match_pair, matmul.

Described in Shape rules.

Broadcasting and the matrix product.

broadcast_pair

broadcast_pair(a: DimLike, b: DimLike) -> Outcome[Dim]

The size two sizes broadcast to along one axis.

Parameters:

Name Type Description Default
a DimLike

The size on one operand.

required
b DimLike

The size on the other.

required

Returns:

Type Description
Outcome[Dim]

Known when the result is certain (3 and 1, n and n), Refused when they never broadcast (3 and 4, n + 2 and n + 3), else Unknown (n and 3, n and m, n and n - 1).

match_pair

match_pair(a: DimLike, b: DimLike) -> Outcome[Dim]

The size of two sizes that must be equal.

For the places where NumPy does not stretch a 1: the inner sizes of a matrix product, the other axes of a concatenation.

Parameters:

Name Type Description Default
a DimLike

One size.

required
b DimLike

The other.

required

Returns:

Type Description
Outcome[Dim]

Known when they are provably equal, Refused when they provably differ, else Unknown.

broadcast

broadcast(*shapes: ShapeLike | str) -> Outcome[Shape]

The shape several shapes broadcast to: numpy.broadcast_shapes.

Shapes align at their last axis. Along each axis the sizes that are not 1 must agree, and a missing leading axis counts as 1.

Parameters:

Name Type Description Default
*shapes ShapeLike | str

The shapes of the operands. None at all gives ().

()

Returns:

Type Description
Outcome[Shape]

The broadcast shape. NumPy raises ValueError where this answers Refused.

Example

from shaperules import broadcast, fmt_shape fmt_shape(broadcast((8, 1, 3), ("n", 3)).value) '(8, n, 3)'

matmul

matmul(
    a: ShapeLike | str, b: ShapeLike | str
) -> Outcome[Shape]

The shape of a matrix product: a @ b, numpy.matmul.

A one-dimensional operand is a row on the left and a column on the right, and its axis is dropped from the result. The last axis of a must equal the last-but-one of b, with no stretching of a 1. The axes before the last two broadcast.

Parameters:

Name Type Description Default
a ShapeLike | str

The shape of the left operand.

required
b ShapeLike | str

The shape of the right operand.

required

Returns:

Type Description
Outcome[Shape]

The shape of the product. NumPy raises ValueError where this answers Refused.

Axes

Module shaperules.axes. At the top level: reduce, reduce_shape, reduce_shape_names, arg_reduce, cumulative, transpose, swapaxes, moveaxis, squeeze, expand_dims, normalize_axis, normalize_axes.

Described in Shape rules.

Rules that remove, add or reorder axes: reductions, running totals, transposes, squeezes.

Axis module-attribute

Axis = int | Sequence[int] | None

An axis argument: one axis, several, or None.

normalize_axis

normalize_axis(axis: int, rank: int) -> int | Refused

Bring one axis into range(rank), the way NumPy counts from the end.

Parameters:

Name Type Description Default
axis int

The axis, negative to count from the last.

required
rank int

The number of axes.

required

Returns:

Type Description
int | Refused

The axis as a non-negative index, or the refusal NumPy's AxisError stands for.

normalize_axes

normalize_axes(
    axis: Axis, rank: int
) -> tuple[int, ...] | Refused

Bring an axis argument to a tuple of distinct non-negative axes.

Parameters:

Name Type Description Default
axis Axis

One axis, several, or None for all of them.

required
rank int

The number of axes.

required

Returns:

Type Description
tuple[int, ...] | Refused

The axes in the order given, or the refusal for an axis out of range (AxisError) or named twice (ValueError).

reduce

reduce(
    shape: ShapeLike | str,
    axis: Axis = None,
    keepdims: bool = False,
    *,
    needs_elements: bool = False,
    scalar_axis: bool = True,
) -> Outcome[Shape]

The shape of a reduction: sum, prod, any, max, mean, and the like.

Parameters:

Name Type Description Default
shape ShapeLike | str

The shape of the operand.

required
axis Axis

The axis or axes reduced, or None for all of them.

None
keepdims bool

Keep each reduced axis with size 1.

False
needs_elements bool

True for a reduction with no value for an empty input (max, min, ptp): NumPy raises ValueError when the axes reduced hold no element.

False
scalar_axis bool

Whether the function accepts axis=0 or axis=-1 for an array with no axes, where the axis names nothing. sum, prod, max, min, any, all, ptp and count_nonzero do. Pass False for mean, std, var, median and average, which raise AxisError there.

True

Returns:

Type Description
Outcome[Shape]

The shape of the result.

Raises:

Type Description
TypeError

When an axis is not an integer. A bool is not one.

arg_reduce

arg_reduce(
    shape: ShapeLike | str,
    axis: int | None = None,
    keepdims: bool = False,
) -> Outcome[Shape]

The shape of argmax or argmin.

Parameters:

Name Type Description Default
shape ShapeLike | str

The shape of the operand.

required
axis int | None

The one axis searched, or None to search the flattened array.

None
keepdims bool

Keep the searched axes with size 1.

False

Returns:

Type Description
Outcome[Shape]

The shape of the result. NumPy raises ValueError for an empty search, and this answers Refused there.

reduce_shape_names

reduce_shape_names() -> tuple[str, ...]

The reductions reduce_shape knows, by their NumPy names.

Returns:

Type Description
tuple[str, ...]

The names, sorted.

reduce_shape

reduce_shape(
    name: str,
    shape: ShapeLike | str,
    axis: Axis = None,
    keepdims: bool = False,
) -> Outcome[Shape]

The shape of a reduction, by the name NumPy gives it.

The reductions agree on the shape of a valid call and differ in what they refuse. numpy.max raises for an empty axis and numpy.sum does not. numpy.mean and numpy.median raise for axis=0 on an array with no axes, where numpy.sum and numpy.nanmean accept it. numpy.argmax takes one axis only. numpy.average raises ZeroDivisionError when its result has no elements. numpy.nanmean, numpy.nanstd and numpy.nanvar accept axis=0 on an array with no axes when it holds floats and raise when it holds integers, so the answer there is Unknown. So is numpy.median over several axes, or over none, when an axis that stays may have size 0: NumPy before 2.5 raises there. This rule knows which is which, so a caller does not pass the flags of reduce itself.

Parameters:

Name Type Description Default
name str

The reduction's NumPy name: "sum", "nanmax", "median". reduce_shape_names lists them.

required
shape ShapeLike | str

The shape of the operand.

required
axis Axis

The axis or axes reduced, or None for all of them.

None
keepdims bool

Keep each reduced axis with size 1.

False

Returns:

Type Description
Outcome[Shape]

The shape of the result. Unknown when the name is not covered.

Raises:

Type Description
TypeError

When an axis is not an integer. A bool is not one.

Example

from shaperules import reduce_shape reduce_shape("sum", (), axis=0) Known(value=()) reduce_shape("median", (), axis=0).refusal.raises 'AxisError' reduce_shape("max", (0, 3), axis=0).refusal.kind 'reduce-empty'

cumulative

cumulative(
    shape: ShapeLike | str, axis: int | None = None
) -> Outcome[Shape]

The shape of a running total: cumsum, cumprod.

Parameters:

Name Type Description Default
shape ShapeLike | str

The shape of the operand.

required
axis int | None

The axis accumulated along, or None to accumulate over the flattened array.

None

Returns:

Type Description
Outcome[Shape]

The operand's shape with an axis, else one axis holding every element.

transpose

transpose(
    shape: ShapeLike | str,
    axes: Sequence[int] | None = None,
) -> Outcome[Shape]

The shape of a transpose: a.T, numpy.transpose.

Parameters:

Name Type Description Default
shape ShapeLike | str

The shape of the operand.

required
axes Sequence[int] | None

The new order of the axes, or None to reverse them.

None

Returns:

Type Description
Outcome[Shape]

The reordered shape. NumPy raises ValueError for a wrong count or a repeated axis, AxisError for an axis out of range.

swapaxes

swapaxes(
    shape: ShapeLike | str, axis1: int, axis2: int
) -> Outcome[Shape]

The shape after two axes change places: numpy.swapaxes.

Parameters:

Name Type Description Default
shape ShapeLike | str

The shape of the operand.

required
axis1 int

One axis.

required
axis2 int

The other.

required

Returns:

Type Description
Outcome[Shape]

The shape with the two sizes exchanged.

moveaxis

moveaxis(
    shape: ShapeLike | str,
    source: int | Sequence[int],
    destination: int | Sequence[int],
) -> Outcome[Shape]

The shape after axes move to new places: numpy.moveaxis.

Parameters:

Name Type Description Default
shape ShapeLike | str

The shape of the operand.

required
source int | Sequence[int]

The axis or axes to move.

required
destination int | Sequence[int]

Where each goes, in the result.

required

Returns:

Type Description
Outcome[Shape]

The shape with those axes moved and the others kept in order.

squeeze

squeeze(
    shape: ShapeLike | str, axis: Axis = None
) -> Outcome[Shape]

The shape with axes of size 1 removed: numpy.squeeze.

Parameters:

Name Type Description Default
shape ShapeLike | str

The shape of the operand.

required
axis Axis

The axes to remove, each of which must have size 1, or None to remove every axis of size 1.

None

Returns:

Type Description
Outcome[Shape]

The squeezed shape. With axis=None a size that may or may not be 1 makes the answer Unknown: the rank itself depends on it.

expand_dims

expand_dims(
    shape: ShapeLike | str, axis: int | Sequence[int]
) -> Outcome[Shape]

The shape with new axes of size 1: numpy.expand_dims.

Parameters:

Name Type Description Default
shape ShapeLike | str

The shape of the operand.

required
axis int | Sequence[int]

Where the new axes go, counted in the result.

required

Returns:

Type Description
Outcome[Shape]

The expanded shape.

Reshaping and joining

Module shaperules.reshaping. At the top level: reshape, concatenate, stack.

Described in Shape rules.

Rules that regroup elements: reshape, concatenate, stack.

reshape

reshape(
    shape: ShapeLike | str,
    newshape: Sequence[DimLike] | DimLike,
) -> Outcome[Shape]

The shape after numpy.reshape.

Parameters:

Name Type Description Default
shape ShapeLike | str

The shape of the operand.

required
newshape Sequence[DimLike] | DimLike

The shape asked for. One size may be -1, to be worked out from the number of elements. A single size stands for a one-axis shape.

required

Returns:

Type Description
Outcome[Shape]

The new shape, with -1 replaced. NumPy raises ValueError where this answers Refused: the element counts differ, two sizes are -1, or -1 has no one value.

concatenate

concatenate(
    shapes: Sequence[ShapeLike | str], axis: int | None = 0
) -> Outcome[Shape]

The shape of numpy.concatenate.

Parameters:

Name Type Description Default
shapes Sequence[ShapeLike | str]

The shapes of the arrays joined.

required
axis int | None

The axis they are joined along, or None to flatten each first.

0

Returns:

Type Description
The joined shape

the sizes along axis added, every other size as it is. NumPy raises ValueError where the other sizes differ, the ranks differ, an array has no axes, or no array is given, and AxisError for an axis out of range.

stack

stack(
    shapes: Sequence[ShapeLike | str], axis: int = 0
) -> Outcome[Shape]

The shape of numpy.stack.

Parameters:

Name Type Description Default
shapes Sequence[ShapeLike | str]

The shapes of the arrays stacked, which must all be one shape.

required
axis int

Where the new axis goes, counted in the result.

0

Returns:

Type Description
The stacked shape

the common shape with a new axis holding the number of arrays.

Indexing

Module shaperules.indexing. At the top level: index, slice_length.

Described in Shape rules.

Basic indexing: integers, slices, None and ....

IndexItem module-attribute

IndexItem = int | slice | None | EllipsisType

One item of a basic index.

index

index(
    shape: ShapeLike | str,
    key: IndexItem | Sequence[IndexItem],
) -> Outcome[Shape]

The shape of a[key] for a basic index.

A basic index holds integers, slices of integers, None and at most one .... An integer removes its axis, a slice keeps it with a new size, None adds an axis of size 1, and ... stands for the axes not named. Indexing by arrays or masks is not covered.

Parameters:

Name Type Description Default
shape ShapeLike | str

The shape of the array.

required
key IndexItem | Sequence[IndexItem]

The index: one item, or a tuple of them.

required

Returns:

Type Description
Outcome[Shape]

The shape selected. NumPy raises IndexError where this answers Refused: too many indices, an integer out of bounds, two ....

Example

from shaperules import index index((10, 4), (slice(2, 8, 2), None, 0)).value (3, 1)

slice_length

slice_length(size: DimLike, item: slice) -> Outcome[Dim]

How many elements a slice selects from an axis.

For a known size this is len(range(*item.indices(size))). For a formula the answer is Known where one formula holds for every assignment (n[::2] is (n+1)//2, n[:] is n) and Unknown with the usual reading otherwise (n[1:] is n-1 unless n is 0).

Parameters:

Name Type Description Default
size DimLike

The size of the axis.

required
item slice

The slice. Its start, stop and step are integers or None.

required

Returns:

Type Description
Outcome[Dim]

The number of elements selected.

Raises:

Type Description
ValueError

When the step is 0, as NumPy and Python do.

TypeError

When a part of the slice is not an integer or None.

Element types

Module shaperules.dtypes. The module itself is exported, as sr.dtypes. At the top level: DTYPES, result_type, can_cast, ufunc_dtype, ufunc_dtypes, reduce_dtype. The rest is reached through the module: shaperules.dtypes.ufunc_names, shaperules.dtypes.promote_all and the others.

Described in Element types.

Element types: what NumPy promotes two of them to, and what each function returns.

An element type is written by its NumPy name, "float32", "int64", "bool". Fourteen are covered: bool, the four signed and four unsigned integers, float16 to float64, complex64 and complex128. A Python number among the operands is written as its type, int, float or complex: under NumPy's promotion rules (NEP 50) it takes the element type of the array it meets, within its kind.

Promotion (result_type) is worked out by rule. What a ufunc or a reduction returns is read from tables that were asked of NumPy itself (shaperules._tables); the tests ask again on the NumPy they run with. The tables describe NumPy 2.1 and later. NumPy 2.0 differs in one place: floor, ceil and trunc of an integer array return floats there. Anything outside those fourteen types is answered Unknown, never guessed.

The answers are those of a 64-bit platform, where NumPy's default integer and its index type are int64: the type of a Python int with no array beside it, and of sum over small integers or argmax.

One thing depends on a value and is not modelled: a Python integer that does not fit the array's type (np.uint8(1) + 300) raises OverflowError.

DTypeLike module-attribute

DTypeLike: TypeAlias = object

What the functions of this module accept for an element type.

A NumPy name ("float32", with or without a leading numpy.), a NumPy dtype or scalar type (np.dtype("f4"), np.float32), or one of the Python types bool, int, float, complex for a Python number.

DTYPE_INFO module-attribute

DTYPE_INFO: dict[str, tuple[str, int]] = {
    "bool": ("b", 1),
    "int8": ("i", 1),
    "int16": ("i", 2),
    "int32": ("i", 4),
    "int64": ("i", 8),
    "uint8": ("u", 1),
    "uint16": ("u", 2),
    "uint32": ("u", 4),
    "uint64": ("u", 8),
    "float16": ("f", 2),
    "float32": ("f", 4),
    "float64": ("f", 8),
    "complex64": ("c", 8),
    "complex128": ("c", 16),
}

Each element type covered, with its kind (b, i, u, f, c) and its size in bytes.

DTYPES module-attribute

DTYPES: tuple[str, ...] = tuple(DTYPE_INFO)

The element types covered, from bool to complex128.

NAME_OF_KIND_SIZE module-attribute

NAME_OF_KIND_SIZE: dict[tuple[str, int], str] = {
    v: k for k, v in DTYPE_INFO.items()
}

The element type of a kind and a size in bytes.

WEAK_DEFAULT module-attribute

WEAK_DEFAULT: dict[type, str] = {
    bool: "bool",
    int: "int64",
    float: "float64",
    complex: "complex128",
}

The element type a Python number has when no array is there to decide.

canonical

canonical(dtype: DTypeLike) -> str | type | None

Read an element type from what a caller wrote.

Parameters:

Name Type Description Default
dtype DTypeLike

A name, a NumPy dtype or scalar type, or a Python number type.

required

Returns:

Type Description
str | type | None

The NumPy name for one of the fourteen types covered; the Python type itself for int, float and complex; None for anything else. Python's bool reads as "bool": NumPy treats True as its own boolean.

kind_bits_name

kind_bits_name(kind: str, bits: int) -> str | None

The element type of a kind and a width in bits.

Parameters:

Name Type Description Default
kind str

b, i, u, f or c.

required
bits int

The width of the whole item: ("c", 64) is complex64.

required

Returns:

Type Description
str | None

The name, or None when there is no such type.

promote

promote(a: str, b: str) -> str | None

The element type two arrays promote to: numpy.result_type of two dtypes.

Parameters:

Name Type Description Default
a str

The name of one element type.

required
b str

The name of the other.

required

Returns:

Type Description
str | None

The promoted name, or None when either is not covered. A signed and an unsigned integer of 64 bits promote to float64, as in NumPy.

promote_all

promote_all(names: Iterable[str]) -> str | None

The element type several arrays promote to: numpy.result_type of their dtypes.

This is the smallest type every operand casts to safely, worked out over all of them at once. Folding promote pair by pair gives a different, wider answer for some mixes: int8, uint8 and float16 promote to float16, while int8 with uint8 is already int16, which with float16 would be float32.

Parameters:

Name Type Description Default
names Iterable[str]

The names of the element types, at least one.

required

Returns:

Type Description
str | None

The promoted name, or None when one is not covered or none is given.

promote_weak

promote_weak(scalar: type, strong: str) -> str | None

The element type of an array combined with a Python number.

Parameters:

Name Type Description Default
scalar type

The Python type of the number: bool, int, float or complex.

required
strong str

The name of the array's element type.

required

Returns:

Type Description
str | None

The promoted name, or None when either is not covered. The number keeps the array's type within its kind (float32 with a Python float stays float32) and lifts it across kinds (int8 with a Python float is float64).

result_type

result_type(*operands: DTypeLike) -> Outcome[str]

The element type the operands promote to: numpy.result_type.

Parameters:

Name Type Description Default
*operands DTypeLike

Element types of arrays, and Python number types for Python numbers.

()

Returns:

Type Description
Outcome[str]

The promoted name. Unknown when an operand is not one of the types covered. With Python numbers alone the answer is their default type (int64, float64, complex128).

Raises:

Type Description
ValueError

When no operand is given, as NumPy does.

Example

from shaperules import result_type result_type("int8", "uint8").value 'int16' result_type("float32", float).value 'float32'

can_cast

can_cast(
    source: DTypeLike, target: DTypeLike
) -> Outcome[bool]

Whether one element type casts to another without loss: numpy.can_cast(..., "safe").

Parameters:

Name Type Description Default
source DTypeLike

The element type cast from.

required
target DTypeLike

The element type cast to.

required

Returns:

Type Description
True when NumPy casts `source` to `target` under its "safe" rule

the same kind or a higher one, and no narrower. That is not exact representability: int64 casts safely to float64. Unknown when either is not one of the types covered, or is a Python number type.

ufunc_names

ufunc_names() -> tuple[str, ...]

The ufuncs ufunc_dtypes knows, under every public NumPy name.

Returns:

Type Description
tuple[str, ...]

The names, sorted.

ufunc_dtypes

ufunc_dtypes(
    name: str, *operands: DTypeLike
) -> Outcome[tuple[str, ...]]

The element types a ufunc returns for its operands, one per output.

Parameters:

Name Type Description Default
name str

The ufunc's NumPy name: "add", "sqrt", "arctan2", "divmod".

required
*operands DTypeLike

The element type of each input: one or two, as the ufunc takes. A Python number is written as its type.

()

Returns:

Type Description
Outcome[tuple[str, ...]]

The result types, a tuple even for one output. Refused, raising TypeError, when NumPy has no loop for these types (np.floor of a complex array, np.subtract of two boolean arrays). Unknown when the ufunc or a type is not covered.

Raises:

Type Description
ValueError

When the number of operands is not what the ufunc takes.

ufunc_dtype

ufunc_dtype(
    name: str, *operands: DTypeLike
) -> Outcome[str]

The element type of a ufunc's first output.

The convenient form of ufunc_dtypes for the ufuncs with one output, which is nearly all of them.

Parameters:

Name Type Description Default
name str

The ufunc's NumPy name.

required
*operands DTypeLike

The element type of each input.

()

Returns:

Type Description
Outcome[str]

The result type, with the same three answers as ufunc_dtypes.

Example

from shaperules import ufunc_dtype ufunc_dtype("true_divide", "int32", "int32").value 'float64' ufunc_dtype("sqrt", "int8").value 'float16'

reduction_names

reduction_names() -> tuple[str, ...]

The reductions reduce_dtype knows.

Returns:

Type Description
tuple[str, ...]

The names, sorted.

reduce_dtype

reduce_dtype(name: str, dtype: DTypeLike) -> Outcome[str]

The element type a reduction or a running total returns.

Parameters:

Name Type Description Default
name str

The NumPy function: "sum", "mean", "std", "max", "argmax", "cumsum", "any", and the others of reduction_names().

required
dtype DTypeLike

The element type of the operand.

required

Returns:

Type Description
Outcome[str]

The result type, for the function's default arguments (no dtype=). Refused, raising TypeError, where NumPy refuses the type (np.ptp of booleans).

Example

from shaperules import reduce_dtype reduce_dtype("sum", "int8").value 'int64' reduce_dtype("mean", "float32").value 'float32'

Canonical forms

Module shaperules.forms. The module itself is exported, as sr.forms. At the top level: Form, LinForm, DivForm, MonoForm.

This is the low-level layer under shaperules.dims. It has no notion of an unknown size and does no coercion. Most clients do not need it.

Canonical forms for symbolic sizes, and the arithmetic that keeps them canonical.

A size that is not a plain integer is written as one of three forms:

  • LinForm: a sum of names with integer coefficients plus a constant, 2*n + m - 1.
  • DivForm: a floored division of a linear form by a positive integer, (n + 1) // 2 + 3.
  • MonoForm: a product of two or more names with an integer coefficient, 2*h*w.

A linear form and a product have exactly one spelling, however they were built, so two of them are the same size for every assignment of their names exactly when they compare equal. For a division that holds one way only: equal forms are equal sizes, but a DivForm built by hand can spell one size two ways, (2*n)//4 and n//2. The arithmetic of shaperules.dims reduces every division it builds (a shared factor cancels, a whole multiple of the divisor leaves the constant). Some sizes cannot be written at all (n*m + n): a function that cannot give a form answers None, and never an approximation.

This module is the low-level layer. It has no notion of an unknown size and does no coercion; shaperules.dims builds the friendlier Dim on top of it.

Form module-attribute

Form = LinForm | DivForm | MonoForm

Any of the three canonical forms.

LinForm

Bases: NamedTuple

A linear size: sum(coeff * name) + const.

Attributes:

Name Type Description
coeffs tuple[tuple[str, int], ...]

(name, coefficient) pairs, sorted by name, no zero coefficient.

const int

The constant term.

DivForm

Bases: NamedTuple

A floored division of a linear size: inner // div + plus.

Attributes:

Name Type Description
inner LinForm

The dividend.

div int

The divisor, a positive integer.

plus int

A constant added after the division.

MonoForm

Bases: NamedTuple

A product of names: coeff * prod(vars).

Only single products are written this way, never a sum of products. A product of fewer than two names is a LinForm, so each size keeps one spelling. Zero is MonoForm(0, ()).

Attributes:

Name Type Description
coeff int

The integer coefficient.

vars tuple[str, ...]

The names, sorted, a repeated name once per power.

lin_add

lin_add(a: LinForm, b: LinForm) -> LinForm

Add two linear forms.

Parameters:

Name Type Description Default
a LinForm

The first form.

required
b LinForm

The second form.

required

Returns:

Type Description
LinForm

The canonical sum.

lin_scale

lin_scale(form: LinForm, c: int) -> LinForm

Multiply a linear form by an integer.

Parameters:

Name Type Description Default
form LinForm

The form.

required
c int

The factor.

required

Returns:

Type Description
LinForm

The canonical product.

mono_normalize

mono_normalize(
    coeff: int, vars: tuple[str, ...]
) -> MonoForm

Build a canonical product: names sorted, zero collapsed.

Parameters:

Name Type Description Default
coeff int

The integer coefficient.

required
vars tuple[str, ...]

The names, in any order.

required

Returns:

Type Description
MonoForm

The canonical MonoForm.

as_product

as_product(
    form: LinForm | MonoForm,
) -> tuple[int, tuple[str, ...]] | None

Read a form as a single product.

A constant, one name with a coefficient, and a MonoForm are products. A sum (n + m, n + 2) is not.

Parameters:

Name Type Description Default
form LinForm | MonoForm

The form to read.

required

Returns:

Type Description
tuple[int, tuple[str, ...]] | None

(coefficient, names), or None when the form is a sum.

from_product

from_product(
    coeff: int, vars: tuple[str, ...]
) -> LinForm | MonoForm

Build the canonical form of a single product.

Parameters:

Name Type Description Default
coeff int

The integer coefficient.

required
vars tuple[str, ...]

The names, a repeated name once per power.

required

Returns:

Type Description
LinForm | MonoForm

A LinForm for fewer than two names, else a MonoForm.

mul

mul(
    a: LinForm | MonoForm, b: LinForm | MonoForm
) -> LinForm | MonoForm | None

Multiply two products.

Parameters:

Name Type Description Default
a LinForm | MonoForm

The first form.

required
b LinForm | MonoForm

The second form.

required

Returns:

Type Description
LinForm | MonoForm | None

The canonical product, or None when either side is a sum.

exact_div

exact_div(
    numer: LinForm | MonoForm, denom: LinForm | MonoForm
) -> LinForm | MonoForm | None

Divide one product by another when the quotient is exact.

Covers an integer divisor (2*n / 2) and cancelled names (n*k / n, b*c*h*w / b).

Parameters:

Name Type Description Default
numer LinForm | MonoForm

The dividend.

required
denom LinForm | MonoForm

The divisor.

required

Returns:

Type Description
LinForm | MonoForm | None

The canonical quotient, or None when either side is a sum, the divisor is zero, or the division leaves a remainder.

names

names(form: object) -> tuple[str, ...]

The names a form mentions, each once, sorted.

Parameters:

Name Type Description Default
form object

A canonical form. Anything else has no names.

required

Returns:

Type Description
tuple[str, ...]

The names.

provably_ne

provably_ne(
    fa: object,
    fb: object,
    nonzero: bool = False,
    *,
    is_wild: Callable[[str], bool] | None = None,
) -> bool

Whether two forms differ for every assignment of their names.

n + 1 against n can never be equal, and neither can n//2 + 1 against n//2. Two different names, a division against a linear form, and anything that mentions a wild name stay unproven: some sizes may make them equal.

A difference in coefficients alone is another matter: 2*n and n are equal exactly when n is 0, and an empty axis is a legal size. Such a pair counts only under nonzero=True, for a caller that has already ruled a zero factor out.

Parameters:

Name Type Description Default
fa object

The first form, or None.

required
fb object

The second form, or None.

required
nonzero bool

Also count pairs that are equal only when a name is 0.

False
is_wild Callable[[str], bool] | None

Says whether a name can stand for several sizes at once (an unknown minted once and met in a loop, say). Nothing is proven from a form that mentions one. None means no name is wild.

None

Returns:

Type Description
bool

True when no assignment makes the two forms equal. False means "not proven", never "equal".

never_size

never_size(form: object) -> bool

Whether a form is below 0 whatever its names are.

Names are sizes, so never negative: a linear form with no positive coefficient is at most its constant. -n - 1 and -3 qualify; -n (0 on an empty axis) and n - 1 do not.

Parameters:

Name Type Description Default
form object

A canonical form.

required

Returns:

Type Description
bool

True when no array can have this size.

lower_bound

lower_bound(form: Form) -> int | None

The least value a form takes over non-negative names, when it has one.

Parameters:

Name Type Description Default
form Form

A canonical form.

required

Returns:

Type Description
int | None

The bound, which some assignment reaches, or None when the form is unbounded below.

upper_bound

upper_bound(form: Form) -> int | None

The greatest value a form takes over non-negative names, when it has one.

Parameters:

Name Type Description Default
form Form

A canonical form.

required

Returns:

Type Description
int | None

The bound, which some assignment reaches, or None when the form is unbounded above.

can_equal

can_equal(form: Form, value: int) -> bool

Whether some assignment of non-negative names may give a form a value.

The answer errs on the side of True: False is a proof that no assignment works, True is the absence of one.

Parameters:

Name Type Description Default
form Form

A canonical form.

required
value int

The integer to reach.

required

Returns:

Type Description
bool

False when the form provably never has this value.

evaluate

evaluate(form: Form, sizes: Mapping[str, int]) -> int

The value of a form under an assignment of its names.

Parameters:

Name Type Description Default
form Form

A canonical form.

required
sizes Mapping[str, int]

A size for every name the form mentions.

required

Returns:

Type Description
The integer the form stands for. It can be negative

n - 1 at n = 0 is -1, which is not a size.

Raises:

Type Description
KeyError

When a name has no size.

format_form

format_form(
    form: Form, display: Callable[[str], str] | None = None
) -> str

A readable formula: 2*n+3, n-1, (n+1)//2, n//2+1, h*w.

Parameters:

Name Type Description Default
form Form

A canonical form.

required
display Callable[[str], str] | None

Maps a name to the text shown for it. None shows names as they are.

None

Returns:

Type Description
str

The formula. shaperules.dims.parse reads it back to the same size when display is None and every name is a dotted identifier.

from_repr

from_repr(text: str | AST) -> Form

Rebuild a form from its repr.

A form's repr is a stable text a caller can store (in a name, a cache key, a file) and read back. Only the three canonical shapes over integers, strings and tuples are accepted, so the text is never evaluated as code. A leading underscore on the class name is accepted too, for texts written before these classes were public.

Parameters:

Name Type Description Default
text str | AST

The repr of a form, or its parsed expression.

required

Returns:

Type Description
Form

The form.

Raises:

Type Description
ValueError

When the text is not the repr of a form.