Skip to content

Shape rules

A shape rule takes the shapes of the operands of one NumPy operation and answers with the shape of its result. This page goes through every rule in version 0.1, with the NumPy function it stands for.

Rule NumPy
broadcast np.broadcast_shapes, the shape of any element-wise operation
broadcast_pair One axis of a broadcast
match_pair Two sizes that must be equal, with no stretching
matmul a @ b, np.matmul
reduce np.sum, np.prod, np.any, np.all, np.max, np.min
reduce_shape 25 reductions by name: np.sum, np.nanmax, np.median, np.average, np.argmax and the others
arg_reduce np.argmax, np.argmin
cumulative np.cumsum, np.cumprod
transpose a.T, np.transpose
swapaxes np.swapaxes
moveaxis np.moveaxis
squeeze np.squeeze
expand_dims np.expand_dims
reshape np.reshape
concatenate np.concatenate
stack np.stack
index a[key] for a basic index
slice_length The length of one sliced axis

Every rule accepts a shape as a tuple or list of sizes, or as one string such as "batch, n, 3". Every rule returns one of the three answers.

The examples print symbolic shapes with a small helper:

>>> import shaperules as sr

>>> def text(answer):
...     """The proven shape of an answer, the way NumPy prints a shape."""
...     return sr.fmt_shape(answer.unwrap())

Broadcasting

Broadcasting is NumPy's rule for combining arrays of different shapes element by element. The shapes are lined up at their last axis. A missing leading axis counts as size 1. Along each axis the sizes that are not 1 must agree, and that size is the size of the result.

broadcast

broadcast(*shapes) is np.broadcast_shapes. It takes any number of shapes.

>>> sr.broadcast((8, 1, 3), (5, 3))
Known(value=(8, 5, 3))
>>> sr.broadcast((3, 1), (1, 4), (5, 1, 1))
Known(value=(5, 3, 4))
>>> text(sr.broadcast(("batch", 1, 3), ("n", 3)))
'(batch, n, 3)'
>>> sr.broadcast()
Known(value=())

A refusal names the axis the shapes disagree at, counted from the end:

>>> print(sr.broadcast((3, 4), (5,)).refusal.message)
shapes (3, 4) (5,) do not broadcast: they disagree at axis -1

With names, the answer depends on what can be proven about the sizes of each axis. A size of 1 stretches, so the rule has to consider that a name might be 1.

Sizes on one axis Answer Why
n and n Known, n The same name is the same size.
n and 1 Known, n A 1 stretches to anything.
n + 2 and n + 3 Refused Never equal, and neither can be 1.
2*n and 3 Refused 2*n is never 3 and never 1.
n and 3 Unknown, likely 3 Valid when n is 3 or 1. The result is 3 both times.
n and m Unknown, no likely reading Valid when they are equal or one of them is 1.
n and n - 1 Unknown, likely Refused Never equal. Valid only when n is 1 or 2.

One axis at a time

broadcast_pair(a, b) is the rule for a single axis: the size two sizes broadcast to. The rows of the table above are calls to it.

>>> sr.broadcast_pair("n", 1) == sr.Known(sr.dim("n"))
True
>>> sr.broadcast_pair("n + 2", "n + 3").refusal.message
'sizes n+2 and n+3 do not broadcast'
>>> sr.broadcast_pair("n", 3)
Unknown(reason='sizes must be equal or 1: n and 3', likely=Known(value=3))
>>> sr.broadcast_pair("n", "m")
Unknown(reason='sizes must be equal or 1: n and m', likely=None)
>>> sr.broadcast_pair("n", "n - 1").likely.refusal.kind
'broadcast'

match_pair(a, b) is for the places where NumPy does not stretch a 1: the inner sizes of a matrix product, and the axes of a concatenation that are not the one joined. The two sizes must be equal.

>>> sr.match_pair("n", "n") == sr.Known(sr.dim("n"))
True
>>> sr.match_pair(3, 1).refusal.message
'sizes 3 and 1 differ'
>>> sr.match_pair("n", 3)
Unknown(reason='sizes must be equal: n and 3', likely=Known(value=3))

These two are the building blocks for a client that writes a rule shaperules does not have.

matmul

matmul(a, b) is the shape of a @ b. The last axis of a must equal the last-but-one axis of b, with no stretching of a 1. The axes before the last two broadcast.

