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

.. only:: html

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

        :ref:`Go to the end <sphx_glr_download_tutorials_filtering_plot_decimate.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_filtering_plot_decimate.py:


Decimate scattered observations
===============================

In this tutorial, we show how to:

* build a synthetic set of observations that are much denser along tracks than elsewhere,
* thin them out with :func:`xoa.filter.decimate`, by picking points or by averaging them,
* choose the radius of selection and the amount of smoothing,
* measure the effect on the noise of the observations.

The concepts are explained in the :ref:`indepth.filtering` guide.
See also: :ref:`sphx_glr_tutorials_regrid_plot_kriging.py`,
:ref:`sphx_glr_tutorials_filtering_plot_filter_space.py`.

.. GENERATED FROM PYTHON SOURCE LINES 19-21

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

.. GENERATED FROM PYTHON SOURCE LINES 21-33

.. code-block:: Python


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

    from xoa import filter as xfilter
    from xoa.plot import add_colorbar

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








.. GENERATED FROM PYTHON SOURCE LINES 34-41

A synthetic set of observations
-------------------------------

The truth is an eddy of 3 °C in a field of 15 °C on a box of 10° by 8°.
The observations are random points, plus many more points that are measured along
two ship tracks, with a noise of 0.3 °C. The order of the points is shuffled,
which matters for the selection, as we'll see.

.. GENERATED FROM PYTHON SOURCE LINES 41-70

.. code-block:: Python


    rng = np.random.default_rng(0)
    lon0, lat0, radius_eddy = -15.0, 45.0, 2.0


    def truth(lon, lat):
        return 15 + 3 * np.exp(-((lon - lon0) ** 2 + (lat - lat0) ** 2) / radius_eddy**2)


    def track(lon_start, lat_start, lon_end, lat_end, npts):
        s = np.sort(rng.uniform(size=npts))
        return lon_start + s * (lon_end - lon_start), lat_start + s * (lat_end - lat_start)


    lon_t1, lat_t1 = track(-19, 41, -11, 49, 1200)
    lon_t2, lat_t2 = track(-19, 48, -11, 42, 800)
    lon = np.concatenate([rng.uniform(-20, -10, 300), lon_t1, lon_t2])
    lat = np.concatenate([rng.uniform(40, 48, 300), lat_t1, lat_t2])
    order = rng.permutation(lon.size)
    lon, lat = lon[order], lat[order]
    obs = xr.Dataset(
        {"temp": ("npts", truth(lon, lat) + rng.normal(scale=0.3, size=lon.size), {"units": "°C"})},
        coords={
            "lon": ("npts", lon, {"standard_name": "longitude"}),
            "lat": ("npts", lat, {"standard_name": "latitude"}),
        },
    )
    print(obs.sizes["npts"], "observations")





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

 .. code-block:: none

    2300 observations




.. GENERATED FROM PYTHON SOURCE LINES 71-81

Pick or average
---------------

:func:`~xoa.filter.decimate` loops over the points and keeps a point only if it is at least
``radius`` meters away from all the points that were kept before. With ``"pick"``, the kept points
have their original values. With ``"average"``, the default, they get the average of all the points
that are within ``radius * smooth_factor`` meters, which reduces the noise.
The kept points are the same in both cases, and they depend on the order of the points,
which is why we shuffled them: along a track, the points would be picked
from one end to the other.

.. GENERATED FROM PYTHON SOURCE LINES 81-94

.. code-block:: Python


    radius = 80e3
    picked = xfilter.decimate(obs, radius, method="pick")
    averaged = xfilter.decimate(obs, radius, method="average")
    print(f"Kept: {picked.sizes['npts']} points, with a radius of {radius * 1e-3:.0f} km")

    kw = dict(cmap=cmocean.cm.thermal, vmin=14.5, vmax=18, s=6)
    fig, axes = plt.subplots(1, 3, figsize=(10, 2.8), sharex=True, sharey=True, constrained_layout=True)
    for ax, (title, d) in zip(axes, {"Original": obs, "Picked": picked, "Averaged": averaged}.items()):
        sc = ax.scatter(d.lon, d.lat, c=d.temp, **kw)
        ax.set_title(f"{title}: {d.sizes['npts']} points")
    add_colorbar(sc, axes, da=obs.temp)




.. image-sg:: /tutorials/filtering/images/sphx_glr_plot_decimate_001.png
   :alt: Original: 2300 points, Picked: 63 points, Averaged: 63 points
   :srcset: /tutorials/filtering/images/sphx_glr_plot_decimate_001.png
   :class: sphx-glr-single-img


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

 .. code-block:: none

    Kept: 63 points, with a radius of 80 km

    <matplotlib.colorbar.Colorbar object at 0x738c04325550>



.. GENERATED FROM PYTHON SOURCE LINES 95-105

The decimated points are evenly spaced, and the tracks no longer dominate. The averaged ones
are smoother, since the noise is averaged, while the picked ones keep the noise.

The smoothing factor
--------------------

``smooth_factor`` is the ratio of the averaging radius to the selection radius. A value
of 0 is the same as ``"pick"``. A value of 1, the default, averages over the same radius,
and a larger value smooths more but also erodes the eddy, until the average is that of the whole
domain with an infinite factor. The error against the truth has a minimum between them.

.. GENERATED FROM PYTHON SOURCE LINES 105-131

.. code-block:: Python


    factors = (0, 0.5, 1, 1.5, 2, 3, 5)
    rmse = [
        float(
            np.sqrt(
                ((d := xfilter.decimate(obs, radius, smooth_factor=factor)).temp - truth(d.lon, d.lat))
                ** 2
            ).mean()
        )
        for factor in factors
    ]
    fig, axes = plt.subplots(1, 2, figsize=(9, 2.8), constrained_layout=True)
    axes[0].plot(factors, rmse, "o-")
    axes[0].set_xlabel("smooth_factor")
    axes[0].set_ylabel("RMSE against the truth (°C)")
    axes[0].set_title("Error of the decimated points")
    for factor, color in ((0, "0.7"), (1, "C0"), (3, "C1")):
        d = xfilter.decimate(obs, radius, smooth_factor=factor)
        axes[1].scatter(d.lat, d.temp, s=8, color=color, label=f"smooth_factor={factor}")
    lats = np.linspace(40, 50, 100)
    axes[1].plot(lats, truth(lon0, lats), "k", lw=1, label="Truth at -15°E")
    axes[1].legend()
    axes[1].set_xlabel("Latitude (°N)")
    axes[1].set_ylabel("Temperature (°C)")
    axes[1].set_title("Smoothing the eddy")




.. image-sg:: /tutorials/filtering/images/sphx_glr_plot_decimate_002.png
   :alt: Error of the decimated points, Smoothing the eddy
   :srcset: /tutorials/filtering/images/sphx_glr_plot_decimate_002.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    Text(0.5, 1.0, 'Smoothing the eddy')



.. GENERATED FROM PYTHON SOURCE LINES 132-139

Choosing the radius
-------------------

The radius is the minimal distance between the kept points, hence the resolution of the
decimated set. It must be smaller than the scale you want to resolve.
Before a kriging, it is chosen smaller than the correlation length of the variogram,
and large enough to keep a reasonable number of points: see :ref:`sphx_glr_tutorials_regrid_plot_kriging.py`.

.. GENERATED FROM PYTHON SOURCE LINES 139-146

.. code-block:: Python


    fig, ax = plt.subplots(figsize=(5, 2.8), constrained_layout=True)
    radii = np.array([10, 20, 40, 80, 160, 320]) * 1e3
    ax.loglog(radii * 1e-3, [xfilter.decimate(obs, r).sizes["npts"] for r in radii], "o-")
    ax.set_xlabel("Radius (km)")
    ax.set_ylabel("Number of kept points")
    ax.set_title("Kept points as a function of the radius")



.. image-sg:: /tutorials/filtering/images/sphx_glr_plot_decimate_003.png
   :alt: Kept points as a function of the radius
   :srcset: /tutorials/filtering/images/sphx_glr_plot_decimate_003.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    Text(0.5, 1.0, 'Kept points as a function of the radius')




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

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


.. _sphx_glr_download_tutorials_filtering_plot_decimate.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/filtering/plot_decimate.ipynb
        :alt: Launch binder
        :width: 150 px

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

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

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

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

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

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


.. only:: html

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

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