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


Select data at a point, in a box, a circle or a polygon
=======================================================

In this tutorial, we show how to:

* get the ``isel`` indexers of a box, a circle or a polygon, on a rectangular grid,
  a curvilinear grid or a cloud of points,
* choose between the smallest window that covers the shape and a mask (``outer``),
  or the largest window with only points inside (``inner``),
* add a margin of grid points, down to the cell edges, or of a distance,
* select a point, with scalar ``lon`` and ``lat``, or the nearest points to targets, among the valid ones if needed,
* reuse a selection for several arrays.

Distances are great circle ones, and the shapes can cross the dateline.
See also: :ref:`sphx_glr_tutorials_grids_plot_neighbors.py`.

.. GENERATED FROM PYTHON SOURCE LINES 21-23

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

.. GENERATED FROM PYTHON SOURCE LINES 23-67

.. code-block:: Python


    import cartopy.crs as ccrs
    import matplotlib.pyplot as plt
    import numpy as np
    import xarray as xr

    import xoa  # noqa: F401
    from xoa.core.grid import create_rotated_grid
    from xoa.geo import GeoSelector, geosel, get_geosel, with_geosel
    from xoa.plot import plot_box, plot_circle, plot_polygon

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


    def new_map(ncols=1, width=4.5, extent=(-7, -2, 45, 49.5)):
        """Create a figure with maps"""
        fig, axes = plt.subplots(
            1,
            ncols,
            figsize=(width * ncols, 3.8),
            subplot_kw={"projection": pc},
            constrained_layout=True,
            squeeze=False,
        )
        for ax in axes[0]:
            ax.set_extent(extent, crs=pc)
            ax.gridlines(draw_labels=True, linewidth=0.3, color="0.5")
        return fig, axes[0]


    def plot_selection(ax, grid, sel, color="C3", title=None):
        """Plot the points of a grid, those selected and those masked"""
        lon, lat = grid.lon, grid.lat
        sub = sel.apply(grid.sst)
        ax.plot(lon.values.ravel(), lat.values.ravel(), ",", color="0.7", transform=pc)
        ax.plot(sub.lon.values.ravel(), sub.lat.values.ravel(), ".", color="0.4", ms=3, transform=pc)
        ok = sub.notnull().values.ravel()
        ax.plot(
            sub.lon.values.ravel()[ok], sub.lat.values.ravel()[ok], ".", color=color, ms=3, transform=pc
        )
        ax.set_title(title)









.. GENERATED FROM PYTHON SOURCE LINES 68-70

Two grids are used: a rectangular one and a rotated curvilinear one, made with
:func:`xoa.core.grid.create_rotated_grid`.

.. GENERATED FROM PYTHON SOURCE LINES 70-86

.. code-block:: Python


    lon = xr.DataArray(np.arange(-7.0, -2.0, 0.1), dims="lon", name="lon")
    lat = xr.DataArray(np.arange(45.0, 49.5, 0.1), dims="lat", name="lat")
    rect = xr.DataArray(
        np.random.default_rng(0).random((lat.size, lon.size)),
        dims=("lat", "lon"),
        coords={"lon": lon, "lat": lat},
        name="sst",
    )

    grid = create_rotated_grid(50, 40, -4.5, 47.0, 25.0, 4.5, 3.5)
    curv = xr.Dataset(
        {"sst": (("y", "x"), np.random.default_rng(1).random(grid["lon"].shape))},
        coords={"lon": (("y", "x"), grid["lon"]), "lat": (("y", "x"), grid["lat"])},
    )








.. GENERATED FROM PYTHON SOURCE LINES 87-95

A box on a rectangular grid
---------------------------

On a rectangular grid, a box is exactly a pair of slices, so no mask is needed.
:func:`~xoa.geo.get_geosel` returns a :class:`~xoa.geo.GeoSelection`, whose ``isel`` attribute
is passed to :meth:`xarray.DataArray.isel`, or that is applied directly with
:meth:`~xoa.geo.GeoSelection.apply`.
The longitudes of a box can cross the dateline: ``lon=(170, -170)``.