>>> text(sr.matmul(("batch", "n", 64), (64, 10)))
'(batch, n, 10)'
>>> text(sr.matmul(("batch", 1, "n", "k"), (8, "k", "m")))
'(batch, 8, n, m)'

An operand with one axis is a row vector on the left and a column vector on the right, and its axis is dropped from the result:

>>> sr.matmul(("n",), ("n",))
Known(value=())
>>> sr.matmul((3, "n"), ("n",))
Known(value=(3,))
>>> sr.matmul(("n",), ("n", 5))
Known(value=(5,))

There are three refusals. NumPy raises ValueError for each.

>>> sr.matmul((2, 3), (4, 5)).refusal.kind
'matmul-core'
>>> sr.matmul((2, 3, "n"), (4, "n", 5)).refusal.kind
'matmul-batch'
>>> sr.matmul((), ("n", 5)).refusal.kind
'matmul-scalar'

When the inner sizes are two different names the answer is Unknown. The shape of the result does not involve them, so where one is an integer the likely reading is still complete:

>>> sr.matmul((2, "n"), ("m", 5)).reason
'the inner sizes of the product must be equal: n and m'
>>> sr.matmul((2, 1), ("n", 5)).likely
Known(value=(2, 5))

Reductions

reduce

reduce(shape, axis=None, keepdims=False) is the shape of a reduction, a function that combines the elements along one or more axes into one: np.sum, np.prod, np.any, np.all. The axes reduced are removed, or kept with size 1 under keepdims=True. axis is one axis, a tuple of axes, or None for all of them. A negative axis counts from the end.

>>> text(sr.reduce(("batch", "n", 3), axis=1))
'(batch, 3)'
>>> text(sr.reduce(("batch", "n", 3), axis=-1))
'(batch, n)'
>>> text(sr.reduce(("batch", "n", 3), axis=(0, 2)))
'(n,)'
>>> text(sr.reduce(("batch", "n", 3), axis=1, keepdims=True))
'(batch, 1, 3)'
>>> sr.reduce(("batch", "n", 3))
Known(value=())

An axis out of range is an AxisError in NumPy, and an axis named twice is a ValueError:

>>> sr.reduce((4, 5), axis=2).refusal.kind
'axis-out-of-range'
>>> sr.reduce((4, 5), axis=(0, 0)).refusal.kind
'axis-repeated'

np.max, np.min and np.ptp have no value for an empty input. NumPy raises ValueError when the axes they reduce hold no element. Pass needs_elements=True for these:

>>> sr.reduce((0, 3), axis=0, needs_elements=True).refusal.kind
'reduce-empty'
>>> sr.reduce((0, 3), axis=1, needs_elements=True)
Known(value=(0,))
>>> text(sr.reduce(("batch", "n + 1"), axis=1, needs_elements=True))
'(batch,)'

The second call reduces the axis of size 3, which holds elements, so NumPy returns an empty result without complaint. In the third, n + 1 is at least 1 whatever n is. A plain n may be 0, so the answer is Unknown with the shape as its likely reading:

>>> answer = sr.reduce(("batch", "n"), axis=1, needs_elements=True)
>>> answer.reason
'the reduction needs an element: n must not be 0'
>>> sr.fmt_shape(answer.likely.value)
'(batch,)'

For an array with no axes, reduce follows np.sum and np.max: a single axis of 0 or -1 is accepted and names nothing, and the same axis inside a tuple is out of range. np.mean, np.std, np.var, np.median and np.average differ from np.sum on this one point and raise AxisError for a single axis of 0 or -1 as well. Pass scalar_axis=False for those:

>>> sr.reduce((), axis=0)
Known(value=())
>>> sr.reduce((), axis=0, scalar_axis=False).refusal.raises
'AxisError'

For every other input their shapes are the ones reduce gives either way.

reduce_shape

reduce_shape(name, shape, axis=None, keepdims=False) is the shape of a reduction by the name NumPy gives it. It knows which reductions need an element, which refuse axis=0 for an array with no axes and which take one axis only, so the caller passes no flags.

>>> sr.reduce_shape("sum", (0, 3), axis=0)
Known(value=(3,))
>>> sr.reduce_shape("max", (0, 3), axis=0).refusal.kind
'reduce-empty'
>>> sr.reduce_shape("sum", (), axis=0)
Known(value=())
>>> sr.reduce_shape("median", (), axis=0).refusal.raises
'AxisError'
>>> sr.reduce_shape("argmax", (4, 5), axis=(0, 1)).refusal.raises
'TypeError'

