Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

MITgcm ECCOv4 Example

Project Pythia Logo Project Pythia Logo

MITgcm ECCOv4 Example


Overview

This Jupyter notebook demonstrates how to use xarray and xgcm to analyze data from the ECCO v4r3 ocean state estimate.

  1. Loading ECCO zarr data and converting to an xarray dataset

  2. Visualize ocean depth using cartopy

  3. Indexing and selecting data using xarray

  4. Use dask cluster to speed up reading the data

  5. Calculate and plot the horizontally integrated heat content anomaly

  6. Use xgcm to compute the time-mean convergence of veritcally-integrated heat fluxes

Prerequisites

ConceptsImportanceNotes
Intro to CartopyHelpful
XarrayHelpfulSlicing, indexing, basic statistics
DaskHelpful
  • Time to learn: 1 hour


Imports

Load the data

The ECCOv4r3 data was converted from its raw MDS (.data / .meta file) format to zarr format, using the xmitgcm package. Zarr is a powerful data storage format that can be thought of as an alternative to HDF. In contrast to HDF, zarr works very well with cloud object storage. Zarr is currently useable in python, java, C++, and julia. It is likely that zarr will form the basis of the next major version of the netCDF library.

If you’re curious, here are some resources to learn more about zarr:

The ECCO zarr data currently lives in Google Cloud Storage as part of the Pangeo Data Catalog. This means we can open the whole dataset using one line of code.

This takes a bit of time to run because the metadata must be downloaded and parsed. The type of object returned is an Xarray dataset.

Could not determine bucket type for bucket name pangeo-ecco-eccov4r3: Your default credentials were not found. To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/external/set-up-adc for more information., falling back to GCSFileSystem
Could not determine bucket type for bucket name pangeo-ecco-eccov4r3: Your default credentials were not found. To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/external/set-up-adc for more information., falling back to GCSFileSystem
Could not determine bucket type for bucket name pangeo-ecco-eccov4r3: Your default credentials were not found. To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/external/set-up-adc for more information., falling back to GCSFileSystem
Could not determine bucket type for bucket name pangeo-ecco-eccov4r3: Your default credentials were not found. To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/external/set-up-adc for more information., falling back to GCSFileSystem
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[2], line 2
      1 cat = intake.open_catalog("https://raw.githubusercontent.com/pangeo-data/pangeo-datastore/master/intake-catalogs/ocean.yaml")
----> 2 ds = cat.ECCOv4r3.to_dask()
      3 ds

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/intake_xarray/base.py:8, in IntakeXarraySourceAdapter.to_dask(self)
      6 def to_dask(self):
      7     if "chunks" not in self.reader.kwargs:
----> 8         return self.reader(chunks={}).read()
      9     else:
     10         return self.reader.read()

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/intake/readers/readers.py:121, in BaseReader.read(self, *args, **kwargs)
    119 kw.update(kwargs)
    120 args = kw.pop("args", ()) or args
--> 121 return self._read(*args, **kw)

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/intake/readers/readers.py:1348, in XArrayDatasetReader._read(self, data, open_local, **kw)
   1346         f = fsspec.open(data.url, **(data.storage_options or {})).open()
   1347         return open_dataset(f, **kw)
-> 1348 return open_dataset(data.url, **kw)

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/xarray/backends/api.py:619, in open_dataset(filename_or_obj, engine, chunks, cache, decode_cf, mask_and_scale, decode_times, decode_timedelta, use_cftime, concat_characters, decode_coords, drop_variables, create_default_indexes, inline_array, chunked_array_type, from_array_kwargs, backend_kwargs, **kwargs)
    607 decoders = _resolve_decoders_kwargs(
    608     decode_cf,
    609     open_backend_dataset_parameters=backend.open_dataset_parameters,
   (...)    615     decode_coords=decode_coords,
    616 )
    618 overwrite_encoded_chunks = kwargs.pop("overwrite_encoded_chunks", None)
--> 619 backend_ds = backend.open_dataset(
    620     filename_or_obj,
    621     drop_variables=drop_variables,
    622     **decoders,
    623     **kwargs,
    624 )
    625 ds = _dataset_from_backend_dataset(
    626     backend_ds,
    627     filename_or_obj,
   (...)    638     **kwargs,
    639 )
    640 return ds

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/xarray/backends/zarr.py:1747, in ZarrBackendEntrypoint.open_dataset(self, filename_or_obj, mask_and_scale, decode_times, concat_characters, decode_coords, drop_variables, use_cftime, decode_timedelta, group, mode, consolidated, storage_options, zarr_format, store, engine, use_zarr_fill_value_as_mask, cache_members)
   1745 filename_or_obj = _normalize_path(filename_or_obj)
   1746 if not store:
