
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "tutorials/grids/plot_tiles.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_tutorials_grids_plot_tiles.py>`
        to download the full example code or to run this example in your browser via Binder.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_tutorials_grids_plot_tiles.py:


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 :class:`xoa.tiles.TileMerger` and :func:`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: :ref:`indepth.grids`.

.. GENERATED FROM PYTHON SOURCE LINES 19-21

Initialisations
---------------

.. GENERATED FROM PYTHON SOURCE LINES 21-35

.. code-block:: Python


    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"})








.. GENERATED FROM PYTHON SOURCE LINES 36-43

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.

.. GENERATED FROM PYTHON SOURCE LINES 43-62

.. code-block:: Python


    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]





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    {'time': 1, 'depth': 3, 'latitude': 48, 'longitude': 60}

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



.. GENERATED FROM PYTHON SOURCE LINES 63-71

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.

.. GENERATED FROM PYTHON SOURCE LINES 71-76

.. code-block:: Python


    tm = TileMerger(lon_range=(-180, 180))
    tm.add(os.path.join(tmpdir.name, "tile*.nc"))
    print(tm)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    <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]




.. GENERATED FROM PYTHON SOURCE LINES 77-79

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.

.. GENERATED FROM PYTHON SOURCE LINES 79-82

.. code-block:: Python


    tm.plot()




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_tiles_001.png
   :alt: 3 tiles on a 60×48 grid (0.1667°×0.1667°)
   :srcset: /tutorials/grids/images/sphx_glr_plot_tiles_001.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none


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



.. GENERATED FROM PYTHON SOURCE LINES 83-89

Merge the tiles
---------------
The :meth:`~xoa.tiles.TileMerger.merge` method puts each tile at its place.
Where tiles overlap, the last valid value is kept by default. The
:func:`~xoa.tiles.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.

.. GENERATED FROM PYTHON SOURCE LINES 89-93

.. code-block:: Python


    merged = merge_tiles(os.path.join(tmpdir.name, "tile*.nc"))
    merged






.. raw:: html

    <div class="output_subarea output_html rendered_html output_result">
    <pre>&lt;xarray.Dataset&gt; 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</pre>
    </div>
    <br />
    <br />

.. GENERATED FROM PYTHON SOURCE LINES 94-96

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

.. GENERATED FROM PYTHON SOURCE LINES 96-99

.. code-block:: Python


    plot_field(merged.thetao.isel(time=0, depth=0), title="Merged tiles")




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_tiles_002.png
   :alt: Merged tiles
   :srcset: /tutorials/grids/images/sphx_glr_plot_tiles_002.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    <cartopy.mpl.geocollection.GeoQuadMesh object at 0x738c03e7de50>



.. GENERATED FROM PYTHON SOURCE LINES 100-107

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.

.. GENERATED FROM PYTHON SOURCE LINES 107-119

.. code-block:: Python


    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")




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_tiles_003.png
   :alt: Meridional section at the overlap
   :srcset: /tutorials/grids/images/sphx_glr_plot_tiles_003.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    Text(0.5, 1.0, 'Meridional section at the overlap')



.. GENERATED FROM PYTHON SOURCE LINES 120-121

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

.. GENERATED FROM PYTHON SOURCE LINES 121-127

.. code-block:: Python


    try:
        merge_tiles(paths, overlap="raise")
    except xoa.exceptions.XoaError as exc:
        print(exc)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    Tile 'tile2-north' differs from the previous ones for 480 values of 'thetao' in the overlaps




.. GENERATED FROM PYTHON SOURCE LINES 128-134

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.

.. GENERATED FROM PYTHON SOURCE LINES 134-148

.. code-block:: Python


    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()




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_tiles_004.png
   :alt: 33 tiles on a 60×48 grid (0.1667°×0.1667°)
   :srcset: /tutorials/grids/images/sphx_glr_plot_tiles_004.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    <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°)'}>



.. GENERATED FROM PYTHON SOURCE LINES 149-151

.. code-block:: Python

    tm_many.plot(color="C0")




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_tiles_005.png
   :alt: 33 tiles on a 60×48 grid (0.1667°×0.1667°)
   :srcset: /tutorials/grids/images/sphx_glr_plot_tiles_005.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none


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



.. GENERATED FROM PYTHON SOURCE LINES 152-158

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.

.. GENERATED FROM PYTHON SOURCE LINES 158-171

.. code-block:: Python


    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()




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_tiles_006.png
   :alt: 3 tiles on a 70×58 grid (0.1667°×0.1667°)
   :srcset: /tutorials/grids/images/sphx_glr_plot_tiles_006.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none


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



.. GENERATED FROM PYTHON SOURCE LINES 172-178

Memory
------
The merge is eager, so that the whole grid is loaded in memory. The estimate is
given by :attr:`~xoa.tiles.TileMerger.nbytes`, and a warning is issued by
:meth:`~xoa.tiles.TileMerger.merge` when it exceeds ``max_memory`` which defaults to half
the physical memory. Here is what happens with a limit of 100 kB.

.. GENERATED FROM PYTHON SOURCE LINES 178-185

.. code-block:: Python


    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)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    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




.. GENERATED FROM PYTHON SOURCE LINES 186-187

Close the files and remove the temporary folder.

.. GENERATED FROM PYTHON SOURCE LINES 187-191

.. code-block:: Python


    tm.close()
    tm2.close()
    tmpdir.cleanup()








.. rst-class:: sphx-glr-timing

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


.. _sphx_glr_download_tutorials_grids_plot_tiles.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: binder-badge

      .. image:: images/binder_badge_logo.svg
        :target: https://mybinder.org/v2/gh/shom-fr/xoa/master?urlpath=lab/tree/notebooks/tutorials/grids/plot_tiles.ipynb
        :alt: Launch binder
        :width: 150 px

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: plot_tiles.ipynb <plot_tiles.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: plot_tiles.py <plot_tiles.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: plot_tiles.zip <plot_tiles.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
