Skip to content

Commit dda738e

Browse files
committed
Apply autoformatting
1 parent fe2c6c1 commit dda738e

20 files changed

+2520
-2257
lines changed

esmvalcore/_main.py

Lines changed: 112 additions & 79 deletions
Large diffs are not rendered by default.

esmvalcore/_recipe/recipe.py

Lines changed: 291 additions & 225 deletions
Large diffs are not rendered by default.

esmvalcore/cmor/_fixes/icon/_base_fixes.py

Lines changed: 55 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Fix base classes for ICON on-the-fly CMORizer."""
2+
23
from __future__ import annotations
34

45
import logging
@@ -27,10 +28,10 @@
2728
class IconFix(NativeDatasetFix):
2829
"""Base class for all ICON fixes."""
2930

30-
CACHE_DIR = Path.home() / '.esmvaltool' / 'cache'
31+
CACHE_DIR = Path.home() / ".esmvaltool" / "cache"
3132
CACHE_VALIDITY = 7 * 24 * 60 * 60 # [s]; = 1 week
3233
TIMEOUT = 5 * 60 # [s]; = 5 min
33-
GRID_FILE_ATTR = 'grid_file_uri'
34+
GRID_FILE_ATTR = "grid_file_uri"
3435

3536
def __init__(self, *args, **kwargs):
3637
"""Initialize ICON fix."""
@@ -65,7 +66,8 @@ def _create_mesh(self, cube: Cube) -> MeshXY:
6566
# 'vertex_of_cell'; since UGRID expects a different dimension ordering
6667
# we transpose the cube here)
6768
vertex_of_cell = horizontal_grid.extract_cube(
68-
NameConstraint(var_name='vertex_of_cell'))
69+
NameConstraint(var_name="vertex_of_cell")
70+
)
6971
vertex_of_cell.transpose()
7072

7173
# Extract start index used to name nodes from the the horizontal grid
@@ -74,8 +76,8 @@ def _create_mesh(self, cube: Cube) -> MeshXY:
7476

7577
# Extract face coordinates from cube (in ICON jargon called 'cell
7678
# latitude' and 'cell longitude')
77-
face_lat = cube.coord('latitude')
78-
face_lon = cube.coord('longitude')
79+
face_lat = cube.coord("latitude")
80+
face_lon = cube.coord("longitude")
7981

8082
# Extract node coordinates from horizontal grid
8183
(node_lat, node_lon) = self._get_node_coords(horizontal_grid)
@@ -87,11 +89,11 @@ def _create_mesh(self, cube: Cube) -> MeshXY:
8789

8890
# Latitude: there might be slight numerical differences (-> check that
8991
# the differences are very small before fixing it)
90-
close_kwargs = {'rtol': 1e-3, 'atol': 1e-5}
92+
close_kwargs = {"rtol": 1e-3, "atol": 1e-5}
9193
if not np.allclose(
92-
face_lat.bounds,
93-
node_lat.points[conn_node_inds],
94-
**close_kwargs, # type: ignore
94+
face_lat.bounds,
95+
node_lat.points[conn_node_inds],
96+
**close_kwargs, # type: ignore
9597
):
9698
logger.warning(
9799
"Latitude bounds of the face coordinate ('clat_vertices' in "
@@ -127,15 +129,15 @@ def _create_mesh(self, cube: Cube) -> MeshXY:
127129
# Create mesh
128130
connectivity = Connectivity(
129131
indices=vertex_of_cell.data,
130-
cf_role='face_node_connectivity',
132+
cf_role="face_node_connectivity",
131133
start_index=start_index,
132134
location_axis=0,
133135
)
134136
mesh = MeshXY(
135137
topology_dimension=2,
136-
node_coords_and_axes=[(node_lat, 'y'), (node_lon, 'x')],
138+
node_coords_and_axes=[(node_lat, "y"), (node_lon, "x")],
137139
connectivities=[connectivity],
138-
face_coords_and_axes=[(face_lat, 'y'), (face_lon, 'x')],
140+
face_coords_and_axes=[(face_lat, "y"), (face_lon, "x")],
139141
)
140142

141143
return mesh
@@ -146,7 +148,8 @@ def _get_grid_url(self, cube):
146148
raise ValueError(
147149
f"Cube does not contain the attribute '{self.GRID_FILE_ATTR}' "
148150
f"necessary to download the ICON horizontal grid file:\n"
149-
f"{cube}")
151+
f"{cube}"
152+
)
150153
grid_url = cube.attributes[self.GRID_FILE_ATTR]
151154
parsed_url = urlparse(grid_url)
152155
grid_name = Path(parsed_url.path).name
@@ -162,21 +165,22 @@ def _get_node_coords(self, horizontal_grid):
162165
163166
"""
164167
dual_area_cube = horizontal_grid.extract_cube(
165-
NameConstraint(var_name='dual_area'))
166-
node_lat = dual_area_cube.coord(var_name='vlat')
167-
node_lon = dual_area_cube.coord(var_name='vlon')
168+
NameConstraint(var_name="dual_area")
169+
)
170+
node_lat = dual_area_cube.coord(var_name="vlat")
171+
node_lon = dual_area_cube.coord(var_name="vlon")
168172