-> 1747     store = ZarrStore.open_group(
   1748         filename_or_obj,
   1749         group=group,
   1750         mode=mode,
   1751         consolidated=consolidated,
   1752         consolidate_on_close=False,
   1753         storage_options=storage_options,
   1754         use_zarr_fill_value_as_mask=None,
   1755         zarr_format=zarr_format,
   1756         cache_members=cache_members,
   1757     )
   1759 store_entrypoint = StoreBackendEntrypoint()
   1760 with close_on_error(store):

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/xarray/backends/zarr.py:797, in ZarrStore.open_group(cls, store, mode, group, consolidated, consolidate_on_close, storage_options, append_dim, write_region, safe_chunks, align_chunks, zarr_format, use_zarr_fill_value_as_mask, write_empty, cache_members)
    774 @classmethod
    775 def open_group(
    776     cls,
   (...)    790     cache_members: bool = True,
    791 ):
    792     (
    793         zarr_group,
    794         consolidate_on_close,
    795         close_store_on_close,
    796         use_zarr_fill_value_as_mask,
--> 797     ) = _get_open_params(
    798         store=store,
    799         mode=mode,
    800         group=group,
    801         consolidated=consolidated,
    802         consolidate_on_close=consolidate_on_close,
    803         storage_options=storage_options,
    804         use_zarr_fill_value_as_mask=use_zarr_fill_value_as_mask,
    805         zarr_format=zarr_format,
    806     )
    808     return cls(
    809         zarr_group,
    810         mode,
   (...)    819         cache_members=cache_members,
    820     )

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/xarray/backends/zarr.py:1915, in _get_open_params(store, mode, group, consolidated, consolidate_on_close, storage_options, use_zarr_fill_value_as_mask, zarr_format)
   1911 group = open_kwargs.pop("path")
   1913 if consolidated:
   1914     # TODO: an option to pass the metadata_key keyword
-> 1915     zarr_root_group = zarr.open_consolidated(store, **open_kwargs)
   1916 elif consolidated is None:
   1917     # same but with more error handling in case no consolidated metadata found
   1918     try:

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/zarr/api/synchronous.py:261, in open_consolidated(use_consolidated, *args, **kwargs)
    256 def open_consolidated(*args: Any, use_consolidated: Literal[True] = True, **kwargs: Any) -> Group:
    257     """
    258     Alias for [`open_group`][zarr.api.synchronous.open_group] with `use_consolidated=True`.
    259     """
    260     return Group(
--> 261         sync(async_api.open_consolidated(*args, use_consolidated=use_consolidated, **kwargs))
    262     )

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/zarr/core/sync.py:155, in sync(coro, loop, timeout)
    152 return_result = next(iter(finished)).result()
    154 if isinstance(return_result, BaseException):
--> 155     raise return_result
    156 else:
    157     return return_result

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/zarr/core/sync.py:116, in _runner(coro)
    111 """
    112 Await a coroutine and return the result of running it. If awaiting the coroutine raises an
    113 exception, the exception will be returned.
    114 """
    115 try:
--> 116     return await coro
    117 except Exception as ex:  # noqa: BLE001 -- the caller re-raises the returned exception
    118     return ex

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/zarr/api/asynchronous.py:464, in open_consolidated(use_consolidated, *args, **kwargs)
    459 if use_consolidated is not True:
    460     raise TypeError(
    461         "'use_consolidated' must be 'True' in 'open_consolidated'. Use 'open' with "
    462         "'use_consolidated=False' to bypass consolidated metadata."
    463     )
--> 464 return await open_group(*args, use_consolidated=use_consolidated, **kwargs)

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/zarr/api/asynchronous.py:915, in open_group(store, mode, cache_attrs, synchronizer, path, chunk_store, storage_options, zarr_format, meta_array, attributes, use_consolidated)
    913 try:
    914     if mode in _READ_MODES:
--> 915         return await AsyncGroup.open(
    916             store_path, zarr_format=zarr_format, use_consolidated=use_consolidated
    917         )
    918 except (KeyError, FileNotFoundError):
    919     pass

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/zarr/core/group.py:621, in AsyncGroup.open(cls, store, zarr_format, use_consolidated)
    614         raise FileNotFoundError(store_path)
    615 elif zarr_format is None:
    616     (
    617         zarr_json_bytes,
    618         zgroup_bytes,
    619         zattrs_bytes,
    620         maybe_consolidated_metadata_bytes,
--> 621     ) = await asyncio.gather(
    622         (store_path / ZARR_JSON).get(),
    623         (store_path / ZGROUP_JSON).get(),
    624         (store_path / ZATTRS_JSON).get(),
    625         (store_path / str(consolidated_key)).get(),
    626     )
    627     if zarr_json_bytes is not None and zgroup_bytes is not None:
    628         # warn and favor v3
    629         msg = f"Both zarr.json (Zarr format 3) and .zgroup (Zarr format 2) metadata objects exist at {store_path}. Zarr format 3 will be used."

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/zarr/storage/_common.py:161, in StorePath.get(self, prototype, byte_range)
    159 if prototype is None:
    160     prototype = default_buffer_prototype()
