
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "tutorials/grids/plot_grid_tools.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_grid_tools.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_grid_tools.py:


Inspect and manipulate horizontal and vertical grids
====================================================

In this tutorial, we show how to:

* compute the horizontal resolution of a regular or curvilinear grid,
* plot the edges and centers of a grid, with an adaptive under-sampling,
* get the geographic extent of the strips along the edges of a grid,
* convert a 2D longitude and latitude to 1D axes when the grid allows it,
* compute the edges of cells from their centers, with extrapolation at the ends,
* pad an array and its coordinates.

The concepts are explained in the :ref:`indepth.grids` guide.
See also: :ref:`sphx_glr_tutorials_regrid_plot_regrid_interp.py`, :ref:`sphx_glr_tutorials_vertical_plot_croco_section.py`.

.. GENERATED FROM PYTHON SOURCE LINES 20-22

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

.. GENERATED FROM PYTHON SOURCE LINES 22-35

.. code-block:: Python


    import matplotlib.pyplot as plt
    import numpy as np
    import xarray as xr

    import xoa
    from xoa import grid
    from xoa.core.grid import create_rotated_grid
    from xoa.plot import plot_grid

    xr.set_options(display_style="text")
    plt.rcParams.update({"font.size": 9, "axes.titlesize": 10, "axes.titleweight": "bold"})








.. GENERATED FROM PYTHON SOURCE LINES 36-40

Horizontal resolution
---------------------

We use the surface temperature of a regional model, with 2D longitudes and latitudes.

.. GENERATED FROM PYTHON SOURCE LINES 40-44

.. code-block:: Python


    ds = xoa.open_data_sample("MODELS/CROCO/SOUTH-AFRICA/croco.south-africa.surf.nc")
    temp = ds.temp.isel(time=0, s_rho=-1)








.. GENERATED FROM PYTHON SOURCE LINES 45-48

:func:`~xoa.grid.get_resolution` gives the distance in meters between adjacent points
along x and y. The arrays have one point less than the grid along the dimension
of the difference.

.. GENERATED FROM PYTHON SOURCE LINES 48-54

.. code-block:: Python


    dx, dy = grid.get_resolution(temp)
    print(dx.dims, dx.shape, dy.shape)
    print(f"dx: {dx.min().item() / 1e3:.1f} - {dx.max().item() / 1e3:.1f} km")
    print(f"dy: {dy.min().item() / 1e3:.1f} - {dy.max().item() / 1e3:.1f} km")





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

 .. code-block:: none

    ('eta_rho', 'xi_rho') (28, 41) (27, 42)
    dx: 14.7 - 15.4 km
    dy: 14.7 - 15.3 km




.. GENERATED FROM PYTHON SOURCE LINES 55-58

The resolution shrinks along x towards the poles, as meridians get closer.
The :func:`~xoa.grid.get_median_resolution` function gives a single value in degrees, which is
convenient to choose the resolution of another dataset.

.. GENERATED FROM PYTHON SOURCE LINES 58-61

.. code-block:: Python


    print(grid.get_median_resolution(temp))





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

 .. code-block:: none

    0.16666603088378906




.. GENERATED FROM PYTHON SOURCE LINES 62-67

Plot the grid
-------------

The :func:`xoa.plot.plot_grid` function draws the edges and the centers of the cells.
Edges are computed from the centers, with extrapolation at the ends of the grid.

.. GENERATED FROM PYTHON SOURCE LINES 67-70

.. code-block:: Python


    plot_grid(temp)




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_grid_tools_001.png
   :alt: plot grid tools
   :srcset: /tutorials/grids/images/sphx_glr_plot_grid_tools_001.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <GeoAxes: >



.. GENERATED FROM PYTHON SOURCE LINES 71-76

Large grids are under-sampled to stay readable. By default, the stride is adapted
to the size of the map, so that cells are at least ``min_spacing`` pixels apart on screen,
whatever the number of cells, the projection or the rotation of the grid.
Here is a grid of 400 x 300 points, from :func:`xoa.core.grid.create_rotated_grid`, that is
drawn with only a few tens of lines, and whose displayed centers are the ones of the coarse cells.

.. GENERATED FROM PYTHON SOURCE LINES 76-86

