diff --git a/docs/sphinx/source/whatsnew/v0.16.2.rst b/docs/sphinx/source/whatsnew/v0.16.2.rst index b9a54f6c26..f90801eb49 100644 --- a/docs/sphinx/source/whatsnew/v0.16.2.rst +++ b/docs/sphinx/source/whatsnew/v0.16.2.rst @@ -14,6 +14,12 @@ Deprecations Bug fixes ~~~~~~~~~ +* :py:func:`pvlib.iotools.get_pvgis_tmy` now accounts for the time zone in + the EPW header when coercing the year or rolling the data. For the PVGIS + sample at 45°N, 8°E, the header declares UTC+1 and the hourly values match + the JSON file on a UTC clock. Applying the header offset moves the EPW + values one hour earlier than JSON. Use ``outputformat='json'`` for the + PVGIS UTC series. (:issue:`2956`) * Correct the Series name in ``ModelChain.results.dc_ohmic_losses`` from ``i_mp`` to ``p_dc_ohmic_loss`` when using ``dc_ohms_from_percent``. (:issue:`1959`, :pull:`2912`) @@ -87,3 +93,4 @@ Contributors * :ghuser:`xiajiahang` * Jakub Krasuski (:ghuser:`Blizzeq`) * Dylan Pulver (:ghuser:`dylanpulver`) +* :ghuser:`LYUml` diff --git a/pvlib/iotools/pvgis.py b/pvlib/iotools/pvgis.py index 74b044abad..ebfc08e26e 100644 --- a/pvlib/iotools/pvgis.py +++ b/pvlib/iotools/pvgis.py @@ -18,7 +18,6 @@ import json from pathlib import Path import requests -import numpy as np import pandas as pd import zoneinfo from pvlib.iotools import read_epw @@ -406,29 +405,21 @@ def read_pvgis_hourly(filename, pvgis_format=None, map_variables=True): def _coerce_and_roll_tmy(tmy_data, tz, year): - """ - Assumes ``tmy_data`` input is UTC, converts from UTC to ``tz``, rolls - dataframe so timeseries starts at midnight, and forces all indices to - ``year``. Only works for integer ``tz``, but ``None`` and ``False`` are - re-interpreted as zero / UTC. + """Convert hourly TMY data from its source time zone to a typical year + in the requested fixed-offset time zone (UTC by default). """ if tz: tzname = zoneinfo.ZoneInfo(f'Etc/GMT{-tz:+d}') # noqa: E231 else: - tz = 0 tzname = zoneinfo.ZoneInfo('UTC') - new_index = pd.DatetimeIndex([ - timestamp.replace(year=year, tzinfo=tzname) - for timestamp in tmy_data.index], - name=f'time({tzname})') - new_tmy_data = pd.DataFrame( - np.roll(tmy_data, tz, axis=0), - columns=tmy_data.columns, - index=new_index) - # GH 2399 - new_tmy_data = \ - new_tmy_data.astype(dtype=dict(zip(tmy_data.columns, tmy_data.dtypes))) - return new_tmy_data + + # The months can come from different years. Convert on a continuous + # non-leap calendar so crossing a month boundary cannot introduce Feb 29. + typical_year = tmy_data.index.map(lambda ts: ts.replace(year=1990)) + local_time = typical_year.tz_convert(tzname) + # Fold observations crossing New Year back into the requested TMY. + index = local_time.map(lambda ts: ts.replace(year=year)) + return tmy_data.set_axis(index.rename(f'time({tzname})')).sort_index() def get_pvgis_tmy(latitude, longitude, outputformat='json', usehorizon=True, @@ -455,7 +446,10 @@ def get_pvgis_tmy(latitude, longitude, outputformat='json', usehorizon=True, Longitude in degrees east outputformat : str, default 'json' Must be in ``['csv', 'epw', 'json']``. See PVGIS TMY tool - documentation [2]_ for more info. + documentation [2]_ for more info. EPW timestamps use the UTC offset + in the file header. At some locations this places the hourly values + one hour earlier than in the PVGIS JSON file. Use + ``outputformat='json'`` for the PVGIS UTC time series. usehorizon : bool, default True include effects of horizon userhorizon : list of float, optional @@ -474,9 +468,10 @@ def get_pvgis_tmy(latitude, longitude, outputformat='json', usehorizon=True, timeout : int, default 30 time in seconds to wait for server response before timeout roll_utc_offset: int, optional - Use to specify a time zone other than the default UTC zero and roll - dataframe by ``roll_utc_offset`` so it starts at midnight on January - 1st. Ignored if ``None``, otherwise will force year to ``coerce_year``. + UTC offset in hours for the output index. The data are ordered from + January 1 in that time zone. Specifying an offset also coerces the + year, even if ``coerce_year`` is None. The default output zone when + coercing the year is UTC. coerce_year: int, default 1990 Use to force indices to desired year. Defaults to 1990. Specify ``None`` to return the actual indices used for the TMY. If diff --git a/tests/iotools/test_pvgis.py b/tests/iotools/test_pvgis.py index 32d820faae..593d509afb 100644 --- a/tests/iotools/test_pvgis.py +++ b/tests/iotools/test_pvgis.py @@ -6,7 +6,9 @@ import pandas as pd import io import pytest +import re import requests +from zoneinfo import ZoneInfo from pvlib.iotools import get_pvgis_tmy, read_pvgis_tmy from pvlib.iotools import get_pvgis_hourly, read_pvgis_hourly from pvlib.iotools import get_pvgis_horizon @@ -542,6 +544,49 @@ def test_get_pvgis_tmy_epw(expected, epw_meta): _compare_pvgis_tmy_epw(expected, epw_meta, pvgis_data) +def test_get_pvgis_tmy_epw_default_utc(requests_mock): + path = TESTS_DATA_DIR / 'tmy_45.000_8.000_2005_2023.epw' + requests_mock.get('https://re.jrc.ec.europa.eu/api/tmy', + content=path.read_bytes()) + data, _ = get_pvgis_tmy(45, 8, outputformat='epw') + + # The file reports 149 W/m² for January 1, EPW hour 10. The interval + # starts at 09:00 local time and the header declares UTC+1. + assert data.at[pd.Timestamp('1990-01-01 08:00', tz='UTC'), 'ghi'] == 149 + + +@pytest.mark.parametrize( + 'source_tz, target_tz, year, first_row, first_minute', + [(9, None, 1990, 9, 0), (0, None, 1990, 0, 0), + (-7, 2, 2020, -9, 0), (5.5, None, 2020, 6, 30)]) +def test_get_pvgis_tmy_epw_timezone(requests_mock, source_tz, target_tz, + year, first_row, first_minute): + # Exercise the EPW reader and the public conversion path without the API. + path = TESTS_DATA_DIR / 'tmy_45.000_8.000_2005_2023.epw' + header, rows = path.read_bytes().split(b'\n', 1) + fields = header.split(b',') + fields[8] = str(source_tz).encode() + # Select February and March from a leap year. Converting in the source + # years would create a February 29 when crossing this month boundary. + rows = re.sub(rb'^\d{4},([23]),', rb'2020,\1,', rows, flags=re.MULTILINE) + requests_mock.get('https://re.jrc.ec.europa.eu/api/tmy', + content=b','.join(fields) + b'\n' + rows) + + raw, _ = get_pvgis_tmy(45, 8, outputformat='epw', coerce_year=None) + data, _ = get_pvgis_tmy(45, 8, outputformat='epw', coerce_year=year, + roll_utc_offset=target_tz) + + # The first observation of the target year can come from either end + # of the local year. A TMY has no February 29, even in a leap year. + tz = ZoneInfo('Etc/GMT-2' if target_tz == 2 else 'UTC') + hours = pd.date_range(f'{year}-01-01', f'{year + 1}-01-01', freq='h', + inclusive='left', tz=tz, name=f'time({tz})') + hours = hours[~((hours.month == 2) & (hours.day == 29))] + expected = pd.concat([raw.iloc[first_row:], raw.iloc[:first_row]]) + expected.index = hours + pd.Timedelta(minutes=first_minute) + pd.testing.assert_frame_equal(data, expected, check_freq=False) + + def _compare_pvgis_tmy_epw(expected, epw_meta, pvgis_data): data, meta = pvgis_data assert np.allclose(data.ghi, expected['G(h)'])