AtsushiSakai/PythonRobotics · error · ValueError
x coordinates must be sorted in ascending order
Error message
x coordinates must be sorted in ascending order
What it means
CubicSpline's constructor computes np.diff(x) and rejects any negative difference, i.e. x points not sorted ascending. Spline math requires monotonically increasing knots.
Source
Thrown at PathPlanning/CubicSpline/cubic_spline_planner.py:50
>>> y = [1.7, -6, 5, 6.5, 0.0]
>>> sp = CubicSpline1D(x, y)
>>> xi = np.linspace(0.0, 5.0)
>>> yi = [sp.calc_position(x) for x in xi]
>>> plt.plot(x, y, "xb", label="Data points")
>>> plt.plot(xi, yi , "r", label="Cubic spline interpolation")
>>> plt.grid(True)
>>> plt.legend()
>>> plt.show()
.. image:: cubic_spline_1d.png
"""
def __init__(self, x, y):
h = np.diff(x)
if np.any(h < 0):
raise ValueError("x coordinates must be sorted in ascending order")
self.a, self.b, self.c, self.d = [], [], [], []
self.x = x
self.y = y
self.nx = len(x) # dimension of x
# calc coefficient a
self.a = [iy for iy in y]
# calc coefficient c
A = self.__calc_A(h)
B = self.__calc_B(h, self.a)
self.c = np.linalg.solve(A, B)
# calc spline coefficient b and d
for i in range(self.nx - 1):
d = (self.c[i + 1] - self.c[i]) / (3.0 * h[i])
b = 1.0 / h[i] * (self.a[i + 1] - self.a[i]) \View on GitHub (pinned to 1fe4fb980f)
Solutions
- Sort points by x before construction: order = np.argsort(x); CubicSpline(x[order], y[order]).
- Fix the data source to emit monotonically increasing x.
- Validate np.all(np.diff(x) > 0) before calling.
Example fix
# before sp = CubicSpline(x, y) # x unsorted # after order = np.argsort(x) sp = CubicSpline(x[order], y[order])
Defensive patterns
Strategy: validation
Validate before calling
import numpy as np assert np.all(np.diff(x) > 0), 'x must be strictly ascending'
Type guard
def sorted_ascending(x) -> bool:
import numpy as np
return bool(np.all(np.diff(x) > 0)) Prevention
- Sort waypoints by x (keeping y aligned) before spline fitting.
- Validate np.diff monotonicity in data-loading tests.
When it happens
Trigger: Constructing CubicSpline(x, y) with x out of order, e.g. [0, 2, 1, 3], or with duplicate/unsorted waypoint data from a file.
Common situations: Waypoints collected from GPS or user input in arbitrary order, or data shuffled during preprocessing before spline fitting.
Related errors
AI-assisted analysis of AtsushiSakai/PythonRobotics@1fe4fb980f (2026-08-28).
Data as JSON: /api/errors/3d2e1c3a1b090b13.
Report an issue: GitHub.