.. GENERATED FROM PYTHON SOURCE LINES 95-102

.. code-block:: Python


    sel = get_geosel(rect, lon=(-5.5, -3.5), lat=(46, 48))
    print(sel)
    print(sel.mask)
    sub = sel.apply(rect)
    print(sub.shape)





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

 .. code-block:: none

    GeoSelection(isel={'lon': slice(16, 36, None), 'lat': slice(10, 30, None)}, mask=no)
    None
    (20, 20)




.. GENERATED FROM PYTHON SOURCE LINES 103-110

A box on a curvilinear grid
---------------------------

The same box is not a rectangle of indices anymore. With ``fit="outer"``, the smallest
window that covers the box is returned with a mask of the points that are inside it,
applied by :meth:`~xoa.geo.GeoSelection.apply` (or ``mask=False`` to keep them). With
``fit="inner"``, the largest window with only points inside is returned, and no mask is needed.

.. GENERATED FROM PYTHON SOURCE LINES 110-119

.. code-block:: Python


    box = dict(lon=(-5.2, -3.8), lat=(46.2, 47.4))
    fig, axes = new_map(2)
    for ax, fit in zip(axes, ["outer", "inner"]):
        sel = get_geosel(curv, fit=fit, **box)
        plot_selection(ax, curv, sel, title=f'fit="{fit}"')
        ax.plot([-5.2, -3.8, -3.8, -5.2, -5.2], [46.2, 46.2, 47.4, 47.4, 46.2], "k-", transform=pc)
        print(fit, sel.isel, None if sel.mask is None else int(sel.mask.sum()))




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_geosel_001.png
   :alt: fit="outer", fit="inner"
   :srcset: /tutorials/grids/images/sphx_glr_plot_geosel_001.png
   :class: sphx-glr-single-img


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

 .. code-block:: none

    outer {'y': slice(9, 27, None), 'x': slice(15, 34, None)} 205
    inner {'y': slice(13, 23, None), 'x': slice(18, 30, None)} None




.. GENERATED FROM PYTHON SOURCE LINES 120-126

Circles and polygons
--------------------

A circle is given by its center and radius, in meters or in kilometers with ``units``,
and a polygon by its vertices. The :class:`~xoa.geo.GeoSelector` class analyses the grid once,
to make several selections, which can be applied to several arrays.

.. GENERATED FROM PYTHON SOURCE LINES 126-136

.. code-block:: Python


    selector = GeoSelector(curv)
    circle = selector.select(circle=(-4.5, 47.0, 100), units="km")
    polygon = selector.select(polygon=[[-6, 46], [-4, 45.5], [-3.5, 47.5], [-5, 48.5]])

    fig, axes = new_map(2)
    plot_selection(axes[0], curv, circle, title="Circle of 100 km")
    plot_selection(axes[1], curv, polygon, title="Polygon")
    sst_circle, sst_polygon = circle.apply(curv.sst), polygon.apply(curv.sst)




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_geosel_002.png
   :alt: Circle of 100 km, Polygon
   :srcset: /tutorials/grids/images/sphx_glr_plot_geosel_002.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 137-144

A cloud of points
-----------------

Scattered observations, like those of a ship or of drifters, share a single dimension.
The selection is then a single array of indices, which is what ``isel`` needs, and there is
no mask. The :func:`~xoa.geo.geosel` function selects an array directly.
A margin in grid points makes no sense here: use a distance.

.. GENERATED FROM PYTHON SOURCE LINES 144-159

.. code-block:: Python


    rng = np.random.default_rng(2)
    obs = xr.Dataset(
        {"temp": ("obs", rng.normal(14, 2, 400))},
        coords={"lon": ("obs", rng.uniform(-7, -2, 400)), "lat": ("obs", rng.uniform(45, 49.5, 400))},
    )
    box_kw = dict(lon=(-6, -4.5), lat=(46, 47.5))
    circle_kw = dict(circle=(-3.5, 48, 70), units="km")
    polygon_kw = dict(polygon=[[-6, 46], [-4, 45.5], [-3.5, 47.5], [-5, 48.5]])
    box = geosel(obs, **box_kw)
    circle = geosel(obs, **circle_kw)
    polygon = geosel(obs, **polygon_kw)
    padded = geosel(obs, **circle_kw, pad=30, pad_units="km")
    print(box.sizes["obs"], circle.sizes["obs"], padded.sizes["obs"])





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

 .. code-block:: none

    39 22 60




