Overview and Warning: Please Read¶
ERA5 data on NCAR’s Geoscience Data Exchange (GDEX) is stored in hourly NetCDF files. But, kerchunk reference files have been created for pressure level data and zarr stores have been created for the surface variables to convert this dataset into an ARCO collection.
In this notebook, we will read hourly data from NCAR’s publicly accessible ERA5 collection using an intake-ESM catalog, compute the annual means and store the result using zarr stores.
If you don’t have write permision to save to NCAR’s GDEX, please save the result to your local folder.
If you need annual means for the following variables, please don’t run the commented cells in this notebook. The data has already been calculated and can be accessed via https from https://
data .gdex .ucar .edu /special _projects /pythia _2024 /annual _means/ Air temperature at 2 m/ VAR_2T
Otherwise, please run this script once to generate the annual means.
Prerequisites¶
| Concepts | Importance | Notes |
|---|---|---|
| Intro to Xarray | Necessary | |
| Intro to Intake | Necessary | |
| Understanding of Zarr | Helpful |
Time to learn: 30 minutes
Imports¶
import glob
import re
import matplotlib as plt
import numpy as np
import scipy as sp
import xarray as xr
import intake
import intake_esm
import pandas as pdimport dask
from dask.distributed import Client, performance_report,LocalCluster
from dask_jobqueue import PBSCluster######## File paths ################
gdex_scratch = "/glade/derecho/scratch/harshah"
era5_catalog = 'https://data.gdex.ucar.edu/d633000/catalogs/d633000-https.json'
annual_means = '/gdex/data/special_projects/pythia_2024/annual_means/' #Posix path, only used for writing data
annual_means_https= 'https://data.gdex.ucar.edu/special_projects/pythia_2024/annual_means/'
print(era5_catalog)https://data.gdex.ucar.edu/d633000/catalogs/d633000-https.json
Create a Dask cluster¶
Dask Introduction¶
Dask is a solution that enables the scaling of Python libraries. It mimics popular scientific libraries such as numpy, pandas, and xarray that enables an easier path to parallel processing without having to refactor code.
There are 3 components to parallel processing with Dask: the client, the scheduler, and the workers.
The Client is best envisioned as the application that sends information to the Dask cluster. In Python applications this is handled when the client is defined with client = Client(CLUSTER_TYPE). A Dask cluster comprises of a single scheduler that manages the execution of tasks on workers. The CLUSTER_TYPE can be defined in a number of different ways.
There is LocalCluster, a cluster running on the same hardware as the application and sharing the available resources, directly in Python with
dask.distributed.In certain JupyterHubs Dask Gateway may be available and a dedicated dask cluster with its own resources can be created dynamically with
dask.gateway.On HPC systems
dask_jobqueueis used to connect to the HPC Slurm and PBS job schedulers to provision resources.
The dask.distributed client python module can also be used to connect to existing clusters. A Dask Scheduler and Workers can be deployed in containers, or on Kubernetes, without using a Python function to create a dask cluster. The dask.distributed Client is configured to connect to the scheduler either by container name, or by the Kubernetes service name.
Select the Dask cluster type¶
The default will be LocalCluster as that can run on any system.
If running on a HPC computer with a PBS Scheduler, set to True. Otherwise, set to False.
USE_PBS_SCHEDULER = FalseIf running on Jupyter server with Dask Gateway configured, set to True. Otherwise, set to False.
USE_DASK_GATEWAY = FalsePython function for a PBS cluster
# Create a PBS cluster object
def get_pbs_cluster():
""" Create cluster through dask_jobqueue.
"""
from dask_jobqueue import PBSCluster
cluster = PBSCluster(
job_name = 'dask-pythia-24',
cores = 1,
memory = '4GiB',
processes = 1,
local_directory = gdex_scratch + '/dask/spill',
resource_spec = 'select=1:ncpus=1:mem=8GB',
queue = 'casper',
walltime = '1:00:00',
#interface = 'ib0'
interface = 'ext'
)
return clusterPython function for a Gateway Cluster
def get_gateway_cluster():
""" Create cluster through dask_gateway
"""
from dask_gateway import Gateway
gateway = Gateway()
cluster = gateway.new_cluster()
cluster.adapt(minimum=2, maximum=4)
return clusterPython function for a Local Cluster
def get_local_cluster():
""" Create cluster using the Jupyter server's resources
"""
from distributed import LocalCluster, performance_report
cluster = LocalCluster()
cluster.scale(6)
return clusterPython logic to select the Dask Cluster type
This uses True/False boolean logic based on the variables set in the previous cells
# Obtain dask cluster in one of three ways
if USE_PBS_SCHEDULER:
cluster = get_pbs_cluster()
elif USE_DASK_GATEWAY:
cluster = get_gateway_cluster()
else:
cluster = get_local_cluster()
# Connect to cluster
from distributed import Client
client = Client(cluster)
# Display cluster dashboard URL
clusterFind data using intake catalog¶
era5_cat = intake.open_esm_datastore(era5_catalog)
era5_cat# Filter the catalog for variables with 'temp' in their long name
cat_filtered = era5_cat.search(long_name='temp*')
cat_filtered.df.head()Search for variable of interest¶
############ Access temperature data ###########
temp_cat = era5_cat.search(variable='VAR_2T')
temp_cat.df# Define the xarray_open_kwargs with a compatible engine
xarray_open_kwargs = {'engine': 'zarr'}%%time
dset_temp = temp_cat.to_dataset_dict(xarray_open_kwargs=xarray_open_kwargs)
--> The keys in the returned dictionary of datasets are constructed as follows:
'variable.short_name'
CPU times: user 798 ms, sys: 118 ms, total: 916 ms
Wall time: 9.13 s
dset_temp.keys()dict_keys(['VAR_2T.2t'])temp_2m = dset_temp['VAR_2T.2t'].VAR_2T
temp_2mResample hourly data to annual data and save¶
# temp_2m_annual = temp_2m.resample(time='YE').mean()
# temp_2m_annual# temp_2m_annual = temp_2m_annual.chunk({'latitude':721,'longitude':1440})
# temp_2m_annual = temp_2m_annual.drop_isel({'time':-1}) # Drop 2024 data
# temp_2m_annualSave annual mean to annual_means folder within gdex_data
You may not have permissions to write to this folder.
If so, please replace the folder path in the cell below with your own path where you have write permissions
# %%time
# temp_2m_annual.to_dataset().to_zarr(annual_means + 'temp_2m_annual_1940_2023.zarr',mode='w')Open the saved file and make a test plot¶
temp_2m_annual = xr.open_zarr(annual_means_https + 'temp_2m_annual_1940_2023.zarr').VAR_2T
temp_2m_annual %%time
temp_2m_annual.isel(time=0).plot()2026-11-29 07:01:45,250 - distributed.worker - ERROR - Compute Failed
Key: getitem-open_dataset-original-finalize-hlgfinalizecompute-4b46a3fa2b554366be34628150c1498a
State: executing
Task: <Task 'getitem-open_dataset-original-finalize-hlgfinalizecompute-4b46a3fa2b554366be34628150c1498a' _execute_subgraph(...)>
Exception: "ServerDisconnectedError('Server disconnected')"
Traceback: ' File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/dask/array/core.py", line 135, in getter\n c = np.asarray(c)\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/core/indexing.py", line 691, in __array__\n return np.asarray(to_numpy(self.get_duck_array()), dtype=dtype, copy=copy)\n ~~~~~~~~~~~~~~~~~~~^^\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/core/indexing.py", line 697, in get_duck_array\n return self.array.get_duck_array()\n ~~~~~~~~~~~~~~~~~~~~~~~~~^^\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/core/indexing.py", line 930, in get_duck_array\n return self.array.get_duck_array()\n ~~~~~~~~~~~~~~~~~~~~~~~~~^^\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/core/indexing.py", line 770, in get_duck_array\n array = self.array[self.key]\n ~~~~~~~~~~^^^^^^^^^^\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/backends/zarr.py", line 316, in __getitem__\n return indexing.explicit_indexing_adapter(\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^\n key, array.shape, indexing.IndexingSupport.VECTORIZED, method\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n )\n ^\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/core/indexing.py", line 1162, in explicit_indexing_adapter\n result = raw_indexing_method(raw_key.tuple)\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/backends/zarr.py", line 279, in _getitem\n return self._array[key]\n ~~~~~~~~~~~^^^^^\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/zarr/core.py", line 797, in __getitem__\n result = self.get_orthogonal_selection(pure_selection, fields=fields)\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/zarr/core.py", line 1079, in get_orthogonal_selection\n return self._get_selection(indexer=indexer, out=out, fields=fields)\n ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/zarr/core.py", line 1342, in _get_selection\n self._chunk_getitems(\n ~~~~~~~~~~~~~~~~~~~~^\n lchunk_coords,\n ^^^^^^^^^^^^^^\n ...<4 lines>...\n fields=fields,\n ^^^^^^^^^^^^^^\n )\n ^\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/zarr/core.py", line 2183, in _chunk_getitems\n cdatas = self.chunk_store.getitems(ckeys, contexts=contexts)\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/zarr/storage.py", line 1435, in getitems\n raise v\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/fsspec/asyn.py", line 359, in _run_coro\n return await asyncio.wait_for(coro, timeout=timeout), i\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/asyncio/tasks.py", line 486, in wait_for\n return await fut\n ^^^^^^^^^\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/fsspec/implementations/http.py", line 248, in _cat_file\n async with session.get(self.encode_url(url), **kw) as r:\n ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/aiohttp/client.py", line 1756, in __aenter__\n self._resp: _RetType_co = await self._coro\n ^^^^^^^^^^^^^^^^\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/aiohttp/client.py", line 900, in _request\n resp = await handler(req)\n ^^^^^^^^^^^^^^^^^^\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/aiohttp/client.py", line 878, in _connect_and_send_request\n await resp.start(conn)\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/aiohttp/client_reqrep.py", line 745, in start\n message, payload = await protocol.read() # type: ignore[union-attr]\n ^^^^^^^^^^^^^^^^^^^^^\n File "/home/runner/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/aiohttp/streams.py", line 716, in read\n await self._waiter\n'
CPU times: user 16.4 ms, sys: 4.08 ms, total: 20.5 ms
Wall time: 137 ms
---------------------------------------------------------------------------
ServerDisconnectedError Traceback (most recent call last)
Cell In[21], line 1
----> 1 get_ipython().run_cell_magic('time', '', 'temp_2m_annual.isel(time=0).plot()\n')
File <timed eval>:1
----> 1 'Could not get source, probably due dynamically evaluated source code.'
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/plot/accessor.py:48, in DataArrayPlotAccessor.__call__(self, **kwargs)
46 @functools.wraps(dataarray_plot.plot, assigned=("__doc__", "__annotations__"))
47 def __call__(self, **kwargs) -> Any:
---> 48 return dataarray_plot.plot(self._da, **kwargs)
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/plot/dataarray_plot.py:279, in plot(darray, row, col, col_wrap, ax, hue, subplot_kws, **kwargs)
226 def plot(
227 darray: DataArray,
228 *,
(...) 235 **kwargs: Any,
236 ) -> Any:
237 """
238 Default plot of DataArray using :py:mod:`matplotlib:matplotlib.pyplot`.
239
(...) 275 xarray.DataArray.squeeze
276 """
277 darray = darray.squeeze(
278 d for d, s in darray.sizes.items() if s == 1 and d not in (row, col, hue)
--> 279 ).compute()
281 plot_dims = set(darray.dims)
282 plot_dims.discard(row)
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/core/dataarray.py:1254, in DataArray.compute(self, **kwargs)
1224 """Trigger loading data into memory and return a new dataarray.
1225
1226 Data will be computed and/or loaded from disk or a remote source.
(...) 1251 Variable.compute
1252 """
1253 new = self.copy(deep=False)
-> 1254 return new.load(**kwargs)
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/core/dataarray.py:1180, in DataArray.load(self, **kwargs)
1150 def load(self, **kwargs) -> Self:
1151 """Trigger loading data into memory and return this dataarray.
1152
1153 Data will be computed and/or loaded from disk or a remote source.
(...) 1178 Variable.load
1179 """
-> 1180 ds = self._to_temp_dataset().load(**kwargs)
1181 new = self._from_temp_dataset(ds)
1182 self._variable = new._variable
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/core/dataset.py:569, in Dataset.load(self, **kwargs)
565 if chunked_data:
566 chunkmanager = get_chunked_array_type(*chunked_data.values())
567
568 # evaluate all the chunked arrays simultaneously
--> 569 evaluated_data: tuple[np.ndarray[Any, Any], ...] = chunkmanager.compute(
570 *chunked_data.values(), **kwargs
571 )
572
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/namedarray/daskmanager.py:85, in DaskManager.compute(self, *data, **kwargs)
80 def compute(
81 self, *data: Any, **kwargs: Any
82 ) -> tuple[np.ndarray[Any, _DType_co], ...]:
83 from dask.array import compute
---> 85 return compute(*data, **kwargs)
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/dask/base.py:769, in compute(traverse, optimize_graph, scheduler, get, *args, **kwargs)
766 expr = expr.optimize()
767 keys = list(flatten(expr.__dask_keys__()))
--> 769 results = schedule(expr, keys, **kwargs)
771 return repack(results)
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/core/indexing.py:691, in __array__()
687 def __array__(
688 self, dtype: DTypeLike | None = None, /, *, copy: bool | None = None
689 ) -> np.ndarray:
690 if Version(np.__version__) >= Version("2.0.0"):
--> 691 return np.asarray(to_numpy(self.get_duck_array()), dtype=dtype, copy=copy)
693 else:
694 return np.asarray(to_numpy(self.get_duck_array()), dtype=dtype)
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/core/indexing.py:697, in get_duck_array()
696 def get_duck_array(self):
--> 697 return self.array.get_duck_array()
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/core/indexing.py:930, in get_duck_array()
929 def get_duck_array(self):
--> 930 return self.array.get_duck_array()
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/core/indexing.py:770, in get_duck_array()
767 from xarray.backends.common import BackendArray
769 if isinstance(self.array, BackendArray):
--> 770 array = self.array[self.key]
771 else:
772 array = apply_indexer(self.array, self.key)
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/backends/zarr.py:316, in __getitem__()
314 elif isinstance(key, indexing.OuterIndexer):
315 method = self._oindex
--> 316 return indexing.explicit_indexing_adapter(
317 key, array.shape, indexing.IndexingSupport.VECTORIZED, method
318 )
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/core/indexing.py:1162, in explicit_indexing_adapter()
1140 """Support explicit indexing by delegating to a raw indexing method.
1141
1142 Outer and/or vectorized indexers are supported by indexing a second time
(...) 1159 Indexing result, in the form of a duck numpy-array.
1160 """
1161 raw_key, numpy_indices = decompose_indexer(key, shape, indexing_support)
-> 1162 result = raw_indexing_method(raw_key.tuple)
1163 if numpy_indices.tuple:
1164 # index the loaded duck array
1165 indexable = as_indexable(result)
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/xarray/backends/zarr.py:279, in _getitem()
278 def _getitem(self, key):
--> 279 return self._array[key]
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/zarr/core.py:797, in __getitem__()
795 result = self.vindex[selection]
796 elif is_pure_orthogonal_indexing(pure_selection, self.ndim):
--> 797 result = self.get_orthogonal_selection(pure_selection, fields=fields)
798 else:
799 result = self.get_basic_selection(pure_selection, fields=fields)
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/zarr/core.py:1079, in get_orthogonal_selection()
1076 # setup indexer
1077 indexer = OrthogonalIndexer(selection, self)
-> 1079 return self._get_selection(indexer=indexer, out=out, fields=fields)
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/zarr/core.py:1342, in _get_selection()
1339 if math.prod(out_shape) > 0:
1340 # allow storage to get multiple items at once
1341 lchunk_coords, lchunk_selection, lout_selection = zip(*indexer)
-> 1342 self._chunk_getitems(
1343 lchunk_coords,
1344 lchunk_selection,
1345 out,
1346 lout_selection,
1347 drop_axes=indexer.drop_axes,
1348 fields=fields,
1349 )
1350 if out.shape:
1351 return out
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/zarr/core.py:2183, in _chunk_getitems()
2181 if not isinstance(self._meta_array, np.ndarray):
2182 contexts = ConstantMap(ckeys, constant=Context(meta_array=self._meta_array))
-> 2183 cdatas = self.chunk_store.getitems(ckeys, contexts=contexts)
2185 for ckey, chunk_select, out_select in zip(ckeys, lchunk_selection, lout_selection):
2186 if ckey in cdatas:
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/zarr/storage.py:1435, in getitems()
1432 continue
1433 elif isinstance(v, Exception):
1434 # Raise any other exception
-> 1435 raise v
1436 else:
1437 # The function calling this method may not recognize the transformed
1438 # keys, so we send the values returned by self.map.getitems back into
1439 # the original key space.
1440 results[keys_transformed[k]] = v
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/fsspec/asyn.py:359, in _run_coro()
357 async def _run_coro(coro, i):
358 try:
--> 359 return await asyncio.wait_for(coro, timeout=timeout), i
360 except Exception as e:
361 if not return_exceptions:
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/asyncio/tasks.py:486, in wait_for()
483 raise TimeoutError from exc
485 async with timeouts.timeout(timeout):
--> 486 return await fut
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/fsspec/implementations/http.py:248, in _cat_file()
246 kw["headers"] = headers
247 session = await self.set_session()
--> 248 async with session.get(self.encode_url(url), **kw) as r:
249 out = await r.read()
250 self._raise_not_found_for_status(r, url)
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/aiohttp/client.py:1756, in __aenter__()
1755 async def __aenter__(self) -> _RetType_co:
-> 1756 self._resp: _RetType_co = await self._coro
1757 return await self._resp.__aenter__()
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/aiohttp/client.py:900, in _request()
897 handler = _connect_and_send_request
899 try:
--> 900 resp = await handler(req)
901 # Client connector errors should not be retried
902 except (
903 ConnectionTimeoutError,
904 ClientConnectorError,
905 ClientConnectorCertificateError,
906 ClientConnectorSSLError,
907 ):
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/aiohttp/client.py:878, in _connect_and_send_request()
876 resp = await req.send(conn)
877 try:
--> 878 await resp.start(conn)
879 except BaseException:
880 resp.close()
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/aiohttp/client_reqrep.py:745, in start()
743 try:
744 protocol = self._protocol
--> 745 message, payload = await protocol.read() # type: ignore[union-attr]
746 except http.HttpProcessingError as exc:
747 raise ClientResponseError(
748 self.request_info,
749 self.history,
(...) 752 headers=exc.headers,
753 ) from exc
File ~/micromamba/envs/ERA5_interactive/lib/python3.14/site-packages/aiohttp/streams.py:716, in read()
714 self._waiter = self._loop.create_future()
715 try:
--> 716 await self._waiter
717 except (asyncio.CancelledError, asyncio.TimeoutError):
718 self._waiter = None
ServerDisconnectedError: Server disconnectedClose up the cluster¶
cluster.close()