--> 161 return await self.store.get(self.path, prototype=prototype, byte_range=byte_range)

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/zarr/storage/_fsspec.py:302, in FsspecStore.get(self, key, prototype, byte_range)
    300 try:
    301     if byte_range is None:
--> 302         value = prototype.buffer.from_bytes(await self.fs._cat_file(path))
    303     elif isinstance(byte_range, RangeByteRequest):
    304         value = prototype.buffer.from_bytes(
    305             await self.fs._cat_file(
    306                 path,
   (...)    309             )
    310         )

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/gcsfs/extended_gcsfs.py:624, in ExtendedGcsFileSystem._cat_file(self, path, start, end, mrd, **kwargs)
    621 bucket, object_name, generation = self.split_path(path)
    622 if not await self._is_zonal_bucket(bucket):
    623     # Fall back to default implementation if not a zonal bucket
--> 624     return await super()._cat_file(
    625         path, start=start, end=end, concurrency=concurrency, **kwargs
    626     )
    628 # Instantiate an MRDPool locally for this call
    629 mrd = await self._mrd_pool_cache.get(
    630     bucket,
    631     object_name,
   (...)    635     cache_source=cache_source,
    636 )

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/gcsfs/core.py:1392, in GCSFileSystem._cat_file(self, path, start, end, **kwargs)
   1385     return await self._cat_file_concurrent(
   1386         path, start=start, end=end, concurrency=concurrency, **kwargs
   1387     )
   1389 # While we could just call _cat_file_concurrent(concurrency=1), we are choosing
   1390 # to keep it separate because concurrency code path is still in an experimental phase.
   1391 # Once concurrency code path is stabilized, we can remove this if-else condition.
-> 1392 return await self._cat_file_sequential(path, start=start, end=end, **kwargs)

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/gcsfs/core.py:1340, in GCSFileSystem._cat_file_sequential(self, path, start, end, **kwargs)
   1338 cache_type = kwargs.get("cache_type")
   1339 cache_source = kwargs.get("cache_source")
-> 1340 headers, out = await self._call(
   1341     "GET", u2, headers=head, cache_type=cache_type, cache_source=cache_source
   1342 )
   1343 return out

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/gcsfs/core.py:653, in GCSFileSystem._call(self, method, path, json_out, info_out, *args, **kwargs)
    649 async def _call(
    650     self, method, path, *args, json_out=False, info_out=False, **kwargs
    651 ):
    652     logger.debug(f"{method.upper()}: {path}, {args}, {kwargs.get('headers')}")
--> 653     status, headers, info, contents = await self._request(
    654         method, path, *args, **kwargs
    655     )
    656     if json_out:
    657         return json.loads(contents)

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/decorator/__init__.py:328, in decorate.<locals>.async_fun(*args, **kw)
    326 if not kwsyntax:
    327     args, kw = fix(args, kw, sig)
--> 328 return await caller(func, *(extras + args), **kw)

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/gcsfs/retry.py:156, in retry_request(func, retries, *args, **kwargs)
    154     if retry > 0:
    155         await asyncio.sleep(min(random.random() + 2 ** (retry - 1), 32))
--> 156     return await func(*args, **kwargs)
    157 except (
    158     HttpError,
    159     requests.exceptions.RequestException,
   (...)    162     aiohttp.client_exceptions.ClientError,
    163 ) as e:
    164     if (
    165         isinstance(e, HttpError)
    166         and e.code == 400
    167         and "requester pays" in e.message
    168     ):

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/gcsfs/core.py:646, in GCSFileSystem._request(self, method, path, headers, json, data, cache_type, cache_source, *args, **kwargs)
    643 info = r.request_info  # for debug only
    644 contents = await r.read()
--> 646 validate_response(status, contents, path, args)
    647 return status, headers, info, contents

File ~/micromamba/envs/po-cookbook-dev/lib/python3.14/site-packages/gcsfs/retry.py:141, in validate_response(status, content, path, args)
    137     raise requests.exceptions.ProxyError()
    138 elif status != 401 and "invalid" in str(msg):
    139     # 401 is excluded so auth errors like "Invalid Credentials: invalid_token"
    140     # surface as HttpError and remain retriable via is_retriable().