.. GENERATED FROM PYTHON SOURCE LINES 160-163

The shapes are drawn with :func:`~xoa.plot.plot_box`, :func:`~xoa.plot.plot_circle` and
:func:`~xoa.plot.plot_polygon`, that take the same arguments as the selection. The circle is
a great circle one, and the margin of a circle is a larger radius.

.. GENERATED FROM PYTHON SOURCE LINES 163-176

.. code-block:: Python


    fig, axes = new_map(3, width=3.4)
    for ax, sub, title in zip(axes, [box, circle, polygon], ["Box", "Circle", "Polygon"]):
        ax.plot(obs.lon, obs.lat, ".", color="0.7", ms=3, transform=pc)
        ax.plot(sub.lon, sub.lat, ".", color="C3", ms=4, transform=pc)
        ax.set_title(title)
    plot_box(**box_kw, ax=axes[0])
    plot_circle(circle_kw["circle"], units="km", ax=axes[1])
    plot_polygon(polygon_kw["polygon"], ax=axes[2])
    axes[1].plot(padded.lon, padded.lat, ".", color="C1", ms=3, transform=pc, zorder=0.5)
    plot_circle((-3.5, 48, 100), units="km", ax=axes[1], edgecolor="C1", linestyle="--")
    axes[1].set_title("Circle, and with 30 km margin")




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_geosel_003.png
   :alt: Box, Circle, and with 30 km margin, Polygon
   :srcset: /tutorials/grids/images/sphx_glr_plot_geosel_003.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    Text(0.5, 1.085809777867711, 'Circle, and with 30 km margin')



.. GENERATED FROM PYTHON SOURCE LINES 177-179

The nearest observations to targets are found the same way, and the result is a pointwise
selection.

.. GENERATED FROM PYTHON SOURCE LINES 179-183

.. code-block:: Python


    sel = get_geosel(obs, nearest=([-6.0, -4.0], [46.0, 48.0]), units="km")
    print(obs.isel(sel.isel).temp.values, sel.dist.values.round(1))





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

 .. code-block:: none

    [10.41753835 15.99940284] [15.5  9.5]




.. GENERATED FROM PYTHON SOURCE LINES 184-192

Margins
-------

The ``pad`` argument grows the shape. In grid points, with ``pad_units="points"``, it uses
a local estimate of the grid step, from the cell edges, so it follows variable and rotated
cells. ``pad=1`` adds about one point around the shape, and ``pad="edges"`` (which is 0.5)
selects the points whose cell touches the shape, which is what is needed to draw
the selection with ``pcolormesh``. A distance is given with ``pad_units="km"``.

.. GENERATED FROM PYTHON SOURCE LINES 192-198

.. code-block:: Python


    fig, axes = new_map(3, width=3.4)
    for ax, pad, pad_units in zip(axes, [0, "edges", 30], ["points", "points", "km"]):
        sel = get_geosel(curv, circle=(-4.5, 47.0, 60), units="km", pad=pad, pad_units=pad_units)
        plot_selection(ax, curv, sel, title=f"pad={pad!r} {pad_units}")




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_geosel_004.png
   :alt: pad=0 points, pad='edges' points, pad=30 km
   :srcset: /tutorials/grids/images/sphx_glr_plot_geosel_004.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 199-206

Selecting a point
-----------------

Scalar ``lon`` and ``lat`` select the nearest point, like ``isel(lon=35, lat=45)`` does with
indices, on any kind of grid or on a cloud of points. The :func:`~xoa.geo.geosel` function and
the :meth:`~xarray.Dataset.xoa.geosel` accessor method return the data at that point, without
the horizontal dimensions.

.. GENERATED FROM PYTHON SOURCE LINES 206-209