.. code-block:: Python


    big = create_rotated_grid(400, 300, 18.5, -36.0, 25.0, 4.0, 2.5)
    big = xr.Dataset(
        {
            "lon": (("y", "x"), big["lon"], {"standard_name": "longitude", "units": "degrees_east"}),
            "lat": (("y", "x"), big["lat"], {"standard_name": "latitude", "units": "degrees_north"}),
        }
    )
    plot_grid(big)




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_grid_tools_002.png
   :alt: plot grid tools
   :srcset: /tutorials/grids/images/sphx_glr_plot_grid_tools_002.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <GeoAxes: >



.. GENERATED FROM PYTHON SOURCE LINES 87-90

The stride can also be set by hand, for each direction, and edges or centers
can be switched off. When it does not divide the number of cells, the coarse cells
are spread evenly instead of leaving a thin one at the end.

.. GENERATED FROM PYTHON SOURCE LINES 90-93

.. code-block:: Python


    plot_grid(big, stride=(40, 60), centers=False)




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_grid_tools_003.png
   :alt: plot grid tools
   :srcset: /tutorials/grids/images/sphx_glr_plot_grid_tools_003.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <GeoAxes: >



.. GENERATED FROM PYTHON SOURCE LINES 94-97

The resolution is shown on a map as the geometric mean of the resolutions along x and y,
and the bathymetry of a dataset is found thanks to its meta-data.
Edges can be drawn over these fields.

.. GENERATED FROM PYTHON SOURCE LINES 97-100

.. code-block:: Python


    plot_grid(temp, kind="resolution")




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_grid_tools_004.png
   :alt: plot grid tools
   :srcset: /tutorials/grids/images/sphx_glr_plot_grid_tools_004.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <GeoAxes: >



.. GENERATED FROM PYTHON SOURCE LINES 101-103

.. code-block:: Python

    plot_grid(ds, kind="bathy", edges=True, map_kw={"land": True})




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_grid_tools_005.png
   :alt: plot grid tools
   :srcset: /tutorials/grids/images/sphx_glr_plot_grid_tools_005.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <GeoAxes: >



.. GENERATED FROM PYTHON SOURCE LINES 104-105

Let's check how the resolution varies on a larger domain, with a regular grid in degrees.

.. GENERATED FROM PYTHON SOURCE LINES 105-125

.. code-block:: Python


    lon_attrs = {"standard_name": "longitude", "units": "degrees_east"}
    lat_attrs = {"standard_name": "latitude", "units": "degrees_north"}
    world = xr.Dataset(
        coords={
            "lon": ("lon", np.arange(0.0, 40.0, 1.0), lon_attrs),
            "lat": ("lat", np.arange(-80.0, 81.0, 1.0), lat_attrs),
        }
    )
    wdx, wdy = grid.get_resolution(world)
    fig, ax = plt.subplots(figsize=(6, 4), constrained_layout=True)
    ax.plot(wdx.isel(lon=0) / 1e3, world.lat[:], label="along x")
    ax.plot(
        wdy.isel(lon=0) / 1e3, 0.5 * (world.lat[1:].values + world.lat[:-1].values), label="along y"
    )
    ax.set_xlabel("Resolution (km)")
    ax.set_ylabel("Latitude")
    ax.grid(alpha=0.3)
    ax.legend()




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_grid_tools_006.png
   :alt: plot grid tools
   :srcset: /tutorials/grids/images/sphx_glr_plot_grid_tools_006.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <matplotlib.legend.Legend object at 0x738c0531dbe0>



.. GENERATED FROM PYTHON SOURCE LINES 126-132

Edge extents
------------

The extent of a rotated grid is much larger than the area it really covers.
:func:`~xoa.grid.get_edge_extents` gives the bounding box of the strips made of the
first or last cells along each edge, which follow the grid.

.. GENERATED FROM PYTHON SOURCE LINES 132-143

.. code-block:: Python


    rotated_grid = create_rotated_grid(30, 20, 18.5, -36.0, 25.0, 4.0, 2.5)
    rotated = xr.Dataset(
        {
            "lon": (("y", "x"), rotated_grid["lon"], lon_attrs),
            "lat": (("y", "x"), rotated_grid["lat"], lat_attrs),
        }
    )
    extents = grid.get_edge_extents(rotated, ["north", "west"], n_cells=3)
    print(extents)





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

 .. code-block:: none

    {'north': [16.159111598750826, 19.895558078934453, -35.95085383890576, -34.02187874272279], 'west': [16.159111598750826, 17.465673194354064, -37.97812125727721, -35.59576744161919]}




.. GENERATED FROM PYTHON SOURCE LINES 144-146

