Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ In addition to the above, the table below presents further partitioning examples
<tr>
<!-- https://github.com/google/weather-tools/pull/503 -->
<td>year-month</td>
<td>Added support for a year‑month key, allowing users to specify downloads using month granularity instead of ranged formats.</td>
<td>Added support for a year‑month key, allowing users to specify downloads using month granularity instead of ranged formats.<br/><br/>Note: year-month must be specified in partition_keys.</td>
<td>[parameters]<br/>target_path={year-month}.gb<br/>partition_keys=year-month<br/>[selection]<br/>year-month=2024-11/to/2025-02</td>
<td>2024-11.gb<br/>2024-12.gb<br/>2025-01.gb<br/>2025-02.gb</td>
</tr>
Expand Down Expand Up @@ -320,9 +320,9 @@ the [Copernicus documentation](https://cds.climate.copernicus.eu/datasets).
See [this example](https://cds.climate.copernicus.eu/datasets/reanalysis-era5-pressure-levels?tab=overview)
for what kind of requests one can make.

**Bypassing CDS Cache (`no_cache`)**:
To download fresh data and bypass the CDS server-side request cache (see [CDS cache issue discussion](https://forum.ecmwf.int/t/how-to-avoid-the-cds-cache-issue/905)), set `no_cache = true` in the `[selection]` section of your configuration file.
* `no_cache`: (optional) Accepts `true` or `false`. When set to `true`, `weather-dl` automatically includes the `nocache` parameter in the CDS request payload to force downloading fresh data instead of retrieving cached data.
**Bypassing Cache (`no_cache`)**:
To download fresh data and bypass server-side request caching (see [CDS cache issue discussion](https://forum.ecmwf.int/t/how-to-avoid-the-cds-cache-issue/905)), set `no_cache = true` in the `[selection]` section of your configuration file.
* `no_cache`: (optional, case-insensitive) Accepts `true` or `false`. When set to `true`, `weather-dl` automatically includes the `nocache` parameter in the request payload (accepted by both CDS and MARS).

### MARS

Expand Down
2 changes: 1 addition & 1 deletion VERSION.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.2.3
0.2.4
6 changes: 3 additions & 3 deletions weather_dl/download_pipeline/clients.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def retrieve(self, dataset: str, selection: t.Dict, output: str, manifest: Manif
warning_callback=self.logger.warning,
error_callback=self.logger.error,
)
selection_ = optimize_selection_partition(selection)
selection_ = optimize_selection_partition(selection, client_name='cds')
with StdoutLogger(self.logger, level=logging.DEBUG):
manifest.set_stage(Stage.FETCH)
precise_fetch_start_time = (
Expand Down Expand Up @@ -323,7 +323,7 @@ def retrieve(self, dataset: str, selection: t.Dict, output: str, manifest: Manif
log=self.logger.debug,
verbose=True,
)
selection_ = optimize_selection_partition(selection)
selection_ = optimize_selection_partition(selection, client_name='mars')
with StdoutLogger(self.logger, level=logging.DEBUG):
manifest.set_stage(Stage.FETCH)
precise_fetch_start_time = (
Expand Down Expand Up @@ -373,7 +373,7 @@ def retrieve(self, dataset: str, selection: t.Dict, output: str, manifest: Manif
verbose=True,
dataset=dataset,
)
selection_ = optimize_selection_partition(selection)
selection_ = optimize_selection_partition(selection, client_name='ecpublic')
with StdoutLogger(self.logger, level=logging.DEBUG):
manifest.set_stage(Stage.FETCH)
precise_fetch_start_time = (
Expand Down
68 changes: 61 additions & 7 deletions weather_dl/download_pipeline/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import calendar
import copy
import dataclasses
import datetime
import itertools
import typing as t

Expand Down Expand Up @@ -77,26 +78,70 @@ def from_dict(cls, config: t.Dict) -> 'Config':
return config_instance


def optimize_selection_partition(selection: t.Dict) -> t.Dict:
def _parse_date_token(token: str) -> datetime.date:
"""Parses a MARS date token into datetime.date."""
if token.startswith('-') and token[1:].isdecimal():
return datetime.date.today() - datetime.timedelta(days=int(token[1:]))
for fmt in ('%Y-%m-%d', '%Y%m%d', '%Y-%j'):
try:
return datetime.datetime.strptime(token, fmt).date()
except ValueError:
continue
raise ValueError(f"Invalid date token '{token}' in 'date_range'.")


def _expand_date_range(block: str) -> t.List[str]:
"""Expands a MARS date_range string (e.g. 'D1/to/D2[/by/N]') into YYYY-MM-DD dates."""
tokens = [b.strip() for b in block.split('/') if b.strip()]
if 'to' not in tokens and 'by' not in tokens:
return [_parse_date_token(tok).strftime('%Y-%m-%d') for tok in tokens]
try:
to_idx = tokens.index('to')
assert to_idx != 0, "There must be a start token."
start = _parse_date_token(tokens[to_idx - 1])
end = _parse_date_token(tokens[to_idx + 1])
increment = int(tokens[tokens.index('by') + 1]) if 'by' in tokens else 1
assert increment != 0, "Increment cannot be 0."
except (AssertionError, IndexError, ValueError) as exc:
raise SyntaxError(f"Improper range syntax in '{block}'.") from exc
if start > end and increment > 0:
increment *= -1
offset = 1 if start <= end else -1
return [
(start + datetime.timedelta(days=x)).strftime('%Y-%m-%d')
for x in range(0, (end - start).days + offset, increment)
]


def optimize_selection_partition(selection: t.Dict, client_name: t.Optional[str] = None) -> t.Dict:
"""Compute right-hand-side values for the selection section of a single partition.

Used to support custom syntax and optimizations, such as 'all'.
"""
selection_ = copy.deepcopy(selection)
# True for direct MARS/ECPublic requests or MARS-brokered CDS datasets.
is_mars = client_name in ('mars', 'ecpublic') or ('class' in selection_ and 'stream' in selection_)

if 'year-month' in selection_.keys():
ym = selection_['year-month'][0]
ym = selection_['year-month'][0] if isinstance(selection_['year-month'], list) else selection_['year-month']
year, month = map(int, ym.split('-'))
last_day = calendar.monthrange(year, month)[1]
selection_['date'] = [f'{year:04d}-{month:02d}-01/to/{year:04d}-{month:02d}-{last_day:02d}']
# Expand to explicit YYYY-MM-DD dates supported by both CDS and MARS.
selection_['date'] = [f'{year:04d}-{month:02d}-{day:02d}' for day in range(1, last_day + 1)]
del selection_['year-month']

if 'date_range' in selection_.keys():
selection_['date'] = selection_['date_range'][0]
# Standard CDS rejects '/to/' syntax; expand to explicit YYYY-MM-DD dates.
selection_['date'] = (
_expand_date_range(selection_['date_range'][0])
if client_name == 'cds' and not is_mars
else selection_['date_range'][0]
)
del selection_['date_range']

if 'day' in selection_.keys() and selection_['day'] == 'all':
years, months = selection_['year'], selection_['month']
# Convert year/month/day into explicit YYYY-MM-DD dates when day='all' or targeting MARS.
if 'day' in selection_.keys() and (selection_['day'] == 'all' or is_mars):
years, months, days = selection_['year'], selection_['month'], selection_['day']

multiples_error = "When using day='all' in selection, '/' is not allowed in {type}."

Expand All @@ -106,6 +151,9 @@ def optimize_selection_partition(selection: t.Dict) -> t.Dict:
if isinstance(months, str):
months = [months]

if isinstance(days, str) and days != 'all':
days = [days]

date_ranges = []

# Generating dates for every year-month.
Expand All @@ -121,7 +169,13 @@ def optimize_selection_partition(selection: t.Dict) -> t.Dict:

_, n_days_in_month = calendar.monthrange(year, month)

date_range = [f'{year:04d}-{month:02d}-{day:02d}' for day in range(1, n_days_in_month + 1)]
# Skip invalid calendar days (e.g. Feb 30/31) when explicit days are provided.
valid_days = (
range(1, n_days_in_month + 1)
if days == 'all'
else [int(d) for d in days if 1 <= int(d) <= n_days_in_month]
)
date_range = [f'{year:04d}-{month:02d}-{day:02d}' for day in valid_days]

date_ranges.extend(date_range)

Expand Down
67 changes: 66 additions & 1 deletion weather_dl/download_pipeline/config_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,73 @@ def test_all_days__invalid_month(self):

def test_date_range(self):
selection_with_date_range = {'date_range': ['2017-01-01/to/2017-01-10']}
actual = optimize_selection_partition(selection_with_date_range)
actual = optimize_selection_partition(selection_with_date_range, client_name='mars')
self.assertEqual(actual['date'], selection_with_date_range['date_range'][0])
self.assertNotIn('date_range', actual)

def test_date_range_cds_standard_expands_dates(self):
selection = {'date_range': ['2025-01-01/to/2025-01-03'], 'variable': '2m_temperature'}
actual = optimize_selection_partition(selection, client_name='cds')
self.assertEqual(actual['date'], ['2025-01-01', '2025-01-02', '2025-01-03'])
self.assertNotIn('date_range', actual)

stepped = {'date_range': ['2025-01-01/to/2025-01-05/by/2'], 'variable': '2m_temperature'}
actual_stepped = optimize_selection_partition(stepped, client_name='cds')
self.assertEqual(actual_stepped['date'], ['2025-01-01', '2025-01-03', '2025-01-05'])

def test_date_range_cds_mars_brokered_keeps_mars_syntax(self):
selection = {
'date_range': ['2025-01-01/to/2025-01-02'],
'class': 'ea',
'stream': 'oper',
}
actual = optimize_selection_partition(selection, client_name='cds')
self.assertEqual(actual['date'], '2025-01-01/to/2025-01-02')
self.assertNotIn('date_range', actual)

def test_year_month(self):
selection_with_year_month = {'year-month': ['2024-02']}
actual = optimize_selection_partition(selection_with_year_month)
expected_leap = [f'2024-02-{day:02d}' for day in range(1, 30)]
self.assertEqual(actual['date'], expected_leap)
self.assertNotIn('year-month', actual)

selection_with_year_month_str = {'year-month': '2025-02'}
actual_str = optimize_selection_partition(selection_with_year_month_str, client_name='cds')
expected_non_leap = [f'2025-02-{day:02d}' for day in range(1, 29)]
self.assertEqual(actual_str['date'], expected_non_leap)
self.assertNotIn('year-month', actual_str)

def test_explicit_year_month_day_mars_and_cds(self):
mars_sel = {'year': ['2025'], 'month': ['01'], 'day': ['01', '02'], 'param': '167.128'}
actual_mars = optimize_selection_partition(mars_sel, client_name='mars')
self.assertEqual(actual_mars['date'], ['2025-01-01', '2025-01-02'])
self.assertNotIn('day', actual_mars)
self.assertNotIn('month', actual_mars)
self.assertNotIn('year', actual_mars)

mars_brok_sel = {
'year': ['2025'],
'month': ['02'],
'day': ['27', '28', '29', '30', '31'],
'class': 'ea',
'stream': 'oper',
}
actual_brok = optimize_selection_partition(mars_brok_sel, client_name='cds')
self.assertEqual(actual_brok['date'], ['2025-02-27', '2025-02-28'])
self.assertNotIn('day', actual_brok)

cds_std_sel = {
'year': ['2025'],
'month': ['01'],
'day': ['01', '02'],
'variable': '2m_temperature',
}
actual_cds = optimize_selection_partition(cds_std_sel, client_name='cds')
self.assertEqual(actual_cds['year'], ['2025'])
self.assertEqual(actual_cds['month'], ['01'])
self.assertEqual(actual_cds['day'], ['01', '02'])
self.assertNotIn('date', actual_cds)

def test_with_year_month_as_string(self):
selection_with_multiple_months = {'year': '2017', 'month': '12', 'day':'all'}
Expand Down
23 changes: 22 additions & 1 deletion weather_dl/download_pipeline/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,25 +452,46 @@ def process_config(file: t.IO, config_name: str) -> Config:
partition keys.
""".format(num_template_replacements, num_partition_keys))

# True for direct MARS/ECPublic requests or MARS-brokered CDS datasets.
is_mars_selection = params.get('client') in ('mars', 'ecpublic') or (
'class' in selection and 'stream' in selection
)

if 'day' in partition_keys:
require(selection['day'] != 'all',
"""If 'all' is used for a selection value, it cannot appear as a partition key.""")

# Require year and month whenever day is converted into explicit YYYY-MM-DD dates.
if 'day' in selection and (selection['day'] == 'all' or is_mars_selection):
require('year' in selection and 'month' in selection,
"""If 'day' is specified in the 'selection' section for MARS or with day='all',
then both 'year' and 'month' are also required.""")

if 'hdate' in selection:
require('date' in partition_keys,
""""If 'hdate' is specified in the 'selection' section,
then 'date' is required as a partition keys.""")
# Reject hdate on standard CDS and ERA5 reanalysis datasets.
require(is_mars_selection and selection.get('class') != 'ea',
"""'hdate' is only supported for hindcast/reforecast MARS requests """
"""(not standard CDS or ERA5 reanalysis datasets).""")

if 'date_range' in selection:
require('date_range' in partition_keys,
""""If 'date_range' is specified in the 'selection' section,
then it is also required as a partition keys.""")

if 'year-month' in selection:
require('year-month' in partition_keys,
""""If 'year-month' is specified in the 'selection' section,
then it is also required as a partition keys.""")

if 'no_cache' in selection:
no_cache = selection['no_cache'].lower()
require(no_cache in ["true", "false"],
"""no_cache can only be true or false.""")
if selection['no_cache'] == "true":
# Compare against lowercased value so no_cache is case-insensitive.
if no_cache == "true":
# To download the fresh data and not from cache.
# https://forum.ecmwf.int/t/how-to-avoid-the-cds-cache-issue/905
config['selection']['nocache'] = '123'
Expand Down
78 changes: 78 additions & 0 deletions weather_dl/download_pipeline/parsers_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1049,6 +1049,24 @@ def test_partition_key_contains_date_range(self):
) as f:
process_config(f, 'test.cfg')

def test_partition_key_contains_year_month(self):
with self.assertRaisesRegex(ValueError, """If 'year-month' is specified in the 'selection' section,
then it is also required as a partition keys."""):
with io.StringIO(
"""
[parameters]
dataset=foo
client=mars
target_path=bar-{}
partition_keys=
time
[selection]
year-month=2024-11/to/2025-01
time=00/12
"""
) as f:
process_config(f, 'test.cfg')

def test_partition_key_contains_date__in_case_of_hdate(self):
with self.assertRaisesRegex(ValueError, "'date' is required as a partition keys."):
with io.StringIO(
Expand All @@ -1067,6 +1085,55 @@ def test_partition_key_contains_date__in_case_of_hdate(self):
) as f:
process_config(f, 'test.cfg')

def test_hdate_rejected_on_cds_standard_and_era5(self):
with self.assertRaisesRegex(ValueError, "'hdate' is only supported for hindcast/reforecast"):
with io.StringIO(
"""
[parameters]
dataset=reanalysis-era5-single-levels
client=cds
target_path=bar-{}
partition_keys=date
[selection]
date=2025-01-09
hdate=1
variable=2m_temperature
"""
) as f:
process_config(f, 'test.cfg')

with self.assertRaisesRegex(ValueError, "'hdate' is only supported for hindcast/reforecast"):
with io.StringIO(
"""
[parameters]
dataset=reanalysis-era5-complete
client=cds
target_path=bar-{}
partition_keys=date
[selection]
class=ea
stream=oper
date=2025-01-09
hdate=1
param=167.128
"""
) as f:
process_config(f, 'test.cfg')

def test_mars_day_requires_year_and_month(self):
with self.assertRaisesRegex(ValueError, "both 'year' and 'month' are also required"):
with io.StringIO(
"""
[parameters]
client=mars
target_path=bar
[selection]
year=2025
day=01/02
"""
) as f:
process_config(f, 'test.cfg')

def test_singleton_partitions_are_converted_to_lists(self):
with io.StringIO(
"""
Expand Down Expand Up @@ -1097,6 +1164,17 @@ def test_nochche_paramete(self):
) as f:
config = process_config(f, 'test.cfg')
self.assertEqual(config.selection['nocache'], "123")
with io.StringIO(
"""
[parameters]
client=cds
target_path=bar
[selection]
no_cache=True
"""
) as f:
config = process_config(f, 'test.cfg')
self.assertEqual(config.selection['nocache'], "123")
with self.assertRaisesRegex(KeyError, "'no_cache'"):
with io.StringIO(
"""
Expand Down
2 changes: 1 addition & 1 deletion weather_dl/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
setup(
name='download_pipeline',
packages=find_packages(),
version='0.1.30',
version='0.1.31',
author='Anthromets',
author_email='anthromets-ecmwf@google.com',
url='https://weather-tools.readthedocs.io/en/latest/weather_dl/',
Expand Down
2 changes: 1 addition & 1 deletion weather_dl_v2/fastapi-server/VERSION.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.0.17
1.0.18
Loading
Loading