169173
# Fix metadata
170174
node_lat.bounds = None
171175
node_lon.bounds = None
172-
node_lat.var_name = 'nlat'
173-
node_lon.var_name = 'nlon'
174-
node_lat.standard_name = 'latitude'
175-
node_lon.standard_name = 'longitude'
176-
node_lat.long_name = 'node latitude'
177-
node_lon.long_name = 'node longitude'
178-
node_lat.convert_units('degrees_north')
179-
node_lon.convert_units('degrees_east')
176+
node_lat.var_name = "nlat"
177+
node_lon.var_name = "nlon"
178+
node_lat.standard_name = "latitude"
179+
node_lon.standard_name = "longitude"
180+
node_lat.long_name = "node latitude"
181+
node_lon.long_name = "node longitude"
182+
node_lat.convert_units("degrees_north")
183+
node_lon.convert_units("degrees_east")
180184

181185
# Convert longitude to [0, 360]
182186
self._set_range_in_0_360(node_lon)
@@ -186,10 +190,10 @@ def _get_node_coords(self, horizontal_grid):
186190
def _get_path_from_facet(self, facet, description=None):
187191
"""Try to get path from facet."""
188192
if description is None:
189-
description = 'File'
193+
description = "File"
190194
path = Path(os.path.expandvars(self.extra_facets[facet])).expanduser()
191195
if not path.is_file():
192-
new_path = self.session['auxiliary_data_dir'] / path
196+
new_path = self.session["auxiliary_data_dir"] / path
193197
if not new_path.is_file():
194198
raise FileNotFoundError(
195199
f"{description} '{path}' given by facet '{facet}' does "
@@ -238,8 +242,8 @@ def add_additional_cubes(self, cubes):
238242
239243
"""
240244
facets_to_consider = [
241-
'zg_file',
242-
'zghalf_file',
245+
"zg_file",
246+
"zghalf_file",
243247
]
244248
for facet in facets_to_consider:
245249
if self.extra_facets.get(facet) is None:
@@ -254,7 +258,7 @@ def add_additional_cubes(self, cubes):
254258
def _get_grid_from_facet(self):
255259
"""Get horizontal grid from user-defined facet `horizontal_grid`."""
256260
grid_path = self._get_path_from_facet(
257-
'horizontal_grid', 'Horizontal grid file'
261+
"horizontal_grid", "Horizontal grid file"
258262
)
259263
grid_name = grid_path.name
260264

@@ -297,7 +301,7 @@ def _get_grid_from_cube_attr(self, cube: Cube) -> Cube:
297301
def _get_grid_from_rootpath(self, grid_name: str) -> CubeList | None:
298302
"""Try to get grid from the ICON rootpath."""
299303
glob_patterns: list[Path] = []
300-
for data_source in _get_data_sources('ICON'):
304+
for data_source in _get_data_sources("ICON"):
301305
glob_patterns.extend(
302306
data_source.get_glob_patterns(**self.extra_facets)
303307
)
@@ -334,8 +338,10 @@ def _get_downloaded_grid(self, grid_url: str, grid_name: str) -> CubeList:
334338
logger.debug("Using cached ICON grid file '%s'", grid_path)
335339
valid_cache = True
336340
else:
337-
logger.debug("Existing cached ICON grid file '%s' is outdated",
338-
grid_path)
341+
logger.debug(
342+
"Existing cached ICON grid file '%s' is outdated",
343+
grid_path,
344+
)
339345

340346
# File is not present in cache or too old -> download it
341347
if not valid_cache:
@@ -347,12 +353,12 @@ def _get_downloaded_grid(self, grid_url: str, grid_name: str) -> CubeList:
347353
tmp_path,
348354
)
349355
with requests.get(
350-
grid_url,
351-
stream=True,
352-
timeout=self.TIMEOUT,
356+
grid_url,
357+
stream=True,
358+
timeout=self.TIMEOUT,
353359
) as response:
354360
response.raise_for_status()
355-
with tmp_path.open('wb') as file:
361+
with tmp_path.open("wb") as file:
356362
copyfileobj(response.raw, file)
357363
shutil.move(tmp_path, grid_path)
358364
logger.info(
@@ -403,7 +409,7 @@ def get_horizontal_grid(self, cube):
403409
file.
404410
405411
"""
406-
if self.extra_facets.get('horizontal_grid') is not None:
412+
if self.extra_facets.get("horizontal_grid") is not None:
407413
grid = self._get_grid_from_facet()
408414
else:
409415
grid = self._get_grid_from_cube_attr(cube)
@@ -444,9 +450,9 @@ def get_mesh(self, cube):
444450
"""
445451
# If specified by the user, use `horizontal_grid` facet to determine
446452
# grid name; otherwise, use the `grid_file_uri` attribute of the cube
447-
if self.extra_facets.get('horizontal_grid') is not None:
453+
if self.extra_facets.get("horizontal_grid") is not None:
448454
grid_path = self._get_path_from_facet(
449-
'horizontal_grid', 'Horizontal grid file'
455+
"horizontal_grid", "Horizontal grid file"
450456
)
451457
grid_name = grid_path.name
452458
else:
@@ -474,32 +480,33 @@ def _get_start_index(horizontal_grid):
474480
475481
"""
476482
vertex_index = horizontal_grid.extract_cube(
477-
NameConstraint(var_name='vertex_index'))
483+
NameConstraint(var_name="vertex_index")
484+
)
478485
return np.int32(np.min(vertex_index.data))
479486

