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

.. only:: html

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

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


Advect particles in the Gulf Stream currents
============================================

In this tutorial, we show how to:

* find the surface currents and the sea level of a reanalysis,
* draw the flow as a "windy" plot of short lagrangian tracks,
* release particles across the stream and follow them,
* see how a patch of particles is stretched and dispersed, with distances on the sphere.

The data are surface fields of the GLORYS12 reanalysis of the Copernicus Marine Service,
averaged over 2 x 2 grid cells, on the 1st of October 2019, in the region of the Gulf Stream.
The currents are steady here, since there is a single date.
See also: :ref:`sphx_glr_tutorials_dynamics_plot_gulfstream_dynamics.py`.

.. GENERATED FROM PYTHON SOURCE LINES 20-22

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

.. GENERATED FROM PYTHON SOURCE LINES 22-41

.. code-block:: Python


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

    import xoa
    import xoa.meta as xmeta
    from xoa.dyn import flow2d, get_sea_level
    from xoa.geo import haversine
    from xoa.plot import plot_field, plot_flow

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

    MAP_KW = {"gridlines_labels_on": ["bottom", "left"], "land": True}
    PCAR = ccrs.PlateCarree()








.. GENERATED FROM PYTHON SOURCE LINES 42-47

The currents
------------

The sea level is searched with :func:`xoa.dyn.get_sea_level`, which knows the
usual variants (SSH, ADT, SLA...) from the naming specifications.

.. GENERATED FROM PYTHON SOURCE LINES 47-57

.. code-block:: Python


    with xmeta.set_meta_specs("mercator"):
        ds = xoa.open_data_sample("MODELS/CMEMS-GLORYS/glorys_gulfstream_3d.nc").xoa.decode()
    ds = ds.isel(time=0, depth=0)
    u, v = ds.xoa.get("u"), ds.xoa.get("v")
    ssh = get_sea_level(ds)
    speed = np.hypot(u, v).rename("speed")
    speed.attrs.update(long_name="Surface current speed", units="m s-1")
    print(ssh.name, ":", ssh.attrs["long_name"])





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

 .. code-block:: none

    ssh : Sea surface height




.. GENERATED FROM PYTHON SOURCE LINES 58-64

The flow as a windy plot
------------------------

:func:`xoa.plot.plot_flow` advects a few thousand random particles during a short time
and draws their tracks with a fading transparency: it reveals the structure of the flow, like
the meanders and the eddies of the stream.

.. GENERATED FROM PYTHON SOURCE LINES 64-68

.. code-block:: Python


    ax = plot_field(speed, cmap=cmocean.cm.deep, map_kw=MAP_KW).axes
    plot_flow(u, v, axes=ax, color="w", particles=3000, linewidth=(0.3, 0.9), transform=PCAR)




.. image-sg:: /tutorials/dynamics/images/sphx_glr_plot_flow_advection_001.png
   :alt: plot flow advection
   :srcset: /tutorials/dynamics/images/sphx_glr_plot_flow_advection_001.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    {'axes': <GeoAxes: >, 'step': np.float64(10674.772895729355), 'duration': np.float64(106747.72895729354), 'linecollection': <matplotlib.collections.LineCollection object at 0x738c03dc20d0>}



.. GENERATED FROM PYTHON SOURCE LINES 69-77

Release particles across the stream
-----------------------------------

:func:`xoa.dyn.flow2d` integrates the particle positions with a fourth-order Runge-Kutta
scheme, from initial longitudes and latitudes, for a duration and with a time step.
We release one particle every 0.1 degree along 69.5 degrees West, across the stream, and follow
them during ten days. The output is a dataset of longitudes and latitudes with the
``time`` and ``particles`` dimensions.

.. GENERATED FROM PYTHON SOURCE LINES 77-83

.. code-block:: Python


    lat0 = np.arange(35.5, 40.0, 0.1)
    lon0 = np.full(lat0.shape, -69.5)
    tracks = flow2d(u, v, (lon0, lat0), np.timedelta64(10, "D"), np.timedelta64(1, "h"))
    print(tracks.sizes)





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

 .. code-block:: none

    Frozen({'time': 241, 'particles': 45})




.. GENERATED FROM PYTHON SOURCE LINES 84-87

