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
¶
What a rule returns.
Refusal
dataclass
¶
Why NumPy refuses a call.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
A stable identifier of the check that failed, such as
|
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: |
axis |
int | None
|
The axis at fault, for a refusal about one axis, else None.
For |
RuleError
¶
Bases: Exception
Base of the two exceptions unwrap raises.
ShapeRefused
¶
Bases: RuleError
Raised by unwrap on a Refused answer.
Attributes:
| Name | Type | Description |
|---|---|---|
refusal |
Why NumPy refuses the call. |
ShapeUnknown
¶
Bases: RuleError
Raised by unwrap on an Unknown answer.
Attributes:
| Name | Type | Description |
|---|---|---|
reason |
What the answer depends on. |
Known
dataclass
¶
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. |
Refused
dataclass
¶
NumPy raises, for every assignment of the names.
Attributes:
| Name | Type | Description |
|---|---|---|
refusal |
Refusal
|
Why. |
Unknown
dataclass
¶
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. |
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
intwhen it is known; - a canonical form (
shaperules.forms) when it is a formula over names,n,2*n + 1,(n + 1) // 2,h*w; ANYwhen 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
¶
A size nothing is known about, not even that it equals itself.
Dim
module-attribute
¶
The size of one axis: an integer, a formula over names, or ANY.
DimLike
module-attribute
¶
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.
ShapeLike
module-attribute
¶
What the functions of this library accept for a shape.
AnyDim
¶
The size nothing is known about. Use the one instance, ANY.
normalize
¶
sym
¶
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
( |
required |
Returns:
| Type | Description |
|---|---|
Dim
|
The size |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the name is empty or holds whitespace. |
fresh
¶
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, |
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 |
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
¶
as_shape
¶
is_known
¶
Whether a size is a plain integer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Dim
|
The size. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True for an |
names
¶
add
¶
neg
¶
sub
¶
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 |
mul
¶
prod
¶
floordiv
¶
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 ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the divisor is not positive. |
exact_div
¶
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
¶
equal
¶
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"
|
|
unequal
¶
can_be
¶
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. |
at_least
¶
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 |
at_most
¶
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 |
substitute
¶
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the names given make the size negative. |
substitute_shape
¶
fmt
¶
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. |
fmt_shape
¶
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
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
Dim
|
The size. A formula with no canonical form ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the text is not such a formula, or is negative
whatever its names are ( |
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
¶
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]
|
|
match_pair
¶
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]
|
|
broadcast
¶
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 |
Example
from shaperules import broadcast, fmt_shape fmt_shape(broadcast((8, 1, 3), ("n", 3)).value) '(8, n, 3)'
matmul
¶
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 |
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
¶
An axis argument: one axis, several, or None.
normalize_axis
¶
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
|
normalize_axes
¶
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 ( |
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 ( |
False
|
scalar_axis
|
bool
|
Whether the function accepts |
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 |
reduce_shape_names
¶
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: |
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. |
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
¶
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
¶
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 |
swapaxes
¶
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
¶
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 |
expand_dims
¶
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
¶
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 |
concatenate
¶
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 |
stack
¶
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
¶
One item of a basic index.
index
¶
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 |
Example
from shaperules import index index((10, 4), (slice(2, 8, 2), None, 0)).value (3, 1)
slice_length
¶
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
¶
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
¶
The element types covered, from bool to complex128.
NAME_OF_KIND_SIZE
module-attribute
¶
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
¶
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 |
kind_bits_name
¶
The element type of a kind and a width in bits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
str
|
|
required |
bits
|
int
|
The width of the whole item: |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The name, or None when there is no such type. |
promote
¶
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 |
promote_all
¶
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
¶
The element type of an array combined with a Python number.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scalar
|
type
|
The Python type of the number: |
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 ( |
result_type
¶
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. |
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
¶
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: |
ufunc_names
¶
The ufuncs ufunc_dtypes knows, under every public NumPy name.
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
The names, sorted. |
ufunc_dtypes
¶
The element types a ufunc returns for its operands, one per output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The ufunc's NumPy name: |
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. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the number of operands is not what the ufunc takes. |
ufunc_dtype
¶
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 |
Example
from shaperules import ufunc_dtype ufunc_dtype("true_divide", "int32", "int32").value 'float64' ufunc_dtype("sqrt", "int8").value 'float16'
reduction_names
¶
The reductions reduce_dtype knows.
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
The names, sorted. |
reduce_dtype
¶
The element type a reduction or a running total returns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The NumPy function: |
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
|
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.
LinForm
¶
Bases: NamedTuple
A linear size: sum(coeff * name) + const.
Attributes:
| Name | Type | Description |
|---|---|---|
coeffs |
tuple[tuple[str, int], ...]
|
|
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_scale
¶
mono_normalize
¶
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 |
as_product
¶
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
|
|
from_product
¶
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 |
mul
¶
exact_div
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
When a name has no size. |
format_form
¶
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. |
from_repr
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
Form
|
The form. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the text is not the |