480487
@staticmethod
481488
def _load_cubes(path: Path | str) -> CubeList:
482489
"""Load cubes and ignore certain warnings."""
483490
with warnings.catch_warnings():
484491
warnings.filterwarnings(
485-
'ignore',
492+
"ignore",
486493
message="Ignoring netCDF variable .* invalid units .*",
487494
category=UserWarning,
488-
module='iris',
495+
module="iris",
489496
) # iris < 3.8
490497
warnings.filterwarnings(
491-
'ignore',
498+
"ignore",
492499
message="Ignoring invalid units .* on netCDF variable .*",
493500
category=UserWarning,
494-
module='iris',
501+
module="iris",
495502
) # iris >= 3.8
496503
warnings.filterwarnings(
497-
'ignore',
504+
"ignore",
498505
message="Failed to create 'height' dimension coordinate: The "
499-
"'height' DimCoord bounds array must be strictly "
500-
"monotonic.",
506+
"'height' DimCoord bounds array must be strictly "
507+
"monotonic.",
501508
category=UserWarning,
502-
module='iris',
509+
module="iris",
503510
)
504511
cubes = iris.load(path)
505512
return cubes

esmvalcore/config/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from ._config_object import CFG, Config, Session
1717

1818
__all__ = (
19-
'CFG',
20-
'Config',
21-
'Session',
19+
"CFG",
20+
"Config",
21+
"Session",
2222
)