reduce_shape_names() lists the names it knows:

>>> sr.reduce_shape_names()
('all', 'amax', 'amin', 'any', 'argmax', 'argmin', 'average', 'count_nonzero', 'max', 'mean', 'median', 'min', 'nanmax', 'nanmean', 'nanmedian', 'nanmin', 'nanprod', 'nanstd', 'nansum', 'nanvar', 'prod', 'ptp', 'std', 'sum', 'var')

Three of the names have a case of their own.

np.average divides by the number of results, so a result with no elements is a ZeroDivisionError:

>>> sr.reduce_shape("average", (0, 3), axis=1).refusal.raises
'ZeroDivisionError'
>>> sr.reduce_shape("mean", (0, 3), axis=1)
Known(value=(0,))

np.nanmean, np.nanstd and np.nanvar accept axis=0 on an array with no axes when it holds floats. For an array of integers, which holds no NaN, NumPy calls np.mean, np.std or np.var, and those raise. The shape does not say which, so the answer is Unknown:

>>> answer = sr.reduce_shape("nanmean", (), axis=0)
>>> answer.reason
'nanmean of an array with no axes takes axis=0 for a float array and raises AxisError for an integer one'
>>> answer.likely
Known(value=())

np.median over several axes, or over none, raises ValueError in NumPy 2.1 to 2.4 when an axis that stays has size 0, and returns the empty result in NumPy 2.5. The answer is Unknown, and the likely reading is the newer one:

>>> sr.reduce_shape("median", (0, 3), axis=())
Unknown(reason='median over several axes or none, with an empty axis kept, is a ValueError before NumPy 2.5', likely=Known(value=(0, 3)))
>>> sr.reduce_shape("median", (2, 3), axis=())
Known(value=(2, 3))

A name that is not in the list gets Unknown.

arg_reduce

arg_reduce(shape, axis=None, keepdims=False) is the shape of np.argmax and np.argmin. It takes one axis or None, never a tuple, and it needs an element to find.

>>> sr.arg_reduce((4, 5), axis=1)
Known(value=(4,))
>>> sr.arg_reduce((4, 5))
Known(value=())
>>> sr.arg_reduce((4, 5), axis=0, keepdims=True)
Known(value=(1, 5))
>>> sr.arg_reduce((4, 0), axis=1).refusal.kind
'reduce-empty'
>>> sr.arg_reduce((4, 5), axis=(0, 1)).refusal.raises
'TypeError'

cumulative

cumulative(shape, axis=None) is the shape of a running total, np.cumsum or np.cumprod. With an axis the shape is unchanged. With axis=None NumPy flattens the array first, so the result has one axis holding every element.

>>> text(sr.cumulative(("batch", "n"), axis=1))
'(batch, n)'
>>> text(sr.cumulative(("batch", "n")))
'(batch*n,)'

Reordering axes

transpose

transpose(shape, axes=None) is a.T and np.transpose. With no axes the order is reversed. With axes, each entry names the old axis that goes to that place.

>>> text(sr.transpose(("batch", "n", 3)))
'(3, n, batch)'
>>> text(sr.transpose(("batch", "n", 3), (0, 2, 1)))
'(batch, 3, n)'
>>> sr.transpose(("batch", "n", 3), (0, 1)).refusal.kind
'transpose-count'
>>> sr.transpose(("batch", "n", 3), (0, 1, 1)).refusal.kind
'axis-repeated'

swapaxes and moveaxis

swapaxes(shape, axis1, axis2) exchanges two axes. moveaxis(shape, source, destination) moves one axis or several to new places and keeps the others in order.

>>> text(sr.swapaxes(("batch", "n", 3), 1, 2))
'(batch, 3, n)'
>>> text(sr.moveaxis(("batch", "h", "w", "c"), -1, 1))
'(batch, c, h, w)'
>>> text(sr.moveaxis(("a", "b", "c", "d"), (0, 1), (-1, -2)))
'(c, d, b, a)'
>>> sr.moveaxis(("batch", "h", "w", "c"), (0, 1), 1).refusal.kind
'moveaxis-count'

