Merge tiles of a regular grid#

In this tutorial, we show how to:

  • make tile files that are subsets of a larger rectangular grid,

  • plot the tiles on the grid they are a subset of, to spot overlaps and gaps,

  • merge them with xoa.tiles.TileMerger and xoa.tiles.merge_tiles(),

  • choose how the overlaps are merged,

  • give the grid instead of inferring it, and check the memory needed.

The grid must have constant steps in degrees. See also: Grid operations, regridding and sigma coordinates.

Initialisations#

import glob
import os
import tempfile
import warnings

import matplotlib.pyplot as plt

import xoa
from xoa.plot import plot_field
from xoa.tiles import TileMerger, merge_tiles

plt.rcParams.update({"font.size": 9, "axes.titlesize": 10, "axes.titleweight": "bold"})

Make the tiles#

We start from a GLORYS12 run of the Gulf Stream, with a single time step, and write three files: a reference tile, a tile at its north and a tile at its west. The northern tile overlaps the reference one by four rows, whereas the western tile just touches it, with no overlap. To see how overlaps are merged, the northern tile is given a bias of 1 °C. The north-west corner is not covered by any tile.

ds = xoa.open_data_sample("MODELS/CMEMS-GLORYS/glorys_gulfstream_3d.nc")
ds = ds[["thetao", "uo", "vo"]].isel(time=slice(0, 1), depth=slice(0, 3))
print(dict(ds.sizes))

tmpdir = tempfile.TemporaryDirectory()
parts = {
    "ref": dict(longitude=slice(20, 60), latitude=slice(0, 30)),
    "north": dict(longitude=slice(20, 60), latitude=slice(26, 48)),
    "west": dict(longitude=slice(0, 20), latitude=slice(0, 30)),
}
for i, (name, sel) in enumerate(parts.items()):
    tile = ds.isel(sel).copy(deep=True)
    if name == "north":
        tile["thetao"] = tile.thetao + 1
    tile.to_netcdf(os.path.join(tmpdir.name, f"tile{i + 1}-{name}.nc"))
paths = sorted(glob.glob(os.path.join(tmpdir.name, "tile*.nc")))
[os.path.basename(path) for path in paths]
{'time': 1, 'depth': 3, 'latitude': 48, 'longitude': 60}

['tile1-ref.nc', 'tile2-north.nc', 'tile3-west.nc']

Describe the grid#

Tiles are added as datasets, as paths or as glob patterns. Files are opened lazily and only their coordinates are read at this stage. The grid steps, origin and size are inferred from the coordinates of the tiles. The representation shows them, the position of each tile as index slices and the estimated memory of the merge. The merged longitudes are put in lon_range, which would otherwise be inferred from the first tile.

tm = TileMerger(lon_range=(-180, 180))
tm.add(os.path.join(tmpdir.name, "tile*.nc"))
print(tm)
<TileMerger: 3 tiles, overlap='last', grid 60x48 (dx=0.1667, dy=0.1667), lon0=288.042, lat0=34.0417, memory~202 KiB>
  tile1-ref: x[20:60] y[0:30]
  tile2-north: x[20:60] y[26:48]
  tile3-west: x[0:20] y[0:30]

The plot shows the extent of the grid and the tiles on it. The overlaps are hatched in red and the gap, which will be filled with nans, in grey.

3 tiles on a 60×48 grid (0.1667°×0.1667°)
<GeoAxes: title={'center': '3 tiles on a 60×48 grid (0.1667°×0.1667°)'}>

Merge the tiles#

The merge() method puts each tile at its place. Where tiles overlap, the last valid value is kept by default. The merge_tiles() function does it all in a single call, from files, a glob pattern or datasets. Variables are transposed with longitude and latitude last.

<xarray.Dataset> Size: 208kB
Dimensions:    (depth: 3, time: 1, latitude: 48, longitude: 60)
Coordinates:
  * depth      (depth) float32 12B 0.494 1.541 2.646
  * time       (time) datetime64[ns] 8B 2019-10-01
  * latitude   (latitude) float64 384B 34.04 34.21 34.37 ... 41.54 41.71 41.87
  * longitude  (longitude) float64 480B -71.96 -71.79 -71.62 ... -62.29 -62.12
Data variables:
    thetao     (time, depth, latitude, longitude) float64 69kB 26.91 ... 18.32
    uo         (time, depth, latitude, longitude) float64 69kB -0.07324 ... 0...
    vo         (time, depth, latitude, longitude) float64 69kB 0.01404 ... 0....
Attributes:
    institution:               MERCATOR OCEAN
    history:                   2023/06/01 16:20:05 MERCATOR OCEAN Netcdf crea...
    source:                    MERCATOR GLORYS12V1
    references:                http://www.mercator-ocean.fr
    Conventions:               CF-1.4
    comment:                   CMEMS product
    title:                     daily mean fields from Global Ocean Physics An...
    copernicusmarine_version:  2.2.1


The sea surface temperature shows the missing corner as nans, and the bias of the northern tile.

plot_field(merged.thetao.isel(time=0, depth=0), title="Merged tiles")
Merged tiles
<cartopy.mpl.geocollection.GeoQuadMesh object at 0x738c03e7de50>

Overlaps#