--> 141     raise ValueError(f"Bad Request: {path}\n{msg}")
    142 elif error and isinstance(error, dict):
    143     raise HttpError({"code": status, **error})

ValueError: Bad Request: https://storage.googleapis.com/download/storage/v1/b/pangeo-ecco-eccov4r3/o/eccov4r3%2F.zmetadata?alt=media
User project specified in the request is invalid.

Note that no data has been actually download yet. Xarray uses the approach of lazy evaluation, in which loading of data and execution of computations is delayed as long as possible (i.e. until data is actually needed for a plot). The data are represented symbolically as dask arrays. For example:

SALT       (time, k, face, j, i) float32 dask.array<shape=(288, 50, 13, 90, 90), chunksize=(1, 50, 13, 90, 90)>

The full shape of the array is (288, 50, 13, 90, 90), quite large. But the chunksize is (1, 50, 13, 90, 90). Here the chunks correspond to the individual granuales of data (objects) in cloud storage. The chunk is the minimum amount of data we can read at one time.

Visualizing Data

A Direct Plot

Let’s try to visualize something simple: the Depth variable. Here is how the data are stored:

Depth      (face, j, i) float32 dask.array<shape=(13, 90, 90), chunksize=(13, 90, 90)>

Although depth is a 2D field, there is an extra, dimension (face) corresponding to the LLC face number. Let’s use xarray’s built in plotting functions to plot each face individually.

This view is not the most useful. It reflects how the data is arranged logically, rather than geographically.

A Pretty Map

To make plotting easier, we can define a quick function to plot the data in a more geographically friendly way. Eventually these plotting functions may be provided by the gcmplots package: https://github.com/xecco/gcmplots. For now, it is easy enough to roll our own.

We can use this with any 2D cell-centered LLC variable.

Selecting data

The entire ECCOv4e3 dataset is contained in a single Xarray.Dataset object. How do we find a view specific pieces of data? This is handled by Xarray’s indexing and selecting functions. To get the SST from January 2000, we do this:

Still no data has been actually downloaded. That doesn’t happen until we call .load() explicitly or try to make a plot.

Do some Calculations

Now let’s start doing something besides just plotting the existing data. For example, let’s calculate the time-mean SST.

As usual, no data was loaded. Instead, mean_sst is a symbolic representation of the data that needs to be pulled and the computations that need to be executed to produce the desired result. In this case, the 288 original chunks all need to be read from cloud storage. Dask coordinates this automatically for us. But it does take some time.

Speeding things up with a Dask Cluster

How can we speed things up? In general, the main bottleneck for this type of data analysis is the speed with which we can read the data. With cloud storage, the access is highly parallelizeable.

From a Pangeo environment, we can create a Dask cluster to spread the work out amongst many compute nodes. This works on both HPC and cloud. In the cloud, the compute nodes are provisioned on the fly and can be shut down as soon as we are done with our analysis.

The code below will create a cluster with five compute nodes. It can take a few minutes to provision our nodes.

Now we re-run the mean calculation. Note how the dashboard helps us visualize what the cluster is doing.

Spatially-Integrated Heat Content Anomaly

Now let’s do something harder. We will calculate the horizontally integrated heat content anomaly for the full 3D model domain.

Spatial Derivatives: Heat Budget

As our final exercise, we will do something much more complicated. We will compute the time-mean convergence of vertically-integrated heat fluxes. This is hard for several reasons.

The first reason it is hard is because it involves variables located at different grid points. Following MITgcm conventions, xmitgcm (which produced this dataset) labels the center point with the coordinates j, i, the u-velocity point as j, i_g, and the v-velocity point as j_g, i. The horizontal advective heat flux variables are

ADVx_TH    (time, k, face, j, i_g) float32 dask.array<shape=(288, 50, 13, 90, 90), chunksize=(1, 50, 13, 90, 90)>
ADVy_TH    (time, k, face, j_g, i) float32 dask.array<shape=(288, 50, 13, 90, 90), chunksize=(1, 50, 13, 90, 90)>

Xarray won’t allow us to add or multiply variables that have different dimensions, and xarray by itself doesn’t understand how to transform from one grid position to another.

That’s why xgcm was created.

Xgcm allows us to create a Grid object, which understands how to interpolate and take differences in a way that is compatible with finite volume models such at MITgcm. Xgcm also works with many other models, including ROMS, POP, MOM5/6, NEMO, etc.

A second reason this is hard is because of the complex topology connecting the different MITgcm faces. Fortunately xgcm also supports this.

Now we can use the grid object we created to take the divergence of a 2D vector


Summary

In this example we used xarray and cartopy to visualize ocean depth and ocean heat content anomalies. Then, we used xgcm to easily work with variables that have different dimensions.

What’s next?

In our last example, we will visualize ocean currents.

Resources and references