pipekit-array¶
Array-API operators on top of pipekit-ops.
One operator runs on NumPy, JAX, CuPy, PyTorch or dask because it dispatches on array_namespace(x).
The design pages have the architecture, the ADRs and the operator catalogue the package was planned from.
What ships today: namespace dispatch, MeanScalar, StackAlong and ConcatenateAlong, the named carrier DimArray, all the dim-level functions with their operator twins (ApplyAlong included), padded batches and BatchAlong, sample tables and Estimator, the einx bridge, KernelOp, the xarray adapter and the test kit.
What is still to build from the v0.1 catalogue: the numeric QC family (AssertClose, AssertValueRange, AssertNoNaN, AssertValidFraction), the array-aware Histogram and the trained-model wrapper ModelOp.
The package is six areas, each with one job.
Import a name from its area, never from a file in it.
An area imports only from the ones before it, and testing from all of them (ADR A30).
Plain arrays¶
pipekit_array.arrays is for functions of plain arrays, such as the formulas of geophysix and radiomax ([numpy,compat]).
Python numbers, sequences and NumPy arrays join the library and the device of the other arrays (ADR A23).
What the array API standard leaves out (indexed updates, loops, padding) is JAX's own call on JAX data, and a plain equivalent on every other library (ADR A27).
pipekit_array.arrays
¶
Functions of plain arrays: any array library, no dimension names.
A function that is no Operator (a formula of a physics library) is written
once, in functions of the array API standard, and runs on NumPy, JAX, torch,
CuPy, dask and any other library that array_api_compat knows:
@elementwise() # labelled arrays
def density(pressure, temperature):
xp, (p, t) = floating_inputs(pressure, temperature) # one dtype, device
return p / (like(287.0, t, xp) * t)
- The call:
namespace_of,floating_inputs,as_inexact,concrete,is_dataarray. - Values of the host:
like,constants_like,table_like,boolean_like. - Numerics:
divide_or_nan,safe_sqrt,safe_power,safe_atan2,squared_magnitude,stand_in. - Copies with changes:
set_at,add_at,multiply_at,pad. - Transformations:
vmap,scan,stop_gradient,optimization_barrier. - Checks:
check_values,require_floating. - Masked, weighted reductions:
weighted_sum,weighted_mean,Groups,reduction_inputs,used_weights. - Records:
register_record.
pipekit_array.kernels.elementwise lets such a function take labelled arrays.
This area needs pipekit-array[numpy,compat], so importing pipekit_array
does not import it. It imports no other area, and no array library but NumPy.
Groups
dataclass
¶
Which samples belong to which group; built once, on the host.
The tables are NumPy arrays and static: under JAX a Groups is a closure or
a static argument, and never a traced one. It is compared by identity, so
build it once; a new one compiles again.
G groups of at most M samples cost G M reads, so one very large group among many small ones costs memory.
Attributes:
| Name | Type | Description |
|---|---|---|
index |
ndarray
|
Positions of each group's samples, padded with 0, (G, M). |
member |
ndarray
|
Which entries of |
labels |
ndarray
|
The group of each of the N samples, -1 for none. |
Example
import numpy as np groups = Groups.from_labels([0, 1, 0, -1], n_groups=3) x = np.asarray([1.0, 2.0, 3.0, 100.0]) groups.sum(x) array([4., 2., 0.]) groups.mean(x) array([ 2., 2., nan]) groups.count(x) array([2, 1, 0], dtype=int32) x - groups.spread(groups.mean(x)) array([-1., 0., 1., nan])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_reductions.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
n_groups
property
¶
G, the number of groups, empty ones included.
n_samples
property
¶
N, the number of samples, those in no group included.
count(values, *, axis=-1, valid=None)
¶
The number of valid samples in each group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Any
|
x, with the N samples on |
required |
axis
|
int
|
The axis of the samples. |
-1
|
valid
|
Any
|
Which samples to count (True = count), broadcast against
|
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The counts, int32, with the G groups on |
Raises:
| Type | Description |
|---|---|
BackendError
|
If an argument is a labelled array, or of another library. |
ValueError
|
If |
Source code in packages/pipekit-array/src/pipekit_array/arrays/_reductions.py
from_labels(labels, n_groups)
classmethod
¶
The groups of samples with the same label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Any
|
The group of each sample, concrete integers in [0, G), or -1 for a sample in no group. |
required |
n_groups
|
int
|
G, at least 1; a group may be empty. |
required |
Returns:
| Type | Description |
|---|---|
Groups
|
The groups. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/pipekit-array/src/pipekit_array/arrays/_reductions.py
mean(values, *, axis=-1, valid=None, weights=None)
¶
The mean of each group's valid samples, weighted by w.
x̄ⱼ = Sⱼ / ∑{n : g(n) = j} mₙ wₙ, with Sⱼ = ∑ mₙ wₙ xₙ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Any
|
x, with the N samples on |
required |
axis
|
int
|
The axis of the samples. |
-1
|
valid
|
Any
|
Which samples to use (True = use), broadcast against
|
None
|
weights
|
Any
|
w ≥ 0, broadcast against |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
x̄, with the G groups on |
Any
|
weights sum to 0. |
Raises:
| Type | Description |
|---|---|
BackendError
|
If an argument is a labelled array, or of another library. |
ValueError
|
If |
Source code in packages/pipekit-array/src/pipekit_array/arrays/_reductions.py
spread(grouped, *, axis=-1)
¶
Each sample's group value: the inverse lookup.
yₙ = x_{g(n)}, so that x - groups.spread(groups.mean(x)) is the
anomaly from the group's mean.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grouped
|
Any
|
One value per group, on |
required |
axis
|
int
|
The axis of the groups. |
-1
|
Returns:
| Type | Description |
|---|---|
Any
|
y, with the N samples on |
Raises:
| Type | Description |
|---|---|
BackendError
|
If |
ValueError
|
If |
Source code in packages/pipekit-array/src/pipekit_array/arrays/_reductions.py
sum(values, *, axis=-1, valid=None)
¶
The sum of each group's valid samples.
Sⱼ = ∑_{n : g(n) = j} mₙ xₙ, with g(n) the group of sample n and m the validity, 1 or 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Any
|
x, with the N samples on |
required |
axis
|
int
|
The axis of the samples. |
-1
|
valid
|
Any
|
Which samples to use (True = use), broadcast against
|
None
|
Returns:
| Type | Description |
|---|---|
Any
|
S, with the G groups on |
Raises:
| Type | Description |
|---|---|
BackendError
|
If an argument is a labelled array, or of another library. |
ValueError
|
If |
Source code in packages/pipekit-array/src/pipekit_array/arrays/_reductions.py
add_at(x, index, values)
¶
A copy of an array with some entries added to: y = x, then y[index] += v.
An entry that the index names twice is added to twice, which y[index] += v
does not do on NumPy. On JAX it is x.at[index].add(values).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The array, which is not changed. |
required |
index
|
Any
|
As in |
required |
values
|
Any
|
What to add, which broadcasts to |
required |
Returns:
| Type | Description |
|---|---|
Any
|
y, in |
Raises:
| Type | Description |
|---|---|
BackendError
|
As |
IndexError
|
As |
Example
import numpy as np add_at(np.zeros(4), np.asarray([0, 2, 2]), [1.0, 10.0, 100.0]) array([ 1., 0., 110., 0.])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_indexing.py
as_inexact(x, xp=None)
¶
An array as it is if floating or complex, else in the default float.
Unlike floating_inputs, it takes one array, and complex numbers. The
default float is the namespace's: float64 on NumPy, and on JAX what
jax_enable_x64 says.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
An array, a sequence or a number. |
required |
xp
|
ModuleType | None
|
The namespace of the call; that of |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
An array of |
Raises:
| Type | Description |
|---|---|
BackendError
|
If |
ValueError
|
If |
Example
import numpy as np as_inexact(np.arange(3)).dtype, as_inexact([1j]).dtype (dtype('float64'), dtype('complex128'))
Source code in packages/pipekit-array/src/pipekit_array/arrays/_backend.py
boolean_like(value, ref, xp, *, name='valid')
¶
A boolean argument (a mask) in ref's library, on its device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
A boolean, a sequence of them, or a boolean array. A value on the
host joins |
required |
ref
|
Any
|
An array of the namespace |
required |
xp
|
ModuleType
|
The namespace of the call. |
required |
name
|
str
|
What the argument is called, for the error. |
'valid'
|
Returns:
| Type | Description |
|---|---|
Any
|
The mask as an array of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
import numpy as np boolean_like([True, False], np.zeros(2), np).tolist() [True, False] boolean_like([1, 0], np.zeros(2), np) Traceback (most recent call last): ... ValueError: 'valid' must be boolean (True = use), got dtype int64
Source code in packages/pipekit-array/src/pipekit_array/arrays/_host.py
check_values(array, bad, message, *, error=ValueError)
¶
An array, or an error if its values are wrong.
The check belongs to the array that is returned: under a trace, use that one, because JAX drops a check whose result nothing uses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
Any
|
The array that the check is about. |
required |
bad
|
Any
|
Whether the check fails, a boolean scalar. |
required |
message
|
str
|
What must hold, naming the argument ( |
required |
error
|
type[Exception]
|
The exception to raise on concrete arrays, such as a library's own. Under a trace it is equinox's, with the same message. |
ValueError
|
Returns:
| Type | Description |
|---|---|
Any
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
|
ImportError
|
Under a trace, if equinox is not installed. |
Example
import numpy as np x = np.asarray([1.0, 2.0]) check_values(x, np.any(x <= 0), "'x' must be positive") array([1., 2.]) check_values(x, np.any(x > 1), "'x' must be ≤ 1") Traceback (most recent call last): ... ValueError: 'x' must be ≤ 1, got array([1., 2.])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_checks.py
concrete(x)
¶
The values of an array on the host, or None if it has none yet.
For a check or a table that needs values and is skipped under jax.jit.
No gradient goes through the copy, and a dask array is computed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
An array, a sequence or a number. |
required |
Returns:
| Type | Description |
|---|---|
ndarray | None
|
The values as a NumPy array, or |
Example
concrete([1.0, 2.0]) array([1., 2.])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_backend.py
constants_like(table, ref, xp)
¶
A table of numbers in ref's library and dtype, on its device.
The numbers are constants of the problem (weights, the spacing of a grid),
and no request for a precision, so a float64 table leaves a float32 field in
float32. A table that is an array of xp already, such as the metric of a
grid that is traced with its field, keeps its gradient.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table
|
Any
|
The numbers: an array, a sequence or a number. |
required |
ref
|
Any
|
An array of the namespace |
required |
xp
|
ModuleType
|
The namespace of the call. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The table as an array of |
Example
import numpy as np constants_like([0.5, 1.5], np.zeros(3, dtype=np.float32), np) array([0.5, 1.5], dtype=float32) constants_like([0.5, 1.5], np.zeros(3, dtype=np.int64), np) array([0.5, 1.5])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_host.py
divide_or_nan(numerator, denominator, xp)
¶
The quotient of two arrays, NaN where the denominator is 0.
It goes through a double where, so a gradient is finite in the other
elements: the division that is not used divides by 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
numerator
|
Any
|
An array of the namespace |
required |
denominator
|
Any
|
An array that broadcasts against it, of its dtype. |
required |
xp
|
ModuleType
|
The namespace of the call. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The quotient. |
Example
import numpy as np divide_or_nan(np.asarray([1.0, 1.0]), np.asarray([2.0, 0.0]), np) array([0.5, nan])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_numerics.py
floating_inputs(*values, params=())
¶
The namespace of a call and its array inputs in one floating dtype.
The dtype is the common one of the floating arrays (float32 stays float32). Python numbers and integer or boolean arrays adopt it; with no floating array, everything takes the namespace's default float. Values on the host join the device of the first array that is not.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*values
|
Any
|
The array inputs: arrays, sequences or Python numbers. |
()
|
params
|
tuple[Any, ...]
|
Other parameters, Python floats or 0-d arrays. They help to choose the namespace and the device, so a traced JAX scalar selects JAX, and never decide the dtype. |
()
|
Returns:
| Type | Description |
|---|---|
tuple[ModuleType, list[Any]]
|
The namespace, and |
Raises:
| Type | Description |
|---|---|
BackendError
|
As |
ValueError
|
If an input is complex, a date or not numeric. |
Example
import numpy as np xp, (x, y) = floating_inputs(np.zeros(2, dtype=np.float32), 1.5) x.dtype, y.dtype (dtype('float32'), dtype('float32'))
Source code in packages/pipekit-array/src/pipekit_array/arrays/_backend.py
is_dataarray(value)
¶
Say whether a value is an xarray DataArray, without importing xarray.
Example
is_dataarray(1.0) False
Source code in packages/pipekit-array/src/pipekit_array/arrays/_backend.py
like(value, ref, xp)
¶
value (a number or a 0-d array) in ref's dtype, on its device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The constant. |
required |
ref
|
Any
|
An array of the namespace |
required |
xp
|
ModuleType
|
The namespace of the call. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A 0-d array, or |
Example
import numpy as np like(0.1, np.zeros(2, dtype=np.float32), np).dtype dtype('float32')
Source code in packages/pipekit-array/src/pipekit_array/arrays/_host.py
multiply_at(x, index, values)
¶
A copy of an array with some entries multiplied: y = x, then y[index] *= v.
An entry that the index names twice is multiplied twice. On JAX it is
x.at[index].multiply(values).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The array, which is not changed. |
required |
index
|
Any
|
As in |
required |
values
|
Any
|
The factors, which broadcast to |
required |
Returns:
| Type | Description |
|---|---|
Any
|
y, in |
Raises:
| Type | Description |
|---|---|
BackendError
|
As |
IndexError
|
As |
Example
import numpy as np multiply_at(np.ones(3), np.asarray([1, 1]), [2.0, 3.0]) array([1., 6., 1.])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_indexing.py
namespace_of(*values)
¶
The array namespace that a computation on values runs in.
Python numbers, None, sequences and NumPy arrays join the library of
the other arrays; on their own they resolve to NumPy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*values
|
Any
|
Arguments of the function being dispatched. |
()
|
Returns:
| Type | Description |
|---|---|
ModuleType
|
The namespace, such as |
Raises:
| Type | Description |
|---|---|
BackendError
|
If a value is not an array of a known library, or if two libraries other than NumPy meet in one call. |
Example
import numpy as np namespace_of(np.zeros(3), 2.0, None).name 'array_api_compat.numpy'
Source code in packages/pipekit-array/src/pipekit_array/arrays/_backend.py
optimization_barrier(x)
¶
The same values, which XLA may not fuse with what comes before.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
An array, or nested tuples, lists and dicts of them. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
Raises:
| Type | Description |
|---|---|
BackendError
|
If a leaf is not an array of a known library. |
Example
optimization_barrier([1.0]) [1.0]
Source code in packages/pipekit-array/src/pipekit_array/arrays/_transforms.py
pad(x, widths)
¶
An array with zeros around it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The array. |
required |
widths
|
tuple[tuple[int, int], ...]
|
How many zeros before and after, for each axis. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The larger array, in |
Raises:
| Type | Description |
|---|---|
BackendError
|
If |
ValueError
|
If |
Example
import numpy as np pad(np.ones(2), ((1, 2),)) array([0., 1., 1., 0., 0.])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_indexing.py
reduction_inputs(values, weights, valid, *, params=())
¶
The namespace of a reduction, and its inputs broadcast against each other.
For a reduction that weighted_sum, weighted_mean and Groups do not
cover, with their rules for masks and weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Any
|
x. |
required |
weights
|
Any
|
w, or |
required |
valid
|
Any
|
The validity, boolean (True = use), or |
required |
params
|
tuple[Any, ...]
|
Other arguments, as in |
()
|
Returns:
| Type | Description |
|---|---|
ModuleType
|
The namespace, x and w in one floating dtype, and the validity as a |
Any
|
boolean array; w and the validity stay |
Raises:
| Type | Description |
|---|---|
BackendError
|
If an argument is a labelled array, or of another library. |
ValueError
|
If |
Example
import numpy as np xp, x, w, m = reduction_inputs(np.ones((2, 3)), [1.0, 2.0, 3.0], None) x.shape, w.shape, m ((2, 3), (2, 3), None)
Source code in packages/pipekit-array/src/pipekit_array/arrays/_reductions.py
register_record(cls, *, meta_fields=())
¶
Register a frozen dataclass as a JAX pytree, now or once JAX loads.
Without JAX the record is never registered, and works as it is.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
T
|
A frozen dataclass whose fields are arrays, numbers or records. |
required |
meta_fields
|
tuple[str, ...]
|
The names of the fields that are static under JAX: they are compared and hashed rather than traced. |
()
|
Returns:
| Type | Description |
|---|---|
T
|
|
Example
@register_record ... @dataclasses.dataclass(frozen=True) ... class Trend: ... slope: float Trend(2.0) Trend(slope=2.0)
Source code in packages/pipekit-array/src/pipekit_array/arrays/_records.py
require_floating(array, name, *, error=ValueError)
¶
Raise unless an array has a real floating dtype; nothing is cast.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
Any
|
An array of any library, concrete or traced, a sequence or a number. |
required |
name
|
str
|
What the argument is called, for the error. |
required |
error
|
type[Exception]
|
The exception to raise. |
ValueError
|
Raises:
| Type | Description |
|---|---|
ValueError
|
|
BackendError
|
If |
Example
import numpy as np require_floating(np.zeros(3), "x") require_floating(np.arange(3), "x") Traceback (most recent call last): ... ValueError: 'x' must have a floating dtype, got int64
Source code in packages/pipekit-array/src/pipekit_array/arrays/_checks.py
safe_atan2(y, x, xp)
¶
atan2(y, x), and 0 with a zero gradient at the origin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Any
|
A floating array of the namespace |
required |
x
|
Any
|
An array that broadcasts against it, of its dtype. |
required |
xp
|
ModuleType
|
The namespace of the call. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The angles [rad], in (-π, π]. |
Example
import numpy as np safe_atan2(np.asarray([0.0, 1.0]), np.asarray([0.0, 0.0]), np).round(6) array([0. , 1.570796])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_numerics.py
safe_power(x, p, xp)
¶
xᵖ for x > 0, 0 with a zero gradient for x ≤ 0, and NaN for NaN.
The rule at x ≤ 0 is that of safe_sqrt, and does not depend on p: it is 0
for a negative p, too. The gradient by p is finite.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A floating array of the namespace |
required |
p
|
Any
|
The exponent, a number or an array that broadcasts against |
required |
xp
|
ModuleType
|
The namespace of the call. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The powers. |
Example
import numpy as np safe_power(np.asarray([4.0, 0.0, -1.0, np.nan]), 1.5, np) array([ 8., 0., 0., nan])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_numerics.py
safe_sqrt(x, xp)
¶
√x for x > 0, 0 with a zero gradient for x ≤ 0, and NaN for NaN.
A difference of squares can round below 0, and its root is then 0; a missing
value stays missing. It goes through a double where, so the gradient is
finite at 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A floating array of the namespace |
required |
xp
|
ModuleType
|
The namespace of the call. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The roots. |
Example
import numpy as np safe_sqrt(np.asarray([4.0, 0.0, -1.0, np.nan]), np) array([ 2., 0., 0., nan])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_numerics.py
scan(f, init, xs=None, length=None, reverse=False)
¶
A recurrence: (c_k, y_k) = f(c_{k-1}, x_k) for k = 0, …, K - 1.
On JAX data, in init or xs, it is jax.lax.scan. Elsewhere f
is called once per step, which is slower than compiled code: a recurrence
should have few steps over large arrays there.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
Callable[[Any, Any], tuple[Any, Any]]
|
The step, from the carry and a slice of |
required |
init
|
Any
|
c_{-1}, the first carry. Off JAX it may be any object. |
required |
xs
|
Any
|
The inputs, sliced along their first axis: an array, or nested
tuples, lists and dicts of arrays. |
None
|
length
|
int | None
|
K, for |
None
|
reverse
|
bool
|
Run from the last input to the first. Each output keeps the place of its input. |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
The last carry, and the outputs stacked along a new first axis; an |
Any
|
output of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the inputs differ in length, or their number is unknown. Off JAX also if there is no step, because the shape of an output is then unknown. |
BackendError
|
If an input is not an array of a known library. |
Example
import numpy as np total, partial = scan(lambda c, x: (c + x, c + x), 0.0, np.arange(4.0)) float(total), partial.tolist() (6.0, [0.0, 1.0, 3.0, 6.0])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_transforms.py
set_at(x, index, values)
¶
A copy of an array with some entries replaced: y = x, then y[index] = v.
On JAX it is x.at[index].set(values).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The array, which is not changed. |
required |
index
|
Any
|
What |
required |
values
|
Any
|
The new entries, which broadcast to |
required |
Returns:
| Type | Description |
|---|---|
Any
|
y, in |
Raises:
| Type | Description |
|---|---|
BackendError
|
If the array library does not take that kind of index, or if two libraries other than NumPy meet in one call. |
IndexError
|
If the index is out of bounds. JAX does not report it, and leaves the array as it is. |
Example
import numpy as np set_at(np.zeros(3), slice(1, None), [1.0, 2.0]) array([0., 1., 2.])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_indexing.py
squared_magnitude(z, xp)
¶
|z|² = Re(z)² + Im(z)², with a gradient at 0, which that of |z| has not.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Any
|
A real or complex array of the namespace |
required |
xp
|
ModuleType
|
The namespace of the call. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The squares, real. |
Example
import numpy as np squared_magnitude(np.asarray([3.0 + 4.0j, 0.0]), np) array([25., 0.])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_numerics.py
stand_in(x, mask, xp, *, reference=None)
¶
Rows of an array, with a valid one in place of each row to leave out.
A function that is undefined at a row gives NaN there, and masking its result alone leaves 0 times NaN in the reverse pass, which spoils the gradient of every row. So it is evaluated somewhere valid instead, and its result masked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The rows, (n, *rest), an array of the namespace |
required |
mask
|
Any
|
Which rows to use (True = use), boolean (n,), of the same library. |
required |
xp
|
ModuleType
|
The namespace of the call. |
required |
reference
|
Any
|
The row, (*rest), to put in place of the others. If not given, the first one in use, or the first one of all if none is. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The rows, in |
Any
|
not in use, or the reference. |
Example
import numpy as np x = np.asarray([[np.nan, 0.0], [1.0, 2.0]]) stand_in(x, np.asarray([False, True]), np) array([[1., 2.], [1., 2.]])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_numerics.py
stop_gradient(x)
¶
The same values, as a constant of the derivative.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
An array, or nested tuples, lists and dicts of them. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
Any
|
|
Raises:
| Type | Description |
|---|---|
BackendError
|
If a leaf is not an array of a known library. |
Example
stop_gradient([1.0]) [1.0]
Source code in packages/pipekit-array/src/pipekit_array/arrays/_transforms.py
table_like(table, ref, xp)
¶
A NumPy table (an index, a mask) in ref's library, on its device.
Unlike like, it keeps its own shape and dtype.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table
|
ndarray
|
The table. |
required |
ref
|
Any
|
An array of the namespace |
required |
xp
|
ModuleType
|
The namespace of the call. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The table as an array of |
Example
import numpy as np table_like(np.arange(3), np.zeros(2, dtype=np.float32), np).tolist() [0, 1, 2]
Source code in packages/pipekit-array/src/pipekit_array/arrays/_host.py
used_weights(xp, x, w, m)
¶
The weight m w that each sample enters a reduction with.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xp
|
ModuleType
|
The namespace of the call. |
required |
x
|
Any
|
The samples, as |
required |
w
|
Any
|
The weights in |
required |
m
|
Any
|
The validity in |
required |
Returns:
| Type | Description |
|---|---|
Any
|
m w, in |
Example
import numpy as np x = np.asarray([1.0, np.nan]) used_weights(np, x, None, np.asarray([True, False])) array([1., 0.])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_reductions.py
vmap(fn, in_axes=0)
¶
A function mapped over an axis of its arguments.
On JAX data it is jax.vmap. Elsewhere fn is called once per entry of
the axis, and the results are stacked, which is slower than a function that
broadcasts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[..., Any]
|
A function of arrays, or of nested tuples, lists and dicts of them. |
required |
in_axes
|
int | None | tuple
|
The axis to map over, of every argument or, in a tuple, of each
one; |
0
|
Returns:
| Type | Description |
|---|---|
Callable[..., Any]
|
The mapped function. The mapped axis comes first in its results. |
Raises:
| Type | Description |
|---|---|
ValueError
|
(the mapped function) if no argument is mapped, or if the mapped axes differ in size or, off JAX, are empty. |
BackendError
|
(the mapped function) if a mapped argument is not an array of a known library. |
Example
import numpy as np vmap(np.linalg.norm)(np.asarray([[3.0, 4.0], [6.0, 8.0]])) array([ 5., 10.]) vmap(np.dot, in_axes=(0, None))(np.eye(2), np.asarray([1.0, 2.0])) array([1., 2.])
Source code in packages/pipekit-array/src/pipekit_array/arrays/_transforms.py
weighted_mean(values, *, weights=None, valid=None, axis=None)
¶
The mean of x over the valid samples, weighted by w.
x̄ = ∑ₙ mₙ wₙ xₙ / ∑ₙ mₙ wₙ, with m the validity, 1 or 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Any
|
x, samples of any shape. |
required |
weights
|
Any
|
w ≥ 0, broadcast against |
None
|
valid
|
Any
|
Which samples to use (True = use), broadcast against |
None
|
axis
|
Axis
|
The axis or axes to average over; every axis if not given. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
x̄, the array without the reduced axes, NaN where the weights used sum |
Any
|
to 0. |
Raises:
| Type | Description |
|---|---|
BackendError
|
If an argument is a labelled array, or of another library. |
ValueError
|
If |
Example
import numpy as np x = np.asarray([[1.0, 4.0], [2.0, np.nan]]) weighted_mean(x, weights=[3.0, 1.0], valid=~np.isnan(x), axis=-1) array([1.75, 2. ]) float(weighted_mean(x[0], weights=[0.0, 0.0])) nan
Source code in packages/pipekit-array/src/pipekit_array/arrays/_reductions.py
weighted_sum(values, *, weights=None, valid=None, axis=None)
¶
The sum of w x over the valid samples.
S = ∑ₙ mₙ wₙ xₙ, with m the validity, 1 or 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Any
|
x, samples of any shape. |
required |
weights
|
Any
|
w, broadcast against |
None
|
valid
|
Any
|
Which samples to use (True = use), broadcast against |
None
|
axis
|
Axis
|
The axis or axes to sum over; every axis if not given. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
S, the array without the reduced axes. An empty sum is 0. |
Raises:
| Type | Description |
|---|---|
BackendError
|
If an argument is a labelled array, or of another library. |
ValueError
|
If |
Example
import numpy as np x = np.asarray([1.0, np.nan, 3.0]) float(weighted_sum(x, valid=[True, False, True])) 4.0 float(weighted_sum(x[[0, 2]], weights=[0.5, 2.0])) 6.5
Source code in packages/pipekit-array/src/pipekit_array/arrays/_reductions.py
Named carriers¶
pipekit_array.named is for carriers with dimension names: a DimArray, an xr.DataArray, or any carrier with a registered adapter.
It joins NumPy to JAX, and refuses other mixes (ADR A24).
to_rows and from_rows turn a carrier into a (n_samples, n_features) table and back (geostack OP-O3), and batch groups carriers into fixed-size Padded batches (ADR A10).
pipekit_array.named
¶
Functions of named carriers: arrays with dimension names.
A carrier is a DimArray, an xr.DataArray ([xarray]), a geoarray
carrier: anything with a registered pipekit_ops.NamedArrayAdapter. Each
function is written once, over that adapter, and behaves the same on every
carrier. The rule for joining this list (GA-Q3): a function never reads
coordinate values or geometry. resample, groupby and rolling
stay xarray's; reprojection and sampling at points stay in geoarray.
- Select:
isel,sel,take_along. - Shape:
transpose,rename,expand_dims,squeeze,broadcast_like,merge_dims,split_dims. - Reduce:
reduce,argreduce,cumreduce,quantile,dot. - Shift:
pad,roll,shift,diff,where. - Window:
window,coarsen. - Join:
stack,stack_items,concat,combine. - Map:
map_over. - Batches and tables:
batch,Padded,to_rows,from_rows,RowLayout. - The plain carrier:
DimArray,DimArrayAdapter;core_dimsandvmapped_dimsfor a carrier that is a pytree. - Dispatch:
array_namespace,join_backends.
Fast paths. An adapter may provide a method of the same name (the
xarray adapter's reduce stays lazy on dask; geoarray's map_over
is one jax.vmap over data and transform rows). It is called with the
same arguments instead of the generic path; the test kit
(pipekit_array.testing) proves the two agree.
The Operator forms live in pipekit_array.operators, in files of the same
names. This area needs no extra.
DimArray
dataclass
¶
A raw array with one name per axis and static labels on some dims.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
A NumPy, JAX or dask array. |
required |
dims
|
tuple[str, ...]
|
One unique name per axis of |
required |
labels
|
Mapping[str, tuple[Any, ...]]
|
Static labels per dim, e.g. |
dict()
|
Raises:
| Type | Description |
|---|---|
ValueError
|
The dims do not match the data's rank, repeat a name, or a label tuple's length differs from its dim's size. |
Example
import numpy as np mu = DimArray(np.zeros((3, 2)), ("col", "band"), {"band": ["B11", "B12"]}) mu.dims, mu.shape, mu.labels["band"] (('col', 'band'), (3, 2), ('B11', 'B12'))
Source code in packages/pipekit-array/src/pipekit_array/named/_carrier.py
dtype
property
¶
The data's dtype.
shape
property
¶
The data's shape.
__array__(dtype=None, copy=None)
¶
The data as a NumPy array, so np.asarray(d) works (dims are dropped).
Source code in packages/pipekit-array/src/pipekit_array/named/_carrier.py
to_xarray()
¶
An xr.DataArray with the same data and dims; labels become coordinates.
Raises:
| Type | Description |
|---|---|
ImportError
|
xarray is not installed ( |
Source code in packages/pipekit-array/src/pipekit_array/named/_carrier.py
DimArrayAdapter
¶
The reference pipekit_ops.NamedArrayAdapter, for DimArray.
Source code in packages/pipekit-array/src/pipekit_array/named/_carrier.py
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 | |
check_compatible(*xs)
¶
The arrays back, if every shared dim has one size and one set of labels.
Raises:
| Type | Description |
|---|---|
ValueError
|
A dim has two sizes, or two different label sets. |
Source code in packages/pipekit-array/src/pipekit_array/named/_carrier.py
data(x)
¶
dims(x)
¶
isel(x, indexers)
¶
Select by position; integers drop their dim, labels follow the data.
Raises:
| Type | Description |
|---|---|
KeyError
|
An indexer names a dim |
Source code in packages/pipekit-array/src/pipekit_array/named/_carrier.py
labels(x, dim)
¶
relabel(x, labels)
¶
x with the labels of the named dims set; None removes them.
The optional pipekit_ops.LabelledAdapter method (ADR A22).
Raises:
| Type | Description |
|---|---|
ValueError
|
A dim is not in |
Source code in packages/pipekit-array/src/pipekit_array/named/_carrier.py
rewrap(x, data, dims)
¶
A DimArray around new data; a kept dim keeps its labels if its size did.
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in packages/pipekit-array/src/pipekit_array/named/_carrier.py
signature(x)
¶
Dims with their sizes, and the dtype's name.
Padded
¶
Bases: NamedTuple
A batch: the items as one carrier and a mask of the real ones.
A NamedTuple, so JAX treats it as a pytree: a jitted step taking a
Padded does not retrace when the mask changes. A full batch is a
Padded whose valid is all True.
Attributes:
| Name | Type | Description |
|---|---|---|
value |
Any
|
The items stacked along the batch dim, first
( |
valid |
Any
|
|
Example
import numpy as np from pipekit_array import DimArray, reduce items = [DimArray(np.full(3, float(i)), ("x",)) for i in range(3)] padded = next(batch(items, size=4, dim="sample")) padded.valid.tolist() [True, True, True, False] reduce(padded.value, "mean", "sample", where=padded.valid).data array([1., 1., 1.])
Source code in packages/pipekit-array/src/pipekit_array/named/_batches.py
RowLayout
dataclass
¶
How to_rows flattened a carrier, so from_rows can rebuild one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dims
|
tuple[str, ...]
|
The carrier's dims, in its order. |
required |
sizes
|
tuple[int, ...]
|
The size of each dim, in the same order. |
required |
sample_dims
|
tuple[str, ...]
|
The dims that became rows, in the carrier's order. |
required |
feature_dims
|
tuple[str, ...]
|
The dims that became columns, in the carrier's order. |
required |
template
|
Any
|
The carrier to rewrap like (left out of equality and repr). |
None
|
Source code in packages/pipekit-array/src/pipekit_array/named/_rows.py
argreduce(x, fn, dim)
¶
The index of a reduction along one dim ("argmax", "argmin").
Example
import numpy as np from pipekit_array import DimArray ndvi = DimArray(np.random.default_rng(0).random((12, 4)), ("time", "x")) argreduce(ndvi, "argmax", "time").dims ('x',)
Source code in packages/pipekit-array/src/pipekit_array/named/_reduce.py
array_namespace(*xs)
¶
Return the Array API namespace shared by all input arrays.
NumPy arrays next to JAX ones join them, so the namespace is JAX's.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*xs
|
Any
|
One or more array-like objects. All must share the same Array API backend, but for NumPy with JAX. |
()
|
Returns:
| Type | Description |
|---|---|
Any
|
The module-like namespace object (e.g. |
Any
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If no input implements the Array API, or if the
inputs span more than one backend. The error message is
consistent whether or not |
Source code in packages/pipekit-array/src/pipekit_array/named/_dispatch.py
batch(items, *, size, dim, pad='last')
¶
Group named carriers into Padded batches of size along dim.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
Iterable[Any]
|
Named carriers with the same dims (each registered with pipekit's adapter registry), consumed lazily. |
required |
size
|
int
|
Items per batch; must be positive. |
required |
dim
|
str
|
The new leading batch dim ( |
required |
pad
|
PadPolicy
|
What to do with a short last batch:
|
'last'
|
Yields:
| Type | Description |
|---|---|
Padded
|
One |
Padded
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Example
import numpy as np from pipekit_array import DimArray items = [DimArray(np.ones((2, 2)), ("y", "x")) for _ in range(5)] def sizes(pad): ... return [len(b.valid) for b in batch(items, size=2, dim="s", pad=pad)] sizes("last"), sizes("none"), sizes("drop") ([2, 2, 2], [2, 2, 1], [2, 2])
Source code in packages/pipekit-array/src/pipekit_array/named/_batches.py
broadcast_like(x, other, /, *, exclude=())
¶
Add other's missing dims to x, in front, in other's order.
y_{a…, d…} = x_{d…}, for every index a of the added dims.
Shared dims must agree exactly in size and labels (xarray outer-joins
instead). x's own dims keep their order, so the result's order is
xarray's only when the shared dims are in other's order. The added
dims carry other's labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
other
|
Any
|
A carrier of the same family; only its dims, sizes and labels are read. |
required |
exclude
|
Sequence[str]
|
Dims of |
()
|
Raises:
| Type | Description |
|---|---|
TypeError
|
The adapter has no |
ValueError
|
A shared dim differs in size or labels. |
Example
import numpy as np from pipekit_array import DimArray cube = DimArray(np.zeros((12, 2, 4)), ("time", "band", "x")) median = DimArray(np.ones((2, 4)), ("band", "x")) broadcast_like(median, cube).shape (12, 2, 4)
Source code in packages/pipekit-array/src/pipekit_array/named/_shape.py
coarsen(x, fn, /, *, boundary='exact', **windows)
¶
Reduce non-overlapping blocks of k entries along each named dim.
z_{…, i', …} = fn_{0 ≤ r < k} x_{…, k·i' + r, …}, i' < ⌊N/k⌋.
A composition: split_dims each dim into (dim, block) then
reduce over the blocks, so coarsen(x, "mean", time=3) is
reduce(split_dims(x, time={"time": 4, "window": 3}), "mean",
"window"). A coarsened dim loses its labels: xarray's coord_func
reads coordinate values, which this layer never does (A15).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
fn
|
Reduction
|
An array-namespace name ( |
required |
boundary
|
str
|
|
'exact'
|
**windows
|
int
|
|
{}
|
Raises:
| Type | Description |
|---|---|
KeyError
|
A dim is not a dim of |
ValueError
|
No dim is given, k is not positive, |
Examples:
>>> import numpy as np
>>> from pipekit_array import DimArray
>>> ndvi = DimArray(np.arange(24.0).reshape(2, 12), ("y", "x"))
>>> coarse = coarsen(ndvi, "mean", x=4)
>>> coarse.dims, coarse.data.tolist()
(('y', 'x'), [[1.5, 5.5, 9.5], [13.5, 17.5, 21.5]])
>>> coarsen(ndvi, "max", boundary="trim", x=5, y=2).data.tolist()
[[16.0, 21.0]]
>>> coarsen(ndvi, "mean", x=5)
Traceback (most recent call last):
...
ValueError: coarsen: 5 does not divide 'x' of size 12; ...
Source code in packages/pipekit-array/src/pipekit_array/named/_window.py
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | |
combine(fn, *xs)
¶
fn of the data of carriers with the same dims; never aligns.
Inputs are put in the first one's dim order by name before fn sees
them, and the result has those dims. NumPy inputs join JAX ones; fn
then decides what it returns (np.add of JAX arrays is NumPy's).
Example
import numpy as np from pipekit_array import DimArray nir = DimArray(np.full((2, 3), 0.4), ("y", "x")) red = DimArray(np.full((2, 3), 0.1), ("y", "x")) nd = combine(lambda a, b: (a - b) / (a + b), nir, red) nd.dims, bool(np.allclose(nd.data, 0.6)) (('y', 'x'), True)
Source code in packages/pipekit-array/src/pipekit_array/named/_join.py
concat(xs, dim)
¶
Join carriers along an existing dim; the other dims must agree.
The generic path drops dim's labels (the joined dim has a new size);
an adapter's concat fast path may join them.
Source code in packages/pipekit-array/src/pipekit_array/named/_join.py
core_dims(dims)
¶
dims without the leading ones that vmapped_dims would add back.
A stack of carriers (from vmap, scan or jnp.stack) and one of
them then have the same tree structure, as a stack of arrays and one array
have: a solver that allocates its output and writes one step into it
compares the two. Leading dims called "batch", "batch_1", … are
taken to be added ones, also when the caller named them so.
Example
core_dims(("batch", "y", "x")), core_dims(("time", "y", "x")) (('y', 'x'), ('time', 'y', 'x'))
Source code in packages/pipekit-array/src/pipekit_array/named/_carrier.py
cumreduce(x, fn, dim)
¶
A cumulative function along dim; labels and length unchanged.
c_t = ∑_{τ ≤ t} x_τ for "cumulative_sum".
No implicit skipna (xarray's cumsum skips NaN by default): ask
for "nancumsum".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
fn
|
Reduction
|
An array-namespace name ( |
required |
dim
|
str
|
The dim to accumulate along. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
|
ValueError
|
The namespace has no |
Examples:
>>> import numpy as np
>>> from pipekit_array import DimArray
>>> change = DimArray(np.array([1.0, 2.0, 3.0]), ("time",))
>>> cumreduce(change, "cumulative_sum", "time").data
array([1., 3., 6.])
>>> gaps = DimArray(np.array([1.0, np.nan, 3.0]), ("time",))
>>> cumreduce(gaps, "nancumsum", "time").data
array([1., 1., 4.])
Source code in packages/pipekit-array/src/pipekit_array/named/_reduce.py
diff(x, dim, /, n=1, *, label='upper')
¶
The n-th forward difference along dim (xarray's diff).
Δy_t = y_{t+1} - y_t, applied n times: N entries become N - n.
The result's labels on dim are the minuend's ("upper", positions
n … N - 1) or the subtrahend's ("lower", positions 0 … N - n - 1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
dim
|
str
|
The dim to difference along. |
required |
n
|
int
|
The order, n ≥ 0; static under |
1
|
label
|
str
|
|
'upper'
|
Raises:
| Type | Description |
|---|---|
KeyError
|
|
ValueError
|
|
Examples:
>>> import numpy as np
>>> from pipekit_array import DimArray
>>> series = DimArray(np.array([1.0, 4.0, 9.0, 16.0]), ("time",))
>>> diff(series, "time").data
array([3., 5., 7.])
>>> labelled = DimArray(series.data, ("time",), {"time": tuple("abcd")})
>>> second = diff(labelled, "time", 2, label="lower")
>>> second.data, second.labels["time"]
(array([2., 2.]), ('a', 'b'))
Source code in packages/pipekit-array/src/pipekit_array/named/_shift.py
dot(*xs, dim)
¶
The sum of the product of carriers over named dims (xr.dot).
s_{o…} = ∑{d ∈ dim} ∏ₖ x⁽ᵏ⁾, where o… are the dims not in dim.
The output dims are every input dim not in dim, in order of first
appearance. A dim shared by several inputs and not in dim is a
batch dim: it appears once, so dot is one named-index einsum,
never tensordot (A17). Shared dims must agree exactly in size and
labels; dims from inputs after the first carry those inputs' labels.
Algorithm
- Give each distinct dim a letter, in order of first appearance.
- Write one subscript per input from its dims, and the output's
from the dims not in
dim. xp.einsum; for a namespace without it, broadcast every input to the union of the dims, multiply, andxp.sumoverdim(exact, but holds the full product).rewrapon the first input, thenrelabelthe dims taken from later inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*xs
|
Any
|
Named carriers of one family and one backend. |
()
|
dim
|
str | Sequence[str]
|
A dim name, or several, to sum over; required (A17): xarray would sum every shared dim, so a dim shared by accident would vanish. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
No carrier is given, a shared dim differs in size or labels, or there are more dims than letters. |
KeyError
|
A name in |
BackendError
|
The inputs sit on more than one backend. |
TypeError
|
The adapter has no |
Examples:
>>> import numpy as np
>>> from pipekit_array import DimArray
>>> x = DimArray(np.ones((12, 13)), ("time", "band"))
>>> w = DimArray(np.ones((12, 13, 3)), ("time", "band", "component"))
>>> s = dot(x, w, dim="band")
>>> s.dims, bool(np.allclose(s.data, 13.0))
(('time', 'component'), True)
>>> pixels = DimArray(np.ones((2, 13, 6)), ("time", "band", "pixel"))
>>> labelled = {"component": ("pc1", "pc2", "pc3")}
>>> weights = DimArray(np.ones((13, 3)), ("band", "component"), labelled)
>>> scores = dot(pixels, weights, dim="band")
>>> scores.dims, scores.labels["component"]
(('time', 'pixel', 'component'), ('pc1', 'pc2', 'pc3'))
Source code in packages/pipekit-array/src/pipekit_array/named/_reduce.py
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 | |
expand_dims(x, dim, /, *, axis=0)
¶
Insert length-1 dims, consecutively, at position axis of the result.
y_{…, 0, …} = x_{…}: the new dims have size 1 and no labels.
A negative axis counts from the end, so axis=-1 appends.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
dim
|
str | Sequence[str]
|
A new dim name, or several. |
required |
axis
|
int
|
Where the first new dim goes in the result. |
0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
A new name is already a dim, a name repeats, or
|
Examples:
>>> import numpy as np
>>> from pipekit_array import DimArray
>>> scene = DimArray(np.zeros((2, 4)), ("band", "x"))
>>> expand_dims(scene, "member").dims
('member', 'band', 'x')
>>> expand_dims(scene, ("member", "run"), axis=-1).shape
(2, 4, 1, 1)
Source code in packages/pipekit-array/src/pipekit_array/named/_shape.py
from_rows(rows, layout, *, feature_dim=None)
¶
A carrier like layout.template from a table of rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
Any
|
|
required |
layout
|
RowLayout
|
From |
required |
feature_dim
|
str | None
|
The name of the new feature dim, for a table whose columns are not the original features. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A carrier with |
Any
|
feature dim (if any) where the first feature dim was, rewrapped by |
Any
|
the template's adapter. |
Raises:
| Type | Description |
|---|---|
ValueError
|
The rows do not match the layout, or a new feature dim
is needed and |
Example
import numpy as np from pipekit_array import DimArray scene = DimArray(np.arange(24.0).reshape(2, 3, 4), ("band", "y", "x")) rows, layout = to_rows(scene, sample_dims=("y", "x")) from_rows(rows[:, :1] * 0, layout, feature_dim="score").dims ('score', 'y', 'x')
Source code in packages/pipekit-array/src/pipekit_array/named/_rows.py
isel(x, /, **indexers)
¶
Select by position on named dims; an integer drops its dim.
x is positional-only, so a dim may be called x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
**indexers
|
Any
|
|
{}
|
Example
import numpy as np from pipekit_array import DimArray cube = DimArray(np.zeros((12, 2, 4)), ("time", "band", "x")) isel(cube, time=0).dims ('band', 'x')
Source code in packages/pipekit-array/src/pipekit_array/named/_select.py
join_backends(datas, what)
¶
The raw arrays on one backend: NumPy arrays next to JAX ones join them.
The order of the inputs does not matter, and a NumPy array is a constant
when a JAX one is traced (ADR A24). pipekit_ops.guard reports the arrays
of one dimension or more that join eagerly, and a dtype they widen.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datas
|
Sequence[Any]
|
Raw arrays. |
required |
what
|
str
|
The function that joins them, for the guard and the errors. |
required |
Raises:
| Type | Description |
|---|---|
BackendError
|
Any other mix: dask with NumPy or JAX, or another library with JAX. |
Example
import numpy as np first, second = join_backends([np.ones(2), np.ones(3)], "stack") first.shape, second.shape ((2,), (3,))
Source code in packages/pipekit-array/src/pipekit_array/named/_dispatch.py
map_over(x, fn, dim)
¶
fn on each item along dim; the results stacked along dim, first.
Each item is isel(x, dim=i); fn returns a named carrier, and every
result must have the same dims.
On JAX data this is one jax.vmap, for a carrier whose only array is its
data (an adapter with more has a fast path of its own). A fn that cannot
be traced (it branches on a value, or runs on NumPy only) is called on each
item in a loop instead, unless x is traced itself.
Raises:
| Type | Description |
|---|---|
KeyError
|
|
TypeError
|
|
ValueError
|
The results have different dims, or have |
Example
import numpy as np from pipekit_array import DimArray, reduce cube = DimArray(np.ones((3, 2, 4)), ("time", "band", "x")) map_over(cube, lambda item: reduce(item, "sum", "band"), "time").dims ('time', 'x')
Source code in packages/pipekit-array/src/pipekit_array/named/_map.py
merge_dims(x, /, **dims)
¶
Merge the listed dims into one, placed last, in C order (xarray's stack).
y_{…, p} = x_{…, i, j}, with p = i·X + j for pixel=("y", "x").
The merged dim's labels are tuples of the source labels, with
positions for an unlabelled source; it has none when no source has
labels. split_dims undoes it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
**dims
|
Sequence[str]
|
|
{}
|
Raises:
| Type | Description |
|---|---|
KeyError
|
A source is not a dim of |
ValueError
|
A merge lists no source, a source is merged twice, or the result repeats a dim name. |
TypeError
|
A merge's sources are one string, or the adapter has no
|
Examples:
>>> import numpy as np
>>> from pipekit_array import DimArray
>>> bands = {"band": ("B4", "B8")}
>>> cube = DimArray(np.zeros((2, 3, 4)), ("band", "y", "x"), bands)
>>> pixels = merge_dims(cube, pixel=("y", "x"))
>>> pixels.dims, pixels.shape
(('band', 'pixel'), (2, 12))
>>> merge_dims(cube, pb=("band", "y")).labels["pb"][:2]
(('B4', 0), ('B4', 1))
Source code in packages/pipekit-array/src/pipekit_array/named/_shape.py
pad(x, /, *, mode='constant', constant_values=None, **pad_width)
¶
Widen named dims at either end (xarray's pad, four modes).
y_{…, t, …} = x_{…, t - b, …} for b ≤ t < b + N; the new entries follow
mode.
A padded dim loses its labels (xarray pads its coordinate with NaN).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
mode
|
str
|
|
'constant'
|
constant_values
|
float | None
|
The fill for |
None
|
**pad_width
|
int | tuple[int, int]
|
|
{}
|
Raises:
| Type | Description |
|---|---|
KeyError
|
A padded dim is not a dim of |
ValueError
|
|
TypeError
|
|
Examples:
>>> import numpy as np
>>> from pipekit_array import DimArray
>>> series = DimArray(np.arange(3.0), ("time",))
>>> pad(series, time=(2, 0)).data
array([nan, nan, 0., 1., 2.])
>>> pad(series, mode="wrap", time=1).data
array([2., 0., 1., 2., 0.])
>>> counts = DimArray(np.arange(3), ("time",))
>>> pad(counts, time=1)
Traceback (most recent call last):
...
TypeError: pad: int64 data has no NaN to fill with; pass constant_values=
Source code in packages/pipekit-array/src/pipekit_array/named/_shift.py
quantile(x, q, dim, /, *, method='linear', skipna=False)
¶
Quantiles over named dims (xarray's quantile).
Q_{k…} = quantile q_k of {x_{…, d…} : d over dim}.
A sequence q adds a leading dim quantile, labelled with q;
a float drops it. A float input keeps its dtype. NaN propagates unless
skipna (no implicit skipna, A12).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
q
|
float | Sequence[float]
|
A probability in [0, 1], or a sequence of them; static under
|
required |
dim
|
str | Sequence[str]
|
A dim name, or several, to reduce over. |
required |
method
|
str
|
One of |
'linear'
|
skipna
|
bool
|
Ignore NaN ( |
False
|
Raises:
| Type | Description |
|---|---|
KeyError
|
A name is not a dim of |
ValueError
|
|
TypeError
|
The adapter has no |
Examples:
>>> import numpy as np
>>> from pipekit_array import DimArray
>>> cube = DimArray(np.arange(24.0).reshape(4, 2, 3), ("time", "band", "x"))
>>> spread = quantile(cube, [0.1, 0.9], "time")
>>> spread.dims, spread.labels["quantile"]
(('quantile', 'band', 'x'), (0.1, 0.9))
>>> quantile(cube, 0.5, ("time", "x"), method="lower").dims
('band',)
Source code in packages/pipekit-array/src/pipekit_array/named/_reduce.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |
reduce(x, fn, dim, *, where=None)
¶
Reduce over one or more named dims.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
fn
|
Reduction
|
An array-namespace name ( |
required |
dim
|
str | Sequence[str]
|
A dim name, or several. |
required |
where
|
Any | None
|
Optional bool mask of the entries to keep, passed to |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
A plain |
TypeError
|
|
Example
import numpy as np from pipekit_array import DimArray cube = DimArray(np.ones((12, 2, 4)), ("time", "band", "x")) reduce(cube, "mean", "time").dims ('band', 'x') batch = DimArray(np.array([[1.0], [3.0], [9.0]]), ("sample", "x")) reduce(batch, "mean", "sample", where=np.array([True, True, False])).data array([2.])
Source code in packages/pipekit-array/src/pipekit_array/named/_reduce.py
rename(x, /, **names)
¶
New dim names; data, order and labels unchanged.
y = x, with each dim d called names[d].
x is positional-only, so a dim may be called x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
**names
|
str
|
|
{}
|
Raises:
| Type | Description |
|---|---|
KeyError
|
An old name is not a dim of |
ValueError
|
The new names repeat a dim. |
TypeError
|
The adapter has neither a |
Examples:
>>> import numpy as np
>>> from pipekit_array import DimArray
>>> scene = DimArray(np.zeros((2, 4)), ("band", "x"), {"band": ("B4", "B8")})
>>> channels = rename(scene, band="channel")
>>> channels.dims, channels.labels["channel"]
(('channel', 'x'), ('B4', 'B8'))
>>> rename(channels, channel="band").labels == scene.labels
True
Source code in packages/pipekit-array/src/pipekit_array/named/_shape.py
roll(x, /, **shifts)
¶
Shift data cyclically along named dims; labels stay (xarray's roll).
y_{…, t, …} = x_{…, (t - k) mod N, …}.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
**shifts
|
int
|
|
{}
|
Raises:
| Type | Description |
|---|---|
KeyError
|
A rolled dim is not a dim of |
Examples:
>>> import numpy as np
>>> from pipekit_array import DimArray
>>> series = DimArray(np.arange(4.0), ("time",), {"time": tuple("abcd")})
>>> rolled = roll(series, time=1)
>>> rolled.data, rolled.labels["time"]
(array([3., 0., 1., 2.]), ('a', 'b', 'c', 'd'))
>>> bool(np.array_equal(roll(rolled, time=-1).data, series.data))
True
Source code in packages/pipekit-array/src/pipekit_array/named/_shift.py
sel(x, /, **labels)
¶
Select by exact label on named dims: no ranges, no nearest.
x is positional-only, so a dim may be called x.
A single label drops its dim; a list of labels keeps it.
Raises:
| Type | Description |
|---|---|
KeyError
|
A dim has no labels, or a label is not among them. |
Example
import numpy as np from pipekit_array import DimArray scene = DimArray(np.zeros((2, 4)), ("band", "x"), {"band": ("B4", "B8")}) sel(scene, band="B8").dims ('x',)
Source code in packages/pipekit-array/src/pipekit_array/named/_select.py
shift(x, /, *, fill_value=None, **shifts)
¶
Shift data along named dims, filling the vacated entries (xarray's shift).
y_{…, t, …} = x_{…, t - k, …} if 0 ≤ t - k < N, else the fill.
Labels stay on their positions. A shift of at least the dim's length fills it entirely.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
fill_value
|
float | None
|
The value of the vacated entries; None is NaN. |
None
|
**shifts
|
int
|
|
{}
|
Raises:
| Type | Description |
|---|---|
KeyError
|
A shifted dim is not a dim of |
TypeError
|
Integer or bool data without |
Examples:
>>> import numpy as np
>>> from pipekit_array import DimArray
>>> series = DimArray(np.arange(4.0), ("time",))
>>> shift(series, time=1).data
array([nan, 0., 1., 2.])
>>> shift(DimArray(np.arange(4), ("time",)), time=-2, fill_value=-1).data
array([ 2, 3, -1, -1])
Source code in packages/pipekit-array/src/pipekit_array/named/_shift.py
split_dims(x, /, **dims)
¶
Split one dim into several, in place, in C order (xarray's unstack).
y_{…, i, j} = x_{…, p}, with p = i·X + j for pixel={"y": Y, "x": X}.
The sizes are given, not read from the labels, so they are static
under jit (A14). Tuple labels from merge_dims are split back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
**dims
|
Mapping[str, int]
|
|
{}
|
Raises:
| Type | Description |
|---|---|
KeyError
|
A dim to split is not a dim of |
ValueError
|
The sizes do not multiply to the dim's length, a split lists no part, or the result repeats a dim name. |
TypeError
|
The adapter has no |
Examples:
>>> import numpy as np
>>> from pipekit_array import DimArray
>>> pixels = DimArray(np.zeros((2, 12)), ("band", "pixel"))
>>> split_dims(pixels, pixel={"y": 3, "x": 4}).dims
('band', 'y', 'x')
>>> cube = DimArray(np.zeros((3, 4)), ("y", "x"), {"x": tuple("abcd")})
>>> back = split_dims(merge_dims(cube, p=("y", "x")), p={"y": 3, "x": 4})
>>> back.labels
{'x': ('a', 'b', 'c', 'd')}
Source code in packages/pipekit-array/src/pipekit_array/named/_shape.py
squeeze(x, dim)
¶
Drop named length-1 dims.
y_{…} = x_{…, 0, …}.
dim is required: squeezing every length-1 dim would also drop a
batch of one (A12).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
dim
|
str | Sequence[str]
|
A dim name, or several; each must have size 1. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
A name is not a dim of |
ValueError
|
A named dim's size is not 1. |
Example
import numpy as np from pipekit_array import DimArray squeeze(DimArray(np.zeros((1, 2, 4)), ("time", "band", "x")), "time").dims ('band', 'x')
Source code in packages/pipekit-array/src/pipekit_array/named/_shape.py
stack(xs, dim)
¶
A new leading dim dim from carriers with the same dims; never aligns.
Source code in packages/pipekit-array/src/pipekit_array/named/_join.py
stack_items(xs, dim)
¶
Items along a new leading dim dim, each keeping its own geometry.
The inverse of the split map_over makes: where stack requires one
shared grid (geoarray's stack never aligns two), stack_items lets
each item carry its own per-item leaves (a patch's transform row, a
frame's grid) and makes dim a batch dim. A carrier family with no
per-item geometry (DimArray, xr.DataArray) has nothing to keep
apart, so this is stack; geoarray's adapter provides the
stack_items fast path.
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Example
import numpy as np from pipekit_array import DimArray items = [DimArray(np.ones((2, 3)), ("y", "x")) for _ in range(4)] stack_items(items, "sample").dims ('sample', 'y', 'x')
Source code in packages/pipekit-array/src/pipekit_array/named/_join.py
take_along(x, index, dim)
¶
Gather one entry of dim per position, with an index carrier.
index has x's dims without dim (an argreduce result, in any
dim order); the result has those dims too.
Example
import numpy as np from pipekit_array import DimArray cube = DimArray(np.arange(24.0).reshape(3, 2, 4), ("time", "band", "x")) best = DimArray(np.array([0, 2, 1, 0]), ("x",)) take_along(cube, best, "time").dims ('band', 'x')
Source code in packages/pipekit-array/src/pipekit_array/named/_select.py
to_rows(x, sample_dims)
¶
x as a (n_samples, n_features) table, and how to undo it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
sample_dims
|
Sequence[str]
|
The dims whose entries are samples (rows); every other
dim of |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The table, on |
RowLayout
|
With no feature dims the table has one column. |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
No sample dims, a repeated one, or one |
Example
import numpy as np from pipekit_array import DimArray scene = DimArray(np.arange(24.0).reshape(2, 3, 4), ("band", "y", "x")) rows, layout = to_rows(scene, sample_dims=("y", "x")) rows.shape, layout.feature_dims ((12, 2), ('band',))
Source code in packages/pipekit-array/src/pipekit_array/named/_rows.py
transpose(x, order)
¶
Reorder dims by name; order names every dim once.
Source code in packages/pipekit-array/src/pipekit_array/named/_shape.py
vmapped_dims(dims, shape)
¶
Static dims matched to leaves jax.vmap added or removed an axis from.
vmap maps leaves but not static dims: inside, the data has lost
its leading axis; outside, the results gained one. With the default
in_axes=0 / out_axes=0 that axis is the first, so drop the
first dims, or prepend "batch" ("batch_1", … if taken). A
shape that already matches, or no shape (a tracing placeholder),
leaves dims alone. Map over any other axis with map_over.
A carrier's pytree stores core_dims as its static dims and calls this
when it is unflattened.
Source code in packages/pipekit-array/src/pipekit_array/named/_carrier.py
where(x, cond, /, other=None)
¶
Keep x where cond is True, other elsewhere (xarray's where).
y = x where v, else the fill; True keeps (A16).
cond aligns by dim name, as reduce(where=) does: a named mask
whose dims are among x's, so a time y x cloud mask applies to a
time band y x cube; or a plain array covering x's leading dims.
It is never right-broadcast.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
cond
|
Any
|
A bool mask v, named or plain. |
required |
other
|
float | None
|
The fill where |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
A named |
TypeError
|
Integer or bool data without |
Examples:
>>> import numpy as np
>>> from pipekit_array import DimArray
>>> cube = DimArray(np.ones((2, 3, 2)), ("time", "band", "x"))
>>> valid = DimArray(np.array([[True, False], [True, True]]), ("time", "x"))
>>> clear = where(cube, valid)
>>> clear.dims, clear.data[0, :, 1]
(('time', 'band', 'x'), array([nan, nan, nan]))
>>> where(cube, valid, 0.0).data[0, 0]
array([1., 0.])
Source code in packages/pipekit-array/src/pipekit_array/named/_shift.py
window(x, /, *, window_dim='window', stride=1, **sizes)
¶
Sliding windows along one dim; the window becomes a new last dim.
w_{…, n, …, r} = x_{…, n·s + r, …}, 0 ≤ r < S, 0 ≤ n < ⌊(N - S)/s⌋ + 1.
Full windows only: there is no NaN fill, so float32 stays float32 and
integers work (A15). Window n carries the label of its last entry,
position n·s + S - 1, as xarray's
rolling(...).construct(window_dim).isel(dim=slice(S - 1, None, s))
does. For xarray's length-N result, pad the dim by S - 1 first.
Algorithm
- Count the full windows, n = ⌊(N - S)/s⌋ + 1.
- Take the S strided slices of the data, x_{r::s}, each n long.
- Stack them on a new last axis and rewrap on the slice of end positions, so the windowed dim keeps the labels of those.
The generic path copies the data S times; the xarray adapter's fast path is a view.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier. |
required |
window_dim
|
str
|
The new last dim, indexing the entries r of a window. |
'window'
|
stride
|
int
|
The step s ≥ 1 between window starts. |
1
|
**sizes
|
int
|
|
{}
|
Raises:
| Type | Description |
|---|---|
KeyError
|
The dim is not a dim of |
ValueError
|
|
Examples:
>>> import numpy as np
>>> from pipekit_array import DimArray
>>> ndvi = DimArray(np.arange(12.0), ("time",), {"time": tuple(range(12))})
>>> windows = window(ndvi, time=3, stride=2)
>>> windows.dims, windows.shape
(('time', 'window'), (5, 3))
>>> windows.labels["time"]
(2, 4, 6, 8, 10)
>>> window(DimArray(np.arange(4), ("time",)), time=2).data.tolist()
[[0, 1], [1, 2], [2, 3]]
Source code in packages/pipekit-array/src/pipekit_array/named/_window.py
Kernels¶
pipekit_array.kernels runs one array function on raw arrays and on every carrier.
pipekit_array.kernels
¶
One array function on every carrier: KernelSpec, KernelOp, elementwise.
A shapes-only kernel declares the axes it consumes and produces with a
generalized-ufunc signature ("(c)->()", "(r,c),(c),(c,d)->(r)"),
the convention NumPy (np.vectorize), JAX (jnp.vectorize) and
xarray (apply_ufunc core dims) already share. KernelOp wraps the
kernel once and runs it:
raw arrays → the kernel, called as is
named carriers → core dims moved last by name, the kernel on the
data, the result rewrapped by the adapter
(NumPy eagerly, JAX traced under jit)
an adapter with → that adapter's own path (the xarray adapter:
``apply_kernel`` one ``apply_ufunc``, lazy on dask)
Kernel conventions:
- Consumed axes last. Core dims arrive as the trailing axes.
- Broadcast over leading axes, or set
vectorize=Trueand pay fornp.vectorize/jnp.vectorize. - Non-carrier inputs are keyword parameters (a background mean, a
threshold), passed whole and never mapped. Geometry derived from the
carrier (
geometry=) is passed the same way; geometry that varies per pixel has the carrier's dims and is a positional input instead. - Write against the array namespace (
xp.linalg.solve) to run on every backend. A kernel that needs a JAX-only library (lineax) declaresbackends=("jax",)(spike finding F3).
Rules from the spike (geotoolz#516):
- Outputs keep the first input's dim order (F2): a gufunc puts core dims last, so each output is transposed back, with dims new to the output last.
- Every output has the loop dims of all the inputs. An output that ignores an input is broadcast (#246).
- A DataArray's name and attributes are dropped, because the kernel
changes the quantity and its unit. Coordinates keep theirs, and other
carriers keep what their adapter's
rewrapkeeps. geometry=needs one geometry per call (F4): on a carrier whose adapter reportsbatch_dims(per-item transforms),KernelOpraises and namesmap_over.- An output-only core dim declares its size (F5):
KernelSpec.sizesmaps it to an input core dim, so a lazy backend can plan the output.
Carriers of different kinds combine by dim name and size (a geo carrier
"band row col" with a DimArray "col band"); grid checks
(check_compatible) run between carriers of the same kind.
elementwise is the decorator for a function of plain arrays that maps each
element: it aligns labelled arrays by name and calls the function on their data.
It needs pipekit-array[numpy,compat] and is imported on first use.
KernelOp
¶
Bases: Operator
An L1 kernel wrapped once, run on raw arrays and on every named carrier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kernel
|
Callable[..., Any]
|
The L1 function: arrays (core dims last) and keyword params in, arrays out. |
required |
spec
|
KernelSpec | str
|
A |
required |
core
|
dict[str, str]
|
Each core letter of the spec → the carrier dim it stands for,
e.g. |
required |
geometry
|
dict[str, Callable[[Any], Any]] | None
|
Kernel keyword → a function of the first carrier returning
arrays ( |
None
|
params
|
Mapping[str, Any] | None
|
Keyword parameters passed to every call, as a mapping: the
way to pass one named |
None
|
**kwargs
|
Any
|
More keyword parameters passed to every call. |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
|
TypeError
|
|
Every output has the loop dims of all the inputs, in the first input's order. On DataArrays an output keeps the coordinates and has no name or attributes: a density is not in the pressure's units.
KernelOp holds a user function, so its config is a debug repr only
(forbid_in_yaml, like pipekit_ops.Lambda); a named operator built on
one by composition (geoops.NDVI) is what serialises.
Example
import numpy as np from pipekit_array import DimArray def nd(a, b, eps): ... return (a - b) / (a + b + eps) op = KernelOp(nd, "(),()->()", core={}, eps=1e-10) nir = DimArray(np.full((2, 3), 0.4), ("y", "x")) red = DimArray(np.full((2, 3), 0.1), ("y", "x")) op(nir, red).dims ('y', 'x')
Source code in packages/pipekit-array/src/pipekit_array/kernels/_op.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | |
compute_output_signature(input_signature)
¶
The output signature(s) for a one-input kernel; None otherwise.
A two-output kernel gives a tuple of signatures. With several inputs
the other inputs' dims are unknown here, so the answer is None.
The dtype is the one spec.dtypes declares ("same": the
input's), else unknown: a kernel may return a mask or an index.
Source code in packages/pipekit-array/src/pipekit_array/kernels/_op.py
KernelSpec
dataclass
¶
A generalized-ufunc signature over abstract core-dim letters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signature
|
str
|
E.g. |
required |
backends
|
tuple[str, ...]
|
The backends the kernel is written for, from |
('numpy', 'jax', 'dask', 'xarray')
|
vectorize
|
bool
|
The kernel handles only its core dims, and is mapped over
the rest with |
False
|
sizes
|
tuple[tuple[str, str], ...]
|
Output-only core letters and the input letter whose size each
has, e.g. |
()
|
dtypes
|
tuple[str, ...]
|
Each output's dtype, for output signatures and lazy
backends: a dtype name ( |
()
|
Raises:
| Type | Description |
|---|---|
ValueError
|
The signature does not parse, |
Example
spec = KernelSpec("(r,c)->(c),(c,d)", sizes=(("d", "c"),)) spec.inputs, spec.outputs ((('r', 'c'),), (('c',), ('c', 'd')))
Source code in packages/pipekit-array/src/pipekit_array/kernels/_spec.py
derive_geometry(geometry, first)
¶
The kernel's derived-geometry keywords, computed from the first carrier.
Raises:
| Type | Description |
|---|---|
ValueError
|
The carrier's adapter reports |
Source code in packages/pipekit-array/src/pipekit_array/kernels/_run.py
elementwise(*, n_outputs=1)
¶
Let an elementwise function take and return labelled arrays.
Algorithm
- With no labelled array among the arguments, call the function as it is.
- Hand DataArrays to
xarray.apply_ufunc, and other carriers with a registered adapter (DimArray, geoarray'sGeoArray) to the path ofKernelOp. Both align by dimension name and call the function on the data. The other arguments are passed through. - Broadcast every result to the dimensions of the inputs together.
- Return labelled arrays with the inputs' coordinates. A DataArray
has no name or attributes, because the quantity and its unit have
changed; another carrier keeps what its adapter's
rewrapkeeps, and its missing elements stay missing (pipekit_ops.MissingValueAdapter).
An array without dimension names cannot be aligned with one that has them, so it is refused, unless it has no dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_outputs
|
int
|
How many arrays the function returns; above 1, a tuple. |
1
|
Returns:
| Type | Description |
|---|---|
Callable[[F], F]
|
The decorator. |
Raises:
| Type | Description |
|---|---|
ValueError
|
(the decorated function) if a labelled array meets an array with dimensions but no names. |
BackendError
|
(the decorated function) if a DataArray meets a carrier of another kind, or carriers hold arrays of several libraries other than NumPy and JAX. |
Example
import numpy as np from pipekit_array import DimArray @elementwise() ... def scaled(x, slope): ... return slope * x scaled(np.asarray([1.0, 2.0]), 2.0).tolist() [2.0, 4.0] scaled(DimArray(np.asarray([1.0, 2.0]), ("x",)), 2.0).dims ('x',)
Source code in packages/pipekit-array/src/pipekit_array/kernels/_elementwise.py
kernel_output_dims(spec, core, input_dims)
¶
The dims of each output, from the inputs' dims, without running.
Loop dims are every input's dims minus its core dims, in order of first appearance. Output k has the loop dims plus its core dims, in the first input's order, with dims new to the output last (F2).
Source code in packages/pipekit-array/src/pipekit_array/kernels/_spec.py
kernel_output_signature(spec, core, input_signature)
¶
KernelOp.compute_output_signature for any operator running spec.
Shared with pipekit_jax.JaxKernelOp, so a converted operator reports
the same dims, sizes, dtypes and output count.
Source code in packages/pipekit-array/src/pipekit_array/kernels/_spec.py
run_kernel(kernel, spec, core, carriers, kwargs)
¶
Run kernel on raw arrays or named carriers; the dispatch behind KernelOp.
Raises:
| Type | Description |
|---|---|
BackendError
|
Carriers on several backends other than NumPy and JAX, or a backend the spec does not list. |
TypeError
|
A raw array next to named carriers. |
ValueError
|
A core dim is missing from its input, or a dim has two sizes. |
Source code in packages/pipekit-array/src/pipekit_array/kernels/_run.py
pipekit_array.kernels._elementwise
¶
Let an elementwise function of plain arrays take and return labelled arrays.
elementwise(*, n_outputs=1)
¶
Let an elementwise function take and return labelled arrays.
Algorithm
- With no labelled array among the arguments, call the function as it is.
- Hand DataArrays to
xarray.apply_ufunc, and other carriers with a registered adapter (DimArray, geoarray'sGeoArray) to the path ofKernelOp. Both align by dimension name and call the function on the data. The other arguments are passed through. - Broadcast every result to the dimensions of the inputs together.
- Return labelled arrays with the inputs' coordinates. A DataArray
has no name or attributes, because the quantity and its unit have
changed; another carrier keeps what its adapter's
rewrapkeeps, and its missing elements stay missing (pipekit_ops.MissingValueAdapter).
An array without dimension names cannot be aligned with one that has them, so it is refused, unless it has no dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_outputs
|
int
|
How many arrays the function returns; above 1, a tuple. |
1
|
Returns:
| Type | Description |
|---|---|
Callable[[F], F]
|
The decorator. |
Raises:
| Type | Description |
|---|---|
ValueError
|
(the decorated function) if a labelled array meets an array with dimensions but no names. |
BackendError
|
(the decorated function) if a DataArray meets a carrier of another kind, or carriers hold arrays of several libraries other than NumPy and JAX. |
Example
import numpy as np from pipekit_array import DimArray @elementwise() ... def scaled(x, slope): ... return slope * x scaled(np.asarray([1.0, 2.0]), 2.0).tolist() [2.0, 4.0] scaled(DimArray(np.asarray([1.0, 2.0]), ("x",)), 2.0).dims ('x',)
Source code in packages/pipekit-array/src/pipekit_array/kernels/_elementwise.py
Operators¶
pipekit_array.operators has the operator twin of each named function, and MeanScalar, StackAlong and ConcatenateAlong for raw arrays.
pipekit_array.operators
¶
The functions of pipekit_array.named as Operators, for pipelines and config.
Each wraps one function and computes its output Signature without running.
Operators that take only names and numbers round-trip through dumps /
loads; those that hold a user function (MapOver, Combine) set
forbid_in_yaml, like pipekit_ops.Lambda.
Reduce and ArgReduce take the reduction by its array-namespace name
("mean", "argmax") so they serialise; the function forms also take a
callable. MeanScalar, StackAlong and ConcatenateAlong run on raw arrays.
A saved pipeline records an operator under pipekit_array, wherever its file
is (ADR A30).
ApplyAlong
¶
Bases: Operator
inner on each item along dim; the results stacked along dim, first.
map_over with an Operator instead of a function, so it serialises
whenever inner does: inner is stored as a nested config, and
ApplyAlong itself does not set forbid_in_yaml (a flagged
inner is found by the serialiser's walk). Use MapOver for a
plain function. Replaces the planned ApplyToBands (A15).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inner
|
Operator
|
The operator applied to each item, |
required |
dim
|
str
|
The dim to map over. |
required |
Example
import numpy as np from pipekit_array import DimArray cube = DimArray(np.ones((3, 2, 4)), ("time", "band", "x")) ApplyAlong(Reduce("sum", dim="band"), dim="time")(cube).dims ('time', 'x')
Source code in packages/pipekit-array/src/pipekit_array/operators/_map.py
ArgReduce
¶
Bases: Operator
The index of a reduction along one dim ("argmax", "argmin").
The output signature's dtype is None: the integer width depends on
the backend.
Source code in packages/pipekit-array/src/pipekit_array/operators/_reduce.py
BatchAlong
¶
Bases: Operator
inner on chunks of size along dim of one carrier, joined back.
y = concat([inner(x_{0:m}), inner(x_{m:2m}), …], dim), m = size.
Not pipekit_ops.BatchedMap, which takes an iterable and calls its
operator on lists of items: BatchAlong splits one named carrier
along a dim (A19, which supersedes A5). The use case is a GPU-bound
model on a cube that does not fit in device memory at once.
inner must keep dim, one output entry per input entry (a
per-item operator), for the "last" padding to be trimmed and for
dim's labels to come back; the result then equals inner(x).
Algorithm
- Cut
diminto chunks ofsize; the last may be short. - Apply
pad(ADR A10) to a short last chunk:"none"keeps it short;"last"pads it tosizewith copies of its last item, so a jittedinnercompiles once, and trims the padding from its output;"drop"drops it. - Join the outputs along
dimand setdim's labels to the input's (an adapter's genericconcatdrops them).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inner
|
Operator
|
The operator applied to each chunk. |
required |
size
|
int
|
Entries per chunk; must be positive. |
required |
dim
|
str
|
The dim to cut. |
required |
pad
|
PadPolicy
|
|
'none'
|
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
|
Example
import numpy as np from pipekit_array import DimArray, Reduce cube = DimArray(np.ones((10, 2, 4)), ("sample", "band", "x")) per_chunk = BatchAlong(Reduce("sum", "band"), size=4, dim="sample") per_chunk(cube).dims, per_chunk(cube).shape (('sample', 'x'), (10, 4)) BatchAlong(Reduce("sum", "band"), 4, "sample", pad="drop")(cube).shape (8, 4)
Source code in packages/pipekit-array/src/pipekit_array/operators/_map.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | |
BroadcastLike
¶
Bases: Operator
Add other's missing dims to x, in front: op(x, other).
compute_output_signature takes the pair (x's, other's): from
x's alone the added dims are unknown, so it returns None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exclude
|
Sequence[str]
|
Dims of |
()
|
Source code in packages/pipekit-array/src/pipekit_array/operators/_shape.py
Coarsen
¶
Bases: Operator
Reduce non-overlapping blocks along named dims by a named reduction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
str
|
The reduction's name in the array namespace: |
required |
boundary
|
str
|
|
'exact'
|
**windows
|
int
|
|
{}
|
Example
import numpy as np from pipekit_array import DimArray Coarsen("mean", y=2, x=2)(DimArray(np.ones((4, 6)), ("y", "x"))).shape (2, 3)
Source code in packages/pipekit-array/src/pipekit_array/operators/_window.py
Combine
¶
Bases: Operator
An element-wise function of carriers with the same dims: op(a, b, …).
Holds a user function, so its config is a debug repr only.
Source code in packages/pipekit-array/src/pipekit_array/operators/_join.py
ConcatenateAlong
¶
Bases: Operator
Concatenate a list-of-arrays along an existing axis via xp.concat.
xp.concat is the Array API standardised name; numpy 2.0+
exposes it as concat alongside the legacy concatenate alias.
All input arrays must share shape (except along axis), dtype,
and backend; NumPy arrays join JAX ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis
|
int | None
|
Existing axis to concatenate along, for raw arrays. Default 0. |
None
|
dim
|
str | None
|
For named carriers instead: the dim to join along
( |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
From |
Example::
out = ConcatenateAlong(axis=0)([arr_a, arr_b]) # shape (2*N, H, W)
Source code in packages/pipekit-array/src/pipekit_array/operators/_join.py
CumReduce
¶
Bases: Operator
A cumulative function along dim, by its array-namespace name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
str
|
|
required |
dim
|
str
|
The dim to accumulate along. |
required |
Example
import numpy as np from pipekit_array import DimArray CumReduce("cumulative_sum", "time")(DimArray(np.ones(3), ("time",))).data array([1., 2., 3.])
Source code in packages/pipekit-array/src/pipekit_array/operators/_reduce.py
Diff
¶
Bases: Operator
The n-th forward difference along dim: N entries become N - n.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
str
|
The dim to difference along. |
required |
n
|
int
|
The order, n ≥ 0. |
1
|
label
|
str
|
The labels kept on |
'upper'
|
Example
import numpy as np from pipekit_array import DimArray Diff("time")(DimArray(np.zeros((12, 4)), ("time", "x"))).shape (11, 4)
Source code in packages/pipekit-array/src/pipekit_array/operators/_shift.py
Dot
¶
Bases: Operator
The sum of the product of carriers over named dims: op(*xs).
compute_output_signature takes the tuple of the inputs' signatures:
from one signature the other inputs' dims are unknown, so it returns
None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
str | Sequence[str]
|
A dim name, or several, to sum over. |
required |
Example
import numpy as np from pipekit_array import DimArray x = DimArray(np.ones((12, 13)), ("time", "band")) w = DimArray(np.ones((13, 3)), ("band", "component")) Dot(dim="band")(x, w).dims ('time', 'component')
Source code in packages/pipekit-array/src/pipekit_array/operators/_reduce.py
ExpandDims
¶
Bases: Operator
Insert length-1 dims at position axis of the result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
str | Sequence[str]
|
A new dim name, or several. |
required |
axis
|
int
|
Where the first new dim goes; negative counts from the end. |
0
|
Example
import numpy as np from pipekit_array import DimArray ExpandDims("member")(DimArray(np.zeros((2, 4)), ("band", "x"))).dims ('member', 'band', 'x')
Source code in packages/pipekit-array/src/pipekit_array/operators/_shape.py
ISel
¶
Bases: Operator
Select by position along one dim; an integer drops the dim.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
str
|
The dim to index. |
required |
index
|
int | slice
|
An int, or a slice (stored in config as start/stop/step). |
required |
Example
import numpy as np from pipekit_array import DimArray ISel(dim="time", index=0)(DimArray(np.zeros((12, 4)), ("time", "x"))).dims ('x',)
Source code in packages/pipekit-array/src/pipekit_array/operators/_select.py
MapOver
¶
Bases: Operator
fn on each item along dim; the results stacked along dim, first.
Holds a user function, so its config is a debug repr only.
Source code in packages/pipekit-array/src/pipekit_array/operators/_map.py
MeanScalar
¶
Bases: Operator
Reduce an array to a scalar (or per-axis means) via xp.mean.
Defaults to a full reduction (axis=None) yielding a scalar of
rank 0. Output dtype matches the input's floating dtype per the
Array API mean contract.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis
|
int | tuple[int, ...] | None
|
Axis or tuple of axes to reduce over. |
None
|
keepdims
|
bool
|
If True, retains the reduced axes with size 1. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
From |
Example::
out = MeanScalar()(image) # scalar
out = MeanScalar(axis=(-2, -1))(image) # per-band mean
out = MeanScalar(axis=0, keepdims=True)(image) # shape (1, H, W)
Source code in packages/pipekit-array/src/pipekit_array/operators/_reduce.py
MergeDims
¶
Bases: Operator
Merge the listed dims into one, placed last, in C order.
Its config lists the merges in order (JSON objects sort their keys).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**dims
|
Sequence[str]
|
|
{}
|
Example
import numpy as np from pipekit_array import DimArray cube = DimArray(np.zeros((2, 3, 4)), ("band", "y", "x")) MergeDims(pixel=("y", "x"))(cube).shape (2, 12)
Source code in packages/pipekit-array/src/pipekit_array/operators/_shape.py
Pad
¶
Bases: Operator
Widen named dims at either end; a padded dim loses its labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
str
|
|
'constant'
|
constant_values
|
float | None
|
The fill for |
None
|
**pad_width
|
int | Sequence[int]
|
|
{}
|
Example
import numpy as np from pipekit_array import DimArray Pad(time=(2, 0))(DimArray(np.zeros((12, 4)), ("time", "x"))).shape (14, 4)
Source code in packages/pipekit-array/src/pipekit_array/operators/_shift.py
Quantile
¶
Bases: Operator
Quantiles over named dims; a sequence q adds a leading quantile dim.
q is stored in config as a float or an ordered list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
float | Sequence[float]
|
A probability in [0, 1], or a sequence of them. |
required |
dim
|
str | Sequence[str]
|
A dim name, or several, to reduce over. |
required |
method
|
str
|
One of |
'linear'
|
skipna
|
bool
|
Ignore NaN. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Example
import numpy as np from pipekit_array import DimArray cube = DimArray(np.ones((12, 2, 4)), ("time", "band", "x")) Quantile([0.1, 0.9], dim="time")(cube).dims ('quantile', 'band', 'x')
Source code in packages/pipekit-array/src/pipekit_array/operators/_reduce.py
Reduce
¶
Bases: Operator
Reduce over named dims with an array-namespace reduction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
str
|
The reduction's name in the array namespace: |
required |
dim
|
str | Sequence[str]
|
A dim name, or several. |
required |
Example
import numpy as np from pipekit_array import DimArray cube = DimArray(np.ones((12, 2, 4)), ("time", "band", "x")) Reduce("median", dim="time")(cube).dims ('band', 'x')
Source code in packages/pipekit-array/src/pipekit_array/operators/_reduce.py
Rename
¶
Bases: Operator
New dim names; data, order and labels unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**names
|
str
|
|
{}
|
Example
import numpy as np from pipekit_array import DimArray Rename(band="channel")(DimArray(np.zeros((2, 4)), ("band", "x"))).dims ('channel', 'x')
Source code in packages/pipekit-array/src/pipekit_array/operators/_shape.py
Roll
¶
Bases: Operator
Shift data cyclically along named dims; labels stay.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**shifts
|
int
|
|
{}
|
Example
import numpy as np from pipekit_array import DimArray Roll(time=1)(DimArray(np.arange(3.0), ("time",))).data array([2., 0., 1.])
Source code in packages/pipekit-array/src/pipekit_array/operators/_shift.py
Sel
¶
Bases: Operator
Select by exact label along one dim; one label drops the dim.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
str
|
The dim to select on; it must have labels. |
required |
label
|
Any
|
One label, or a list of labels (the dim is kept). A tuple is one label when the dim has tuple-valued labels, else several. |
required |
Source code in packages/pipekit-array/src/pipekit_array/operators/_select.py
Shift
¶
Bases: Operator
Shift data along named dims, filling the vacated entries; labels stay.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fill_value
|
float | None
|
The value of the vacated entries; None is NaN. |
None
|
**shifts
|
int
|
|
{}
|
Example
import numpy as np from pipekit_array import DimArray Shift(time=1)(DimArray(np.arange(3.0), ("time",))).data array([nan, 0., 1.])
Source code in packages/pipekit-array/src/pipekit_array/operators/_shift.py
SplitDims
¶
Bases: Operator
Split one dim into several, in place, in C order.
Its config lists each split's parts in order (JSON objects sort their keys).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**dims
|
Mapping[str, int]
|
|
{}
|
Example
import numpy as np from pipekit_array import DimArray pixels = DimArray(np.zeros((2, 12)), ("band", "pixel")) SplitDims(pixel={"y": 3, "x": 4})(pixels).dims ('band', 'y', 'x')
Source code in packages/pipekit-array/src/pipekit_array/operators/_shape.py
Squeeze
¶
Bases: Operator
Drop named length-1 dims.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
str | Sequence[str]
|
A dim name, or several; each must have size 1. |
required |
Source code in packages/pipekit-array/src/pipekit_array/operators/_shape.py
StackAlong
¶
Bases: Operator
Stack a list-of-arrays along a new axis via xp.stack.
All input arrays must share the same shape, dtype, and backend; NumPy arrays join JAX ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis
|
int | None
|
Position of the new axis in the output, for raw arrays. Default 0. |
None
|
dim
|
str | None
|
For named carriers instead: the new dim's name
( |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
From |
Example::
out = StackAlong(axis=0)([arr_a, arr_b, arr_c]) # shape (3, H, W)
Source code in packages/pipekit-array/src/pipekit_array/operators/_join.py
TakeAlong
¶
Bases: Operator
Gather one entry of dim per position: op(x, index).
index is a named carrier with x's dims without dim, such as
an ArgReduce result.
Source code in packages/pipekit-array/src/pipekit_array/operators/_select.py
Transpose
¶
Bases: Operator
Reorder dims by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order
|
Sequence[str]
|
Every dim, once, in the new order. |
required |
Source code in packages/pipekit-array/src/pipekit_array/operators/_shape.py
Where
¶
Bases: Operator
Keep x where cond is True, other elsewhere: op(x, cond).
compute_output_signature takes x's signature, or the pair
(x's, cond's): the output has x's dims and dtype either way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
float | None
|
The fill where |
None
|
Example
import numpy as np from pipekit_array import DimArray valid = DimArray(np.array([True, False]), ("x",)) Where()(DimArray(np.ones(2), ("x",)), valid).data array([ 1., nan])
Source code in packages/pipekit-array/src/pipekit_array/operators/_shift.py
Window
¶
Bases: Operator
Sliding windows along one dim, as a new last dim; full windows only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window_dim
|
str
|
The new last dim. |
'window'
|
stride
|
int
|
The step between window starts. |
1
|
**sizes
|
int
|
|
{}
|
Example
import numpy as np from pipekit_array import DimArray Window(stride=2, time=3)(DimArray(np.zeros((12, 4)), ("time", "x"))).shape (5, 4, 3)
Source code in packages/pipekit-array/src/pipekit_array/operators/_window.py
Bridges¶
pipekit_array.bridges is for other libraries on named carriers.
xarray¶
The adapter of xr.DataArray loads the first time one arrives ([xarray]).
pipekit_array.bridges.xarray
¶
The xr.DataArray adapter (pipekit-array[xarray]).
Registered lazily: importing pipekit-array never imports xarray; the
adapter loads the first time a DataArray reaches pipekit_ops.get_adapter
(pipekit_ops.register_lazy_adapter). This module is the only place
pipekit-array imports xarray.
- Exact coordinates.
XarrayAdapter.check_compatiblealigns withjoin="exact": two cubes whose x differ by 1e-7 raise instead of inner-joining to an empty result. - Lazy on dask.
KernelOpruns as onexr.apply_ufunccall,dask="parallelized", one task per chunk; the dim-level fast paths (reduce,argreduce,take_along,stack,concat,combine,transpose,rename,window) are native xarray calls, so nothing computes until.compute(). DataArrayonly (PK-P5):DatasetandDataTreedispatch stays in xrops.
from_xarray turns a DataArray into a DimArray, keeping the labels of
dims that have a 1-D index coordinate.
XarrayAdapter
¶
The pipekit_ops.NamedArrayAdapter for xr.DataArray, with fast paths.
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | |
apply_kernel(kernel, spec, core, kwargs, *xs)
¶
A KernelOp call as one xr.apply_ufunc: lazy, exact, in input order.
Core dims move last; kwargs (params and derived geometry) are
passed whole; output-only core dims take their sizes from
spec.sizes; outputs come back with the loop dims of all the inputs,
in the first input's dim order (F2), without a name or attributes.
Raises:
| Type | Description |
|---|---|
BackendError
|
The spec does not list |
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
argreduce(x, fn, dim)
¶
x.reduce with NumPy's argmax / argmin (or fn).
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
check_compatible(*xs)
¶
The inputs back if their shared coordinates are exactly equal.
Raises:
| Type | Description |
|---|---|
ValueError
|
Coordinates differ; xarray would otherwise inner-join. |
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
combine(fn, *xs)
¶
apply_ufunc(fn, …, join="exact"), lazy on dask.
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
concat(xs, dim)
¶
Along an existing dim, joining its coordinate; others must be identical.
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
data(x)
¶
dims(x)
¶
isel(x, indexers)
¶
labels(x, dim)
¶
The values of dim's 1-D index coordinate, or None.
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
reduce(x, fn, dims, *, where=None)
¶
x.reduce with the array-namespace function, lazy on dask.
A name resolves to NumPy's function ("nanmean" included), so NaN
handling matches the generic path: DataArray's own mean would
skip NaN by default. where arrives aligned to x's full shape
(pipekit_array.reduce aligns it) and is passed to the function.
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
relabel(x, labels)
¶
assign_coords for a tuple, drop_vars for None (ADR A22).
Tuple-valued labels (pipekit_array.merge_dims) become a 1-D object
coordinate, one tuple per entry.
Raises:
| Type | Description |
|---|---|
ValueError
|
A dim is not in |
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
rename(x, names)
¶
x.rename, which also renames the dim in non-index coordinates.
The generic path (rewrap then relabel) would drop a
coordinate such as quality(time, x) on a renamed dim (A22).
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
rewrap(x, data, dims)
¶
A DataArray around new data, keeping coords and attrs of surviving dims.
A coordinate is kept when all its dims survive with their sizes; a
scalar one named after a new dim (left by isel) is dropped, since
xarray refuses a scalar variable named after a dim.
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
signature(x)
¶
Dims with their sizes, and the dtype's name.
stack(xs, dim)
¶
A new leading dim; coordinates must be identical (never aligned).
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
take_along(x, index, dim)
¶
One entry of dim per position, lazily on dask, in x's dim order.
An apply_ufunc over take_along_axis, not a vectorized
isel: dask cannot index with a lazy indexer. Attributes are kept,
auxiliary coordinates on dim (quality(time, x)) are gathered
with the same index, and dim's own coordinate is dropped.
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
transpose(x, order)
¶
window(x, dim, size, *, window_dim, stride)
¶
rolling(...).construct(window_dim) from the first full window: a view.
The fill is zero, not NaN, so integers keep their dtype; the
isel drops every filled window.
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
from_xarray(da)
¶
A DimArray with the same data and dims; 1-D index coordinates become labels.
Source code in packages/pipekit-array/src/pipekit_array/bridges/xarray.py
register()
¶
Register XarrayAdapter for xr.DataArray (the lazy loader calls this).
einx¶
einx patterns whose axis names are the carrier's dim names ([einx], geostack OP-O2).
A dask input raises BackendError naming .compute(), because einx has no dask backend.
pipekit_array.bridges.einx
¶
A named-dims einx bridge on any carrier (geostack OP-O2).
einx <https://github.com/fferflo/einx>_ writes tensor algebra as patterns
("band y x -> y x band"). Here the pattern's axis names are the
carrier's dim names: each input is matched to its slot by name, einx runs
on the data's own backend (NumPy, JAX under jit), and the result is
rewrapped through the first input's adapter with the output slot's dims, so
it keeps the labels, coordinates and (for geoarray) the grid of the dims
that survive:
rearrange("band y x -> y x band", scene) # transpose by name
reduce("time band y x -> band y x", cube, op="mean") # over time
einsum("time band, band k -> time k", cube, w) # contract band
repeat("y x -> member y x", field, member=8) # broadcast
einsum, reduce and repeat match input slots to dims by name, in
any order. rearrange also splits and merges dims ("(a b)"), so its
input slot is read positionally: it lists the input's dims in order, a
group standing for one dim that is split. A merged output group
(a b) becomes one dim named a_b.
dask is not an einx backend: a dask-backed input raises
pipekit_ops.BackendError naming .compute() rather than computing it
silently. einx is imported lazily: install the [einx] extra.
Einx
¶
Bases: Operator
One einx operation as an operator: Einx("reduce", pattern, op="mean").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
operation
|
str
|
|
required |
pattern
|
str
|
The pattern, with dim names as axis names. |
required |
op
|
str | None
|
The reduction, for |
None
|
sizes
|
dict[str, int] | None
|
Axis sizes forwarded to einx. |
None
|
Example
import numpy as np from pipekit_array import DimArray cube = DimArray(np.ones((2, 3, 4)), ("time", "y", "x")) Einx("reduce", "time y x -> y x", op="mean")(cube).dims ('y', 'x')
Source code in packages/pipekit-array/src/pipekit_array/bridges/einx.py
PatternError
¶
einsum(pattern, *xs, **sizes)
¶
Contract the dims named on the input slots and left off the output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
|
required |
*xs
|
Any
|
One named carrier per input slot; carriers of one family are checked to combine first (geoarray: the same grid). |
()
|
**sizes
|
int
|
Forwarded to einx. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
A carrier with the output slot's dims, rewrapped by the first |
Any
|
input's adapter. |
Example
import numpy as np from pipekit_array import DimArray a = DimArray(np.ones((2, 3)), ("time", "band")) w = DimArray(np.ones((3, 4)), ("band", "k")) einsum("time band, band k -> time k", a, w).shape (2, 4)
Source code in packages/pipekit-array/src/pipekit_array/bridges/einx.py
rearrange(pattern, x, **sizes)
¶
Transpose, split or merge dims by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
One input slot and one output slot. The input slot lists
|
required |
x
|
Any
|
A named carrier. |
required |
**sizes
|
int
|
Sizes of split dims einx cannot infer ( |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
A carrier with the output slot's dims (a merged |
Any
|
|
Raises:
| Type | Description |
|---|---|
PatternError
|
The input slot does not describe |
Example
import numpy as np from pipekit_array import DimArray scene = DimArray(np.zeros((3, 4, 5)), ("band", "y", "x")) rearrange("band y x -> y x band", scene).dims ('y', 'x', 'band')
Source code in packages/pipekit-array/src/pipekit_array/bridges/einx.py
reduce(pattern, x, *, op, **sizes)
¶
Reduce over the dims on the input slot that the output slot leaves out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
|
required |
x
|
Any
|
A named carrier. |
required |
op
|
str | Callable[..., Any]
|
|
required |
**sizes
|
int
|
Forwarded to einx. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
A carrier with the output slot's dims. |
Example
import numpy as np from pipekit_array import DimArray cube = DimArray(np.ones((2, 3, 4)), ("time", "y", "x")) reduce("time y x -> y x", cube, op="sum").data[0, 0] np.float64(2.0)
Source code in packages/pipekit-array/src/pipekit_array/bridges/einx.py
repeat(pattern, x, **sizes)
¶
Broadcast x along new dims (sizes in sizes).
Example
import numpy as np from pipekit_array import DimArray field = DimArray(np.zeros((4, 5)), ("y", "x")) repeat("y x -> member y x", field, member=8).shape (8, 4, 5)
Source code in packages/pipekit-array/src/pipekit_array/bridges/einx.py
scikit-learn¶
Estimator fits and applies a scikit-learn-style estimator on any named carrier, through to_rows and from_rows ([sklearn], imported lazily; geostack OP-O3).
pipekit_array.bridges.sklearn
¶
Estimator: one scikit-learn wrapper for every named carrier (geostack OP-O3).
A scikit-learn-style estimator learns from a (n_samples, n_features)
table. Estimator chooses the samples by dim name, flattens the carrier
with pipekit_array.to_rows, fits or applies the estimator, and rebuilds a
carrier like the input with pipekit_array.from_rows:
cube (time, band, y, x) ── Estimator(PCA(3), sample_dims=("time", "y", "x"),
feature_dim="component") ──>
(time, component, y, x)
It satisfies pipekit_ops.FittableTransformer: fit returns the operator
with estimator_ and layout_ set, and transform (and
predict, predict_proba, inverse_transform) only read them. Fitting
and applying run on the host: scikit-learn computes on NumPy, so a dask
input is computed and a JAX input converted, eagerly; inside a JAX trace
fit raises.
NaN policies. nan_policy decides what a non-finite entry costs:
"propagate"(default): the rows go to the estimator as they are;"raise": any non-finite entry raises, naming the policy;"mask_samples": rows with a non-finite entry are left out of fitting and applying, and come back asNaNin the output;"mask_features": columns non-finite in every fitted row are dropped at fit time and at transform time, and come back asNaNfrominverse_transform;"mask":"mask_features"then"mask_samples"on the columns kept, for a land-masked field that also has gaps.
The scikit-learn import is lazy: install the [sklearn] extra.
Estimator
¶
Bases: Operator
A scikit-learn-style estimator fitted and applied on a named carrier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
Any
|
Any object with scikit-learn's |
required |
sample_dims
|
tuple[str, ...] | list[str]
|
The dims whose entries are samples; every other dim is a feature. |
required |
feature_dim
|
str | None
|
The name of the output dim when the estimator's output
columns are not the input's features (PCA components, class
probabilities). Left |
None
|
nan_policy
|
NanPolicy
|
|
'propagate'
|
method
|
str
|
What calling the operator runs once fitted:
|
'transform'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
An unknown |
Example
import numpy as np from sklearn.decomposition import PCA from pipekit_array import DimArray rng = np.random.default_rng(0) cube = DimArray(rng.normal(size=(5, 4, 3)), ("band", "y", "x")) pca = Estimator(PCA(2), sample_dims=("y", "x"), feature_dim="component") pca.fit(cube).transform(cube).dims ('component', 'y', 'x')
Source code in packages/pipekit-array/src/pipekit_array/bridges/sklearn.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | |
fit(x, y=None)
¶
Learn the estimator from x (and y, for a supervised one).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A named carrier with the sample dims. |
required |
y
|
Any
|
Targets: a carrier whose dims are the sample dims (plus at
most one target dim), or |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
This operator, fitted. |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
|
Source code in packages/pipekit-array/src/pipekit_array/bridges/sklearn.py
inverse_transform(z)
¶
Map transform's output back to the fitted features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Any
|
A carrier with the sample dims and the output dim ( |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A carrier with the fitted feature dims and sizes in place of the |
Any
|
output dim; dropped features ( |
Source code in packages/pipekit-array/src/pipekit_array/bridges/sklearn.py
predict(x)
¶
predict_proba(x)
¶
Class probabilities per sample, along feature_dim ("class").
transform(x)
¶
Test kit¶
The test kit ships in the wheel, for other libraries' own test suites.
check_adapter and check_kernel_op are for carrier libraries (gates PK-K1 and PK-K4); pipekit's own tests run PK-K2, PK-K3 and, under -m slow, PK-K5.
The others are for functions on any array library (ADR A29).
pipekit_array.testing
¶
Checks for the test suites of the libraries built on pipekit-array.
They ship in the wheel, so that a library tests itself with one call instead of
copying the check. Each raises AssertionError, saying where and by how much.
A check of a number has a twin that returns what it measured, for a notebook or
a run report: oracle_error, adjoint_error, equivariance_error,
idempotence_error, grad_fd_error, invariant_ratio, taylor_slopes and
observed_order.
- Contracts of a carrier library (gates PK-K1 and PK-K4):
check_adapterandcheck_kernel_op. - Array libraries:
assert_backends_agreeruns a function on each kind of array that is installed (array_kinds), andassert_refuses_dataarrayschecks that labels are never lost silently. - Values:
assert_matches_oracle,assert_adjoint, the dot-product test, andassert_order, the order of convergence of a scheme under refinement. - Structure:
assert_equivariant(a function commutes with a transform) andassert_idempotent(a function is a projection), on any array library. - JAX:
assert_traces,assert_grad_matches_fd,assert_finite_gradient,assert_taylor(the Taylor remainder along one direction falls as ε², for a state too large for a Jacobian) andassert_invariant(a field conserves a functional). They skip without JAX, and need its 64-bit mode. - Samples:
assert_mean,assert_varianceandassert_uniform, with thresholds from the sampling distribution.
Importing this module needs NumPy, and neither pytest nor another array library.
ArrayKind
dataclass
¶
One kind of array: how to make it, what comes back, and how to read it.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
What it is called in a message, and in |
make |
Callable[[ndarray], Any]
|
An array of this kind from a NumPy one. |
type |
Any
|
The class, or classes, that a result must have. |
host |
Callable[[Any], ndarray]
|
The values of a result as NumPy; it checks the device. |
Source code in packages/pipekit-array/src/pipekit_array/testing/_arrays.py
read(array)
¶
The array as NumPy, after checking that it is of this kind.
Raises:
| Type | Description |
|---|---|
AssertionError
|
If it is of another kind, or on another device. |
Example
array_kinds()[0].read(np.ones(2)) array([1., 1.])
Source code in packages/pipekit-array/src/pipekit_array/testing/_arrays.py
adjoint_error(apply, apply_adjoint, n_source, n_target, *, seed=0)
¶
The relative error of the dot-product test, on random NumPy x and r.
|⟨Hx, r⟩ - ⟨x, Gr⟩| / max(‖Hx‖ ‖r‖, ‖x‖ ‖Gr‖)
The measurement behind assert_adjoint. The larger product of norms is the
scale, so that a G which is too large also shows. If both products are 0,
the error is absolute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
apply
|
Callable[[Any], Any]
|
H, a linear map from ℝᴺ to ℝᴹ. |
required |
apply_adjoint
|
Callable[[Any], Any]
|
G, the claimed adjoint Hᵀ, from ℝᴹ to ℝᴺ. |
required |
n_source
|
int
|
N, the length of x. |
required |
n_target
|
int
|
M, the length of Hx. |
required |
seed
|
int
|
The seed of x and r. |
0
|
Returns:
| Type | Description |
|---|---|
float
|
The relative error, near the unit round-off for a true adjoint. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If an output has the wrong shape. |
Example
import numpy as np H = np.array([[1.0, 2.0, 0.0], [0.0, 1.0, -1.0]]) adjoint_error(lambda x: H @ x, lambda r: H.T @ r, 3, 2) < 1e-15 True
Source code in packages/pipekit-array/src/pipekit_array/testing/_oracles.py
array_kinds()
cached
¶
The kinds of array whose library is installed.
The call imports those libraries. In this order: numpy; strict and
second device, array_api_strict on its default device and on another
one; jax; dask; torch; xarray.
Returns:
| Type | Description |
|---|---|
tuple[ArrayKind, ...]
|
The kinds, for |
Example
array_kinds()[0].name 'numpy'
Source code in packages/pipekit-array/src/pipekit_array/testing/_arrays.py
assert_adjoint(apply, apply_adjoint, n_source, n_target, *, seed=0, rtol=1e-12)
¶
Assert the dot-product test ⟨Hx, r⟩ = ⟨x, Gr⟩ on random NumPy x and r.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
apply
|
Callable[[Any], Any]
|
H, a linear map from ℝᴺ to ℝᴹ. |
required |
apply_adjoint
|
Callable[[Any], Any]
|
G, the claimed adjoint Hᵀ, from ℝᴹ to ℝᴺ. |
required |
n_source
|
int
|
N, the length of x. |
required |
n_target
|
int
|
M, the length of Hx. |
required |
seed
|
int
|
The seed of x and r. |
0
|
rtol
|
float
|
The tolerance, relative to max(‖Hx‖ ‖r‖, ‖x‖ ‖Gr‖). |
1e-12
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If an output has the wrong shape, or the relative error
exceeds |
Example
import numpy as np H = np.array([[1.0, 2.0, 0.0], [0.0, 1.0, -1.0]]) assert_adjoint(lambda x: H @ x, lambda r: H.T @ r, 3, 2)
Source code in packages/pipekit-array/src/pipekit_array/testing/_oracles.py
assert_backends_agree(fn, *args, rtol=1e-12, atol=0.0, rtol32=1e-05, atol32=0.0, kinds=None, labelled=False)
¶
Assert that a function gives NumPy's numbers on every kind of array.
For each kind: the same kind comes back, on the same device; float64 values
agree with NumPy's to rtol and atol; and float32 in gives float32 out,
which agrees with NumPy's float64 to rtol32 and atol32. JAX is also
checked under jit. Boolean and integer arguments keep their dtype, and
boolean and integer results must match exactly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[..., Any]
|
The function under test; it returns an array or a tuple of them. |
required |
*args
|
Any
|
NumPy arrays to call it with; the floating ones are float64. |
()
|
rtol
|
float
|
Relative tolerance in float64. |
1e-12
|
atol
|
float
|
Absolute tolerance in float64, for results that cross zero. |
0.0
|
rtol32
|
float
|
Relative tolerance of float32 against float64. |
1e-05
|
atol32
|
float
|
Absolute tolerance of float32 against float64. |
0.0
|
kinds
|
Collection[str] | None
|
The names of the kinds to check; one that is not installed is left
out. |
None
|
labelled
|
bool
|
Also check DataArrays, for an elementwise function. Their dimensions are named from the right, so they broadcast as NumPy does. |
False
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If a check fails; the message names the kind, the dtype and the worst index. Also if JAX is checked without its 64-bit mode. |
ValueError
|
If |
Example
from pipekit_array.arrays import floating_inputs def root(x): ... xp, (x,) = floating_inputs(x) ... return xp.sqrt(x) assert_backends_agree(root, np.arange(3.0), kinds=["numpy", "strict"])
Source code in packages/pipekit-array/src/pipekit_array/testing/_arrays.py
assert_equivariant(fn, transform, x, *, transform_out=None, rtol=1e-13)
¶
Assert f(S x) = S' f(x): the function commutes with a transform.
The error max |f(S x) - S' f(x)| must not exceed rtol · max |f(x)|, the
maxima taken over every entry of every leaf. Translation in a periodic box is
S = S', a roll; a reflection of a vector field needs another S'. It runs on any
array library, and on pytrees (dicts, lists and tuples, and any pytree of JAX
once JAX is imported).
Pass a state that is random in every entry: a smooth or resting state hides a wrong stencil behind a small output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[Any], Any]
|
f, the function under test. |
required |
transform
|
Callable[[Any], Any]
|
S, the transform of the input. |
required |
x
|
Any
|
The point, an array or a pytree of them. |
required |
transform_out
|
Callable[[Any], Any] | None
|
S', the transform of the output; |
None
|
rtol
|
float
|
The tolerance, relative to max |f(x)|. |
1e-13
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the outputs have different structures or shapes, or
the relative error exceeds |
Example
import numpy as np def laplacian(x): ... return np.roll(x, 1) - 2.0 * x + np.roll(x, -1) x = np.random.default_rng(0).standard_normal(8) assert_equivariant(laplacian, lambda x: np.roll(x, 3), x)
Source code in packages/pipekit-array/src/pipekit_array/testing/_oracles.py
assert_finite_gradient(fn, x, *, where=None)
¶
Assert the derivative of every output by each chosen input is finite.
It checks that an undefined or invalid cell does not spoil the others: a
single where passes a test of the values and fails this one, because 0
times NaN is NaN in the backward pass. Skips without JAX.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[Any], Any]
|
The function under test, which JAX can trace. |
required |
x
|
Any
|
The point, a float64 array; its invalid cells may be NaN. |
required |
where
|
Any
|
A boolean mask of the inputs to check, |
None
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If JAX's 64-bit mode is off, or a derivative is not finite; the message gives the first (output, input) index. |
Example
assert_finite_gradient(lambda x: x**2, np.zeros(2)) # doctest: +SKIP
Source code in packages/pipekit-array/src/pipekit_array/testing/_transforms.py
assert_grad_matches_fd(fn, x, *, eps=1e-06, rtol=1e-06, indices=None)
¶
Assert jax.jacrev(fn) agrees with central finite differences at x.
For each entry k of the input, (f(x + ε eₖ) - f(x - ε eₖ)) / 2ε approximates column k of the Jacobian. The tolerance is relative to its largest entry, since an entry near zero carries the O(ε²) truncation error at full size, and never below the rounding of f divided by ε. Skips without JAX.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[Any], Any]
|
The function under test, which JAX can trace. |
required |
x
|
Any
|
The point: a float64 array, or a pytree of them. |
required |
eps
|
float
|
The step ε. |
1e-06
|
rtol
|
float
|
The relative tolerance. |
1e-06
|
indices
|
Sequence[int] | None
|
The entries of the flattened input to check, which keeps the
check affordable on a long state; |
None
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If JAX's 64-bit mode is off, if the Jacobians differ, or
if an entry of one is not finite; the message gives the (output,
input) index, the input counted within |
Example
assert_grad_matches_fd(lambda x: x**2, np.ones(2)) # doctest: +SKIP
Source code in packages/pipekit-array/src/pipekit_array/testing/_transforms.py
assert_idempotent(fn, x, *, rtol=1e-14)
¶
Assert B(B(x)) = B(x): the function is a projection.
The error max |B(B(x)) - B(x)| must not exceed rtol · max |B(x)|. A fill of
ghost cells, or a projection onto a constraint, must pass. It runs on any array
library, and on pytrees as assert_equivariant does.
Pass a state that is random in every entry, so that B has something to change.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[Any], Any]
|
B, the function under test. |
required |
x
|
Any
|
The point, an array or a pytree of them. |
required |
rtol
|
float
|
The tolerance, relative to max |B(x)|. |
1e-14
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the outputs have different structures or shapes, or
the relative error exceeds |
Example
import numpy as np x = np.random.default_rng(0).standard_normal(8) assert_idempotent(lambda x: np.clip(x, -0.5, 0.5), x)
Source code in packages/pipekit-array/src/pipekit_array/testing/_oracles.py
assert_invariant(functional, field, x, *, rtol=1e-14)
¶
Assert a field conserves a functional: dC/dt = ⟨∇C(x), f(x)⟩ = 0.
With g = ∇C(x) from jax.grad and f = field(x), the conservation ratio
rho = |∑ᵢ gᵢ fᵢ| / ∑ᵢ |gᵢ fᵢ|
lies in [0, 1], has no units, and is 0 in exact arithmetic for an invariant.
It must not exceed rtol; if every product is 0, the check passes. A sum
of n terms of mixed sign leaves an error near √n times the unit round-off, so
the default suits float64. A nonlinear invariant, such as an energy, needs
nothing more, since jax.grad gives g. Skips without JAX.
Pass a state that is random in every entry: a smooth or resting state hides a wrong stencil behind a small tendency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
functional
|
Callable[[Any], Any]
|
C, a scalar function of the state, which JAX can trace. |
required |
field
|
Callable[[Any], Any]
|
f, the tendency; it returns a tree of the state's shape. |
required |
x
|
Any
|
The state: a float64 array, or a pytree of them. |
required |
rtol
|
float
|
The tolerance of rho. |
1e-14
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If JAX's 64-bit mode is off, the field's size differs
from the state's, or rho exceeds |
Example
import jax.numpy as jnp def centred(x): # a centred difference in a periodic box ... return jnp.roll(x, -1) - jnp.roll(x, 1) x = np.random.default_rng(0).standard_normal(8) assert_invariant(jnp.sum, centred, x) # doctest: +SKIP
Source code in packages/pipekit-array/src/pipekit_array/testing/_transforms.py
assert_matches_oracle(actual, expected, *, rtol, atol=0.0, where=None)
¶
Assert |actual - expected| ≤ atol + rtol·|expected| wherever where holds.
NaNs match only NaNs at the same index. Boolean and integer arrays must match exactly, whatever the tolerances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
actual
|
Any
|
The values under test. |
required |
expected
|
Any
|
The reference values, the same shape. |
required |
rtol
|
float
|
The relative tolerance. |
required |
atol
|
float
|
The absolute tolerance, for references that cross zero. |
0.0
|
where
|
Any
|
A boolean mask; only |
None
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the shapes differ or any compared entry is out of tolerance. The message gives the number of failures, the worst index, both values there, the error and the tolerance. |
Example
import numpy as np assert_matches_oracle( ... np.array([1.0, np.nan]), np.array([1.0, np.nan]), rtol=1e-12 ... )
Source code in packages/pipekit-array/src/pipekit_array/testing/_oracles.py
assert_mean(sample, expected, *, n_sigma=4.0)
¶
Assert that a sample's mean is the expected one, within its sampling error.
The bound is n_sigma standard errors s/√N of the sample itself: at 4 a
right mean fails about once in 16,000 draws. The entries must be
independent, so average over anything that shares a draw first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample
|
Any
|
Independent draws, of any shape. |
required |
expected
|
float
|
The mean they should have. |
required |
n_sigma
|
float
|
The bound, in standard errors. |
4.0
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the mean is further away, if a draw is not finite, or if the sample is too small or has no spread to bound it by. |
Example
import numpy as np assert_mean(np.random.default_rng(0).normal(3.0, 1.0, 1000), 3.0)
Source code in packages/pipekit-array/src/pipekit_array/testing/_samples.py
assert_order(errors, expected, *, ratio=2.0, atol=0.2, at_least=True)
¶
Assert a scheme converges with order expected under refinement.
For a scheme of order p the error at spacing Δ is e(Δ) = C Δᵖ + O(Δᵖ⁺¹), so
the observed order between levels l and l + 1, refined by ratio, is
pₗ = log(eₗ / eₗ₊₁) / log(ratio).
It approaches p from the coarse end and is spoiled by round-off at the fine
end, so the check reads the last order and the caller chooses the levels.
With at_least an order above expected passes, as it does for a
scheme that is better than its nominal order on a smooth problem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
errors
|
Sequence[float]
|
The L errors, from the coarsest level to the finest. |
required |
expected
|
float
|
The order p of the scheme. |
required |
ratio
|
float
|
The refinement ratio r between neighbouring levels, above 1. |
2.0
|
atol
|
float
|
The tolerance of the last order. |
0.2
|
at_least
|
bool
|
Whether an order above |
True
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If there are fewer than two errors, an error is 0 or not finite (the message names its level), or the last order is out of tolerance; the message gives every order. |
Example
assert_order([1e-2, 2.5e-3, 6.25e-4], expected=2)
Source code in packages/pipekit-array/src/pipekit_array/testing/_oracles.py
assert_refuses_dataarrays(fn, *args)
¶
Assert that a DataArray in any argument raises BackendError.
A function over a grid or an axis takes plain arrays, so that labels are never lost silently. Skips without xarray.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[..., Any]
|
The function under test. |
required |
*args
|
Any
|
NumPy arrays to call it with; each is labelled in turn. |
()
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If a call is accepted; the message names the argument. |
Example
from pipekit_array.arrays import floating_inputs def plain(x): ... _, (x,) = floating_inputs(x) ... return x assert_refuses_dataarrays(plain, np.ones(2))
Source code in packages/pipekit-array/src/pipekit_array/testing/_arrays.py
assert_taylor(fn, x, *, min_slope=1.9, steps=_STEPS, seed=0)
¶
Assert the Taylor remainder of fn at x falls as ε², along one direction.
With v a random direction of unit norm and J(x) v from one jax.jvp, the
remainder
r(ε) = ‖f(x + ε v) - f(x) - ε J(x) v‖
is O(ε²) when the derivative is right, and O(ε) when it is wrong, so the
slope of log r against log ε between neighbouring steps is 2 or 1. Every
slope must be at least min_slope; a scheme that switches on a sign, such
as an upwind flux, needs about 1.7. If r is below the rounding of f at every
step, √D·u·(‖f(x)‖ + ε‖J(x) v‖) with u the unit round-off and D the size of
x, f is linear and the check passes.
Unlike assert_grad_matches_fd, it never forms the Jacobian: it costs one
evaluation of fn per step and one jax.jvp, whatever the size of x. Skips
without JAX.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[Any], Any]
|
The function under test, which JAX can trace; it returns a scalar or a pytree, whose flattened norm is taken. |
required |
x
|
Any
|
The point: a float64 array, or a pytree of them. |
required |
min_slope
|
float
|
The smallest slope that passes. |
1.9
|
steps
|
Sequence[float]
|
The steps ε, relative to the norm of x (or absolute at x = 0), from the largest down. |
_STEPS
|
seed
|
int
|
The seed of the direction v. |
0
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If JAX's 64-bit mode is off, or a slope is below
|
Example
import jax.numpy as jnp assert_taylor(lambda x: jnp.sin(x).sum(), np.ones(3)) # doctest: +SKIP
Source code in packages/pipekit-array/src/pipekit_array/testing/_transforms.py
assert_traces(fn, *args, rtol=1e-12)
¶
Assert jit(fn), vmap(fn) and an eager loop agree over a batch.
Every array of args has a leading batch axis of the same length B. The
reference is the eager loop over it, stacked; jit(fn) on each slice,
vmap(fn) and jit(vmap(fn)) on the batch must match it. Skips without
JAX.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[..., Any]
|
The function under test; it may take and return pytrees. |
required |
*args
|
Any
|
The batched arguments; a NumPy array goes to JAX. |
()
|
rtol
|
float
|
The relative tolerance. |
1e-12
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If JAX's 64-bit mode is off, the batch axes differ, or a variant disagrees; the message names the variant. |
Example
assert_traces(lambda x: 2.0 * x, np.arange(4.0)) # doctest: +SKIP
Source code in packages/pipekit-array/src/pipekit_array/testing/_transforms.py
assert_uniform(sample, low, high, *, level=0.001)
¶
Assert that independent draws are uniform on [low, high].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample
|
Any
|
Independent draws, of any shape. |
required |
low
|
float
|
The lower end of the interval. |
required |
high
|
float
|
Its upper end. |
required |
level
|
float
|
The probability that a uniform sample fails. |
0.001
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If a draw is outside the interval or not finite, if there are fewer than 30, or if the Kolmogorov-Smirnov statistic exceeds its critical value at N. |
Example
import numpy as np assert_uniform( ... np.random.default_rng(0).uniform(2.0, 5.0, 1000), 2.0, 5.0 ... )
Source code in packages/pipekit-array/src/pipekit_array/testing/_samples.py
assert_variance(sample, expected, *, n_sigma=4.0)
¶
Assert that Gaussian draws have the expected variance.
The variance of N Gaussian draws has a relative standard error (2/N)^½, so
the bound on s²/σ² - 1 is n_sigma of it. A bias of the scheme counts as
an error, so the step must be short enough for it to be smaller.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample
|
Any
|
Independent Gaussian draws, of any shape. |
required |
expected
|
float
|
The variance they should have. |
required |
n_sigma
|
float
|
The bound, in standard errors. |
4.0
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the variance is further away, or if the sample is too small or holds a draw that is not finite. |
Example
import numpy as np assert_variance(np.random.default_rng(0).normal(0.0, 2.0, 1000), 4.0)
Source code in packages/pipekit-array/src/pipekit_array/testing/_samples.py
check_adapter(adapter, make_carrier, *, rtol=1e-12, seed=0)
¶
Assert that adapter and its fast paths agree with the reference adapter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adapter
|
NamedArrayAdapter
|
The adapter under test; it must be the one registered for
the carriers |
required |
make_carrier
|
MakeCarrier
|
|
required |
rtol
|
float
|
Tolerance for reductions; selections compare exactly. |
1e-12
|
seed
|
int
|
For the random data. |
0
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
On the first mismatch, naming the function and the carrier type. |
Source code in packages/pipekit-array/src/pipekit_array/testing/_carriers.py
check_kernel_op(op, calls, *, rtol=1e-06)
¶
Assert that one KernelOp agrees across carrier families (PK-K1, PK-K4).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
op
|
KernelOp
|
The operator under test. |
required |
calls
|
Sequence[Any]
|
The inputs of each call, one entry per carrier family: a carrier for a one-input kernel, or a tuple of inputs. The first entry is the reference. |
required |
rtol
|
float
|
Relative tolerance on the outputs' values. |
1e-06
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
Outputs differ in dims or values, or a one-input
kernel's output dims differ from |
Source code in packages/pipekit-array/src/pipekit_array/testing/_carriers.py
equivariance_error(fn, transform, x, *, transform_out=None)
¶
The relative error max |f(S x) - S' f(x)| / max |f(x)|.
The measurement behind assert_equivariant, over every entry of every leaf.
If f(x) is 0 everywhere, the error is absolute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[Any], Any]
|
f, the function under test. |
required |
transform
|
Callable[[Any], Any]
|
S, the transform of the input. |
required |
x
|
Any
|
The point, an array or a pytree of them. |
required |
transform_out
|
Callable[[Any], Any] | None
|
S', the transform of the output; |
None
|
Returns:
| Type | Description |
|---|---|
float
|
The relative error, 0 for an equivariant f; NaN if a value is NaN. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the outputs have different structures or shapes. |
Example
import numpy as np x = np.array([1.0, 2.0, 4.0]) equivariance_error(lambda x: x**2, lambda x: np.roll(x, 1), x) 0.0
Source code in packages/pipekit-array/src/pipekit_array/testing/_oracles.py
grad_fd_error(fn, x, *, eps=1e-06, indices=None)
¶
The relative error max |J - J_fd| / max |J_fd| of JAX's Jacobian at x.
The measurement behind assert_grad_matches_fd: J from jax.jacrev (or
jax.jvp for the columns in indices) and J_fd from central finite
differences with step ε. It is about ε² for a smooth function, and near 1 for
a gradient that is cut. If J_fd is 0 everywhere, the error is absolute.
Skips without JAX.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[Any], Any]
|
The function under test, which JAX can trace. |
required |
x
|
Any
|
The point: a float64 array, or a pytree of them. |
required |
eps
|
float
|
The step ε. |
1e-06
|
indices
|
Sequence[int] | None
|
The entries of the flattened input to check; |
None
|
Returns:
| Type | Description |
|---|---|
float
|
The relative error; NaN or infinite if a derivative is not finite. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If JAX's 64-bit mode is off. |
Example
grad_fd_error(lambda x: x**2, np.ones(2)) < 1e-8 # doctest: +SKIP True
Source code in packages/pipekit-array/src/pipekit_array/testing/_transforms.py
idempotence_error(fn, x)
¶
The relative error max |B(B(x)) - B(x)| / max |B(x)|.
The measurement behind assert_idempotent, over every entry of every leaf.
If B(x) is 0 everywhere, the error is absolute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[Any], Any]
|
B, the function under test. |
required |
x
|
Any
|
The point, an array or a pytree of them. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The relative error, 0 for a projection; NaN if a value is NaN. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the outputs have different structures or shapes. |
Example
import numpy as np idempotence_error(lambda x: 0.5 * x, np.array([2.0, -4.0])) 0.5
Source code in packages/pipekit-array/src/pipekit_array/testing/_oracles.py
invariant_ratio(functional, field, x)
¶
The conservation ratio rho = |∑ᵢ gᵢ fᵢ| / ∑ᵢ |gᵢ fᵢ|, g = ∇C(x), f = field(x).
The measurement behind assert_invariant. It lies in [0, 1], has no units,
and is 0 in exact arithmetic when the field conserves the functional; it is
0 when every product is 0. Skips without JAX.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
functional
|
Callable[[Any], Any]
|
C, a scalar function of the state, which JAX can trace. |
required |
field
|
Callable[[Any], Any]
|
f, the tendency; it returns a tree of the state's shape. |
required |
x
|
Any
|
The state: a float64 array, or a pytree of them. |
required |
Returns:
| Type | Description |
|---|---|
float
|
rho; NaN if a product is not finite. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If JAX's 64-bit mode is off, or the field's size differs from the state's. |
Example
import jax.numpy as jnp x = np.array([1.0, 2.0]) invariant_ratio(jnp.sum, jnp.ones_like, x) # doctest: +SKIP 1.0
Source code in packages/pipekit-array/src/pipekit_array/testing/_transforms.py
ks_critical_value(size, level)
¶
The large-sample critical value of the Kolmogorov-Smirnov statistic.
c = √(-½ ln(level / 2)) / √N, which is 1.95 / √N at a level of 10⁻³.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
int
|
N, how many draws. |
required |
level
|
float
|
The probability that a sample of the law exceeds it. |
required |
Returns:
| Type | Description |
|---|---|
float
|
c. |
Example
round(ks_critical_value(100, 1e-3), 3) 0.195
Source code in packages/pipekit-array/src/pipekit_array/testing/_samples.py
ks_statistic(sample, low, high)
¶
The Kolmogorov-Smirnov distance of a sample from the uniform law.
D = sup_x |F_N(x) - (x - low) / (high - low)|.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample
|
Any
|
Independent draws, of any shape. |
required |
low
|
float
|
The lower end of the interval. |
required |
high
|
float
|
Its upper end. |
required |
Returns:
| Type | Description |
|---|---|
float
|
D. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If there are fewer than 30 draws, or one is not finite. |
Example
import numpy as np round(ks_statistic((np.arange(50) + 0.5) / 50, 0.0, 1.0), 12) 0.01
Source code in packages/pipekit-array/src/pipekit_array/testing/_samples.py
observed_order(errors, *, ratio=2.0)
¶
The observed orders pₗ = log(eₗ / eₗ₊₁) / log(ratio) of a refinement.
The measurement behind assert_order: for L errors at spacings Δ, Δ/r, …,
the L - 1 orders between neighbouring levels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
errors
|
Sequence[float]
|
The L errors, from the coarsest level to the finest. |
required |
ratio
|
float
|
The refinement ratio r between neighbouring levels, above 1. |
2.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The L - 1 observed orders. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If there are fewer than two errors, or an error is 0 or not finite; the message names its level. |
Example
observed_order([1e-2, 2.5e-3, 6.25e-4]) array([2., 2.])
Source code in packages/pipekit-array/src/pipekit_array/testing/_oracles.py
oracle_error(actual, expected)
¶
The relative error max |actual - expected| / max |expected|.
The measurement behind assert_matches_oracle, which compares each entry
with its own tolerance; this gives one number for a table or a run report.
NaNs match only NaNs at the same index, and an infinity only itself; any
other NaN or infinity makes the error infinite. If max |expected| is 0, or
no entry of it is finite, the error is absolute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
actual
|
Any
|
The values under test. |
required |
expected
|
Any
|
The reference values, the same shape. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The relative error, 0 when the two agree exactly. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the shapes differ. |
Example
import numpy as np oracle_error(np.array([1.0, 2.2]), np.array([1.0, 2.0])) 0.10000000000000009
Source code in packages/pipekit-array/src/pipekit_array/testing/_oracles.py
taylor_slopes(fn, x, *, steps=_STEPS, seed=0)
¶
The slopes of log r(ε) against log ε between neighbouring steps.
The measurement behind assert_taylor, with the remainder
r(ε) = ‖f(x + ε v) - f(x) - ε J(x) v‖
along a random direction v of unit norm. The slope between steps i and i + 1 is log(rᵢ / rᵢ₊₁) / log(εᵢ / εᵢ₊₁): 2 for a right derivative, 1 for a wrong one, and a fall at the small end shows round-off. Skips without JAX.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[Any], Any]
|
The function under test, which JAX can trace; it returns a scalar or a pytree, whose flattened norm is taken. |
required |
x
|
Any
|
The point: a float64 array, or a pytree of them. |
required |
steps
|
Sequence[float]
|
The E steps ε, relative to the norm of x (or absolute at x = 0). |
_STEPS
|
seed
|
int
|
The seed of the direction v. |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The E - 1 slopes; NaN where a remainder is 0, as for a linear fn. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If JAX's 64-bit mode is off. |
Example
import jax.numpy as jnp taylor_slopes(lambda x: jnp.sum(x**2), np.ones(3)) # doctest: +SKIP array([2., 2., 2.])
Source code in packages/pipekit-array/src/pipekit_array/testing/_transforms.py
values_of(x)
¶
A named carrier's data on the host, computing it if lazy.