The overlap argument is "last" or "first" to keep the value of the last or first tile, "mean" to average them or "raise" to fail when they differ. The nans of a tile never erase the values of another one. Here is a meridional section across the overlap, in the northern tile and the reference tile, which differ by 1 °C.

fig, ax = plt.subplots(figsize=(5, 3), constrained_layout=True)
for overlap in "first", "mean", "last":
    out = merge_tiles(paths, overlap=overlap)
    out.thetao.isel(time=0, depth=0, longitude=40).plot(ax=ax, label=overlap, marker=".")
lat = merged.latitude
ax.axvspan(float(lat[26]), float(lat[29]), color="r", alpha=0.15, lw=0)
ax.set_xlim(float(lat[18]), float(lat[36]))
ax.set_ylim(21, 28)
ax.legend(title="overlap")
ax.set_title("Meridional section at the overlap")
Meridional section at the overlap
Text(0.5, 1.0, 'Meridional section at the overlap')

With "raise", we get an error that tells which tile differs.

try:
    merge_tiles(paths, overlap="raise")
except xoa.exceptions.XoaError as exc:
    print(exc)
Tile 'tile2-north' differs from the previous ones for 480 values of 'thetao' in the overlaps

Numerous tiles#

With many tiles, filling each one with its own color gets messy. The tiles still get different colors from their neighbours, but a single color is better: the tiles are then only framed, and their names are written when they fit. Here, a 6 by 6 tiles split of the same grid, with two points of overlap and three tiles missing.

many = []
missing = {(1, 4), (2, 4), (5, 0)}
for j in range(6):
    for i in range(6):
        if (i, j) not in missing:
            tile = ds.isel(longitude=slice(10 * i, 10 * i + 12), latitude=slice(8 * j, 8 * j + 10))
            tile.attrs = {"name": f"{j}{i}"}
            many.append(tile)
tm_many = TileMerger(lon_range=(-180, 180))
tm_many.add(many)
print(tm_many)
tm_many.plot()
33 tiles on a 60×48 grid (0.1667°×0.1667°)
<TileMerger: 33 tiles, overlap='last', grid 60x48 (dx=0.1667, dy=0.1667), lon0=288.042, lat0=34.0417, memory~202 KiB>
  00: x[0:12] y[0:10]
  01: x[10:22] y[0:10]
  02: x[20:32] y[0:10]
  03: x[30:42] y[0:10]
  04: x[40:52] y[0:10]
  10: x[0:12] y[8:18]
  11: x[10:22] y[8:18]
  12: x[20:32] y[8:18]
  13: x[30:42] y[8:18]
  14: x[40:52] y[8:18]
  15: x[50:60] y[8:18]
  20: x[0:12] y[16:26]
  21: x[10:22] y[16:26]
  22: x[20:32] y[16:26]
  23: x[30:42] y[16:26]
  24: x[40:52] y[16:26]
  25: x[50:60] y[16:26]
  30: x[0:12] y[24:34]
  31: x[10:22] y[24:34]
  32: x[20:32] y[24:34]
  33: x[30:42] y[24:34]
  34: x[40:52] y[24:34]
  35: x[50:60] y[24:34]
  40: x[0:12] y[32:42]
  43: x[30:42] y[32:42]
  44: x[40:52] y[32:42]
  45: x[50:60] y[32:42]
  50: x[0:12] y[40:48]
  51: x[10:22] y[40:48]
  52: x[20:32] y[40:48]
  53: x[30:42] y[40:48]
  54: x[40:52] y[40:48]
  55: x[50:60] y[40:48]

<GeoAxes: title={'center': '33 tiles on a 60×48 grid (0.1667°×0.1667°)'}>
tm_many.plot(color="C0")
33 tiles on a 60×48 grid (0.1667°×0.1667°)
<GeoAxes: title={'center': '33 tiles on a 60×48 grid (0.1667°×0.1667°)'}>

Give the grid#

The grid may be given with the steps, the origin and the size, instead of being inferred. This is useful to merge the tiles on a larger domain, and to check that the tiles fit a known grid. A tile that is not on the grid, within tol times the step, raises an error. Here, we add a margin of 5 points all around.

grid = tm.grid
tm2 = TileMerger(
    dx=grid["dx"],
    dy=grid["dy"],
    lon0=grid["lon0"] - 5 * grid["dx"],
    lat0=grid["lat0"] - 5 * grid["dy"],
    nx=grid["nx"] + 10,
    ny=grid["ny"] + 10,
)
tm2.add(paths)
tm2.plot()
3 tiles on a 70×58 grid (0.1667°×0.1667°)
<GeoAxes: title={'center': '3 tiles on a 70×58 grid (0.1667°×0.1667°)'}>

Memory#

The merge is eager, so that the whole grid is loaded in memory. The estimate is given by nbytes, and a warning is issued by merge() when it exceeds max_memory which defaults to half the physical memory. Here is what happens with a limit of 100 kB.

print(tm2.memory)
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    TileMerger(max_memory=100e3).add(paths).merge()
print(caught[0].message)
285 KiB
The merged dataset needs about 202 KiB, which is more than the 97.7 KiB allowed: reduce the grid, drop variables or increase max_memory

Close the files and remove the temporary folder.

Total running time of the script: (0 minutes 2.663 seconds)

Gallery generated by Sphinx-Gallery