These three rules never answer Unknown. Their result does not depend on any size, only on the number of axes.

Adding and removing axes

squeeze

squeeze(shape, axis=None) is np.squeeze. With no axis it removes every axis of size 1.

>>> sr.squeeze((1, 3, 1))
Known(value=(3,))
>>> text(sr.squeeze((1, "n + 2", 1)))
'(n+2,)'

n + 2 is never 1, so that axis stays. A plain n may be 1, and then the number of axes of the result depends on n. The answer is Unknown, and the likely reading keeps the axis:

>>> answer = sr.squeeze((1, "n", 3))
>>> answer.reason
'an axis is removed only when its size is 1: n'
>>> sr.fmt_shape(answer.likely.value)
'(n, 3)'

With axis, each axis named must have size 1:

>>> sr.squeeze((1, 3), axis=0)
Known(value=(3,))
>>> print(sr.squeeze((1, 3), axis=1).refusal.message)
squeeze: axis 1 of (1, 3) has size 3, not 1
>>> sr.squeeze(("n", 3), axis=0)
Unknown(reason='squeeze: n must be 1', likely=Known(value=(3,)))

expand_dims

expand_dims(shape, axis) is np.expand_dims. It inserts axes of size 1. The positions are counted in the result.

>>> text(sr.expand_dims(("n", 3), 0))
'(1, n, 3)'
>>> text(sr.expand_dims(("n", 3), -1))
'(n, 3, 1)'
>>> text(sr.expand_dims(("n", 3), (0, -1)))
'(1, n, 3, 1)'

Regrouping elements

reshape

reshape(shape, newshape) is np.reshape. The new shape must hold the same number of elements. One size of the new shape may be -1, and the rule works out its value.

>>> text(sr.reshape(("batch", 28, 28), ("batch", 784)))
'(batch, 784)'
>>> text(sr.reshape((2, "n"), ("n", 2)))
'(n, 2)'
>>> text(sr.reshape(("batch", "c", "h", "w"), (-1,)))
'(batch*c*h*w,)'
>>> text(sr.reshape(("2*n",), (2, -1)))
'(2, n)'

The new shape can be a string as well, or a single size for a result with one axis:

>>> text(sr.reshape("2, n", "-1, 2"))
'(n, 2)'
>>> sr.reshape((2, 3), 6)
Known(value=(6,))

A refusal is proven where the element counts can never match:

>>> print(sr.reshape((6,), (4,)).refusal.message)
reshape: cannot reshape (6,) (6 elements) into (4,)
>>> sr.reshape(("2*n + 1",), (2, -1)).refusal.kind
'reshape-size'
>>> sr.reshape((6,), (-1, -1)).refusal.kind
'reshape-two-unknowns'

2*n + 1 is odd whatever n is, so it never splits into two rows.

Three cases answer Unknown.

The count may or may not divide. The likely reading has ANY where the -1 was:

>>> answer = sr.reshape(("n",), (2, -1))
>>> answer.reason
'reshape: n elements must divide by 2'
>>> sr.fmt_shape(answer.likely.value)
'(2, ?)'

The sizes next to the -1 may be 0. NumPy cannot give -1 a value when the other sizes multiply to 0, and raises. So flattening everything after a symbolic batch is not a proof:

>>> answer = sr.reshape(("batch", "c", "h", "w"), ("batch", -1))
>>> answer.reason
'reshape: batch must not be 0 for -1 to have a value'
>>> sr.fmt_shape(answer.likely.value)
'(batch, c*h*w)'

The counts are equal only when a name is 0. The likely reading is then a refusal:

>>> answer = sr.reshape(("2*n",), ("n",))
>>> answer.reason
'reshape: 2*n elements must be n'
>>> answer.likely.refusal.kind
'reshape-size'

concatenate

concatenate(shapes, axis=0) is np.concatenate. The shapes are passed as one list. The sizes along axis are added and every other size must be equal across the arrays, with no stretching.

>>> text(sr.concatenate([("n", 3), ("m", 3), (2, 3)]))
'(m+n+2, 3)'
>>> text(sr.concatenate([("n", 3), ("n", "k")], axis=-1))
'(n, k+3)'

With axis=None NumPy flattens each array first, and the result has one axis:

>>> text(sr.concatenate([("n", 3), ("m",)], axis=None))
'(m+3*n,)'

The refusals:

>>> sr.concatenate([("n", 3), ("m", 4)]).refusal.kind
'join-mismatch'
>>> sr.concatenate([("n", 3), ("m",)]).refusal.kind
'join-rank'
>>> sr.concatenate([(), ()]).refusal.kind
'join-scalar'
>>> sr.concatenate([]).refusal.kind
'join-empty'

stack

stack(shapes, axis=0) is np.stack. All the arrays must have one shape. The result has a new axis whose size is the number of arrays, at position axis counted in the result.

>>> text(sr.stack([("n", 3)] * 4))
'(4, n, 3)'
>>> text(sr.stack([("n", 3)] * 4, axis=1))
'(n, 4, 3)'
>>> sr.stack([("n", 3), ("n + 1", 3)]).refusal.kind
'stack-mismatch'
>>> sr.stack([("n", 3), ("m", 3)]).reason
'sizes at axis 0 must be equal: n and m'

Indexing

index

index(shape, key) is the shape of a[key] for a basic index. A basic index holds integers, slices of integers, None and at most one ..., alone or in a tuple.

Item Effect on the shape
An integer Removes its axis. The integer must be in bounds.
A slice Keeps its axis with a new size.
None Adds an axis of size 1.
... Stands for the axes not named.
>>> sr.index((10, 4), 2)
Known(value=(4,))
>>> sr.index((10, 4), (slice(2, 8, 2), None, 0))
Known(value=(3, 1))
>>> text(sr.index(("batch", "n", 4), (..., 0)))
'(batch, n)'
>>> text(sr.index(("n", 4), (None, ...)))
'(1, n, 4)'

NumPy raises IndexError for the three refusals:

>>> sr.index((3, 4), 5).refusal.kind
'index-out-of-bounds'
>>> sr.index((3, 4), (0, 0, 0)).refusal.kind
'index-too-many'
>>> sr.index((3, 4), (..., ...)).refusal.kind
'index-ellipsis'

An integer index into an axis of symbolic size is proven only when the axis is provably long enough:

>>> sr.index(("n + 3", 4), 2)
Known(value=(4,))
>>> sr.index(("n", 4), -1)
Unknown(reason='index -1 needs n to be at least 1', likely=Known(value=(4,)))

Indexing by an array of integers or by a boolean mask is not covered. A key that holds a list, a string, a float or a bool raises TypeError.

slice_length

slice_length(size, item) is the number of elements a slice selects from one axis. index calls it for each slice in the key. The size is a size object, as dim returns one.

For a known size it is len(range(*item.indices(size))):

>>> sr.slice_length(10, slice(2, 8, 2))
Known(value=3)

For a symbolic size the answer is Known where one formula holds for every value of the names:

>>> n = sr.dim("n")
>>> sr.fmt(sr.slice_length(n, slice(None, None, 2)).unwrap())
'(n+1)//2'
>>> sr.fmt(sr.slice_length(n, slice(None, None, -1)).unwrap())
'n'
>>> sr.fmt(sr.slice_length(sr.dim("n + 5"), slice(3, None)).unwrap())
'n+2'

Where the slice has a bound and the axis may be shorter than the bound, no one formula holds. a[:3] has 3 elements unless the axis has fewer. The answer is Unknown, and the likely reading assumes the axis is long enough:

>>> sr.slice_length(n, slice(None, 3))
Unknown(reason='the slice selects 3 elements only when the axis, of size n, is long enough',
        likely=Known(value=3))
>>> answer = sr.slice_length(n, slice(1, None))
>>> sr.fmt(answer.likely.value)
'n-1'

A slice with a negative step and a bound has no formula for a symbolic size. Its likely reading is ANY.

Axis helpers

normalize_axis(axis, rank) brings one axis into range(rank), counting a negative axis from the end, where rank is the number of axes. normalize_axes(axis, rank) does the same for an axis argument that may be one axis, several, or None. Both return a Refused for an axis out of range or named twice. They are the checks the rules above use, exported for a client that writes its own rule.

>>> sr.normalize_axis(-1, 3)
2
>>> sr.normalize_axes((-1, 0), 3)
(2, 0)
>>> sr.normalize_axes(None, 3)
(0, 1, 2)
>>> sr.normalize_axis(3, 3).refusal.kind
'axis-out-of-range'

Each rule is documented in the API reference, and each refusal in the refusals reference.