.. code-block:: Python


    print(curv.xoa.geosel(lon=-4.5, lat=46.5))





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

 .. code-block:: none

    <xarray.Dataset> Size: 24B
    Dimensions:  ()
    Coordinates:
        lon      float64 8B -4.499
        lat      float64 8B 46.46
    Data variables:
        sst      float64 8B 0.8626




.. GENERATED FROM PYTHON SOURCE LINES 210-214

To get the indices and the distance to the point instead, give ``nearest=(lon, lat)`` to
:func:`~xoa.geo.get_geosel`. A scalar target gives integers, like ``isel`` does.
Several targets give a pointwise selection along a ``target`` dimension, and the distances
to them.

.. GENERATED FROM PYTHON SOURCE LINES 214-223

.. code-block:: Python


    sel = get_geosel(rect, nearest=(-4.53, 47.02), units="km")
    print(sel.isel, float(sel.dist))
    print(rect.isel(sel.isel).values)

    targets = ([-6.0, -5.0, -4.0], [46.0, 47.0, 48.0])
    sel = get_geosel(curv, nearest=targets, units="km")
    print(curv.isel(sel.isel).sst.values, sel.dist.values.round(1))





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

 .. code-block:: none

    {'lon': 25, 'lat': 20} 3.1811328764183946
    0.3924678243761738
    [0.07732382 0.30168325 0.35142922] [4.7 3.9 2.4]




.. GENERATED FROM PYTHON SOURCE LINES 224-230

The nearest valid point
-----------------------

A target on land has a land point as nearest neighbor, which has no data. With ``valid``, the
search is restricted to the points of a boolean mask, or to the points that have data with
``valid="auto"``, as given by :func:`~xoa.geo.get_valid_mask`.

.. GENERATED FROM PYTHON SOURCE LINES 230-245

.. code-block:: Python


    land = (lon > -4.3 + 0.5 * np.sin(4 * (lat - 45))).transpose("lat", "lon")
    sst = rect.where(~land)
    targets = ([-3.5, -3.0], [46.0, 47.5])

    fig, axes = new_map(2, width=3.4)
    for ax, valid in zip(axes, [None, "auto"]):
        sel = get_geosel(sst, nearest=targets, units="km", valid=valid)
        near = sst.isel(sel.isel)
        ax.pcolormesh(lon, lat, np.where(land, 0, 1), cmap="Blues", transform=pc, shading="nearest")
        ax.plot(*targets, "k^", transform=pc)
        ax.plot(near.lon, near.lat, "ro", transform=pc)
        ax.set_title(f"valid={valid!r}")
        print(valid, near.values, sel.dist.values.round(1))




.. image-sg:: /tutorials/grids/images/sphx_glr_plot_geosel_005.png
   :alt: valid=None, valid='auto'
   :srcset: /tutorials/grids/images/sphx_glr_plot_geosel_005.png
   :class: sphx-glr-single-img


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

 .. code-block:: none

    None [nan nan] [0. 0.]
    auto [0.94367777 0.14770547] [59.  81.1]




.. GENERATED FROM PYTHON SOURCE LINES 246-254

Reusing a selector, and the decorator
-------------------------------------

The selector analyses the grid once and makes as many selections as needed, which is
also done by the :meth:`~xarray.DataArray.xoa.get_geosel` method of the ``xoa`` accessor, that
caches it, while its :meth:`~xarray.DataArray.xoa.geosel` method applies the selection to the
object directly. The :func:`~xoa.geo.with_geosel` decorator adds a ``geosel`` argument to any
function that takes an array or dataset as first argument.

.. GENERATED FROM PYTHON SOURCE LINES 254-264

.. code-block:: Python



    @with_geosel
    def mean_sst(ds):
        return float(ds.sst.mean())


    print(mean_sst(curv))
    print(mean_sst(curv, geosel=dict(circle=(-4.5, 47.0, 50), units="km")))
    print(curv.xoa.geosel(lon=(-5, -4), lat=(46, 47)).sst.shape)




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

 .. code-block:: none

    0.5012847032599971
    0.4956501109558917
    (14, 14)





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

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


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

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

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

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

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

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

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


.. only:: html

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

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