ML Foundations
Use coordinate spacing in NumPy gradients
Distinguish changes per array index from rates per coordinate on an irregular grid.

Evidence and testing
Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.
A sample index is not a measurement coordinate
Measurements may be taken at unequal positions or times. NumPy gradient assumes unit spacing when no spacing argument is supplied. Its default result therefore expresses changes with respect to the index positions, which can differ from rates per actual coordinate. [1]
For a one-dimensional series, pass a coordinate array of the same length to calculate the gradient with respect to those positions. NumPy uses central differences for interior points and one-sided differences at the boundaries. [1]
References: [1]
Compare points and intervals
Run python examples/numpy_gradient_irregular_spacing.py. Coordinates zero, one, three and six are unevenly spaced. Values follow the exact line y = 2x + 1. With default spacing the reported values differ, while passing the coordinates gives two at each point in this fixture. [1]
Dividing adjacent value differences by adjacent coordinate differences also gives two here. Those are interval slopes: there are three for four sample points. Gradient returns four point-aligned values. The example checks both results for this linear fixture. [1, 2]
Executed with Python 3.12.14; stdout and checksum recorded in private evidence.
import numpy as np
coordinates = np.array([0.0, 1.0, 3.0, 6.0])
values = 2.0 * coordinates + 1.0
per_index = np.gradient(values)
per_coordinate = np.gradient(values, coordinates)
interval_slopes = np.diff(values) / np.diff(coordinates)
print('per index:', per_index.tolist())
print('per coordinate:', per_coordinate.tolist())
print('interval slopes:', interval_slopes.tolist())
print('point and interval counts:', len(per_coordinate), len(interval_slopes))
assert np.allclose(per_coordinate, 2.0)
assert np.allclose(interval_slopes, 2.0)
Recorded output
per index: [2.0, 3.0, 5.0, 6.0] per coordinate: [2.0, 2.0, 2.0, 2.0] interval slopes: [2.0, 2.0, 2.0] point and interval counts: 4 3
Validate coordinates and interpret edges
Coordinates should describe the corresponding measurements in order and use the intended units. Before taking interval ratios, check for duplicate coordinates to avoid zero denominators. A gradient is a numerical approximation and noisy or sparse data can affect its interpretation. [1, 2]
This example uses a strictly increasing, finite, one-dimensional coordinate array and a linear function. Nonlinear functions, repeated positions, multidimensional axes and alternative edge rules need separate checks. It makes no accuracy or performance claim outside this fixture. [1]