esmvalcore/config/_config.py

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Functions dealing with config-developer.yml and extra facets."""
2+
23
from __future__ import annotations
34

45
import collections.abc
@@ -43,7 +44,7 @@ def _load_extra_facets(project, extra_facets_dir):
4344
config_file_paths = config_path.glob(f"{project.lower()}-*.yml")
4445
for config_file_path in sorted(config_file_paths):
4546
logger.debug("Loading extra facets from %s", config_file_path)
46-
with config_file_path.open(encoding='utf-8') as config_file:
47+
with config_file_path.open(encoding="utf-8") as config_file:
4748
config_piece = yaml.safe_load(config_file)
4849
if config_piece:
4950
_deep_update(config, config_piece)
@@ -54,7 +55,7 @@ def get_extra_facets(dataset, extra_facets_dir):
5455
"""Read files with additional variable information ("extra facets")."""
5556
extra_facets_dir = tuple(extra_facets_dir)
5657
project_details = _load_extra_facets(
57-
dataset.facets['project'],
58+
dataset.facets["project"],
5859
extra_facets_dir,
5960
)
6061

@@ -76,10 +77,11 @@ def pattern_filter(patterns, name):
7677
return [pat for pat in patterns if fnmatch.fnmatchcase(name, pat)]
7778

7879
extra_facets = {}
79-
for dataset_ in pattern_filter(project_details, dataset['dataset']):
80-
for mip_ in pattern_filter(project_details[dataset_], dataset['mip']):
81-
for var in pattern_filter(project_details[dataset_][mip_],
82-
dataset['short_name']):
80+
for dataset_ in pattern_filter(project_details, dataset["dataset"]):
81+
for mip_ in pattern_filter(project_details[dataset_], dataset["mip"]):
82+
for var in pattern_filter(
83+
project_details[dataset_][mip_], dataset["short_name"]
84+
):
8385
facets = project_details[dataset_][mip_][var]
8486
extra_facets.update(facets)
8587

@@ -88,23 +90,25 @@ def pattern_filter(patterns, name):
8890

8991
def load_config_developer(cfg_file):
9092
"""Read the developer's configuration file."""
91-
with open(cfg_file, 'r', encoding='utf-8') as file:
93+
with open(cfg_file, "r", encoding="utf-8") as file:
9294
cfg = yaml.safe_load(file)
9395

94-
if 'obs4mips' in cfg:
96+
if "obs4mips" in cfg:
9597
logger.warning(
9698
"Correcting capitalization, project 'obs4mips'"
97-
" should be written as 'obs4MIPs' in %s", cfg_file)
98-
cfg['obs4MIPs'] = cfg.pop('obs4mips')
99+
" should be written as 'obs4MIPs' in %s",
100+
cfg_file,
101+
)
102+
cfg["obs4MIPs"] = cfg.pop("obs4mips")
99103

100104
for project, settings in cfg.items():
101-
for site, drs in settings.get('input_dir', {}).items():
105+
for site, drs in settings.get("input_dir", {}).items():
102106
# Since v2.8, 'version' can be used instead of 'latestversion'
103107
if isinstance(drs, list):
104-
drs = [d.replace('{latestversion}', '{version}') for d in drs]
108+
drs = [d.replace("{latestversion}", "{version}") for d in drs]
105109
else:
106-
drs = drs.replace('{latestversion}', '{version}')
107-
settings['input_dir'][site] = drs
110+
drs = drs.replace("{latestversion}", "{version}")
111+
settings["input_dir"][site] = drs
108112
CFG[project] = settings
109113

110114
read_cmor_tables(cfg_file)
@@ -119,8 +123,8 @@ def get_project_config(project):
119123

120124
def get_institutes(variable):
121125
"""Return the institutes given the dataset name in CMIP6."""
122-
dataset = variable['dataset']
123-
project = variable['project']
126+
dataset = variable["dataset"]
127+
project = variable["project"]
124128
try:
125129
return CMOR_TABLES[project].institutes[dataset]
126130
except (KeyError, AttributeError):
@@ -129,9 +133,9 @@ def get_institutes(variable):
129133

130134
def get_activity(variable):
131135
"""Return the activity given the experiment name in CMIP6."""
132-
project = variable['project']
136+
project = variable["project"]
133137
try:
134-
exp = variable['exp']
138+
exp = variable["exp"]
135139
if isinstance(exp, list):
136140
return [CMOR_TABLES[project].activities[value][0] for value in exp]
137141
return CMOR_TABLES[project].activities[exp][0]
@@ -144,8 +148,8 @@ def get_ignored_warnings(project: FacetValue, step: str) -> None | list:
144148
if project not in CFG:
145149
return None
146150
project_cfg = CFG[project]
147-
if 'ignore_warnings' not in project_cfg:
151+
if "ignore_warnings" not in project_cfg:
148152
return None
149-
if step not in project_cfg['ignore_warnings']:
153+
if step not in project_cfg["ignore_warnings"]:
150154
return None
151-
return project_cfg['ignore_warnings'][step]
155+
return project_cfg["ignore_warnings"][step]

0 commit comments

Comments
 (0)