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 ~~~~~~~~~~~~~ diff --git a/pvlib/ivtools/sde.py b/pvlib/ivtools/sde.py index 236e91e390..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 0d0ef1382a..4fb53b57be 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,130 @@ 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 ``(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 + ``(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 ``(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 ``(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 ``(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]``. + + 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) + + # 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") + 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) + return t, c, yhat, kflag, int(nknots) + else: + t, c, yhat, kflag, nknots = _schumaker_qspline_numpy(x, y) + kflag = np.asarray(kflag, dtype=bool) + return t, c, yhat, kflag, 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) + else: + return _schumaker_qspline_numpy_2d(x_2d, 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 + + 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 +346,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 +406,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 +458,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 +563,165 @@ 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 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, :] + y = y[None, :] + + x = np.ascontiguousarray(x, dtype=np.float64) + y = np.ascontiguousarray(y, dtype=np.float64) + + 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 ( + 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..b39b928209 100644 --- a/tests/ivtools/test_utils.py +++ b/tests/ivtools/test_utils.py @@ -5,7 +5,7 @@ from pvlib.ivtools.utils import _schumaker_qspline 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 @@ -42,21 +42,9 @@ def test_rectify_iv_curve(ivcurve): np.testing.assert_allclose(i, iexp, atol=.0001) +# run tests generated by original Matlab implementation +@requires_numba @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 +59,159 @@ 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) - 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) +def test__schmumaker_qspline_1d(x, y, expected): + # with numpy + 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_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) + # 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 +@pytest.mark.parametrize("seed", [0, 1, 42]) +def test__schmumaker_qspline_2d(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) + + t_ref, c_ref, yhat_ref, kflag_ref, nknots_ref = _schumaker_qspline( + x, y) + + # compare results: iterate through rows of x, y, since output is padded + # with nan + for row in range(batch): + + 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, :c1], + t_ref[row, :c2], + rtol=1e-11, + atol=1e-12, + ) + np.testing.assert_allclose( + 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, 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() + + +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