Skip to content
Open
2 changes: 2 additions & 0 deletions docs/sphinx/source/whatsnew/v0.16.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
~~~~~~~~~~~~~
Expand Down
4 changes: 2 additions & 2 deletions pvlib/ivtools/sde.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
312 changes: 305 additions & 7 deletions pvlib/ivtools/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
-----
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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),
Expand Down
Loading
Loading