:func:`xoa.plot.plot_grid` draws the mesh and these strips, which are compatible with
:func:`xoa.geo.get_extent` that gives the extent of the whole grid.

.. GENERATED FROM PYTHON SOURCE LINES 146-149

.. code-block:: Python


    plot_grid(rotated, strips=["north", "west"], n_cells=3)




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_grid_tools_007.png
   :alt: plot grid tools
   :srcset: /tutorials/grids/images/sphx_glr_plot_grid_tools_007.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <GeoAxes: >



.. GENERATED FROM PYTHON SOURCE LINES 150-156

Convert to rectangular axes
---------------------------

When 2D longitudes and latitudes are constant along one dimension, they are in fact
1D axes. :func:`~xoa.grid.to_rect` converts them, and the dimensions are renamed
accordingly. The check is based on :func:`xoa.core.grid.check_grid_type`.

.. GENERATED FROM PYTHON SOURCE LINES 156-159

.. code-block:: Python


    print(temp.dims, "->", grid.to_rect(temp).dims)





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

 .. code-block:: none

    ('eta_rho', 'xi_rho') -> ('lat_rho', 'lon_rho')




.. GENERATED FROM PYTHON SOURCE LINES 160-161

It leaves curvilinear grids unchanged, and warns unless ``errors="ignore"``.

.. GENERATED FROM PYTHON SOURCE LINES 161-169

.. code-block:: Python


    data = xr.DataArray(
        np.zeros(rotated.lon.shape),
        dims=rotated.lon.dims,
        coords={"lon": rotated.lon, "lat": rotated.lat},
    )
    print(grid.to_rect(data, errors="ignore").lon.ndim)





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

 .. code-block:: none

    2




.. GENERATED FROM PYTHON SOURCE LINES 170-176

Cell edges
----------

:func:`~xoa.grid.get_edges` computes the edges of the cells from their centers.
Inner edges are in the middle of the centers, and outer ones are extrapolated
by default. This is what the conservative regridding along a dimension needs.

.. GENERATED FROM PYTHON SOURCE LINES 176-181

.. code-block:: Python


    depth = xoa.open_data_sample("MODELS/CMEMS-IBI/ibi-argo-7900573.nc").depth
    edges = grid.get_edges(depth, "depth")
    print(depth.values[:4], edges.values[:5])





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

 .. code-block:: none

    [0.494025 1.541375 2.645669 3.819495] [-0.02965003  1.0177      2.093522    3.232582    4.4488597 ]




.. GENERATED FROM PYTHON SOURCE LINES 182-184

The ``edge`` mode replicates the end values instead, so that the first and last
cells are half as thick as their neighbours.

.. GENERATED FROM PYTHON SOURCE LINES 184-187

.. code-block:: Python


    print(grid.get_edges(depth, "depth", mode="edge").values[:5])





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

 .. code-block:: none

    [0.494025  1.0177    2.093522  3.232582  4.4488597]




.. GENERATED FROM PYTHON SOURCE LINES 188-189

Conversely, :func:`~xoa.grid.get_centers` gives the middle of consecutive points.

.. GENERATED FROM PYTHON SOURCE LINES 189-192

.. code-block:: Python


    print(grid.get_centers(edges, "depth").values[:4])





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

 .. code-block:: none

    [0.49402493 1.555611   2.663052   3.840721  ]




.. GENERATED FROM PYTHON SOURCE LINES 193-198

Padding
-------

:func:`~xoa.grid.pad` adds points along dimensions, to the data and to their coordinates,
which are linearly extrapolated by default.

.. GENERATED FROM PYTHON SOURCE LINES 198-203

.. code-block:: Python


    sst = temp.isel(eta_rho=slice(0, 3), xi_rho=slice(0, 4))
    padded = grid.pad(sst, {"eta_rho": 1, "xi_rho": (0, 2)}, mode="linear_extrap")
    print(sst.shape, "->", padded.shape)
    print(sst.lon_rho.values[0], padded.lon_rho.values[0])




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

 .. code-block:: none

    (3, 4) -> (5, 6)
    [15.083333 15.25     15.416667 15.583333] [15.083333 15.25     15.416667 15.583333 15.749999 15.916665]





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

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


.. _sphx_glr_download_tutorials_grids_plot_grid_tools.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_grid_tools.ipynb
        :alt: Launch binder
        :width: 150 px

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

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

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

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

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

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


.. only:: html

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

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