From e9840fcb695c031317146cac433b8a9503d841e6 Mon Sep 17 00:00:00 2001 From: cwhanse Date: Sun, 29 Nov 2026 16:08:29 -0700 Subject: [PATCH 01/13] add numba version of schumaker and tests --- pvlib/ivtools/utils.py | 317 +++++++++++++++++++++++++++++++++++- tests/ivtools/test_utils.py | 69 ++++++-- 2 files changed, 362 insertions(+), 24 deletions(-) diff --git a/pvlib/ivtools/utils.py b/pvlib/ivtools/utils.py index 0d0ef1382a..44f285787b 100644 --- a/pvlib/ivtools/utils.py +++ b/pvlib/ivtools/utils.py @@ -8,11 +8,25 @@ import pandas as pd from numpy.polynomial.polynomial import Polynomial as Poly +try: + from numba import njit, prange + NUMBA_AVAILABLE = True +except ImportError: + NUMBA_AVAILABLE = False + prange = range + + # Allow the module to load and run without Numba (without JIT compilation). + def njit(*args, **kwargs): + def decorator(func): + return func + return decorator + # A small number used to decide when a slope is equivalent to zero -EPS_slope = np.finfo('float').eps**(1/3) +_EPS_SLOPE = np.finfo('float').eps**(1/3) # A small number used to decide when a slope is equivalent to zero -EPS_val = np.finfo('float').eps +_EPS_VAL = np.finfo('float').eps +_RTOL_ISCLOSE = 1e-5 def _numdiff(x, f): @@ -178,7 +192,128 @@ def rectify_iv_curve(voltage, current, decimals=None): return tmp[0, ], tmp[1, ] -def _schumaker_qspline(x, y): +def _schumaker_qspline(x, y, use_numba=False): + """Fit shape-preserving quadratic spline(s) to one or more curves. + + A curve is defined by corresponding x and y samples. For 2D inputs, + a separate spline is fitted along each row. + + Parameters + ---------- + x : array_like, shape (K,) or (N, K) + Independent sample points. Must be strictly increasing. + For 1D ``y``, provide a 1D ``x``. + For 2D ``y``, ``x`` may be a shared 1D grid of length K or a + 2D array with the same shape as ``y``. + y : array_like, shape (K,) or (N, K) + Dependent sample values. A 1D array defines one curve. A 2D array + defines N curves, one per row. + use_numba : bool, default False + If True, dispatch to the Numba implementation. If Numba is not + installed, raise ImportError. If False, use the NumPy + implementation. + + Returns + ------- + t : ndarray + Knot locations. For 1D input, shape is ``(M,)``. For 2D input, + shape is ``(B, 2*K - 1)`` and rows are padded with NaN. + c : ndarray + Quadratic coefficients for intervals between successive knots. + The polynomial for interval i is + ``c[i, 0] * (z - t[i])**2 + c[i, 1] * (z - t[i]) + c[i, 2]``. + For 1D input, shape is ``(M - 1, 3)``. For 2D input, shape is + ``(B, 2*K - 2, 3)`` and rows are padded with NaN. + yhat : ndarray + Values at the knots. For 1D input, shape is ``(M,)``. For 2D + input, shape is ``(B, 2*K - 1)`` and rows are padded with NaN. + kflag : ndarray + Boolean flags identifying inserted knots. For 1D input, shape is + ``(M,)``. For 2D input, shape is ``(B, 2*K - 1)``. Padding is + False; use ``nknots`` to distinguish padding from valid entries. + nknots : int or ndarray of int + Number of valid knots. For 1D input, this is an integer. For 2D + input, this is an integer array of shape ``(B,)``. For row b, + the valid outputs are ``t[b, :nknots[b]]``, + ``yhat[b, :nknots[b]]``, ``kflag[b, :nknots[b]]``, and + ``c[b, :nknots[b] - 1]``. + + Notes + ----- + The algorithm may insert at most one knot between each pair of input + points. The 2D outputs use fixed-size padded arrays because the number + of inserted knots may differ between rows. + """ + x = np.asarray(x, dtype=np.float64) + y = np.asarray(y, dtype=np.float64) + + if y.ndim not in (1, 2): + raise ValueError("y must be a 1D or 2D array") + + if y.shape[-1] < 3: + raise ValueError("Each curve must contain at least 3 points") + + if y.ndim == 1: + if x.ndim != 1 or x.shape != y.shape: + raise ValueError("For 1D y, x must be 1D and have the same shape") + if np.any(np.diff(x) <= 0.0): + raise ValueError("x must be strictly increasing") + + if use_numba: + t, c, yhat, kflag, nknots = _schumaker_qspline_numba(x, y) + else: + t, c, yhat, kflag, nknots = _schumaker_qspline_numpy(x, y) + kflag = np.asarray(kflag, dtype=bool) + + return t, c, yhat, kflag, int(nknots) + + # 2D y: each row is a separate curve. + if x.ndim == 1: + if x.shape[0] != y.shape[1]: + raise ValueError("1D x must have one value per column of y") + x_2d = np.broadcast_to(x, y.shape) + elif x.ndim == 2: + if x.shape != y.shape: + raise ValueError("2D x and y must have the same shape") + x_2d = x + else: + raise ValueError("x must be a 1D or 2D array") + + if np.any(np.diff(x_2d, axis=1) <= 0.0): + raise ValueError("Each row of x must be strictly increasing") + + if use_numba: + return _schumaker_qspline_numba(x_2d, y) + + return _schumaker_qspline_numpy_batch(x_2d, y) + + +def _schumaker_qspline_numpy_batch(x, y): + """Apply the 1D NumPy implementation row by row and pad its results.""" + batch, n = y.shape + max_knots = 2 * n - 1 + + t_out = np.full((batch, max_knots), np.nan) + c_out = np.full((batch, max_knots - 1, 3), np.nan) + yhat_out = np.full((batch, max_knots), np.nan) + kflag_out = np.zeros((batch, max_knots), dtype=bool) + nknots = np.empty(batch, dtype=np.int64) + + for row in range(batch): + t, c, yhat, kflag, count = _schumaker_qspline_numpy( + x[row], y[row] + ) + count = int(count) + nknots[row] = count + t_out[row, :count] = t + c_out[row, :count - 1] = c + yhat_out[row, :count] = yhat + kflag_out[row, :count] = np.asarray(kflag, dtype=bool) + + return t_out, c_out, yhat_out, kflag_out, nknots + + +def _schumaker_qspline_numpy(x, y): """ Fit a quadratic spline which preserves monotonicity and convexity in the data. @@ -209,6 +344,9 @@ def _schumaker_qspline(x, y): kflag : array a vector of len(t) of logicals, which are set to true for elements of t that are knots inserted by the algorithm. + k : int + total number of knots, equal to len(t). Provided for compatibility + with numba version. Notes ----- @@ -266,7 +404,7 @@ def _schumaker_qspline(x, y): # [2], Algorithm 4.1 first 'if' condition of step 5 defines intervals # which won't get internal knots tests = s[:-1] + s[1:] - u = np.isclose(tests, 2.0 * delta, atol=EPS_slope) + u = np.isclose(tests, 2.0 * delta, atol=_EPS_SLOPE) # u = true for an interval which will not get an internal knot k = n + sum(~u) # total number of knots = original data + inserted knots @@ -318,8 +456,8 @@ def _schumaker_qspline(x, y): # Since the above two lines can lead to numerical errors, aa and b # are rounded to 0.0 is their absolute value is small enough. - aa[np.isclose(aa, 0., atol=EPS_val)] = 0. - b[np.isclose(b, 0., atol=EPS_val)] = 0. + aa[np.isclose(aa, 0., atol=_EPS_VAL)] = 0. + b[np.isclose(b, 0., atol=_EPS_VAL)] = 0. sbar = np.zeros(k) eta = np.zeros(k) @@ -423,7 +561,172 @@ def _schumaker_qspline(x, y): c = tmp2[0:(outn - 1), 1:4] yhat = tmp2[:, 4] kflag = tmp2[:, 5] - return t, c, yhat, kflag + return t, c, yhat, kflag, len(t) + + +@njit(parallel=True, cache=True) +def _schumaker_qspline_numba_kernel(x, y): + batch, n = x.shape + max_knots = 2 * n - 1 + + t_out = np.full((batch, max_knots), np.nan) + c_out = np.full((batch, max_knots - 1, 3), np.nan) + yhat_out = np.full((batch, max_knots), np.nan) + kflag_out = np.zeros((batch, max_knots), dtype=np.bool_) + nknots = np.empty(batch, dtype=np.int64) + + for row in prange(batch): + delta = np.empty(n - 1, dtype=np.float64) + for i in range(n - 1): + delta[i] = ( + (y[row, i + 1] - y[row, i]) + / (x[row, i + 1] - x[row, i]) + ) + + # Derivative estimates at the data points. + s = np.zeros(n, dtype=np.float64) + + for i in range(1, n - 1): + left = delta[i - 1] + right = delta[i] + product = left * right + if product > 0.0: + s[i] = product / (0.5 * left + 0.5 * right) + + left_end = 2.0 * delta[0] - s[1] + if delta[0] * left_end > 0.0: + s[0] = left_end + + right_end = 2.0 * delta[n - 2] - s[n - 2] + if delta[n - 2] * right_end > 0.0: + s[n - 1] = right_end + + knot_idx = 0 + + for i in range(n - 1): + x0 = x[row, i] + x1 = x[row, i + 1] + y0 = y[row, i] + h = x1 - x0 + d = delta[i] + + # Equivalent to np.isclose(s[i] + s[i + 1], 2*d, + # atol=_EPS_SLOPE) with default rtol. + tests = s[i] + s[i + 1] + no_internal_knot = ( + abs(tests - 2.0 * d) + <= _EPS_SLOPE + _RTOL_ISCLOSE * abs(2.0 * d) + ) + + # Every interval starts at an original knot. + t_out[row, knot_idx] = x0 + yhat_out[row, knot_idx] = y0 + kflag_out[row, knot_idx] = False + + if no_internal_knot: + c_out[row, knot_idx, 0] = ( + 0.5 * (s[i + 1] - s[i]) / h + ) + c_out[row, knot_idx, 1] = s[i] + c_out[row, knot_idx, 2] = y0 + knot_idx += 1 + continue + + aa = s[i] - d + b = s[i + 1] - d + + if abs(aa) <= _EPS_VAL: + aa = 0.0 + if abs(b) <= _EPS_VAL: + b = 0.0 + + slope_diff = s[i + 1] - s[i] + + if aa * b >= 0.0: + xi = 0.5 * (x0 + x1) + elif abs(aa) > abs(b): + xi = x1 + aa * h / slope_diff + else: + xi = x0 + b * h / slope_diff + + dx = xi - x0 + sbar = ( + (2.0 * d - s[i + 1]) + + (s[i + 1] - s[i]) * dx / h + ) + eta = (sbar - s[i]) / dx + + # Coefficients for the interval from x0 to the inserted knot. + c_out[row, knot_idx, 0] = 0.5 * eta + c_out[row, knot_idx, 1] = s[i] + c_out[row, knot_idx, 2] = y0 + + # The inserted knot and its y-value. + inserted_idx = knot_idx + 1 + y_at_xi = y0 + s[i] * dx + 0.5 * eta * dx * dx + + t_out[row, inserted_idx] = xi + yhat_out[row, inserted_idx] = y_at_xi + kflag_out[row, inserted_idx] = True + + # Coefficients for the interval from the inserted knot to x1. + c_out[row, inserted_idx, 0] = ( + 0.5 * (s[i + 1] - sbar) / h + ) + c_out[row, inserted_idx, 1] = sbar + c_out[row, inserted_idx, 2] = y_at_xi + + knot_idx += 2 + + # Final original input knot. + t_out[row, knot_idx] = x[row, n - 1] + yhat_out[row, knot_idx] = y[row, n - 1] + kflag_out[row, knot_idx] = False + nknots[row] = knot_idx + 1 + + return t_out, c_out, yhat_out, kflag_out, nknots + + +def _schumaker_qspline_numba(x, y): + """Run the Numba kernel and return outputs matching the wrapper API.""" + if not NUMBA_AVAILABLE: + raise ImportError( + "use_numba=True requires Numba to be installed" + ) + + x = np.asarray(x, dtype=np.float64) + y = np.asarray(y, dtype=np.float64) + + # The kernel processes batches. Promote 1D inputs to a one-row batch, + # then remove that batch dimension and the padding for the 1D result. + was_1d = x.ndim == 1 and y.ndim == 1 + if was_1d: + x = x[None, :] + y = y[None, :] + + x = np.ascontiguousarray(x, dtype=np.float64) + y = np.ascontiguousarray(y, dtype=np.float64) + + if x.ndim != 2 or y.ndim != 2 or x.shape != y.shape: + raise ValueError("Numba inputs must be matching 2D arrays") + if x.shape[1] < 3: + raise ValueError("Each row must contain at least 3 points") + if np.any(np.diff(x, axis=1) <= 0.0): + raise ValueError("Each row of x must be strictly increasing") + + t, c, yhat, kflag, nknots = _schumaker_qspline_numba_kernel(x, y) + + if was_1d: + count = int(nknots[0]) + return ( + t[0, :count], + c[0, :count - 1], + yhat[0, :count], + kflag[0, :count], + count, + ) + + return t, c, yhat, kflag, nknots def astm_e1036(v, i, imax_limits=(0.75, 1.15), vmax_limits=(0.75, 1.15), diff --git a/tests/ivtools/test_utils.py b/tests/ivtools/test_utils.py index ae87d9c496..2f23ad9505 100644 --- a/tests/ivtools/test_utils.py +++ b/tests/ivtools/test_utils.py @@ -2,7 +2,7 @@ import pandas as pd import pytest from pvlib.ivtools.utils import _numdiff, rectify_iv_curve, astm_e1036 -from pvlib.ivtools.utils import _schumaker_qspline +from pvlib.ivtools.utils import _schumaker_qspline, _schumaker_qspline_numpy from pvlib.ivtools.utils import _lambertw_pvlib from tests.conftest import TESTS_DATA_DIR @@ -42,21 +42,8 @@ def test_rectify_iv_curve(ivcurve): np.testing.assert_allclose(i, iexp, atol=.0001) +# run tests generated by original Matlab implementation @pytest.mark.parametrize('x,y,expected', [ - (np.array([0., 1., 2., 3., 4., 1., 2., 3., 4., 5.]), - np.array([2., 1., 0., 1., 2., 3., 2., 1., 2., 3.]), - (np.array([[0., -1., 2.], [-0.5, -1., 1.], [-0.75, -0.5, 3.], - [0.75, -1.5, 0.375], [0.125, -1.25, 2.5625], [1.5, 0., 0.], - [-0.5, -1., 2.], [-0.25, 1.5, 0.375], [0.75, -1.5, 1.375], - [0.5, 1., 1.], [1.5, 0., 1.], [0.0278, -0.3333, 2.1667], - [-0.75, 1.5, 1.625], [-0.25, 1.5, 1.375], [0.1667, 0., 2.], - [0., 1., 2.]]), - np.array([0., 1., 1., 1.5, 1.5, 2., 2., 2.5, 2.5, 3., 3., 3., 3.5, 3.5, - 4., 4., 5.]), - np.array([2., 1., 3., 0.375, 2.5625, 0., 2., 0.375, 1.375, 1., 1., - 2.1667, 1.625, 1.375, 2., 2., 3.]), - np.array([0., 0., 0., 1., 1., 0., 0., 1., 1., 0., 0., 1., 1., 1., 0., 0., - 0.]))), (np.array([1., 2., 3., 4., 5.]), np.array([-2., -1., 0., 1., 2.]), (np.array([[0., 1., -2.], [0., 1., -1.], [0., 1., 0.], [0., 1., 1.]]), @@ -71,12 +58,60 @@ def test_rectify_iv_curve(ivcurve): np.array([-.5, -.1, -.05, 0., .1, .2, .3]), np.array([-5., -1., -.297, .2, .3485, .5, 2.]), np.array([0., 0., 1., 0., 1., 0., 0.])))]) -def test__schmumaker_qspline(x, y, expected): - [t, c, yhat, kflag] = _schumaker_qspline(x, y) +def test__schmumaker_qspline_numpy(x, y, expected): + t, c, yhat, kflag, nknots = _schumaker_qspline_numpy(x, y) np.testing.assert_allclose(c, expected[0], atol=0.0001) np.testing.assert_allclose(t, expected[1], atol=0.0001) np.testing.assert_allclose(yhat, expected[2], atol=0.0001) np.testing.assert_allclose(kflag, expected[3], atol=0.0001) + assert nknots==len(t) + + +@pytest.mark.parametrize("seed", [0, 1, 42]) +def test__schmumaker_qspline_numba_matches_numpy(seed): + rng = np.random.default_rng(seed) + + batch = 32 + n = 100 + + # Give each row a strictly increasing x grid, with slight row-to-row + # variation, and varied y values that exercise different spline shapes. + x = np.cumsum(rng.uniform(0.05, 0.15, size=(batch, n)), axis=1) + y = rng.normal(size=(batch, n)).cumsum(axis=1) + + # Include smooth curves as well as the random curves. + rows = np.arange(batch) + y[::4] = ( + np.sin(x[::4] * rng.uniform(0.5, 2.0, size=(len(rows[::4]), 1))) + + 0.03 * x[::4] + ) + + t_batch, c_batch, yhat, kflag, nknots = _schumaker_qspline(x, y, use_numba=True) + + # iterate through rows of x, y and use numpy + for row in range(batch): + t_ref, c_ref, yhat_ref, kflag_ref, nknots_ref = _schumaker_qspline(x[row], y[row]) + + count = nknots[row] + np.testing.assert_array_equal(t_batch[row, :count].shape, t_ref.shape) + np.testing.assert_array_equal(c_batch[row, :count - 1].shape, c_ref.shape) + + np.testing.assert_allclose( + t_batch[row, :count], + t_ref, + rtol=1e-11, + atol=1e-12, + ) + np.testing.assert_allclose( + c_batch[row, :count - 1], + c_ref, + rtol=1e-11, + atol=1e-12, + ) + + # Check that the unused, padded output entries are NaN. + assert np.isnan(t_batch[row, count:]).all() + assert np.isnan(c_batch[row, count - 1:]).all() @pytest.fixture From a556b26046b4d2db15a086c5e130fda4f505f89b Mon Sep 17 00:00:00 2001 From: Cliff Hansen Date: Sun, 29 Nov 2026 16:18:09 -0700 Subject: [PATCH 02/13] keep old return behavior --- pvlib/ivtools/utils.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pvlib/ivtools/utils.py b/pvlib/ivtools/utils.py index 44f285787b..099d1e59fe 100644 --- a/pvlib/ivtools/utils.py +++ b/pvlib/ivtools/utils.py @@ -285,7 +285,9 @@ def _schumaker_qspline(x, y, use_numba=False): if use_numba: return _schumaker_qspline_numba(x_2d, y) - return _schumaker_qspline_numpy_batch(x_2d, y) + results = _schumaker_qspline_numpy_batch(x_2d, y) + # keep old behavior, drop nknots + return results[:4] def _schumaker_qspline_numpy_batch(x, y): From 5c0de57f99f3a9a86c6c612d03a5e4cc541f60b2 Mon Sep 17 00:00:00 2001 From: Cliff Hansen Date: Sun, 29 Nov 2026 16:19:56 -0700 Subject: [PATCH 03/13] formatting --- tests/ivtools/test_utils.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/ivtools/test_utils.py b/tests/ivtools/test_utils.py index 2f23ad9505..67ed565ed6 100644 --- a/tests/ivtools/test_utils.py +++ b/tests/ivtools/test_utils.py @@ -64,7 +64,7 @@ def test__schmumaker_qspline_numpy(x, y, expected): np.testing.assert_allclose(t, expected[1], atol=0.0001) np.testing.assert_allclose(yhat, expected[2], atol=0.0001) np.testing.assert_allclose(kflag, expected[3], atol=0.0001) - assert nknots==len(t) + assert nknots == len(t) @pytest.mark.parametrize("seed", [0, 1, 42]) @@ -86,15 +86,18 @@ def test__schmumaker_qspline_numba_matches_numpy(seed): + 0.03 * x[::4] ) - t_batch, c_batch, yhat, kflag, nknots = _schumaker_qspline(x, y, use_numba=True) + t_batch, c_batch, yhat, kflag, nknots = _schumaker_qspline( + x, y, use_numba=True) # iterate through rows of x, y and use numpy for row in range(batch): - t_ref, c_ref, yhat_ref, kflag_ref, nknots_ref = _schumaker_qspline(x[row], y[row]) + t_ref, c_ref, yhat_ref, kflag_ref, nknots_ref = _schumaker_qspline( + x[row], y[row]) count = nknots[row] np.testing.assert_array_equal(t_batch[row, :count].shape, t_ref.shape) - np.testing.assert_array_equal(c_batch[row, :count - 1].shape, c_ref.shape) + np.testing.assert_array_equal(c_batch[row, :count - 1].shape, + c_ref.shape) np.testing.assert_allclose( t_batch[row, :count], From 49726dcfe7c073914ca96da46f08a18ab2c11ae3 Mon Sep 17 00:00:00 2001 From: Cliff Hansen Date: Sun, 29 Nov 2026 17:05:01 -0700 Subject: [PATCH 04/13] decorator --- tests/ivtools/test_utils.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/ivtools/test_utils.py b/tests/ivtools/test_utils.py index 67ed565ed6..d10d93ab60 100644 --- a/tests/ivtools/test_utils.py +++ b/tests/ivtools/test_utils.py @@ -5,7 +5,7 @@ from pvlib.ivtools.utils import _schumaker_qspline, _schumaker_qspline_numpy from pvlib.ivtools.utils import _lambertw_pvlib -from tests.conftest import TESTS_DATA_DIR +from tests.conftest import TESTS_DATA_DIR, requires_numba @pytest.fixture @@ -67,6 +67,7 @@ def test__schmumaker_qspline_numpy(x, y, expected): assert nknots == len(t) +@requires_numba @pytest.mark.parametrize("seed", [0, 1, 42]) def test__schmumaker_qspline_numba_matches_numpy(seed): rng = np.random.default_rng(seed) From 842266e89858f24d6325363f8d6b8c4553a771d3 Mon Sep 17 00:00:00 2001 From: Cliff Hansen Date: Sun, 29 Nov 2026 17:10:54 -0700 Subject: [PATCH 05/13] remove list operator --- pvlib/ivtools/sde.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pvlib/ivtools/sde.py b/pvlib/ivtools/sde.py index 236e91e390..90a3efd782 100644 --- a/pvlib/ivtools/sde.py +++ b/pvlib/ivtools/sde.py @@ -331,7 +331,7 @@ def _fit_sandia_cocontent(voltage, current, nsvth): # Fit quadratic spline to IV curve in order to compute the co-content # (i.e., integral of Isc - I over V) more accurately - [t, c, yhat, kflag] = _schumaker_qspline(voltage, current) + t, c, yhat, kflag = _schumaker_qspline(voltage, current) # Calculate co-content integral cci = _cocontent(t, c, isc, kflag) From 4743a235b63f57d26f1bb7989e6cb2cb250d4632 Mon Sep 17 00:00:00 2001 From: Cliff Hansen Date: Sun, 29 Nov 2026 17:27:52 -0700 Subject: [PATCH 06/13] adjust output structure --- pvlib/ivtools/utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pvlib/ivtools/utils.py b/pvlib/ivtools/utils.py index 099d1e59fe..173ee8f7ba 100644 --- a/pvlib/ivtools/utils.py +++ b/pvlib/ivtools/utils.py @@ -285,9 +285,9 @@ def _schumaker_qspline(x, y, use_numba=False): if use_numba: return _schumaker_qspline_numba(x_2d, y) - results = _schumaker_qspline_numpy_batch(x_2d, y) + t, c, yhat, kflag, _ = _schumaker_qspline_numpy_batch(x_2d, y) # keep old behavior, drop nknots - return results[:4] + return t, c, yhat, kflag def _schumaker_qspline_numpy_batch(x, y): From 02eb7b5fd726b168cce2af4a1dba3db2406b5482 Mon Sep 17 00:00:00 2001 From: Cliff Hansen Date: Sun, 29 Nov 2026 17:44:32 -0700 Subject: [PATCH 07/13] fix 1D branch --- pvlib/ivtools/utils.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pvlib/ivtools/utils.py b/pvlib/ivtools/utils.py index 173ee8f7ba..8ab8790ceb 100644 --- a/pvlib/ivtools/utils.py +++ b/pvlib/ivtools/utils.py @@ -261,11 +261,11 @@ def _schumaker_qspline(x, y, use_numba=False): if use_numba: t, c, yhat, kflag, nknots = _schumaker_qspline_numba(x, y) + return t, c, yhat, kflag, int(nknots) else: - t, c, yhat, kflag, nknots = _schumaker_qspline_numpy(x, y) + t, c, yhat, kflag, _ = _schumaker_qspline_numpy(x, y) kflag = np.asarray(kflag, dtype=bool) - - return t, c, yhat, kflag, int(nknots) + return t, c, yhat, kflag # 2D y: each row is a separate curve. if x.ndim == 1: From b0f199109e60b3d608f977b5d99e72fa6ae24cea Mon Sep 17 00:00:00 2001 From: Cliff Hansen Date: Sun, 29 Nov 2026 18:16:30 -0700 Subject: [PATCH 08/13] adjust output inside test --- tests/ivtools/test_utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/ivtools/test_utils.py b/tests/ivtools/test_utils.py index d10d93ab60..fed15a8f3a 100644 --- a/tests/ivtools/test_utils.py +++ b/tests/ivtools/test_utils.py @@ -92,7 +92,7 @@ def test__schmumaker_qspline_numba_matches_numpy(seed): # iterate through rows of x, y and use numpy for row in range(batch): - t_ref, c_ref, yhat_ref, kflag_ref, nknots_ref = _schumaker_qspline( + t_ref, c_ref, yhat_ref, kflag_ref = _schumaker_qspline( x[row], y[row]) count = nknots[row] From 0eb41fa4b685917fa2bd78c795a2f2194b26bb4c Mon Sep 17 00:00:00 2001 From: cwhanse Date: Mon, 30 Nov 2026 08:05:57 -0700 Subject: [PATCH 09/13] improve tests and coverage --- pvlib/ivtools/utils.py | 2 + tests/ivtools/test_utils.py | 103 +++++++++++++++++++++++++++++++++--- 2 files changed, 97 insertions(+), 8 deletions(-) diff --git a/pvlib/ivtools/utils.py b/pvlib/ivtools/utils.py index 8ab8790ceb..4624b583c5 100644 --- a/pvlib/ivtools/utils.py +++ b/pvlib/ivtools/utils.py @@ -247,12 +247,14 @@ def _schumaker_qspline(x, y, use_numba=False): x = np.asarray(x, dtype=np.float64) y = np.asarray(y, dtype=np.float64) + # check inputs: array dimension, minimum points if y.ndim not in (1, 2): raise ValueError("y must be a 1D or 2D array") if y.shape[-1] < 3: raise ValueError("Each curve must contain at least 3 points") + # operate on 1D input if y.ndim == 1: if x.ndim != 1 or x.shape != y.shape: raise ValueError("For 1D y, x must be 1D and have the same shape") diff --git a/tests/ivtools/test_utils.py b/tests/ivtools/test_utils.py index fed15a8f3a..3d87e0c42d 100644 --- a/tests/ivtools/test_utils.py +++ b/tests/ivtools/test_utils.py @@ -58,18 +58,30 @@ def test_rectify_iv_curve(ivcurve): np.array([-.5, -.1, -.05, 0., .1, .2, .3]), np.array([-5., -1., -.297, .2, .3485, .5, 2.]), np.array([0., 0., 1., 0., 1., 0., 0.])))]) -def test__schmumaker_qspline_numpy(x, y, expected): - t, c, yhat, kflag, nknots = _schumaker_qspline_numpy(x, y) - np.testing.assert_allclose(c, expected[0], atol=0.0001) - np.testing.assert_allclose(t, expected[1], atol=0.0001) - np.testing.assert_allclose(yhat, expected[2], atol=0.0001) - np.testing.assert_allclose(kflag, expected[3], atol=0.0001) - assert nknots == len(t) +def test__schmumaker_qspline_1d(x, y, expected): + # with numpy + t_np, c_np, yhat_np, kflag_np = _schumaker_qspline(x, y, use_numba=False) + np.testing.assert_allclose(c_np, expected[0], atol=0.0001) + np.testing.assert_allclose(t_np, expected[1], atol=0.0001) + np.testing.assert_allclose(yhat_np, expected[2], atol=0.0001) + np.testing.assert_allclose(kflag_np, expected[3], atol=0.0001) + # with numba + t_nb, c_nb, yhat_nb, kflag_nb, nknots = _schumaker_qspline(x, y, use_numba=True) + np.testing.assert_allclose(c_nb, expected[0], atol=0.0001) + np.testing.assert_allclose(t_nb, expected[1], atol=0.0001) + np.testing.assert_allclose(yhat_nb, expected[2], atol=0.0001) + np.testing.assert_allclose(kflag_nb, expected[3], atol=0.0001) + assert nknots == len(t_nb) + # numpy and numba match + np.testing.assert_allclose(t_np, t_nb, rtol=1e-12) + np.testing.assert_allclose(c_np, c_nb, rtol=1e-12) + np.testing.assert_allclose(yhat_np, yhat_nb, rtol=1e-12) + np.testing.assert_array_equal(kflag_np, kflag_nb) @requires_numba @pytest.mark.parametrize("seed", [0, 1, 42]) -def test__schmumaker_qspline_numba_matches_numpy(seed): +def test__schmumaker_qspline_2d(seed): rng = np.random.default_rng(seed) batch = 32 @@ -118,6 +130,81 @@ def test__schmumaker_qspline_numba_matches_numpy(seed): assert np.isnan(c_batch[row, count - 1:]).all() +def test__schumaker_qspline_error_messages(): + # y must be 1D or 2D. + with pytest.raises(ValueError, match=r"^y must be a 1D or 2D array$"): + _schumaker_qspline( + x=np.zeros((3,)), + y=np.zeros((1, 1, 1)), + ) + # Each curve must contain at least three points. + with pytest.raises( + ValueError, + match=r"^Each curve must contain at least 3 points$", + ): + _schumaker_qspline( + x=np.array([0.0, 1.0]), + y=np.array([0.0, 1.0]), + ) + # For 1D y, x must be 1D and have the same shape. + with pytest.raises( + ValueError, + match=r"^For 1D y, x must be 1D and have the same shape$", + ): + _schumaker_qspline( + x=np.array([[0.0, 1.0, 2.0]]), + y=np.array([0.0, 1.0, 2.0]), + ) + # x must be strictly increasing for 1D inputs. + with pytest.raises( + ValueError, + match=r"^x must be strictly increasing$", + ): + _schumaker_qspline( + x=np.array([0.0, 2.0, 1.0]), + y=np.array([0.0, 1.0, 2.0]), + ) + # A shared 1D x grid must have one value per column of y. + with pytest.raises( + ValueError, + match=r"^1D x must have one value per column of y$", + ): + _schumaker_qspline( + x=np.array([0.0, 1.0]), + y=np.zeros((2, 3)), + ) + # A 2D x array must have the same shape as y. + with pytest.raises( + ValueError, + match=r"^2D x and y must have the same shape$", + ): + _schumaker_qspline( + x=np.zeros((2, 4)), + y=np.zeros((2, 3)), + ) + # x must be either 1D or 2D. + with pytest.raises( + ValueError, + match=r"^x must be a 1D or 2D array$", + ): + _schumaker_qspline( + x=np.zeros((1, 2, 3)), + y=np.zeros((2, 3)), + ) + # Every row of a 2D x array must be strictly increasing. + with pytest.raises( + ValueError, + match=r"^Each row of x must be strictly increasing$", + ): + _schumaker_qspline( + x=np.array([ + [0.0, 2.0, 1.0], + [0.0, 1.0, 2.0], + ]), + y=np.zeros((2, 3)), + ) + + @pytest.fixture def i_array(): i = np.array([8.09403993, 8.09382549, 8.09361103, 8.09339656, 8.09318205, From c9f2b3eadf886601b55ee46c14e6df480df9df8c Mon Sep 17 00:00:00 2001 From: cwhanse Date: Mon, 30 Nov 2026 08:08:51 -0700 Subject: [PATCH 10/13] decorator, formatting --- tests/ivtools/test_utils.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/ivtools/test_utils.py b/tests/ivtools/test_utils.py index 3d87e0c42d..0b980e077d 100644 --- a/tests/ivtools/test_utils.py +++ b/tests/ivtools/test_utils.py @@ -2,7 +2,7 @@ import pandas as pd import pytest from pvlib.ivtools.utils import _numdiff, rectify_iv_curve, astm_e1036 -from pvlib.ivtools.utils import _schumaker_qspline, _schumaker_qspline_numpy +from pvlib.ivtools.utils import _schumaker_qspline from pvlib.ivtools.utils import _lambertw_pvlib from tests.conftest import TESTS_DATA_DIR, requires_numba @@ -43,6 +43,7 @@ def test_rectify_iv_curve(ivcurve): # run tests generated by original Matlab implementation +@requires_numba @pytest.mark.parametrize('x,y,expected', [ (np.array([1., 2., 3., 4., 5.]), np.array([-2., -1., 0., 1., 2.]), @@ -66,7 +67,8 @@ def test__schmumaker_qspline_1d(x, y, expected): np.testing.assert_allclose(yhat_np, expected[2], atol=0.0001) np.testing.assert_allclose(kflag_np, expected[3], atol=0.0001) # with numba - t_nb, c_nb, yhat_nb, kflag_nb, nknots = _schumaker_qspline(x, y, use_numba=True) + t_nb, c_nb, yhat_nb, kflag_nb, nknots = _schumaker_qspline(x, y, + use_numba=True) np.testing.assert_allclose(c_nb, expected[0], atol=0.0001) np.testing.assert_allclose(t_nb, expected[1], atol=0.0001) np.testing.assert_allclose(yhat_nb, expected[2], atol=0.0001) From 2cefba3b90abf45d1c822c13226a4a9754015dbf Mon Sep 17 00:00:00 2001 From: cwhanse Date: Mon, 30 Nov 2026 09:03:12 -0700 Subject: [PATCH 11/13] switch back to 5 outputs so that 2D numpy is executed --- pvlib/ivtools/sde.py | 4 +-- pvlib/ivtools/utils.py | 20 +++++------ tests/ivtools/test_utils.py | 66 +++++++++++++++++++++++++++---------- 3 files changed, 60 insertions(+), 30 deletions(-) diff --git a/pvlib/ivtools/sde.py b/pvlib/ivtools/sde.py index 90a3efd782..dc7b5e70ed 100644 --- a/pvlib/ivtools/sde.py +++ b/pvlib/ivtools/sde.py @@ -330,8 +330,8 @@ def _fit_sandia_cocontent(voltage, current, nsvth): # Fit quadratic spline to IV curve in order to compute the co-content # (i.e., integral of Isc - I over V) more accurately - - t, c, yhat, kflag = _schumaker_qspline(voltage, current) + # ignore 5th output since input here is 1D + t, c, yhat, kflag, _ = _schumaker_qspline(voltage, current) # Calculate co-content integral cci = _cocontent(t, c, isc, kflag) diff --git a/pvlib/ivtools/utils.py b/pvlib/ivtools/utils.py index 4624b583c5..87a9e1bcf2 100644 --- a/pvlib/ivtools/utils.py +++ b/pvlib/ivtools/utils.py @@ -217,23 +217,23 @@ def _schumaker_qspline(x, y, use_numba=False): ------- t : ndarray Knot locations. For 1D input, shape is ``(M,)``. For 2D input, - shape is ``(B, 2*K - 1)`` and rows are padded with NaN. + shape is ``(N, 2*K - 1)`` and rows are padded with NaN. c : ndarray Quadratic coefficients for intervals between successive knots. The polynomial for interval i is ``c[i, 0] * (z - t[i])**2 + c[i, 1] * (z - t[i]) + c[i, 2]``. For 1D input, shape is ``(M - 1, 3)``. For 2D input, shape is - ``(B, 2*K - 2, 3)`` and rows are padded with NaN. + ``(N, 2*K - 2, 3)`` and rows are padded with NaN. yhat : ndarray Values at the knots. For 1D input, shape is ``(M,)``. For 2D - input, shape is ``(B, 2*K - 1)`` and rows are padded with NaN. + input, shape is ``(N, 2*K - 1)`` and rows are padded with NaN. kflag : ndarray Boolean flags identifying inserted knots. For 1D input, shape is - ``(M,)``. For 2D input, shape is ``(B, 2*K - 1)``. Padding is + ``(M,)``. For 2D input, shape is ``(N, 2*K - 1)``. Padding is False; use ``nknots`` to distinguish padding from valid entries. nknots : int or ndarray of int Number of valid knots. For 1D input, this is an integer. For 2D - input, this is an integer array of shape ``(B,)``. For row b, + input, this is an integer array of shape ``(N,)``. For row b, the valid outputs are ``t[b, :nknots[b]]``, ``yhat[b, :nknots[b]]``, ``kflag[b, :nknots[b]]``, and ``c[b, :nknots[b] - 1]``. @@ -265,9 +265,9 @@ def _schumaker_qspline(x, y, use_numba=False): t, c, yhat, kflag, nknots = _schumaker_qspline_numba(x, y) return t, c, yhat, kflag, int(nknots) else: - t, c, yhat, kflag, _ = _schumaker_qspline_numpy(x, y) + t, c, yhat, kflag, nknots = _schumaker_qspline_numpy(x, y) kflag = np.asarray(kflag, dtype=bool) - return t, c, yhat, kflag + return t, c, yhat, kflag, nknots # 2D y: each row is a separate curve. if x.ndim == 1: @@ -286,10 +286,8 @@ def _schumaker_qspline(x, y, use_numba=False): if use_numba: return _schumaker_qspline_numba(x_2d, y) - - t, c, yhat, kflag, _ = _schumaker_qspline_numpy_batch(x_2d, y) - # keep old behavior, drop nknots - return t, c, yhat, kflag + else: + return _schumaker_qspline_numpy_batch(x_2d, y) def _schumaker_qspline_numpy_batch(x, y): diff --git a/tests/ivtools/test_utils.py b/tests/ivtools/test_utils.py index 0b980e077d..0f6c9989f4 100644 --- a/tests/ivtools/test_utils.py +++ b/tests/ivtools/test_utils.py @@ -61,24 +61,25 @@ def test_rectify_iv_curve(ivcurve): np.array([0., 0., 1., 0., 1., 0., 0.])))]) def test__schmumaker_qspline_1d(x, y, expected): # with numpy - t_np, c_np, yhat_np, kflag_np = _schumaker_qspline(x, y, use_numba=False) + t_np, c_np, yhat_np, kflag_np, nknots_np = _schumaker_qspline( + x, y, use_numba=False) np.testing.assert_allclose(c_np, expected[0], atol=0.0001) np.testing.assert_allclose(t_np, expected[1], atol=0.0001) np.testing.assert_allclose(yhat_np, expected[2], atol=0.0001) np.testing.assert_allclose(kflag_np, expected[3], atol=0.0001) # with numba - t_nb, c_nb, yhat_nb, kflag_nb, nknots = _schumaker_qspline(x, y, - use_numba=True) + t_nb, c_nb, yhat_nb, kflag_nb, nknots_nb = _schumaker_qspline( + x, y, use_numba=True) np.testing.assert_allclose(c_nb, expected[0], atol=0.0001) np.testing.assert_allclose(t_nb, expected[1], atol=0.0001) np.testing.assert_allclose(yhat_nb, expected[2], atol=0.0001) np.testing.assert_allclose(kflag_nb, expected[3], atol=0.0001) - assert nknots == len(t_nb) # numpy and numba match np.testing.assert_allclose(t_np, t_nb, rtol=1e-12) np.testing.assert_allclose(c_np, c_nb, rtol=1e-12) np.testing.assert_allclose(yhat_np, yhat_nb, rtol=1e-12) np.testing.assert_array_equal(kflag_np, kflag_nb) + np.testing.assert_array_equal(nknots_np, nknots_nb) @requires_numba @@ -104,32 +105,63 @@ def test__schmumaker_qspline_2d(seed): t_batch, c_batch, yhat, kflag, nknots = _schumaker_qspline( x, y, use_numba=True) - # iterate through rows of x, y and use numpy + t_ref, c_ref, yhat_ref, kflag_ref, nknots_ref = _schumaker_qspline( + x, y) + + # compare results: iterate through rows of x, y for row in range(batch): - t_ref, c_ref, yhat_ref, kflag_ref = _schumaker_qspline( - x[row], y[row]) - count = nknots[row] - np.testing.assert_array_equal(t_batch[row, :count].shape, t_ref.shape) - np.testing.assert_array_equal(c_batch[row, :count - 1].shape, - c_ref.shape) + c1 = nknots[row] + c2 = nknots_ref[row] + np.testing.assert_array_equal(t_batch[row, :c1].shape, + t_ref[row, :c2].shape) + np.testing.assert_array_equal(c_batch[row, :c1 - 1].shape, + c_ref[row, :c2 - 1].shape) np.testing.assert_allclose( - t_batch[row, :count], - t_ref, + t_batch[row, :c1], + t_ref[row, :c2], rtol=1e-11, atol=1e-12, ) np.testing.assert_allclose( - c_batch[row, :count - 1], - c_ref, + c_batch[row, :c1 - 1], + c_ref[row, :c2 -1], rtol=1e-11, atol=1e-12, ) # Check that the unused, padded output entries are NaN. - assert np.isnan(t_batch[row, count:]).all() - assert np.isnan(c_batch[row, count - 1:]).all() + assert np.isnan(t_batch[row, c1:]).all() + assert np.isnan(c_batch[row, c1 - 1:]).all() + assert np.isnan(t_ref[row, c2:]).all() + assert np.isnan(c_ref[row, c2 - 1:]).all() + # # iterate through rows of x, y and use numpy + # for row in range(batch): + # t_ref, c_ref, yhat_ref, kflag_ref = _schumaker_qspline( + # x[row], y[row]) + + # count = nknots[row] + # np.testing.assert_array_equal(t_batch[row, :count].shape, t_ref.shape) + # np.testing.assert_array_equal(c_batch[row, :count - 1].shape, + # c_ref.shape) + + # np.testing.assert_allclose( + # t_batch[row, :count], + # t_ref, + # rtol=1e-11, + # atol=1e-12, + # ) + # np.testing.assert_allclose( + # c_batch[row, :count - 1], + # c_ref, + # rtol=1e-11, + # atol=1e-12, + # ) + + # # Check that the unused, padded output entries are NaN. + # assert np.isnan(t_batch[row, count:]).all() + # assert np.isnan(c_batch[row, count - 1:]).all() def test__schumaker_qspline_error_messages(): From 543346771bfd5acbbb448152f14c5e4ca7c28ed5 Mon Sep 17 00:00:00 2001 From: cwhanse Date: Mon, 30 Nov 2026 09:22:19 -0700 Subject: [PATCH 12/13] a bit of cleanup --- pvlib/ivtools/utils.py | 15 ++++----------- tests/ivtools/test_utils.py | 31 +++---------------------------- 2 files changed, 7 insertions(+), 39 deletions(-) diff --git a/pvlib/ivtools/utils.py b/pvlib/ivtools/utils.py index 87a9e1bcf2..4fb53b57be 100644 --- a/pvlib/ivtools/utils.py +++ b/pvlib/ivtools/utils.py @@ -287,10 +287,10 @@ def _schumaker_qspline(x, y, use_numba=False): if use_numba: return _schumaker_qspline_numba(x_2d, y) else: - return _schumaker_qspline_numpy_batch(x_2d, y) + return _schumaker_qspline_numpy_2d(x_2d, y) -def _schumaker_qspline_numpy_batch(x, y): +def _schumaker_qspline_numpy_2d(x, y): """Apply the 1D NumPy implementation row by row and pad its results.""" batch, n = y.shape max_knots = 2 * n - 1 @@ -699,8 +699,7 @@ def _schumaker_qspline_numba(x, y): x = np.asarray(x, dtype=np.float64) y = np.asarray(y, dtype=np.float64) - # The kernel processes batches. Promote 1D inputs to a one-row batch, - # then remove that batch dimension and the padding for the 1D result. + # The numba kernel processes 2d. Promote 1D inputs to 2D (1, n), was_1d = x.ndim == 1 and y.ndim == 1 if was_1d: x = x[None, :] @@ -709,15 +708,9 @@ def _schumaker_qspline_numba(x, y): x = np.ascontiguousarray(x, dtype=np.float64) y = np.ascontiguousarray(y, dtype=np.float64) - if x.ndim != 2 or y.ndim != 2 or x.shape != y.shape: - raise ValueError("Numba inputs must be matching 2D arrays") - if x.shape[1] < 3: - raise ValueError("Each row must contain at least 3 points") - if np.any(np.diff(x, axis=1) <= 0.0): - raise ValueError("Each row of x must be strictly increasing") - t, c, yhat, kflag, nknots = _schumaker_qspline_numba_kernel(x, y) + # if input is 1D, return 1D results if was_1d: count = int(nknots[0]) return ( diff --git a/tests/ivtools/test_utils.py b/tests/ivtools/test_utils.py index 0f6c9989f4..b39b928209 100644 --- a/tests/ivtools/test_utils.py +++ b/tests/ivtools/test_utils.py @@ -108,7 +108,8 @@ def test__schmumaker_qspline_2d(seed): t_ref, c_ref, yhat_ref, kflag_ref, nknots_ref = _schumaker_qspline( x, y) - # compare results: iterate through rows of x, y + # compare results: iterate through rows of x, y, since output is padded + # with nan for row in range(batch): c1 = nknots[row] @@ -126,7 +127,7 @@ def test__schmumaker_qspline_2d(seed): ) np.testing.assert_allclose( c_batch[row, :c1 - 1], - c_ref[row, :c2 -1], + c_ref[row, :c2 - 1], rtol=1e-11, atol=1e-12, ) @@ -136,32 +137,6 @@ def test__schmumaker_qspline_2d(seed): assert np.isnan(c_batch[row, c1 - 1:]).all() assert np.isnan(t_ref[row, c2:]).all() assert np.isnan(c_ref[row, c2 - 1:]).all() - # # iterate through rows of x, y and use numpy - # for row in range(batch): - # t_ref, c_ref, yhat_ref, kflag_ref = _schumaker_qspline( - # x[row], y[row]) - - # count = nknots[row] - # np.testing.assert_array_equal(t_batch[row, :count].shape, t_ref.shape) - # np.testing.assert_array_equal(c_batch[row, :count - 1].shape, - # c_ref.shape) - - # np.testing.assert_allclose( - # t_batch[row, :count], - # t_ref, - # rtol=1e-11, - # atol=1e-12, - # ) - # np.testing.assert_allclose( - # c_batch[row, :count - 1], - # c_ref, - # rtol=1e-11, - # atol=1e-12, - # ) - - # # Check that the unused, padded output entries are NaN. - # assert np.isnan(t_batch[row, count:]).all() - # assert np.isnan(c_batch[row, count - 1:]).all() def test__schumaker_qspline_error_messages(): From 90c5b7de9afb22497b4e8cbd0a2e3bbd5165bf65 Mon Sep 17 00:00:00 2001 From: cwhanse Date: Mon, 30 Nov 2026 09:40:21 -0700 Subject: [PATCH 13/13] whats new --- docs/sphinx/source/whatsnew/v0.16.2.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/sphinx/source/whatsnew/v0.16.2.rst b/docs/sphinx/source/whatsnew/v0.16.2.rst index b9a54f6c26..5a7ab344a3 100644 --- a/docs/sphinx/source/whatsnew/v0.16.2.rst +++ b/docs/sphinx/source/whatsnew/v0.16.2.rst @@ -31,6 +31,8 @@ Enhancements * Add ``dataset`` parameter to :py:func:`~pvlib.iotools.get_era5` allowing for choosing between ERA5 and ERA5-Land datasets. (:pull:`2780`) +* Add capability to use numba with :py:func:`pvlib.ivtools.utils._schumaker_qspline`. + Note that this function now has 5 outputs (was 4). (:issue:`2966`, :pull:`2968`) Documentation ~~~~~~~~~~~~~