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

.. only:: html

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

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


Analyse the tide of a gridded field
===================================

In this tutorial, we show how to:

* analyse sea level and currents of shape ``(time, y, x)`` in a single call,
* draw a co-tidal chart and the spectrum of the constituents,
* predict the tide on the whole grid at one given moment,
* describe the tidal currents with ellipses on maps,
* classify the tide with the form number.

The concepts are explained in the :ref:`indepth.tide` guide.
The fields are synthetic: a standing wave in a gulf that is closed at its eastern end.
See also: :ref:`sphx_glr_tutorials_tides_plot_tide_station.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

    from xoa import plot as xplot
    from xoa import tide as xtide
    from xoa.tide import plot as tplot

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








.. GENERATED FROM PYTHON SOURCE LINES 36-42

Synthetic sea level and currents
--------------------------------

One month of hourly data on a 20 x 30 grid. The amplitudes grow toward the closed
end and the currents are strongest at the mouth, with ellipses that are more open
in the south.

.. GENERATED FROM PYTHON SOURCE LINES 42-74

.. code-block:: Python


    names = ["M2", "S2", "K1", "O1"]
    base_amp = {"M2": 1.5, "S2": 0.5, "K1": 0.3, "O1": 0.2}
    base_pha = {"M2": 0.5, "S2": 1.0, "K1": 2.0, "O1": 3.0}

    x = xr.DataArray(np.linspace(-6, -2, 30), dims="x", name="lon", attrs={"units": "degrees_east"})
    y = xr.DataArray(np.linspace(47, 49, 20), dims="y", name="lat", attrs={"units": "degrees_north"})
    x, y = x.assign_coords(lon=x), y.assign_coords(lat=y)
    s = (x - x.min()) / (x.max() - x.min())  # 0 at the mouth, 1 at the closed end
    t = np.datetime64("2024-03-01") + np.arange(30 * 24) * np.timedelta64(1, "h")
    hours = xr.DataArray(np.arange(t.size) * 1.0, dims="time", coords={"time": t})
    omega = dict(zip(names, xtide.get_frequencies(names) * 3600))  # rad per hour

    ssh = sum(
        base_amp[n]
        * (0.5 + 0.5 * s)
        * (1 + 0.1 * (y - 48))
        * np.cos(omega[n] * hours - base_pha[n] - 0.3 * s)
        for n in names
    )
    ssh += 0.05 * np.random.default_rng(0).standard_normal(ssh.shape)
    ssh = ssh.transpose("time", "y", "x").rename("ssh").assign_attrs(units="m")

    umax = (0.8 * (1 - s) + 0.1) * (1 + 0.2 * (y - 48))
    u = sum(0.5 * base_amp[n] * umax * np.cos(omega[n] * hours - base_pha[n]) for n in names).transpose(
        "time", "y", "x"
    )
    v = sum(
        0.5 * base_amp[n] * umax * (y - 47) / 2 * np.sin(omega[n] * hours - base_pha[n]) for n in names
    ).transpose("time", "y", "x")
    print(ssh.dims, ssh.shape)





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

 .. code-block:: none

    ('time', 'y', 'x') (720, 20, 30)




.. GENERATED FROM PYTHON SOURCE LINES 75-80

Harmonic analysis of the whole grid
-----------------------------------

The pseudo-inverse of the design matrix is computed once and applied to all the points.
The ``greenwich`` option gives the phase lags that are used by tidal atlases.

.. GENERATED FROM PYTHON SOURCE LINES 80-84

.. code-block:: Python


    coef = xtide.harmonic_analysis(ssh, names=names, greenwich=True)
    print(coef)





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

 .. code-block:: none

    <xarray.Dataset> Size: 82kB
    Dimensions:      (x: 30, y: 20, constituent: 4)
    Coordinates:
        lon          (x) float64 240B -6.0 -5.862 -5.724 ... -2.276 -2.138 -2.0
        lat          (y) float64 160B 47.0 47.11 47.21 47.32 ... 48.79 48.89 49.0
      * constituent  (constituent) <U2 32B 'M2' 'S2' 'K1' 'O1'
        frequency    (constituent) float64 32B 1.932 2.0 1.003 0.9295
    Dimensions without coordinates: x, y
    Data variables:
        h0           (y, x) float64 5kB -0.0009804 0.0001041 ... -0.0001501
        amp          (constituent, y, x) float64 19kB 0.6973 0.7225 ... 0.1845
        phase        (constituent, y, x) float64 19kB 4.42 4.429 ... 6.046 6.081
        amp_std      (constituent, y, x) float64 19kB 0.002716 0.002833 ... 0.002274
        phase_std    (constituent, y, x) float64 19kB 0.003894 0.003921 ... 0.0123
    Attributes:
        t_ref:             1710547200.0
        nodal:             True
        phase_convention:  greenwich




.. GENERATED FROM PYTHON SOURCE LINES 85-89

Co-tidal chart
--------------

:func:`~xoa.tide.plot.plot_cotidal` maps the amplitude in colors and the phase in lines.

.. GENERATED FROM PYTHON SOURCE LINES 89-93

.. code-block:: Python


    tplot.plot_cotidal(coef, "M2", map_kw=MAP_KW)
    plt.tight_layout()




.. image-sg:: /tutorials/tides/images/sphx_glr_plot_tide_map_001.png
   :alt: M2 co-tidal chart
   :srcset: /tutorials/tides/images/sphx_glr_plot_tide_map_001.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 94-99

Prediction at one moment
------------------------

The coefficients can be evaluated at any time, here a single one, which is not
in the analysed period. The result is the tide on the whole grid at this moment.

.. GENERATED FROM PYTHON SOURCE LINES 99-110

.. code-block:: Python


    t0 = np.array([np.datetime64("2024-04-02T06:00")])
    snapshot = xtide.harmonic_predict(coef, t0).isel(time=0)
    print(snapshot.dims, snapshot.shape)

    xplot.plot_field(
        snapshot.assign_attrs(long_name="Sea level", units="m"), cmap="auto", map_kw=MAP_KW
    )
    plt.title("Predicted tide on 2 April 06:00")
    plt.tight_layout()




.. image-sg:: /tutorials/tides/images/sphx_glr_plot_tide_map_002.png
   :alt: Predicted tide on 2 April 06:00
   :srcset: /tutorials/tides/images/sphx_glr_plot_tide_map_002.png
   :class: sphx-glr-single-img


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

 .. code-block:: none

    ('y', 'x') (20, 30)




.. GENERATED FROM PYTHON SOURCE LINES 111-116

Tidal currents and ellipses
---------------------------

For the currents, each constituent describes an ellipse at each point.
The semi-minor axis is negative when the current rotates clockwise.

.. GENERATED FROM PYTHON SOURCE LINES 116-123

.. code-block:: Python


    coef_uv = xtide.tidal_ellipses(xtide.harmonic_analysis_uv(u, v, names=names))
    m2 = coef_uv.sel(constituent="M2")

    tplot.plot_tidal_ellipses(coef_uv, "M2", ref=0.5, background=m2.semi_major, step=2, map_kw=MAP_KW)
    plt.tight_layout()




.. image-sg:: /tutorials/tides/images/sphx_glr_plot_tide_map_003.png
   :alt: M2 tidal current ellipses
   :srcset: /tutorials/tides/images/sphx_glr_plot_tide_map_003.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 124-126

Constituents can be compared side by side, coloured by their phase, and one ellipse
can be detailed at a given point.

.. GENERATED FROM PYTHON SOURCE LINES 126-131

.. code-block:: Python


    tplot.plot_tidal_constituents(
        coef_uv, ["M2", "S2", "K1"], color_by="phase", step=2, figsize=(10, 3.2)
    )




.. image-sg:: /tutorials/tides/images/sphx_glr_plot_tide_map_004.png
   :alt: M2 tidal current ellipses, S2 tidal current ellipses, K1 tidal current ellipses
   :srcset: /tutorials/tides/images/sphx_glr_plot_tide_map_004.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    (<Figure size 1000x320 with 4 Axes>, [<GeoAxes: title={'center': 'M2 tidal current ellipses'}>, <GeoAxes: title={'center': 'S2 tidal current ellipses'}>, <GeoAxes: title={'center': 'K1 tidal current ellipses'}>])



.. GENERATED FROM PYTHON SOURCE LINES 132-134

.. code-block:: Python

    tplot.plot_tidal_ellipse(coef_uv.isel(x=5, y=10), "M2")




.. image-sg:: /tutorials/tides/images/sphx_glr_plot_tide_map_005.png
   :alt: M2 tidal current ellipse
   :srcset: /tutorials/tides/images/sphx_glr_plot_tide_map_005.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <Axes: title={'center': 'M2 tidal current ellipse'}, xlabel='u [m s$^{-1}$]', ylabel='v [m s$^{-1}$]'>



.. GENERATED FROM PYTHON SOURCE LINES 135-139

Spectrum
--------

The mean amplitude of the constituents against their frequency tells which dominate.

.. GENERATED FROM PYTHON SOURCE LINES 139-142

.. code-block:: Python


    tplot.plot_tidal_spectrum(coef, record_days=30)




.. image-sg:: /tutorials/tides/images/sphx_glr_plot_tide_map_006.png
   :alt: Tidal constituents
   :srcset: /tutorials/tides/images/sphx_glr_plot_tide_map_006.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <Axes: title={'center': 'Tidal constituents'}, xlabel='Frequency [cycles per day]', ylabel='Amplitude [m]'>



.. GENERATED FROM PYTHON SOURCE LINES 143-148

Form number
-----------

The form number ``(K1 + O1) / (M2 + S2)`` tells whether the tide is
semi-diurnal (below 0.25), mixed or diurnal (above 3).

.. GENERATED FROM PYTHON SOURCE LINES 148-152

.. code-block:: Python


    form = xtide.form_number(coef)
    print(f"form number from {float(form.min()):.2f} to {float(form.max()):.2f}")
    plt.show()




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

 .. code-block:: none

    form number from 0.21 to 0.22





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

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


.. _sphx_glr_download_tutorials_tides_plot_tide_map.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/tides/plot_tide_map.ipynb
        :alt: Launch binder
        :width: 150 px

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

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

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

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

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

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


.. only:: html

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

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