The tracks are colored by the day, and their end points are marked: the particles that
are caught by the core of the stream travel far to the east, and the others stay in the
slow waters or recirculate in the eddies.

.. GENERATED FROM PYTHON SOURCE LINES 87-104

.. code-block:: Python


    days = (tracks.time - tracks.time[0]) / np.timedelta64(1, "D")
    fig, ax = plt.subplots(figsize=(7.5, 5.5), subplot_kw={"projection": PCAR}, constrained_layout=True)
    plot_field(speed, ax=ax, cmap="Greys", alpha=0.6, add_colorbar=False, map_kw=MAP_KW)
    for k in range(tracks.sizes["particles"]):
        sc = ax.scatter(
            tracks.lon[:, k],
            tracks.lat[:, k],
            c=days,
            s=1.5,
            cmap=cmocean.cm.thermal,
            transform=PCAR,
        )
    ax.plot(lon0, lat0, "k-", lw=1.5, transform=PCAR)
    fig.colorbar(sc, ax=ax, shrink=0.75, label="Day")
    ax.set_title("Particles released across the stream")




.. image-sg:: /tutorials/dynamics/images/sphx_glr_plot_flow_advection_002.png
   :alt: Particles released across the stream
   :srcset: /tutorials/dynamics/images/sphx_glr_plot_flow_advection_002.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    Text(0.5, 1.0, 'Particles released across the stream')



.. GENERATED FROM PYTHON SOURCE LINES 105-111

Dispersion of a patch
---------------------

A patch of 200 particles is released at the northern flank of the stream. The distance
between them is computed on the sphere with :func:`xoa.geo.haversine`, in meters,
and its growth shows how fast the stream stretches the patch.

.. GENERATED FROM PYTHON SOURCE LINES 111-145

.. code-block:: Python


    rng = np.random.default_rng(0)
    plon = rng.normal(-68.0, 0.15, 200)
    plat = rng.normal(37.5, 0.15, 200)
    patch = flow2d(u, v, (plon, plat), np.timedelta64(10, "D"), np.timedelta64(1, "h"))
    cx = patch.lon.mean("particles").values[:, None]
    cy = patch.lat.mean("particles").values[:, None]
    dist = haversine(patch.lon.values, patch.lat.values, cx, cy)  # to the center of mass, in m
    spread = np.sqrt((dist**2).mean(axis=1)) * 1e-3

    fig, axes = plt.subplots(
        1, 2, figsize=(9, 3.8), gridspec_kw={"width_ratios": (1.25, 1)}, constrained_layout=True
    )
    axes[0].remove()
    axes[0] = fig.add_subplot(1, 2, 1, projection=PCAR)
    plot_field(speed, ax=axes[0], cmap="Greys", alpha=0.5, add_colorbar=False, map_kw=MAP_KW)
    for day, color in zip((0, 5, 10), ("tab:blue", "tab:orange", "tab:red")):
        step = int(day * 24)
        axes[0].scatter(
            patch.lon[step],
            patch.lat[step],
            s=4,
            color=color,
            label=f"Day {day}",
            transform=PCAR,
        )
    axes[0].legend(loc="lower left", markerscale=2)
    axes[0].set_title("A patch of particles")
    axes[1].plot((patch.time - patch.time[0]) / np.timedelta64(1, "D"), spread, color="k")
    axes[1].set_xlabel("Day")
    axes[1].set_ylabel("Root mean square distance [km]")
    axes[1].set_title("Dispersion")
    axes[1].grid(alpha=0.3)




.. image-sg:: /tutorials/dynamics/images/sphx_glr_plot_flow_advection_003.png
   :alt: Dispersion, A patch of particles
   :srcset: /tutorials/dynamics/images/sphx_glr_plot_flow_advection_003.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 146-149

The patch is first advected and stretched along the stream, and its size grows with time.
With currents that vary in time, like a series of daily means, the same tools give
realistic trajectories, for example to search the origin of a water mass.


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

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


.. _sphx_glr_download_tutorials_dynamics_plot_flow_advection.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/dynamics/plot_flow_advection.ipynb
        :alt: Launch binder
        :width: 150 px

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

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

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

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

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

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


.. only:: html

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

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