From 1aeafaf633298fe952d06c095a55fbf39689a01b Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Thu, 19 Nov 2020 20:21:40 -0700 Subject: [PATCH 01/18] jit fuentes --- pvlib/temperature.py | 76 +++++++++++++++++++++++++------------------- pvlib/tools.py | 16 ++++++++++ 2 files changed, 59 insertions(+), 33 deletions(-) diff --git a/pvlib/temperature.py b/pvlib/temperature.py index 1f27180a9a..c9600aa33b 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 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,6 +518,41 @@ 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): + # 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) @@ -610,6 +646,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 @@ -668,39 +705,12 @@ def fuentes(poa_global, temp_air, wind_speed, noct_installed, module_height=5, 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/tools.py b/pvlib/tools.py index b6ee3e7c3a..6d308297d4 100644 --- a/pvlib/tools.py +++ b/pvlib/tools.py @@ -318,3 +318,19 @@ 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 func is not None: + return func + return wrapper + + +try: + from numba import jit +except ImportError: + jit = dummy_jit From 7c9ee259100bc92a800433725ade821e4a3ff578 Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Thu, 19 Nov 2020 22:13:01 -0700 Subject: [PATCH 02/18] cleanup --- pvlib/temperature.py | 74 ++++++++++++++++----------------- pvlib/tests/test_temperature.py | 4 +- 2 files changed, 37 insertions(+), 41 deletions(-) diff --git a/pvlib/temperature.py b/pvlib/temperature.py index c9600aa33b..6d7e674d16 100644 --- a/pvlib/temperature.py +++ b/pvlib/temperature.py @@ -522,34 +522,35 @@ def _fuentes_hconv(tave, windmod, tinoct, temp_delta, xlen, tilt, def _fuentes_iteration(tmod0, sun0, tmod, sun, tamb, tsky, tinoct, xlen, emiss, cap, windmod, convrat, tgrat, surface_tilt, dtime, boltz): - # 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) + 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 @@ -677,10 +678,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: @@ -699,18 +696,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): - tmod = tmod0 - for j in range(10): - tmod, sun = _fuentes_iteration(tmod0, sun0, tmod, sun, tamb, tsky, - tinoct, xlen, emiss, cap, windmod, - convrat, tgrat, surface_tilt, dtime, - boltz) + 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/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() From 746780c95f196eaf66ac784e01d90c9806c2e8b4 Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Fri, 20 Nov 2020 10:11:42 -0700 Subject: [PATCH 03/18] add jit_annotate decorator and docs section --- docs/sphinx/source/installation.rst | 20 ++++++++++++++++++++ pvlib/temperature.py | 3 ++- pvlib/tools.py | 14 ++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/docs/sphinx/source/installation.rst b/docs/sphinx/source/installation.rst index 39b7bfc974..b747a4efed 100644 --- a/docs/sphinx/source/installation.rst +++ b/docs/sphinx/source/installation.rst @@ -270,6 +270,26 @@ 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 +------------------ + +It is not always possible to use python and numpy to create an efficient +implementation of complex modeling algorithms. As a result, some function +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 API Reference. + +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. For more details, see numba's +`documentation `_. + + .. _references: References diff --git a/pvlib/temperature.py b/pvlib/temperature.py index 6d7e674d16..75bfbf692d 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 jit +from pvlib.tools import jit, jit_annotate TEMPERATURE_MODEL_PARAMETERS = { 'sapm': { @@ -559,6 +559,7 @@ def _hydraulic_diameter(width, height): 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): diff --git a/pvlib/tools.py b/pvlib/tools.py index 6d308297d4..cfe849dfec 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): @@ -334,3 +335,16 @@ def wrapper(func): from numba import jit except ImportError: jit = dummy_jit + + +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 From 1212a90021b30941e9118ea455cd0aaa2caab715 Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Fri, 20 Nov 2020 10:13:54 -0700 Subject: [PATCH 04/18] put back lost comment --- pvlib/temperature.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pvlib/temperature.py b/pvlib/temperature.py index 75bfbf692d..e116944616 100644 --- a/pvlib/temperature.py +++ b/pvlib/temperature.py @@ -522,6 +522,9 @@ def _fuentes_hconv(tave, windmod, tinoct, temp_delta, xlen, tilt, 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 From 61c17335380bce2a6d877fce215dc4457a0967de Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Wed, 25 Nov 2020 19:57:09 -0700 Subject: [PATCH 05/18] remodel the spa --- pvlib/solarposition.py | 83 +++++-------------------- pvlib/spa.py | 133 +++++++++++++++------------------------- pvlib/tests/test_spa.py | 60 +++++++++--------- pvlib/tools.py | 15 ++++- 4 files changed, 110 insertions(+), 181 deletions(-) diff --git a/pvlib/solarposition.py b/pvlib/solarposition.py index 040f9d5f14..5dab66624f 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,13 @@ 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. See (TODO)', 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 +232,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, numthreads=4, **kwargs): """ Calculate the solar position using a python implementation of the NREL SPA algorithm. @@ -314,12 +274,8 @@ 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. numthreads : int, optional, default 4 - Number of threads to use if how == 'numba'. + Number of threads to use when numba acceleration is used. Returns ------- @@ -367,8 +323,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,6 +338,7 @@ def spa_python(time, latitude, longitude, return result +@jit_annotate def sun_rise_set_transit_spa(times, latitude, longitude, how='numpy', delta_t=67.0, numthreads=4): """ @@ -447,8 +402,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( @@ -1003,8 +956,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) diff --git a/pvlib/spa.py b/pvlib/spa.py index 743df5ce8e..618472208c 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,14 +739,14 @@ 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)', +@jit('float64(float64, float64, float64, float64, float64, float64)', nopython=True) def topocentric_sun_declination(geocentric_sun_declination, xterm, yterm, equatorial_horizontal_parallax, @@ -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/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/tools.py b/pvlib/tools.py index cfe849dfec..c9b20ec53f 100644 --- a/pvlib/tools.py +++ b/pvlib/tools.py @@ -322,7 +322,7 @@ def _golden_sect_DataFrame(params, VL, VH, func): # Enable numba JIT if it's installed, otherwise just define a no-op decorator -def dummy_jit(func=None, *args, **kwargs): +def _dummy_jit(func=None, *args, **kwargs): # accommodate using as either `@jit` or `@jit()` def wrapper(func): return func @@ -331,10 +331,19 @@ def wrapper(func): return wrapper +NUMBA_ACTIVE = False +jit = _dummy_jit + try: - from numba import jit + 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: - jit = dummy_jit + pass def jit_annotate(func): From e61222c9b4bc4f36d94ecab5c3ae9523a8e24de5 Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Wed, 25 Nov 2020 20:07:39 -0700 Subject: [PATCH 06/18] more docs --- docs/sphinx/source/installation.rst | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/sphinx/source/installation.rst b/docs/sphinx/source/installation.rst index b747a4efed..ac4f3775f3 100644 --- a/docs/sphinx/source/installation.rst +++ b/docs/sphinx/source/installation.rst @@ -286,7 +286,14 @@ with numba have a corresponding note on their page in the API Reference. 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. For more details, see numba's +``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 `_. From ac872d138272f1ef237e07a7814e01f9eff04afc Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Wed, 25 Nov 2020 20:13:29 -0700 Subject: [PATCH 07/18] deprecations --- pvlib/solarposition.py | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/pvlib/solarposition.py b/pvlib/solarposition.py index 5dab66624f..5835b76cbb 100644 --- a/pvlib/solarposition.py +++ b/pvlib/solarposition.py @@ -339,7 +339,7 @@ def spa_python(time, latitude, longitude, @jit_annotate -def sun_rise_set_transit_spa(times, latitude, longitude, how='numpy', +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 @@ -368,12 +368,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 ------- @@ -389,6 +387,10 @@ def sun_rise_set_transit_spa(times, latitude, longitude, how='numpy', """ # Added by Tony Lorenzo (@alorenzo175), University of Arizona, 2015 + if how is not None: + warnings.warn("The 'how' parameter is deprecated; see (TODO)", + pvlibDeprecationWarning) + lat = latitude lon = longitude @@ -907,7 +909,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. @@ -919,10 +921,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 @@ -934,7 +934,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 ------- @@ -948,6 +948,10 @@ def nrel_earthsun_distance(time, how='numpy', delta_t=67.0, numthreads=4): USA, http://www.nrel.gov. """ + if how is not None: + warnings.warn("The 'how' parameter is deprecated; see (TODO)", + pvlibDeprecationWarning) + if not isinstance(time, pd.DatetimeIndex): try: time = pd.DatetimeIndex(time) From c078e788c029d8274de0dca4f0b7796e0bb3bf31 Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Wed, 25 Nov 2020 20:25:51 -0700 Subject: [PATCH 08/18] fix no-op jit decorator --- pvlib/tools.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pvlib/tools.py b/pvlib/tools.py index c9b20ec53f..960ce8963a 100644 --- a/pvlib/tools.py +++ b/pvlib/tools.py @@ -326,7 +326,7 @@ def _dummy_jit(func=None, *args, **kwargs): # accommodate using as either `@jit` or `@jit()` def wrapper(func): return func - if func is not None: + if callable(func): return func return wrapper From 76eb20befc6e8411ee807fec87fdaddc626be026 Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Thu, 26 Nov 2020 09:46:58 -0700 Subject: [PATCH 09/18] remove signatures --- pvlib/spa.py | 93 +++++++++++++++++++++++++--------------------------- 1 file changed, 44 insertions(+), 49 deletions(-) diff --git a/pvlib/spa.py b/pvlib/spa.py index 618472208c..8c9f7210fc 100644 --- a/pvlib/spa.py +++ b/pvlib/spa.py @@ -388,8 +388,7 @@ ]) -@jit('float64(int64, int64, int64, int64, int64, int64, int64)', - nopython=True) +@jit(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 @@ -407,37 +406,37 @@ def julian_day_dt(year, month, day, hour, minute, second, microsecond): return jd -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def julian_day(unixtime): jd = unixtime * 1.0 / 86400 + 2440587.5 return jd -@jit('float64(float64, float64)', nopython=True) +@jit(nopython=True) def julian_ephemeris_day(julian_day, delta_t): jde = julian_day + delta_t * 1.0 / 86400 return jde -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def julian_century(julian_day): jc = (julian_day - 2451545) * 1.0 / 36525 return jc -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def julian_ephemeris_century(julian_ephemeris_day): jce = (julian_ephemeris_day - 2451545) * 1.0 / 36525 return jce -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def julian_ephemeris_millennium(julian_ephemeris_century): jme = julian_ephemeris_century * 1.0 / 10 return jme -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def heliocentric_longitude(jme): l0 = 0.0 l1 = 0.0 @@ -478,7 +477,7 @@ def heliocentric_longitude(jme): return l % 360 -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def heliocentric_latitude(jme): b0 = 0.0 b1 = 0.0 @@ -497,7 +496,7 @@ def heliocentric_latitude(jme): return b -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def heliocentric_radius_vector(jme): r0 = 0.0 r1 = 0.0 @@ -530,19 +529,19 @@ def heliocentric_radius_vector(jme): return r -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def geocentric_longitude(heliocentric_longitude): theta = heliocentric_longitude + 180.0 return theta % 360 -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def geocentric_latitude(heliocentric_latitude): beta = -1.0*heliocentric_latitude return beta -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def mean_elongation(julian_ephemeris_century): x0 = (297.85036 + 445267.111480 * julian_ephemeris_century @@ -551,7 +550,7 @@ def mean_elongation(julian_ephemeris_century): return x0 -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def mean_anomaly_sun(julian_ephemeris_century): x1 = (357.52772 + 35999.050340 * julian_ephemeris_century @@ -560,7 +559,7 @@ def mean_anomaly_sun(julian_ephemeris_century): return x1 -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def mean_anomaly_moon(julian_ephemeris_century): x2 = (134.96298 + 477198.867398 * julian_ephemeris_century @@ -569,7 +568,7 @@ def mean_anomaly_moon(julian_ephemeris_century): return x2 -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def moon_argument_latitude(julian_ephemeris_century): x3 = (93.27191 + 483202.017538 * julian_ephemeris_century @@ -578,7 +577,7 @@ def moon_argument_latitude(julian_ephemeris_century): return x3 -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def moon_ascending_longitude(julian_ephemeris_century): x4 = (125.04452 - 1934.136261 * julian_ephemeris_century @@ -587,8 +586,7 @@ def moon_ascending_longitude(julian_ephemeris_century): return x4 -@jit('float64(float64, float64, float64, float64, float64, float64)', - nopython=True) +@jit(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]): @@ -605,8 +603,7 @@ def longitude_nutation(julian_ephemeris_century, x0, x1, x2, x3, x4): return delta_psi -@jit('float64(float64, float64, float64, float64, float64, float64)', - nopython=True) +@jit(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]): @@ -623,7 +620,7 @@ def obliquity_nutation(julian_ephemeris_century, x0, x1, x2, x3, x4): return delta_eps -@jit('float64(float64)', nopython=True) +@jit(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 @@ -633,7 +630,7 @@ def mean_ecliptic_obliquity(julian_ephemeris_millennium): return e0 -@jit('float64(float64, float64)', nopython=True) +@jit(nopython=True) def true_ecliptic_obliquity(mean_ecliptic_obliquity, obliquity_nutation): e0 = mean_ecliptic_obliquity deleps = obliquity_nutation @@ -641,27 +638,27 @@ def true_ecliptic_obliquity(mean_ecliptic_obliquity, obliquity_nutation): return e -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def aberration_correction(earth_radius_vector): deltau = -20.4898 / (3600 * earth_radius_vector) return deltau -@jit('float64(float64, float64, float64)', nopython=True) +@jit(nopython=True) def apparent_sun_longitude(geocentric_longitude, longitude_nutation, aberration_correction): lamd = geocentric_longitude + longitude_nutation + aberration_correction return lamd -@jit('float64(float64, float64)', nopython=True) +@jit(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 -@jit('float64(float64, float64, float64)', nopython=True) +@jit(nopython=True) def apparent_sidereal_time(mean_sidereal_time, longitude_nutation, true_ecliptic_obliquity): v = mean_sidereal_time + longitude_nutation * np.cos( @@ -669,7 +666,7 @@ def apparent_sidereal_time(mean_sidereal_time, longitude_nutation, return v -@jit('float64(float64, float64, float64)', nopython=True) +@jit(nopython=True) def geocentric_sun_right_ascension(apparent_sun_longitude, true_ecliptic_obliquity, geocentric_latitude): @@ -682,7 +679,7 @@ def geocentric_sun_right_ascension(apparent_sun_longitude, return alpha % 360 -@jit('float64(float64, float64, float64)', nopython=True) +@jit(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)) * @@ -693,7 +690,7 @@ def geocentric_sun_declination(apparent_sun_longitude, true_ecliptic_obliquity, return delta -@jit('float64(float64, float64, float64)', nopython=True) +@jit(nopython=True) def local_hour_angle(apparent_sidereal_time, observer_longitude, sun_right_ascension): """Measured westward from south""" @@ -701,33 +698,33 @@ def local_hour_angle(apparent_sidereal_time, observer_longitude, return H % 360 -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def equatorial_horizontal_parallax(earth_radius_vector): xi = 8.794 / (3600 * earth_radius_vector) return xi -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def uterm(observer_latitude): u = np.arctan(0.99664719 * np.tan(np.radians(observer_latitude))) return u -@jit('float64(float64, float64, float64)', nopython=True) +@jit(nopython=True) def xterm(u, observer_latitude, observer_elevation): x = (np.cos(u) + observer_elevation / 6378140 * np.cos(np.radians(observer_latitude))) return x -@jit('float64(float64, float64, float64)', nopython=True) +@jit(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 -@jit('float64(float64, float64,float64, float64)', nopython=True) +@jit(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)) @@ -739,15 +736,14 @@ def parallax_sun_right_ascension(xterm, equatorial_horizontal_parallax, return delta_alpha -@jit('float64(float64, float64)', nopython=True) +@jit(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 -@jit('float64(float64, float64, float64, float64, float64, float64)', - nopython=True) +@jit(nopython=True) def topocentric_sun_declination(geocentric_sun_declination, xterm, yterm, equatorial_horizontal_parallax, parallax_sun_right_ascension, @@ -762,14 +758,14 @@ def topocentric_sun_declination(geocentric_sun_declination, xterm, yterm, return delta -@jit('float64(float64, float64)', nopython=True) +@jit(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 -@jit('float64(float64, float64, float64)', nopython=True) +@jit(nopython=True) def topocentric_elevation_angle_without_atmosphere(observer_latitude, topocentric_sun_declination, topocentric_local_hour_angle @@ -783,7 +779,7 @@ def topocentric_elevation_angle_without_atmosphere(observer_latitude, return e0 -@jit('float64(float64, float64, float64, float64)', nopython=True) +@jit(nopython=True) def atmospheric_refraction_correction(local_pressure, local_temp, topocentric_elevation_angle_wo_atmosphere, atmos_refract): @@ -798,7 +794,7 @@ def atmospheric_refraction_correction(local_pressure, local_temp, return delta_e -@jit('float64(float64, float64)', nopython=True) +@jit(nopython=True) def topocentric_elevation_angle(topocentric_elevation_angle_without_atmosphere, atmospheric_refraction_correction): e = (topocentric_elevation_angle_without_atmosphere @@ -806,13 +802,13 @@ def topocentric_elevation_angle(topocentric_elevation_angle_without_atmosphere, return e -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def topocentric_zenith_angle(topocentric_elevation_angle): theta = 90 - topocentric_elevation_angle return theta -@jit('float64(float64, float64, float64)', nopython=True) +@jit(nopython=True) def topocentric_astronomers_azimuth(topocentric_local_hour_angle, topocentric_sun_declination, observer_latitude): @@ -825,13 +821,13 @@ def topocentric_astronomers_azimuth(topocentric_local_hour_angle, return gamma % 360 -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def topocentric_azimuth_angle(topocentric_astronomers_azimuth): phi = topocentric_astronomers_azimuth + 180 return phi % 360 -@jit('float64(float64)', nopython=True) +@jit(nopython=True) def sun_mean_longitude(julian_ephemeris_millennium): M = (280.4664567 + 360007.6982779 * julian_ephemeris_millennium + 0.03032028 * julian_ephemeris_millennium**2 @@ -841,7 +837,7 @@ def sun_mean_longitude(julian_ephemeris_millennium): return M -@jit('float64(float64, float64, float64, float64)', nopython=True) +@jit(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 + @@ -857,8 +853,7 @@ def equation_of_time(sun_mean_longitude, geocentric_sun_right_ascension, return E -@jit('void(float64[:], float64[:], float64[:,:])', nopython=True, - nogil=True) +@jit(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] From 7842720bc6c6b136f80de52ee43c6832db72f45d Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Fri, 27 Nov 2020 15:43:32 -0700 Subject: [PATCH 10/18] test updates --- pvlib/solarposition.py | 8 ++- pvlib/tests/conftest.py | 20 +++----- pvlib/tests/test_solarposition.py | 81 ++++++++++++++----------------- 3 files changed, 50 insertions(+), 59 deletions(-) diff --git a/pvlib/solarposition.py b/pvlib/solarposition.py index 5835b76cbb..453d18b443 100644 --- a/pvlib/solarposition.py +++ b/pvlib/solarposition.py @@ -235,7 +235,7 @@ def spa_c(time, latitude, longitude, pressure=101325, altitude=0, @jit_annotate def spa_python(time, latitude, longitude, altitude=0, pressure=101325, temperature=12, delta_t=67.0, - atmos_refract=None, numthreads=4, **kwargs): + atmos_refract=None, how=None, numthreads=4, **kwargs): """ Calculate the solar position using a python implementation of the NREL SPA algorithm. @@ -274,6 +274,8 @@ 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 : + Deprecated numthreads : int, optional, default 4 Number of threads to use when numba acceleration is used. @@ -308,6 +310,10 @@ def spa_python(time, latitude, longitude, # Added by Tony Lorenzo (@alorenzo175), University of Arizona, 2015 + if how is not None: + warnings.warn("The 'how' parameter is deprecated; see (TODO)", + pvlibDeprecationWarning) + lat = latitude lon = longitude elev = altitude diff --git a/pvlib/tests/conftest.py b/pvlib/tests/conftest.py index aa04af406d..ead2e40685 100644 --- a/pvlib/tests/conftest.py +++ b/pvlib/tests/conftest.py @@ -121,20 +121,14 @@ 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 + 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 numba") try: import siphon diff --git a/pvlib/tests/test_solarposition.py b/pvlib/tests/test_solarposition.py index 3d29749fb2..a5d359847d 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. @@ -581,6 +586,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 +748,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) From 4cd29f1e0268692dafcae9862fddec1e7578d89a Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Fri, 27 Nov 2020 16:15:44 -0700 Subject: [PATCH 11/18] lint --- pvlib/tests/conftest.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pvlib/tests/conftest.py b/pvlib/tests/conftest.py index ead2e40685..bfb013fe8a 100644 --- a/pvlib/tests/conftest.py +++ b/pvlib/tests/conftest.py @@ -122,16 +122,16 @@ def has_spa_c(): try: - import numba + import numba # noqa: F401 has_numba = True except ImportError: has_numba = False requires_numba = pytest.mark.skipif(not has_numba, reason="requires numba") -requires_no_numba = pytest.mark.skipif(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 From 513112440a8883b0cf5cc1acd22578c11c961fb8 Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Fri, 1 Jan 2021 11:54:01 -0700 Subject: [PATCH 12/18] improve sphinx rendering --- docs/sphinx/source/installation.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/sphinx/source/installation.rst b/docs/sphinx/source/installation.rst index ac4f3775f3..27c246e4c2 100644 --- a/docs/sphinx/source/installation.rst +++ b/docs/sphinx/source/installation.rst @@ -287,7 +287,7 @@ with numba have a corresponding note on their page in the API Reference. 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 +by importing and configuring numba prior to importing pvlib, like this:: import numba numba.config.DISABLE_JIT = 1 From 63abed3a3f22d6593659a9ec957114b12e3578c7 Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Fri, 1 Jan 2021 12:48:44 -0700 Subject: [PATCH 13/18] update coverage reporting --- ci/azure/conda_linux.yml | 2 ++ 1 file changed, 2 insertions(+) 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 From 1b034f4d22ac934578bef7665c53f37f386ab405 Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Sun, 3 Jan 2021 13:22:37 -0700 Subject: [PATCH 14/18] better docs --- docs/sphinx/source/api.rst | 2 ++ docs/sphinx/source/installation.rst | 7 ++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/sphinx/source/api.rst b/docs/sphinx/source/api.rst index 7db1b09034..db284cf377 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 27c246e4c2..377a306833 100644 --- a/docs/sphinx/source/installation.rst +++ b/docs/sphinx/source/installation.rst @@ -276,13 +276,14 @@ To install the NREL SPA algorithm for use with pvlib: Numba Acceleration ------------------ -It is not always possible to use python and numpy to create an efficient -implementation of complex modeling algorithms. As a result, some function +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 API Reference. +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 From 5ef132b7adefc475407e37c6400ce40e07cb90b1 Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Sat, 23 Jan 2021 10:14:48 -0700 Subject: [PATCH 15/18] put signatures back --- pvlib/spa.py | 89 ++++++++++++++++++++++++++-------------------------- 1 file changed, 45 insertions(+), 44 deletions(-) diff --git a/pvlib/spa.py b/pvlib/spa.py index 8c9f7210fc..af3d856023 100644 --- a/pvlib/spa.py +++ b/pvlib/spa.py @@ -388,7 +388,7 @@ ]) -@jit(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 @@ -406,37 +406,37 @@ def julian_day_dt(year, month, day, hour, minute, second, microsecond): return jd -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def julian_day(unixtime): jd = unixtime * 1.0 / 86400 + 2440587.5 return jd -@jit(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 -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def julian_century(julian_day): jc = (julian_day - 2451545) * 1.0 / 36525 return jc -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def julian_ephemeris_century(julian_ephemeris_day): jce = (julian_ephemeris_day - 2451545) * 1.0 / 36525 return jce -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def julian_ephemeris_millennium(julian_ephemeris_century): jme = julian_ephemeris_century * 1.0 / 10 return jme -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def heliocentric_longitude(jme): l0 = 0.0 l1 = 0.0 @@ -477,7 +477,7 @@ def heliocentric_longitude(jme): return l % 360 -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def heliocentric_latitude(jme): b0 = 0.0 b1 = 0.0 @@ -496,7 +496,7 @@ def heliocentric_latitude(jme): return b -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def heliocentric_radius_vector(jme): r0 = 0.0 r1 = 0.0 @@ -529,19 +529,19 @@ def heliocentric_radius_vector(jme): return r -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def geocentric_longitude(heliocentric_longitude): theta = heliocentric_longitude + 180.0 return theta % 360 -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def geocentric_latitude(heliocentric_latitude): beta = -1.0*heliocentric_latitude return beta -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def mean_elongation(julian_ephemeris_century): x0 = (297.85036 + 445267.111480 * julian_ephemeris_century @@ -550,7 +550,7 @@ def mean_elongation(julian_ephemeris_century): return x0 -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def mean_anomaly_sun(julian_ephemeris_century): x1 = (357.52772 + 35999.050340 * julian_ephemeris_century @@ -559,7 +559,7 @@ def mean_anomaly_sun(julian_ephemeris_century): return x1 -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def mean_anomaly_moon(julian_ephemeris_century): x2 = (134.96298 + 477198.867398 * julian_ephemeris_century @@ -568,7 +568,7 @@ def mean_anomaly_moon(julian_ephemeris_century): return x2 -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def moon_argument_latitude(julian_ephemeris_century): x3 = (93.27191 + 483202.017538 * julian_ephemeris_century @@ -577,7 +577,7 @@ def moon_argument_latitude(julian_ephemeris_century): return x3 -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def moon_ascending_longitude(julian_ephemeris_century): x4 = (125.04452 - 1934.136261 * julian_ephemeris_century @@ -586,7 +586,7 @@ def moon_ascending_longitude(julian_ephemeris_century): return x4 -@jit(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]): @@ -603,7 +603,7 @@ def longitude_nutation(julian_ephemeris_century, x0, x1, x2, x3, x4): return delta_psi -@jit(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]): @@ -620,7 +620,7 @@ def obliquity_nutation(julian_ephemeris_century, x0, x1, x2, x3, x4): return delta_eps -@jit(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 @@ -630,7 +630,7 @@ def mean_ecliptic_obliquity(julian_ephemeris_millennium): return e0 -@jit(nopython=True) +@jit('float64(float64, float64)', nopython=True) def true_ecliptic_obliquity(mean_ecliptic_obliquity, obliquity_nutation): e0 = mean_ecliptic_obliquity deleps = obliquity_nutation @@ -638,27 +638,27 @@ def true_ecliptic_obliquity(mean_ecliptic_obliquity, obliquity_nutation): return e -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def aberration_correction(earth_radius_vector): deltau = -20.4898 / (3600 * earth_radius_vector) return deltau -@jit(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 -@jit(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 -@jit(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( @@ -666,7 +666,7 @@ def apparent_sidereal_time(mean_sidereal_time, longitude_nutation, return v -@jit(nopython=True) +@jit('float64(float64, float64, float64)', nopython=True) def geocentric_sun_right_ascension(apparent_sun_longitude, true_ecliptic_obliquity, geocentric_latitude): @@ -679,7 +679,7 @@ def geocentric_sun_right_ascension(apparent_sun_longitude, return alpha % 360 -@jit(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)) * @@ -690,7 +690,7 @@ def geocentric_sun_declination(apparent_sun_longitude, true_ecliptic_obliquity, return delta -@jit(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""" @@ -698,33 +698,33 @@ def local_hour_angle(apparent_sidereal_time, observer_longitude, return H % 360 -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def equatorial_horizontal_parallax(earth_radius_vector): xi = 8.794 / (3600 * earth_radius_vector) return xi -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def uterm(observer_latitude): u = np.arctan(0.99664719 * np.tan(np.radians(observer_latitude))) return u -@jit(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 -@jit(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 -@jit(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)) @@ -736,14 +736,14 @@ def parallax_sun_right_ascension(xterm, equatorial_horizontal_parallax, return delta_alpha -@jit(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 -@jit(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, @@ -758,14 +758,14 @@ def topocentric_sun_declination(geocentric_sun_declination, xterm, yterm, return delta -@jit(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 -@jit(nopython=True) +@jit('float64(float64, float64, float64)', nopython=True) def topocentric_elevation_angle_without_atmosphere(observer_latitude, topocentric_sun_declination, topocentric_local_hour_angle @@ -779,7 +779,7 @@ def topocentric_elevation_angle_without_atmosphere(observer_latitude, return e0 -@jit(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): @@ -794,7 +794,7 @@ def atmospheric_refraction_correction(local_pressure, local_temp, return delta_e -@jit(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 @@ -802,13 +802,13 @@ def topocentric_elevation_angle(topocentric_elevation_angle_without_atmosphere, return e -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def topocentric_zenith_angle(topocentric_elevation_angle): theta = 90 - topocentric_elevation_angle return theta -@jit(nopython=True) +@jit('float64(float64, float64, float64)', nopython=True) def topocentric_astronomers_azimuth(topocentric_local_hour_angle, topocentric_sun_declination, observer_latitude): @@ -821,13 +821,13 @@ def topocentric_astronomers_azimuth(topocentric_local_hour_angle, return gamma % 360 -@jit(nopython=True) +@jit('float64(float64)', nopython=True) def topocentric_azimuth_angle(topocentric_astronomers_azimuth): phi = topocentric_astronomers_azimuth + 180 return phi % 360 -@jit(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 @@ -837,7 +837,7 @@ def sun_mean_longitude(julian_ephemeris_millennium): return M -@jit(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 + @@ -853,7 +853,8 @@ def equation_of_time(sun_mean_longitude, geocentric_sun_right_ascension, return E -@jit(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] From 1aed69e7dc7f90acb461bf7c4b8ee971099e2267 Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Sat, 23 Jan 2021 10:17:19 -0700 Subject: [PATCH 16/18] stickler --- pvlib/spa.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/pvlib/spa.py b/pvlib/spa.py index af3d856023..efef857dac 100644 --- a/pvlib/spa.py +++ b/pvlib/spa.py @@ -388,7 +388,8 @@ ]) -@jit('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 @@ -586,7 +587,8 @@ def moon_ascending_longitude(julian_ephemeris_century): return x4 -@jit('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]): @@ -603,7 +605,8 @@ def longitude_nutation(julian_ephemeris_century, x0, x1, x2, x3, x4): return delta_psi -@jit('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]): @@ -743,7 +746,8 @@ def topocentric_sun_right_ascension(geocentric_sun_right_ascension, return alpha_prime -@jit('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, From 9d181d92c41f5ba3863eb6496171ab8f987638e6 Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Sun, 14 Feb 2021 11:22:45 -0700 Subject: [PATCH 17/18] update benchmarks --- benchmarks/benchmarks/solarposition.py | 10 +++++++--- benchmarks/benchmarks/solarposition_numba.py | 8 ++------ 2 files changed, 9 insertions(+), 9 deletions(-) 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'): From 981f7f3696ab68dd584931990aee921c1b69afc1 Mon Sep 17 00:00:00 2001 From: Kevin Anderson Date: Sun, 14 Feb 2021 13:16:00 -0700 Subject: [PATCH 18/18] cleanup --- pvlib/modelchain.py | 16 ++++++++-------- pvlib/solarposition.py | 24 ++++++++++++++---------- pvlib/tests/test_modelchain.py | 2 +- pvlib/tests/test_solarposition.py | 7 +++---- 4 files changed, 26 insertions(+), 23 deletions(-) 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 453d18b443..5c61f444c0 100644 --- a/pvlib/solarposition.py +++ b/pvlib/solarposition.py @@ -99,7 +99,8 @@ def get_solarposition(time, latitude, longitude, elif method in {'nrel', 'nrel_numpy', 'nrel_numba'}: if method != 'nrel': warnings.warn(f'method={method} is deprecated; Use method="nrel" ' - 'instead. See (TODO)', pvlibDeprecationWarning) + 'instead. Numba will be used automatically if it ' + 'is available.', pvlibDeprecationWarning) ephem_df = spa_python(time, latitude, longitude, altitude, pressure, temperature, **kwargs) @@ -310,9 +311,7 @@ def spa_python(time, latitude, longitude, # Added by Tony Lorenzo (@alorenzo175), University of Arizona, 2015 - if how is not None: - warnings.warn("The 'how' parameter is deprecated; see (TODO)", - pvlibDeprecationWarning) + _warn_how_numba(how) lat = latitude lon = longitude @@ -393,9 +392,7 @@ def sun_rise_set_transit_spa(times, latitude, longitude, how=None, """ # Added by Tony Lorenzo (@alorenzo175), University of Arizona, 2015 - if how is not None: - warnings.warn("The 'how' parameter is deprecated; see (TODO)", - pvlibDeprecationWarning) + _warn_how_numba(how) lat = latitude lon = longitude @@ -954,9 +951,7 @@ def nrel_earthsun_distance(time, how=None, delta_t=67.0, numthreads=4): USA, http://www.nrel.gov. """ - if how is not None: - warnings.warn("The 'how' parameter is deprecated; see (TODO)", - pvlibDeprecationWarning) + _warn_how_numba(how) if not isinstance(time, pd.DatetimeIndex): try: @@ -1437,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/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 a5d359847d..185f5fa20c 100644 --- a/pvlib/tests/test_solarposition.py +++ b/pvlib/tests/test_solarposition.py @@ -149,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]) @@ -162,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]) @@ -516,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():