Sizes¶
A size is the length of one axis of an array. A shape is a tuple of sizes, one per axis. In shaperules a size is one of three things:
- an
int, when it is known; - a formula over names, such as
n,2*n+1,(n+1)//2orh*w; ANY, when nothing is known about it.
Writing sizes¶
Every rule accepts a size as an integer, as a string holding a formula, or as
a size object built earlier. dim reads one size and shape reads several:
>>> sr.dim(3)
3
>>> sr.fmt(sr.dim("2*n + 1"))
'2*n+1'
>>> sr.fmt_shape(sr.shape("batch", "2*n + 1", 3))
'(batch, 2*n+1, 3)'
A whole shape can be one string. as_shape reads it, and so does every rule:
>>> sr.fmt_shape(sr.as_shape("batch, n, 3"))
'(batch, n, 3)'
>>> sr.fmt_shape(sr.matmul("batch, n, 64", "64, 10").value)
'(batch, n, 10)'
You rarely need dim, shape or as_shape yourself, since the rules call
them on their arguments. They are useful for building a shape once and for
comparing answers.
A size is never negative, and a bool is not a size:
>>> sr.dim(-1)
Traceback (most recent call last):
...
ValueError: a size is not negative: -1
>>> sr.dim(True)
Traceback (most recent call last):
...
TypeError: a size is an integer, a formula or ANY, not a bool
Names¶
A name stands for one non-negative integer, the same one wherever the name appears. Two consequences follow, and the rules rely on both:
nequalsn, in one shape or across shapes.n + 1never equalsn.
Zero is a legal value. NumPy allows an axis of length 0, so a rule that claims
something for every n has to be right at n = 0 too. This is why taking
a[0] from an axis of size n is not a proven success.
A name is a Python identifier, and it can be dotted: pkg.mod.N is one name.
sym makes a named size from its name directly, without parsing a formula:
Formulas¶
parse reads a formula. A formula is built from integers, names, +, -,
*, // by a positive integer, and parentheses. dim calls parse on a
string, so the two read the same text.
>>> sr.fmt(sr.parse("1 + n*2"))
'2*n+1'
>>> sr.fmt(sr.parse("(n + 1) // 2"))
'(n+1)//2'
>>> sr.fmt(sr.parse("w * h * 2"))
'2*h*w'
Formulas are kept in a canonical form: a fixed way of writing a formula, so
that the order you wrote it in does not matter. Two sizes that have the same
canonical form compare equal with ==.
>>> sr.dim("n + m") == sr.dim("m + n")
True
>>> sr.dim("2 * (n + 1)") == sr.dim("2*n + 2")
True
>>> sr.dim("n - n")
0
>>> sr.fmt(sr.dim("4*n // 2"))
'2*n'
A formula with no names left is a plain int.
There are three kinds of form, and each is a named tuple you can inspect:
| Form | Holds | Example |
|---|---|---|
LinForm |
A sum of names with integer coefficients, plus a constant. | 2*n + m - 1 |
DivForm |
A linear form divided by a positive integer and rounded down, plus a constant. | (n + 1) // 2 + 3 |
MonoForm |
One product of two or more names with an integer coefficient. | 2*h*w |
>>> type(sr.dim("2*n + 1")).__name__
'LinForm'
>>> type(sr.dim("(n + 1) // 2")).__name__
'DivForm'
>>> type(sr.dim("h * w")).__name__
'MonoForm'
Formulas with no form¶
The three forms do not cover every formula. There is no form for a sum of
products, for a product with a sum in it, or for a division that is then
multiplied. Such a formula is read as ANY. No formula is ever approximated.
Text that is not a formula at all is an error:
>>> sr.dim("n / 2")
Traceback (most recent call last):
...
ValueError: not a size formula: 'n / 2'
>>> sr.dim("n // m")
Traceback (most recent call last):
...
ValueError: a size is divided by a positive integer only: 'n // m'
ANY¶
ANY is the size nothing is known about. Write it as sr.ANY or as "?" in
a string.
A name is known to equal itself. ANY is not: two ANY sizes may be
different sizes. So a rule proves less about ANY than about a name.
>>> sr.broadcast(("n",), ("n",)) == sr.Known(sr.shape("n"))
True
>>> sr.broadcast(("?",), ("?",)).reason
'sizes at axis -1 must be equal or 1: ? and ?'
ANY in a Known answer means that axis exists and its size is not known:
Fresh names¶
fresh returns a named size that no other call returns. Use it for a length
that is fixed but not known yet, such as the number of elements a boolean mask
selects. It equals itself, and it is not known to equal anything else. That is
more than ANY gives you.
>>> selected = sr.fresh("selected")
>>> other = sr.fresh("selected")
>>> selected == other
False
>>> sr.broadcast((selected, 3), (selected, 1)) == sr.Known((selected, 3))
True
The names are numbered in the order they are made, selected#1, selected#2
and so on, counting from the start of the process. fmt prints such a name,
but parse does not read that text back to the same size, because # is not
part of a formula.
Arithmetic¶
The arithmetic on sizes lives in shaperules.dims. Each function accepts what
dim accepts and returns a size in canonical form, or ANY when the result
has no form.
>>> from shaperules import dims
>>> sr.fmt(dims.add("n", "n + 1"))
'2*n+1'
>>> sr.fmt(dims.sub("n", 1))
'n-1'
>>> sr.fmt(dims.mul("h", "w"))
'h*w'
>>> sr.fmt(dims.mul(2, "n + 1"))
'2*n+2'
>>> dims.mul("n + 1", "m")
ANY
>>> sr.fmt(dims.floordiv("n + 1", 2))
'(n+1)//2'
prod multiplies the sizes of a shape, which gives its number of elements:
exact_div divides when the division leaves no remainder, and returns None
when it may leave one. reshape uses it to work out a -1.
Two details are worth knowing:
subreturns a formula, and a formula can go below zero.n-1is -1 whennis 0. A rule that subtracts checks the bounds itself.- A product with a known 0 is 0, whatever the other size is,
ANYincluded.
Comparing sizes¶
The comparisons in shaperules.dims are proofs, like the answers of the
rules. True means the statement holds for every assignment of the names.
False means it was not proven. It does not mean the opposite holds.
| Function | True when |
|---|---|
equal(a, b) |
The two sizes are equal for every assignment. |
unequal(a, b) |
The two sizes differ for every assignment. |
can_be(a, k) |
False only when the size provably never has the value k. |
at_least(a, k) |
The size is at least k for every assignment. |
at_most(a, k) |
The size is at most k for every assignment. |
>>> n, m = sr.dim("n"), sr.dim("m")
>>> dims.equal(n, n), dims.equal(n, m)
(True, False)
>>> dims.unequal(n, sr.dim("n + 1")), dims.unequal(n, m)
(True, False)
n and m are neither provably equal nor provably unequal, since they may or
may not have the same value. The same goes for 2*n and n, which are equal
exactly when n is 0:
The bounds come from the form itself. Every size is at least 0, n + 2 is at
least 2, and 2*n is never 1:
>>> dims.at_least(sr.dim("n + 2"), 2), dims.at_least(n, 1)
(True, False)
>>> dims.can_be(n, 1), dims.can_be(sr.dim("2*n"), 1)
(True, False)
ANY proves nothing: it is not known to equal or to differ from anything.
Printing and reading back¶
fmt prints a size and fmt_shape prints a shape, the way NumPy prints one.
For a formula over ordinary names, parse reads the text of fmt back to the
same size.
>>> sr.fmt_shape(sr.shape("n"))
'(n,)'
>>> sr.fmt_shape(())
'()'
>>> size = sr.dim("(n + 1) // 2 + 3")
>>> sr.fmt(size)
'(n+1)//2+3'
>>> sr.parse(sr.fmt(size)) == size
True
Both take a display function that maps a name to the text shown for it. A
client whose names are long can shorten them for a message:
>>> long = sr.dim("pkg.mod.N + 1")
>>> sr.fmt(long)
'pkg.mod.N+1'
>>> sr.fmt(long, display=lambda name: name.rsplit(".", 1)[-1])
'N+1'
Putting numbers in¶
substitute replaces names by integers. With every name given, the result is
an int. With some given, it is a smaller formula. substitute_shape does
the same for a whole shape.
>>> sr.substitute(sr.dim("2*n + 1"), {"n": 4})
9
>>> sr.fmt(sr.substitute(sr.dim("n + m"), {"n": 4}))
'm+4'
>>> sr.substitute_shape(sr.shape("batch", "2*n + 1", 3), {"batch": 8, "n": 5})
(8, 11, 3)
Values that make a size negative are an error, since no array has that size:
>>> sr.substitute(sr.dim("n - 1"), {"n": 0})
Traceback (most recent call last):
...
ValueError: n-1 is negative for these sizes
A client can use this to turn a symbolic answer into a concrete shape once the sizes are known, without asking the rule again.
Looking inside¶
is_known says whether a size is a plain integer. dims.names lists the
names a size or a shape mentions.
>>> sr.is_known(sr.dim(3)), sr.is_known(sr.dim("n")), sr.is_known(sr.ANY)
(True, False, False)
>>> dims.names(sr.shape("batch", "h*w", "2*n + 1"))
('batch', 'h', 'n', 'w')
The functions on this page are documented one by one in the API reference.