diff --git a/benchmarks/benchmarks/solarposition.py b/benchmarks/benchmarks/solarposition.py
index 4fac0ea470..5458dbb060 100644
--- a/benchmarks/benchmarks/solarposition.py
+++ b/benchmarks/benchmarks/solarposition.py
@@ -4,11 +4,15 @@
import datetime
import pandas as pd
-import pvlib
-from pvlib import solarposition
-
from pkg_resources import parse_version
+# Numba is installed in the benchmark environments, but we'll disable it here.
+# so pvlib will switch to numpy functions (see NUMBA_ACTIVE in pvlib.tools).
+import numba
+numba.config.DISABLE_JIT = 1
+import pvlib # NOQA: E402
+from pvlib import solarposition # NOQA: E402
+
if parse_version(pvlib.__version__) >= parse_version('0.6.1'):
sun_rise_set_transit_spa = solarposition.sun_rise_set_transit_spa
diff --git a/benchmarks/benchmarks/solarposition_numba.py b/benchmarks/benchmarks/solarposition_numba.py
index bcadfd1893..d70f252a85 100644
--- a/benchmarks/benchmarks/solarposition_numba.py
+++ b/benchmarks/benchmarks/solarposition_numba.py
@@ -10,12 +10,8 @@
from pkg_resources import parse_version
import pandas as pd
-import os
-os.environ['PVLIB_USE_NUMBA'] = '1'
-
-
-import pvlib # NOQA: E402
-from pvlib import solarposition # NOQA: E402
+import pvlib
+from pvlib import solarposition
if parse_version(pvlib.__version__) >= parse_version('0.6.1'):
diff --git a/ci/azure/conda_linux.yml b/ci/azure/conda_linux.yml
index 583ac71226..65e7f81e53 100644
--- a/ci/azure/conda_linux.yml
+++ b/ci/azure/conda_linux.yml
@@ -11,6 +11,8 @@ jobs:
Python36-min:
python.version: '36'
suffix: '-min'
+ coverage: true # report coverage for both 36 and 36-min to combine
+ # coverage for both numba and non-numba codepaths
Python36:
python.version: '36'
coverage: true
diff --git a/docs/sphinx/source/api.rst b/docs/sphinx/source/api.rst
index 8805d199a4..de1fd36725 100644
--- a/docs/sphinx/source/api.rst
+++ b/docs/sphinx/source/api.rst
@@ -1,3 +1,5 @@
+.. _api:
+
.. currentmodule:: pvlib
#############
diff --git a/docs/sphinx/source/installation.rst b/docs/sphinx/source/installation.rst
index 39b7bfc974..377a306833 100644
--- a/docs/sphinx/source/installation.rst
+++ b/docs/sphinx/source/installation.rst
@@ -270,6 +270,34 @@ To install the NREL SPA algorithm for use with pvlib:
#. From the ``pvlib-python`` directory, run ``pip uninstall pvlib``
followed by ``pip install .``
+
+.. _using_numba:
+
+Numba Acceleration
+------------------
+
+Some of the models offered by pvlib-python are difficult to implement
+using vectorized numpy code and instead use comparatively inefficient
+python code. To avoid the slowdown of using basic python, some functions
+in pvlib-python include optional JIT-compiling support through the
+`numba `_ python package. Installing numba
+is not required to run these functions, but it will improve the runtime
+of these functions significantly. Functions that can be accelerated
+with numba have a corresponding note on their page in the :ref:`api`.
+
+By default, numba is used automatically if it is present in your
+python environment. However, it can be disabled by using the
+``NUMBA_DISABLE_JIT`` environment variable. The same can be accomplished
+by importing and configuring numba prior to importing pvlib, like this::
+
+ import numba
+ numba.config.DISABLE_JIT = 1
+ import pvlib
+
+For more details, see numba's
+`documentation `_.
+
+
.. _references:
References
diff --git a/pvlib/modelchain.py b/pvlib/modelchain.py
index 1c07857745..10c8f6ffee 100644
--- a/pvlib/modelchain.py
+++ b/pvlib/modelchain.py
@@ -69,7 +69,7 @@ def basic_chain(times, latitude, longitude,
surface_tilt=None, surface_azimuth=None,
orientation_strategy=None,
transposition_model='haydavies',
- solar_position_method='nrel_numpy',
+ solar_position_method='nrel',
airmass_model='kastenyoung1989',
altitude=None, pressure=None,
**kwargs):
@@ -132,7 +132,7 @@ def basic_chain(times, latitude, longitude,
transposition_model : str, default 'haydavies'
Passed to system.get_irradiance.
- solar_position_method : str, default 'nrel_numpy'
+ solar_position_method : str, default 'nrel'
Passed to solarposition.get_solarposition.
airmass_model : str, default 'kastenyoung1989'
@@ -344,7 +344,7 @@ class ModelChain:
transposition_model : str, default 'haydavies'
Passed to system.get_irradiance.
- solar_position_method : str, default 'nrel_numpy'
+ solar_position_method : str, default 'nrel'
Passed to location.get_solarposition.
airmass_model : str, default 'kastenyoung1989'
@@ -398,7 +398,7 @@ def __init__(self, system, location,
orientation_strategy=None,
clearsky_model='ineichen',
transposition_model='haydavies',
- solar_position_method='nrel_numpy',
+ solar_position_method='nrel',
airmass_model='kastenyoung1989',
dc_model=None, ac_model=None, aoi_model=None,
spectral_model=None, temperature_model=None,
@@ -505,7 +505,7 @@ def with_pvwatts(cls, system, location,
orientation_strategy: None
clearsky_model: ineichen
transposition_model: perez
- solar_position_method: nrel_numpy
+ solar_position_method: nrel
airmass_model: kastenyoung1989
dc_model: pvwatts_dc
ac_model: pvwatts_inverter
@@ -530,7 +530,7 @@ def with_sapm(cls, system, location,
orientation_strategy=None,
clearsky_model='ineichen',
transposition_model='haydavies',
- solar_position_method='nrel_numpy',
+ solar_position_method='nrel',
airmass_model='kastenyoung1989',
name=None,
**kwargs):
@@ -560,7 +560,7 @@ def with_sapm(cls, system, location,
transposition_model : str, default 'haydavies'
Passed to system.get_irradiance.
- solar_position_method : str, default 'nrel_numpy'
+ solar_position_method : str, default 'nrel'
Passed to location.get_solarposition.
airmass_model : str, default 'kastenyoung1989'
@@ -592,7 +592,7 @@ def with_sapm(cls, system, location,
orientation_strategy: None
clearsky_model: ineichen
transposition_model: haydavies
- solar_position_method: nrel_numpy
+ solar_position_method: nrel
airmass_model: kastenyoung1989
dc_model: sapm
ac_model: snlinverter
diff --git a/pvlib/solarposition.py b/pvlib/solarposition.py
index 040f9d5f14..5c61f444c0 100644
--- a/pvlib/solarposition.py
+++ b/pvlib/solarposition.py
@@ -8,31 +8,24 @@
# Tony Lorenzo (@alorenzo175), University of Arizona, 2015
# Cliff hansen (@cwhanse), Sandia National Laboratories, 2018
-import os
import datetime as dt
-try:
- from importlib import reload
-except ImportError:
- try:
- from imp import reload
- except ImportError:
- pass
import numpy as np
import pandas as pd
import scipy.optimize as so
import warnings
-from pvlib import atmosphere
-from pvlib.tools import datetime_to_djd, djd_to_datetime
+from pvlib import atmosphere, spa
+from pvlib.tools import datetime_to_djd, djd_to_datetime, jit_annotate
+from pvlib._deprecation import pvlibDeprecationWarning
NS_PER_HR = 1.e9 * 3600. # nanoseconds per hour
def get_solarposition(time, latitude, longitude,
altitude=None, pressure=None,
- method='nrel_numpy',
+ method='nrel',
temperature=12, **kwargs):
"""
A convenience wrapper for the solar position calculators.
@@ -58,13 +51,10 @@ def get_solarposition(time, latitude, longitude,
If None, computed from altitude. Assumed to be 101325 Pa
if altitude is also None.
- method : string, default 'nrel_numpy'
- 'nrel_numpy' uses an implementation of the NREL SPA algorithm
- described in [1] (default, recommended): :py:func:`spa_python`
-
- 'nrel_numba' uses an implementation of the NREL SPA algorithm
- described in [1], but also compiles the code first:
- :py:func:`spa_python`
+ method : string, default 'nrel'
+ 'nrel' uses an implementation of the NREL SPA algorithm
+ described in [1], optionally accelerated with numba
+ if possible (default, recommended): :py:func:`spa_python`
'pyephem' uses the PyEphem package: :py:func:`pyephem`
@@ -106,14 +96,14 @@ def get_solarposition(time, latitude, longitude,
if method == 'nrel_c':
ephem_df = spa_c(time, latitude, longitude, pressure, temperature,
**kwargs)
- elif method == 'nrel_numba':
- ephem_df = spa_python(time, latitude, longitude, altitude,
- pressure, temperature,
- how='numba', **kwargs)
- elif method == 'nrel_numpy':
+ elif method in {'nrel', 'nrel_numpy', 'nrel_numba'}:
+ if method != 'nrel':
+ warnings.warn(f'method={method} is deprecated; Use method="nrel" '
+ 'instead. Numba will be used automatically if it '
+ 'is available.', pvlibDeprecationWarning)
ephem_df = spa_python(time, latitude, longitude, altitude,
pressure, temperature,
- how='numpy', **kwargs)
+ **kwargs)
elif method == 'pyephem':
ephem_df = pyephem(time, latitude, longitude,
altitude=altitude,
@@ -243,39 +233,10 @@ def spa_c(time, latitude, longitude, pressure=101325, altitude=0,
return dfout
-def _spa_python_import(how):
- """Compile spa.py appropriately"""
-
- from pvlib import spa
-
- # check to see if the spa module was compiled with numba
- using_numba = spa.USE_NUMBA
-
- if how == 'numpy' and using_numba:
- # the spa module was compiled to numba code, so we need to
- # reload the module without compiling
- # the PVLIB_USE_NUMBA env variable is used to tell the module
- # to not compile with numba
- warnings.warn('Reloading spa to use numpy')
- os.environ['PVLIB_USE_NUMBA'] = '0'
- spa = reload(spa)
- del os.environ['PVLIB_USE_NUMBA']
- elif how == 'numba' and not using_numba:
- # The spa module was not compiled to numba code, so set
- # PVLIB_USE_NUMBA so it does compile to numba on reload.
- warnings.warn('Reloading spa to use numba')
- os.environ['PVLIB_USE_NUMBA'] = '1'
- spa = reload(spa)
- del os.environ['PVLIB_USE_NUMBA']
- elif how != 'numba' and how != 'numpy':
- raise ValueError("how must be either 'numba' or 'numpy'")
-
- return spa
-
-
+@jit_annotate
def spa_python(time, latitude, longitude,
altitude=0, pressure=101325, temperature=12, delta_t=67.0,
- atmos_refract=None, how='numpy', numthreads=4, **kwargs):
+ atmos_refract=None, how=None, numthreads=4, **kwargs):
"""
Calculate the solar position using a python implementation of the
NREL SPA algorithm.
@@ -314,12 +275,10 @@ def spa_python(time, latitude, longitude,
atmos_refrac : None or float, optional, default None
The approximate atmospheric refraction (in degrees)
at sunrise and sunset.
- how : str, optional, default 'numpy'
- Options are 'numpy' or 'numba'. If numba >= 0.17.0
- is installed, how='numba' will compile the spa functions
- to machine code and run them multithreaded.
+ how :
+ Deprecated
numthreads : int, optional, default 4
- Number of threads to use if how == 'numba'.
+ Number of threads to use when numba acceleration is used.
Returns
-------
@@ -352,6 +311,8 @@ def spa_python(time, latitude, longitude,
# Added by Tony Lorenzo (@alorenzo175), University of Arizona, 2015
+ _warn_how_numba(how)
+
lat = latitude
lon = longitude
elev = altitude
@@ -367,8 +328,6 @@ def spa_python(time, latitude, longitude,
unixtime = np.array(time.astype(np.int64)/10**9)
- spa = _spa_python_import(how)
-
delta_t = delta_t or spa.calculate_deltat(time.year, time.month)
app_zenith, zenith, app_elevation, elevation, azimuth, eot = \
@@ -384,7 +343,8 @@ def spa_python(time, latitude, longitude,
return result
-def sun_rise_set_transit_spa(times, latitude, longitude, how='numpy',
+@jit_annotate
+def sun_rise_set_transit_spa(times, latitude, longitude, how=None,
delta_t=67.0, numthreads=4):
"""
Calculate the sunrise, sunset, and sun transit times using the
@@ -413,12 +373,10 @@ def sun_rise_set_transit_spa(times, latitude, longitude, how='numpy',
delta_t = None will break code using nrel_numba,
this will be fixed in a future version.
By default, use USNO historical data and predictions
- how : str, optional, default 'numpy'
- Options are 'numpy' or 'numba'. If numba >= 0.17.0
- is installed, how='numba' will compile the spa functions
- to machine code and run them multithreaded.
+ how :
+ Deprecated
numthreads : int, optional, default 4
- Number of threads to use if how == 'numba'.
+ Number of threads to use if using numba.
Returns
-------
@@ -434,6 +392,8 @@ def sun_rise_set_transit_spa(times, latitude, longitude, how='numpy',
"""
# Added by Tony Lorenzo (@alorenzo175), University of Arizona, 2015
+ _warn_how_numba(how)
+
lat = latitude
lon = longitude
@@ -447,8 +407,6 @@ def sun_rise_set_transit_spa(times, latitude, longitude, how='numpy',
utcday = pd.DatetimeIndex(times.date).tz_localize('UTC')
unixtime = np.array(utcday.astype(np.int64)/10**9)
- spa = _spa_python_import(how)
-
delta_t = delta_t or spa.calculate_deltat(times.year, times.month)
transit, sunrise, sunset = spa.transit_sunrise_sunset(
@@ -954,7 +912,7 @@ def pyephem_earthsun_distance(time):
return pd.Series(earthsun, index=time)
-def nrel_earthsun_distance(time, how='numpy', delta_t=67.0, numthreads=4):
+def nrel_earthsun_distance(time, how=None, delta_t=67.0, numthreads=4):
"""
Calculates the distance from the earth to the sun using the
NREL SPA algorithm.
@@ -966,10 +924,8 @@ def nrel_earthsun_distance(time, how='numpy', delta_t=67.0, numthreads=4):
time : pandas.DatetimeIndex
Must be localized or UTC will be assumed.
- how : str, optional, default 'numpy'
- Options are 'numpy' or 'numba'. If numba >= 0.17.0
- is installed, how='numba' will compile the spa functions
- to machine code and run them multithreaded.
+ how :
+ Deprecated
delta_t : float, optional, default 67.0
If delta_t is None, uses spa.calculate_deltat
@@ -981,7 +937,7 @@ def nrel_earthsun_distance(time, how='numpy', delta_t=67.0, numthreads=4):
By default, use USNO historical data and predictions
numthreads : int, optional, default 4
- Number of threads to use if how == 'numba'.
+ Number of threads to use if using numba.
Returns
-------
@@ -995,6 +951,8 @@ def nrel_earthsun_distance(time, how='numpy', delta_t=67.0, numthreads=4):
USA, http://www.nrel.gov.
"""
+ _warn_how_numba(how)
+
if not isinstance(time, pd.DatetimeIndex):
try:
time = pd.DatetimeIndex(time)
@@ -1003,8 +961,6 @@ def nrel_earthsun_distance(time, how='numpy', delta_t=67.0, numthreads=4):
unixtime = np.array(time.astype(np.int64)/10**9)
- spa = _spa_python_import(how)
-
delta_t = delta_t or spa.calculate_deltat(time.year, time.month)
dist = spa.earthsun_distance(unixtime, delta_t, numthreads)
@@ -1476,3 +1432,12 @@ def sun_rise_set_transit_geometric(times, latitude, longitude, declination,
sunset = _local_times_from_hours_since_midnight(times, sunset_hour)
transit = _local_times_from_hours_since_midnight(times, transit_hour)
return sunrise, sunset, transit
+
+
+def _warn_how_numba(how):
+ # https://github.com/pvlib/pvlib-python/issues/1060
+ # https://github.com/pvlib/pvlib-python/pull/1098
+ if how is not None:
+ warnings.warn("The 'how' parameter is deprecated; numba is now used "
+ "automatically if it is available.",
+ pvlibDeprecationWarning)
diff --git a/pvlib/spa.py b/pvlib/spa.py
index 743df5ce8e..efef857dac 100644
--- a/pvlib/spa.py
+++ b/pvlib/spa.py
@@ -6,41 +6,10 @@
# Contributors:
# Created by Tony Lorenzo (@alorenzo175), Univ. of Arizona, 2015
-import os
import threading
import warnings
-
import numpy as np
-
-
-# this block is a way to use an environment variable to switch between
-# compiling the functions with numba or just use numpy
-def nocompile(*args, **kwargs):
- return lambda func: func
-
-
-if os.getenv('PVLIB_USE_NUMBA', '0') != '0':
- try:
- from numba import jit, __version__
- except ImportError:
- warnings.warn('Could not import numba, falling back to numpy ' +
- 'calculation')
- jcompile = nocompile
- USE_NUMBA = False
- else:
- major, minor = __version__.split('.')[:2]
- if int(major + minor) >= 17:
- # need at least numba >= 0.17.0
- jcompile = jit
- USE_NUMBA = True
- else:
- warnings.warn('Numba version must be >= 0.17.0, falling back to ' +
- 'numpy')
- jcompile = nocompile
- USE_NUMBA = False
-else:
- jcompile = nocompile
- USE_NUMBA = False
+from pvlib.tools import jit, jit_annotate, NUMBA_ACTIVE
TABLE_1_DICT = {
@@ -419,8 +388,8 @@ def nocompile(*args, **kwargs):
])
-@jcompile('float64(int64, int64, int64, int64, int64, int64, int64)',
- nopython=True)
+@jit('float64(int64, int64, int64, int64, int64, int64, int64)',
+ nopython=True)
def julian_day_dt(year, month, day, hour, minute, second, microsecond):
"""This is the original way to calculate the julian day from the NREL paper.
However, it is much faster to convert to unix/epoch time and then convert
@@ -438,37 +407,37 @@ def julian_day_dt(year, month, day, hour, minute, second, microsecond):
return jd
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def julian_day(unixtime):
jd = unixtime * 1.0 / 86400 + 2440587.5
return jd
-@jcompile('float64(float64, float64)', nopython=True)
+@jit('float64(float64, float64)', nopython=True)
def julian_ephemeris_day(julian_day, delta_t):
jde = julian_day + delta_t * 1.0 / 86400
return jde
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def julian_century(julian_day):
jc = (julian_day - 2451545) * 1.0 / 36525
return jc
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def julian_ephemeris_century(julian_ephemeris_day):
jce = (julian_ephemeris_day - 2451545) * 1.0 / 36525
return jce
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def julian_ephemeris_millennium(julian_ephemeris_century):
jme = julian_ephemeris_century * 1.0 / 10
return jme
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def heliocentric_longitude(jme):
l0 = 0.0
l1 = 0.0
@@ -509,7 +478,7 @@ def heliocentric_longitude(jme):
return l % 360
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def heliocentric_latitude(jme):
b0 = 0.0
b1 = 0.0
@@ -528,7 +497,7 @@ def heliocentric_latitude(jme):
return b
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def heliocentric_radius_vector(jme):
r0 = 0.0
r1 = 0.0
@@ -561,19 +530,19 @@ def heliocentric_radius_vector(jme):
return r
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def geocentric_longitude(heliocentric_longitude):
theta = heliocentric_longitude + 180.0
return theta % 360
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def geocentric_latitude(heliocentric_latitude):
beta = -1.0*heliocentric_latitude
return beta
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def mean_elongation(julian_ephemeris_century):
x0 = (297.85036
+ 445267.111480 * julian_ephemeris_century
@@ -582,7 +551,7 @@ def mean_elongation(julian_ephemeris_century):
return x0
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def mean_anomaly_sun(julian_ephemeris_century):
x1 = (357.52772
+ 35999.050340 * julian_ephemeris_century
@@ -591,7 +560,7 @@ def mean_anomaly_sun(julian_ephemeris_century):
return x1
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def mean_anomaly_moon(julian_ephemeris_century):
x2 = (134.96298
+ 477198.867398 * julian_ephemeris_century
@@ -600,7 +569,7 @@ def mean_anomaly_moon(julian_ephemeris_century):
return x2
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def moon_argument_latitude(julian_ephemeris_century):
x3 = (93.27191
+ 483202.017538 * julian_ephemeris_century
@@ -609,7 +578,7 @@ def moon_argument_latitude(julian_ephemeris_century):
return x3
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def moon_ascending_longitude(julian_ephemeris_century):
x4 = (125.04452
- 1934.136261 * julian_ephemeris_century
@@ -618,8 +587,8 @@ def moon_ascending_longitude(julian_ephemeris_century):
return x4
-@jcompile('float64(float64, float64, float64, float64, float64, float64)',
- nopython=True)
+@jit('float64(float64, float64, float64, float64, float64, float64)',
+ nopython=True)
def longitude_nutation(julian_ephemeris_century, x0, x1, x2, x3, x4):
delta_psi_sum = 0
for row in range(NUTATION_YTERM_ARRAY.shape[0]):
@@ -636,8 +605,8 @@ def longitude_nutation(julian_ephemeris_century, x0, x1, x2, x3, x4):
return delta_psi
-@jcompile('float64(float64, float64, float64, float64, float64, float64)',
- nopython=True)
+@jit('float64(float64, float64, float64, float64, float64, float64)',
+ nopython=True)
def obliquity_nutation(julian_ephemeris_century, x0, x1, x2, x3, x4):
delta_eps_sum = 0.0
for row in range(NUTATION_YTERM_ARRAY.shape[0]):
@@ -654,7 +623,7 @@ def obliquity_nutation(julian_ephemeris_century, x0, x1, x2, x3, x4):
return delta_eps
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def mean_ecliptic_obliquity(julian_ephemeris_millennium):
U = 1.0*julian_ephemeris_millennium/10
e0 = (84381.448 - 4680.93 * U - 1.55 * U**2
@@ -664,7 +633,7 @@ def mean_ecliptic_obliquity(julian_ephemeris_millennium):
return e0
-@jcompile('float64(float64, float64)', nopython=True)
+@jit('float64(float64, float64)', nopython=True)
def true_ecliptic_obliquity(mean_ecliptic_obliquity, obliquity_nutation):
e0 = mean_ecliptic_obliquity
deleps = obliquity_nutation
@@ -672,27 +641,27 @@ def true_ecliptic_obliquity(mean_ecliptic_obliquity, obliquity_nutation):
return e
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def aberration_correction(earth_radius_vector):
deltau = -20.4898 / (3600 * earth_radius_vector)
return deltau
-@jcompile('float64(float64, float64, float64)', nopython=True)
+@jit('float64(float64, float64, float64)', nopython=True)
def apparent_sun_longitude(geocentric_longitude, longitude_nutation,
aberration_correction):
lamd = geocentric_longitude + longitude_nutation + aberration_correction
return lamd
-@jcompile('float64(float64, float64)', nopython=True)
+@jit('float64(float64, float64)', nopython=True)
def mean_sidereal_time(julian_day, julian_century):
v0 = (280.46061837 + 360.98564736629 * (julian_day - 2451545)
+ 0.000387933 * julian_century**2 - julian_century**3 / 38710000)
return v0 % 360.0
-@jcompile('float64(float64, float64, float64)', nopython=True)
+@jit('float64(float64, float64, float64)', nopython=True)
def apparent_sidereal_time(mean_sidereal_time, longitude_nutation,
true_ecliptic_obliquity):
v = mean_sidereal_time + longitude_nutation * np.cos(
@@ -700,7 +669,7 @@ def apparent_sidereal_time(mean_sidereal_time, longitude_nutation,
return v
-@jcompile('float64(float64, float64, float64)', nopython=True)
+@jit('float64(float64, float64, float64)', nopython=True)
def geocentric_sun_right_ascension(apparent_sun_longitude,
true_ecliptic_obliquity,
geocentric_latitude):
@@ -713,7 +682,7 @@ def geocentric_sun_right_ascension(apparent_sun_longitude,
return alpha % 360
-@jcompile('float64(float64, float64, float64)', nopython=True)
+@jit('float64(float64, float64, float64)', nopython=True)
def geocentric_sun_declination(apparent_sun_longitude, true_ecliptic_obliquity,
geocentric_latitude):
delta = np.degrees(np.arcsin(np.sin(np.radians(geocentric_latitude)) *
@@ -724,7 +693,7 @@ def geocentric_sun_declination(apparent_sun_longitude, true_ecliptic_obliquity,
return delta
-@jcompile('float64(float64, float64, float64)', nopython=True)
+@jit('float64(float64, float64, float64)', nopython=True)
def local_hour_angle(apparent_sidereal_time, observer_longitude,
sun_right_ascension):
"""Measured westward from south"""
@@ -732,33 +701,33 @@ def local_hour_angle(apparent_sidereal_time, observer_longitude,
return H % 360
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def equatorial_horizontal_parallax(earth_radius_vector):
xi = 8.794 / (3600 * earth_radius_vector)
return xi
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def uterm(observer_latitude):
u = np.arctan(0.99664719 * np.tan(np.radians(observer_latitude)))
return u
-@jcompile('float64(float64, float64, float64)', nopython=True)
+@jit('float64(float64, float64, float64)', nopython=True)
def xterm(u, observer_latitude, observer_elevation):
x = (np.cos(u) + observer_elevation / 6378140
* np.cos(np.radians(observer_latitude)))
return x
-@jcompile('float64(float64, float64, float64)', nopython=True)
+@jit('float64(float64, float64, float64)', nopython=True)
def yterm(u, observer_latitude, observer_elevation):
y = (0.99664719 * np.sin(u) + observer_elevation / 6378140
* np.sin(np.radians(observer_latitude)))
return y
-@jcompile('float64(float64, float64,float64, float64)', nopython=True)
+@jit('float64(float64, float64,float64, float64)', nopython=True)
def parallax_sun_right_ascension(xterm, equatorial_horizontal_parallax,
local_hour_angle, geocentric_sun_declination):
num = (-xterm * np.sin(np.radians(equatorial_horizontal_parallax))
@@ -770,15 +739,15 @@ def parallax_sun_right_ascension(xterm, equatorial_horizontal_parallax,
return delta_alpha
-@jcompile('float64(float64, float64)', nopython=True)
+@jit('float64(float64, float64)', nopython=True)
def topocentric_sun_right_ascension(geocentric_sun_right_ascension,
parallax_sun_right_ascension):
alpha_prime = geocentric_sun_right_ascension + parallax_sun_right_ascension
return alpha_prime
-@jcompile('float64(float64, float64, float64, float64, float64, float64)',
- nopython=True)
+@jit('float64(float64, float64, float64, float64, float64, float64)',
+ nopython=True)
def topocentric_sun_declination(geocentric_sun_declination, xterm, yterm,
equatorial_horizontal_parallax,
parallax_sun_right_ascension,
@@ -793,14 +762,14 @@ def topocentric_sun_declination(geocentric_sun_declination, xterm, yterm,
return delta
-@jcompile('float64(float64, float64)', nopython=True)
+@jit('float64(float64, float64)', nopython=True)
def topocentric_local_hour_angle(local_hour_angle,
parallax_sun_right_ascension):
H_prime = local_hour_angle - parallax_sun_right_ascension
return H_prime
-@jcompile('float64(float64, float64, float64)', nopython=True)
+@jit('float64(float64, float64, float64)', nopython=True)
def topocentric_elevation_angle_without_atmosphere(observer_latitude,
topocentric_sun_declination,
topocentric_local_hour_angle
@@ -814,7 +783,7 @@ def topocentric_elevation_angle_without_atmosphere(observer_latitude,
return e0
-@jcompile('float64(float64, float64, float64, float64)', nopython=True)
+@jit('float64(float64, float64, float64, float64)', nopython=True)
def atmospheric_refraction_correction(local_pressure, local_temp,
topocentric_elevation_angle_wo_atmosphere,
atmos_refract):
@@ -829,7 +798,7 @@ def atmospheric_refraction_correction(local_pressure, local_temp,
return delta_e
-@jcompile('float64(float64, float64)', nopython=True)
+@jit('float64(float64, float64)', nopython=True)
def topocentric_elevation_angle(topocentric_elevation_angle_without_atmosphere,
atmospheric_refraction_correction):
e = (topocentric_elevation_angle_without_atmosphere
@@ -837,13 +806,13 @@ def topocentric_elevation_angle(topocentric_elevation_angle_without_atmosphere,
return e
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def topocentric_zenith_angle(topocentric_elevation_angle):
theta = 90 - topocentric_elevation_angle
return theta
-@jcompile('float64(float64, float64, float64)', nopython=True)
+@jit('float64(float64, float64, float64)', nopython=True)
def topocentric_astronomers_azimuth(topocentric_local_hour_angle,
topocentric_sun_declination,
observer_latitude):
@@ -856,13 +825,13 @@ def topocentric_astronomers_azimuth(topocentric_local_hour_angle,
return gamma % 360
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def topocentric_azimuth_angle(topocentric_astronomers_azimuth):
phi = topocentric_astronomers_azimuth + 180
return phi % 360
-@jcompile('float64(float64)', nopython=True)
+@jit('float64(float64)', nopython=True)
def sun_mean_longitude(julian_ephemeris_millennium):
M = (280.4664567 + 360007.6982779 * julian_ephemeris_millennium
+ 0.03032028 * julian_ephemeris_millennium**2
@@ -872,7 +841,7 @@ def sun_mean_longitude(julian_ephemeris_millennium):
return M
-@jcompile('float64(float64, float64, float64, float64)', nopython=True)
+@jit('float64(float64, float64, float64, float64)', nopython=True)
def equation_of_time(sun_mean_longitude, geocentric_sun_right_ascension,
longitude_nutation, true_ecliptic_obliquity):
E = (sun_mean_longitude - 0.0057183 - geocentric_sun_right_ascension +
@@ -888,8 +857,8 @@ def equation_of_time(sun_mean_longitude, geocentric_sun_right_ascension,
return E
-@jcompile('void(float64[:], float64[:], float64[:,:])', nopython=True,
- nogil=True)
+@jit('void(float64[:], float64[:], float64[:,:])', nopython=True,
+ nogil=True)
def solar_position_loop(unixtime, loc_args, out):
"""Loop through the time array and calculate the solar position"""
lat = loc_args[0]
@@ -1016,7 +985,6 @@ def solar_position_numpy(unixtime, lat, lon, elev, pressure, temp, delta_t,
this function will not work if the solar position functions were
compiled with numba.
"""
-
jd = julian_day(unixtime)
jde = julian_ephemeris_day(jd, delta_t)
jc = julian_century(jd)
@@ -1068,6 +1036,7 @@ def solar_position_numpy(unixtime, lat, lon, elev, pressure, temp, delta_t,
return theta, theta0, e, e0, phi, eot
+@jit_annotate
def solar_position(unixtime, lat, lon, elev, pressure, temp, delta_t,
atmos_refract, numthreads=8, sst=False, esd=False):
@@ -1135,7 +1104,7 @@ def solar_position(unixtime, lat, lon, elev, pressure, temp, delta_t,
[2] I. Reda and A. Andreas, Corrigendum to Solar position algorithm for
solar radiation applications. Solar Energy, vol. 81, no. 6, p. 838, 2007.
"""
- if USE_NUMBA:
+ if NUMBA_ACTIVE:
do_calc = solar_position_numba
else:
do_calc = solar_position_numpy
diff --git a/pvlib/temperature.py b/pvlib/temperature.py
index 03871143e8..6619f6d7b5 100644
--- a/pvlib/temperature.py
+++ b/pvlib/temperature.py
@@ -5,7 +5,7 @@
import numpy as np
import pandas as pd
-from pvlib.tools import sind
+from pvlib.tools import jit, jit_annotate
TEMPERATURE_MODEL_PARAMETERS = {
'sapm': {
@@ -491,6 +491,7 @@ def ross(poa_global, temp_air, noct):
return temp_air + (noct - 20.) / 80. * poa_global * 0.1
+@jit(nopython=True)
def _fuentes_hconv(tave, windmod, tinoct, temp_delta, xlen, tilt,
check_reynold):
# Calculate the convective coefficient as in Fuentes 1987 -- a mixture of
@@ -509,7 +510,7 @@ def _fuentes_hconv(tave, windmod, tinoct, temp_delta, xlen, tilt,
hforce = 0.8600 / reynold**0.5 * densair * windmod * 1007 / 0.71**0.67
# free convection via Grashof number
# NB: Fuentes hardwires sind(tilt) as 0.5 for tilt=30
- grashof = 9.8 / tave * temp_delta * xlen**3 / visair**2 * sind(tilt)
+ grashof = 9.8 / tave * temp_delta * xlen**3 / visair**2 * np.sin(tilt)
# product of Nusselt number and (k/l)
hfree = 0.21 * (grashof * 0.71)**0.32 * condair / xlen
# combine free and forced components
@@ -517,11 +518,51 @@ def _fuentes_hconv(tave, windmod, tinoct, temp_delta, xlen, tilt,
return hconv
+@jit(nopython=True)
+def _fuentes_iteration(tmod0, sun0, tmod, sun, tamb, tsky, tinoct, xlen, emiss,
+ cap, windmod, convrat, tgrat, surface_tilt, dtime,
+ boltz):
+ # solve the heat transfer equation, iterating because the heat loss
+ # terms depend on tmod. NB Fuentes doesn't show that 10 iterations is
+ # sufficient for convergence.
+ for j in range(10):
+ # overall convective coefficient
+ tave = (tmod + tamb) / 2
+ hconv = convrat * _fuentes_hconv(tave, windmod, tinoct,
+ abs(tmod-tamb), xlen,
+ surface_tilt, True)
+ # sky radiation coefficient (Equation 3)
+ hsky = emiss * boltz * (tmod**2 + tsky**2) * (tmod + tsky)
+ # ground radiation coeffieicient (Equation 4)
+ tground = tamb + tgrat * (tmod - tamb)
+ hground = emiss * boltz * (tmod**2 + tground**2) * (tmod + tground)
+ # thermal lag -- Equation 8
+ eigen = - (hconv + hsky + hground) / cap * dtime * 3600
+ # not sure why this check is done, maybe as a speed optimization?
+ if eigen > -10:
+ ex = np.exp(eigen)
+ else:
+ ex = 0
+ # Equation 7 -- note that `sun` and `sun0` already account for
+ # absorption (alpha)
+ tmod = tmod0 * ex + (
+ (1 - ex) * (
+ hconv * tamb
+ + hsky * tsky
+ + hground * tground
+ + sun0
+ + (sun - sun0) / eigen
+ ) + sun - sun0
+ ) / (hconv + hsky + hground)
+ return tmod, sun
+
+
def _hydraulic_diameter(width, height):
# calculate the hydraulic diameter of a rectangle
return 2 * (width * height) / (width + height)
+@jit_annotate
def fuentes(poa_global, temp_air, wind_speed, noct_installed, module_height=5,
wind_height=9.144, emissivity=0.84, absorption=0.83,
surface_tilt=30, module_width=0.31579, module_length=1.2):
@@ -610,6 +651,7 @@ def fuentes(poa_global, temp_air, wind_speed, noct_installed, module_height=5,
# specific heat of the module.
cap0 = 11000
tinoct = noct_installed + 273.15
+ surface_tilt = np.radians(surface_tilt)
# convective coefficient of top surface of module at NOCT
windmod = 1.0
@@ -640,10 +682,6 @@ def fuentes(poa_global, temp_air, wind_speed, noct_installed, module_height=5,
if tinoct > 321.15:
cap = cap * (1 + (tinoct - 321.15) / 12)
- # iterate through timeseries inputs
- sun0 = 0
- tmod0 = 293.15
-
# n.b. the way Fuentes calculates the first timedelta makes it seem like
# the value doesn't matter -- rather than recreate it here, just assume
# it's the same as the second timedelta:
@@ -662,45 +700,17 @@ def fuentes(poa_global, temp_air, wind_speed, noct_installed, module_height=5,
# behave well if wind == 0?
windmod_array = wind_speed * (module_height/wind_height)**0.2 + 1e-4
- tmod0 = 293.15
+ sun0 = 0
+ tmod = tmod0 = 293.15
tmod_array = np.zeros_like(poa_global)
iterator = zip(tamb_array, sun_array, windmod_array, tsky_array,
timedelta_hours)
for i, (tamb, sun, windmod, tsky, dtime) in enumerate(iterator):
- # solve the heat transfer equation, iterating because the heat loss
- # terms depend on tmod. NB Fuentes doesn't show that 10 iterations is
- # sufficient for convergence.
- tmod = tmod0
- for j in range(10):
- # overall convective coefficient
- tave = (tmod + tamb) / 2
- hconv = convrat * _fuentes_hconv(tave, windmod, tinoct,
- abs(tmod-tamb), xlen,
- surface_tilt, True)
- # sky radiation coefficient (Equation 3)
- hsky = emiss * boltz * (tmod**2 + tsky**2) * (tmod + tsky)
- # ground radiation coeffieicient (Equation 4)
- tground = tamb + tgrat * (tmod - tamb)
- hground = emiss * boltz * (tmod**2 + tground**2) * (tmod + tground)
- # thermal lag -- Equation 8
- eigen = - (hconv + hsky + hground) / cap * dtime * 3600
- # not sure why this check is done, maybe as a speed optimization?
- if eigen > -10:
- ex = np.exp(eigen)
- else:
- ex = 0
- # Equation 7 -- note that `sun` and `sun0` already account for
- # absorption (alpha)
- tmod = tmod0 * ex + (
- (1 - ex) * (
- hconv * tamb
- + hsky * tsky
- + hground * tground
- + sun0
- + (sun - sun0) / eigen
- ) + sun - sun0
- ) / (hconv + hsky + hground)
+ tmod, sun = _fuentes_iteration(tmod0, sun0, tmod, sun, tamb, tsky,
+ tinoct, xlen, emiss, cap, windmod,
+ convrat, tgrat, surface_tilt, dtime,
+ boltz)
tmod_array[i] = tmod
tmod0 = tmod
sun0 = sun
diff --git a/pvlib/tests/conftest.py b/pvlib/tests/conftest.py
index aa04af406d..bfb013fe8a 100644
--- a/pvlib/tests/conftest.py
+++ b/pvlib/tests/conftest.py
@@ -121,23 +121,17 @@ def has_spa_c():
requires_spa_c = pytest.mark.skipif(not has_spa_c(), reason="requires spa_c")
-def has_numba():
- try:
- import numba
- except ImportError:
- return False
- else:
- vers = numba.__version__.split('.')
- if int(vers[0] + vers[1]) < 17:
- return False
- else:
- return True
-
+try:
+ import numba # noqa: F401
+ has_numba = True
+except ImportError:
+ has_numba = False
-requires_numba = pytest.mark.skipif(not has_numba(), reason="requires numba")
+requires_numba = pytest.mark.skipif(not has_numba, reason="requires numba")
+requires_no_numba = pytest.mark.skipif(has_numba, reason="requires no numba")
try:
- import siphon
+ import siphon # noqa: F401
has_siphon = True
except ImportError:
has_siphon = False
diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py
index c45fd5026f..1803c78868 100644
--- a/pvlib/tests/test_modelchain.py
+++ b/pvlib/tests/test_modelchain.py
@@ -1735,7 +1735,7 @@ def test_ModelChain___repr__(sapm_dc_snl_ac_system, location, strategy,
' orientation_strategy: ' + strategy_str,
' clearsky_model: ineichen',
' transposition_model: haydavies',
- ' solar_position_method: nrel_numpy',
+ ' solar_position_method: nrel',
' airmass_model: kastenyoung1989',
' dc_model: sapm',
' ac_model: sandia_inverter',
diff --git a/pvlib/tests/test_solarposition.py b/pvlib/tests/test_solarposition.py
index 3d29749fb2..185f5fa20c 100644
--- a/pvlib/tests/test_solarposition.py
+++ b/pvlib/tests/test_solarposition.py
@@ -12,7 +12,12 @@
from pvlib.location import Location
from pvlib import solarposition, spa
-from conftest import requires_ephem, requires_spa_c, requires_numba
+from conftest import (
+ requires_ephem, requires_spa_c, requires_numba, requires_no_numba
+)
+
+from pvlib._deprecation import pvlibDeprecationWarning
+from conftest import fail_on_pvlib_version
# setup times and locations to be tested.
@@ -144,8 +149,7 @@ def test_spa_python_numpy_physical(expected_solpos, golden_mst):
golden_mst.longitude,
pressure=82000,
temperature=11, delta_t=67,
- atmos_refract=0.5667,
- how='numpy')
+ atmos_refract=0.5667)
expected_solpos.index = times
assert_frame_equal(expected_solpos, ephem_data[expected_solpos.columns])
@@ -157,8 +161,7 @@ def test_spa_python_numpy_physical_dst(expected_solpos, golden):
golden.longitude,
pressure=82000,
temperature=11, delta_t=67,
- atmos_refract=0.5667,
- how='numpy')
+ atmos_refract=0.5667)
expected_solpos.index = times
assert_frame_equal(expected_solpos, ephem_data[expected_solpos.columns])
@@ -511,6 +514,7 @@ def test_get_solarposition_altitude(altitude, expected, golden):
])
def test_get_solarposition_deltat(delta_t, method, expected_solpos_multi,
golden):
+ # TODO: update this
times = pd.date_range(datetime.datetime(2003, 10, 17, 13, 30, 30),
periods=2, freq='D', tz=golden.tz)
with warnings.catch_warnings():
@@ -581,6 +585,7 @@ def test_equation_of_time():
assert np.allclose(eot_2 / eot_rng, eot / eot_rng, atol=0.4) # pvcdrom
+@requires_no_numba
def test_declination():
times = pd.date_range(start="1/1/2015 0:00", end="12/31/2015 23:00",
freq="H")
@@ -742,55 +747,40 @@ def test_sun_rise_set_transit_geometric(expected_rise_set_spa, golden_mst):
atol=np.abs(expected_transit_error).max())
-# put numba tests at end of file to minimize reloading
-
@requires_numba
-def test_spa_python_numba_physical(expected_solpos, golden_mst):
- times = pd.date_range(datetime.datetime(2003, 10, 17, 12, 30, 30),
- periods=1, freq='D', tz=golden_mst.tz)
- with warnings.catch_warnings():
- # don't warn on method reload or num threads
- # ensure that numpy is the most recently used method so that
- # we can use the warns filter below
- warnings.simplefilter("ignore")
- ephem_data = solarposition.spa_python(times, golden_mst.latitude,
- golden_mst.longitude,
- pressure=82000,
- temperature=11, delta_t=67,
- atmos_refract=0.5667,
- how='numpy', numthreads=1)
- with pytest.warns(UserWarning):
- ephem_data = solarposition.spa_python(times, golden_mst.latitude,
- golden_mst.longitude,
- pressure=82000,
- temperature=11, delta_t=67,
- atmos_refract=0.5667,
- how='numba', numthreads=1)
+@pytest.mark.parametrize('location,date',
+ [('golden', '2003-10-17 13:30:30'),
+ ('golden_mst', '2003-10-17 12:30:30')])
+def test_spa_python_numba_physical(expected_solpos, location, date, request):
+
+ # workaround for https://github.com/pytest-dev/pytest/issues/349
+ location = request.getfixturevalue(location)
+
+ times = pd.date_range(date, periods=1, freq='D', tz=location.tz)
+
+ ephem_data = solarposition.spa_python(times, location.latitude,
+ location.longitude,
+ pressure=82000,
+ temperature=11, delta_t=67,
+ atmos_refract=0.5667,
+ numthreads=1)
expected_solpos.index = times
assert_frame_equal(expected_solpos, ephem_data[expected_solpos.columns])
-@requires_numba
-def test_spa_python_numba_physical_dst(expected_solpos, golden):
- times = pd.date_range(datetime.datetime(2003, 10, 17, 13, 30, 30),
+@fail_on_pvlib_version('0.10')
+def test_spa_python_deprecated(golden):
+
+ times = pd.date_range(datetime.datetime(2003, 10, 17, 12, 30, 30),
periods=1, freq='D', tz=golden.tz)
- with warnings.catch_warnings():
- # don't warn on method reload or num threads
- warnings.simplefilter("ignore")
- ephem_data = solarposition.spa_python(times, golden.latitude,
- golden.longitude, pressure=82000,
- temperature=11, delta_t=67,
- atmos_refract=0.5667,
- how='numba', numthreads=1)
- expected_solpos.index = times
- assert_frame_equal(expected_solpos, ephem_data[expected_solpos.columns])
+ match = "The 'how' parameter is deprecated;"
+ with pytest.warns(pvlibDeprecationWarning, match=match):
- with pytest.warns(UserWarning):
- # test that we get a warning when reloading to use numpy only
- ephem_data = solarposition.spa_python(times, golden.latitude,
- golden.longitude,
- pressure=82000,
- temperature=11, delta_t=67,
- atmos_refract=0.5667,
- how='numpy', numthreads=1)
+ _ = solarposition.spa_python(times, golden.latitude,
+ golden.longitude,
+ pressure=82000,
+ temperature=11, delta_t=67,
+ atmos_refract=0.5667,
+ how='numba',
+ numthreads=1)
diff --git a/pvlib/tests/test_spa.py b/pvlib/tests/test_spa.py
index ecd28a5123..8ed43051f9 100644
--- a/pvlib/tests/test_spa.py
+++ b/pvlib/tests/test_spa.py
@@ -2,29 +2,15 @@
import datetime as dt
import warnings
-try:
- from importlib import reload
-except ImportError:
- try:
- from imp import reload
- except ImportError:
- pass
+from importlib import reload
import numpy as np
from numpy.testing import assert_almost_equal
import pandas as pd
+import pvlib
import unittest
-import pytest
-
-
-try:
- from numba import __version__ as numba_version
- numba_version_int = int(numba_version.split('.')[0] +
- numba_version.split('.')[1])
-except ImportError:
- numba_version_int = 0
-
+from conftest import requires_numba
times = (pd.date_range('2003-10-17 12:30:30', periods=1, freq='D')
.tz_localize('MST'))
@@ -378,34 +364,48 @@ class NumpySpaTest(unittest.TestCase, SpaBase):
"""Import spa without compiling to numba then run tests"""
@classmethod
def setUpClass(self):
- os.environ['PVLIB_USE_NUMBA'] = '0'
- import pvlib.spa as spa
- spa = reload(spa)
- self.spa = spa
+ try:
+ import numba
+ numba.config.DISABLE_JIT = 1
+ except ImportError:
+ pass
+
+ self.pvlib = reload(pvlib)
+ self.pvlib.tools = reload(pvlib.tools)
+ self.spa = reload(pvlib.spa)
@classmethod
def tearDownClass(self):
- del os.environ['PVLIB_USE_NUMBA']
+ try:
+ import numba
+ numba.config.DISABLE_JIT = 0
+ except ImportError:
+ pass
+
+ def test_numba_active(self):
+ assert not self.pvlib.tools.NUMBA_ACTIVE
def test_julian_day(self):
assert_almost_equal(JD, self.spa.julian_day(unixtimes)[0], 6)
-@pytest.mark.skipif(numba_version_int < 17,
- reason='Numba not installed or version not >= 0.17.0')
+@requires_numba
class NumbaSpaTest(unittest.TestCase, SpaBase):
"""Import spa, compiling to numba, and run tests"""
@classmethod
def setUpClass(self):
- os.environ['PVLIB_USE_NUMBA'] = '1'
- if numba_version_int >= 17:
- import pvlib.spa as spa
- spa = reload(spa)
- self.spa = spa
+ import numba
+ numba.config.DISABLE_JIT = 0
+ self.pvlib = reload(pvlib)
+ self.pvlib.tools = reload(pvlib.tools)
+ self.spa = reload(pvlib.spa)
@classmethod
def tearDownClass(self):
- del os.environ['PVLIB_USE_NUMBA']
+ pass
+
+ def test_numba_active(self):
+ assert self.pvlib.tools.NUMBA_ACTIVE
def test_julian_day(self):
assert_almost_equal(JD, self.spa.julian_day(unixtimes[0]), 6)
diff --git a/pvlib/tests/test_temperature.py b/pvlib/tests/test_temperature.py
index f8ea3a8bc1..0ebc04e005 100644
--- a/pvlib/tests/test_temperature.py
+++ b/pvlib/tests/test_temperature.py
@@ -189,8 +189,8 @@ def test_fuentes(filename, inoct):
is_daytime = (inputs['poa_global'] > 0) & ~is_dawn
# the accuracy is probably higher than 3 digits here, but the PVWatts
# export data has low precision so can only test up to 3 digits
- assert_series_equal(expected_tcell[is_daytime].round(3),
- actual_tcell[is_daytime].round(3))
+ day_difference = expected_tcell[is_daytime] - actual_tcell[is_daytime]
+ assert (day_difference.abs() < 1e-3).all()
# use lower precision for dawn times to accommodate the dawn transient
error = actual_tcell[is_dawn] - expected_tcell[is_dawn]
assert (error.abs() < 0.1).all()
diff --git a/pvlib/tools.py b/pvlib/tools.py
index b6ee3e7c3a..960ce8963a 100644
--- a/pvlib/tools.py
+++ b/pvlib/tools.py
@@ -6,6 +6,7 @@
import numpy as np
import pandas as pd
import pytz
+import textwrap
def cosd(angle):
@@ -318,3 +319,41 @@ def _golden_sect_DataFrame(params, VL, VH, func):
raise Exception("EXCEPTION:iterations exceeded maximum (50)")
return func(df, 'V1'), df['V1']
+
+
+# Enable numba JIT if it's installed, otherwise just define a no-op decorator
+def _dummy_jit(func=None, *args, **kwargs):
+ # accommodate using as either `@jit` or `@jit()`
+ def wrapper(func):
+ return func
+ if callable(func):
+ return func
+ return wrapper
+
+
+NUMBA_ACTIVE = False
+jit = _dummy_jit
+
+try:
+ import numba
+ jit = numba.jit
+ if numba.config.DISABLE_JIT == 0:
+ # NUMBA_DISABLE_JIT will turn the decorator into a no-op, but
+ # for cases like the SPA where we need to switch manually
+ # between functions, we need a flag for which branch to take:
+ NUMBA_ACTIVE = True
+except ImportError:
+ pass
+
+
+def jit_annotate(func):
+ original_docstring = func.__doc__
+ annotation = "\n".join([
+ "",
+ ".. note::",
+ " This function can be accelerated using Numba;",
+ " see :ref:`using_numba`.",
+ ])
+ new_docstring = textwrap.dedent(original_docstring) + annotation
+ func.__doc__ = new_docstring
+ return func