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


Mixed layer, thermocline and isotherms
======================================

In this tutorial, we show how to:

* compute the mixed layer depth with a temperature or a density criterion,
* find the depth of an isotherm and the temperature at a given depth with
  :func:`~xoa.interp.isoslice`,
* check the diagnostics on a vertical profile and on a section.

The data are a GLORYS reanalysis of the Gulf Stream region. The concepts are explained
in the :ref:`indepth.vertical` guide.
See also: :ref:`sphx_glr_tutorials_dynamics_plot_vertical_modes.py`.

.. GENERATED FROM PYTHON SOURCE LINES 19-21

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

.. GENERATED FROM PYTHON SOURCE LINES 21-43

.. code-block:: Python


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

    import xoa
    from xoa import meta
    from xoa.interp import isoslice
    from xoa.plot import plot_fields, plot_minimap
    from xoa.thermdyn import convert_sal, convert_temp, mixed_layer_depth

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

    with meta.set_meta_specs("mercator"):
        ds = xoa.open_data_sample("MODELS/CMEMS-GLORYS/glorys_gulfstream_3d.nc").xoa.decode()
    ds = ds.isel(time=0, drop=True)
    temp, sal = ds.temp, ds.sal
    print(temp.depth.attrs["positive"], float(temp.depth[-1]))





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

 .. code-block:: none

    down 1941.8929443359375




.. GENERATED FROM PYTHON SOURCE LINES 44-49

The potential density is needed for the density criterion. We compute it with the
`gsw <https://teos-10.github.io/GSW-Python/>`_ package from the absolute salinity and the
conservative temperature, that :func:`xoa.thermdyn.convert_sal` and
:func:`xoa.thermdyn.convert_temp` deduce from the practical salinity and the potential
temperature, whose kinds are inferred.

.. GENERATED FROM PYTHON SOURCE LINES 49-55

.. code-block:: Python


    asal = convert_sal(sal, "absolute")
    ctemp = convert_temp(temp, "conservative", sal=sal)
    sigma0 = gsw.sigma0(asal, ctemp).rename("sigma0")
    sigma0.attrs.update(long_name="Potential density anomaly", units="kg m-3")








.. GENERATED FROM PYTHON SOURCE LINES 56-64

Mixed layer depth
-----------------

The mixed layer is the surface layer whose properties are homogeneous.
Its depth, given by :func:`~xoa.thermdyn.mixed_layer_depth`, is where
the temperature has decreased by a given amount (``deltatemp``, 0.2 degC by default)
or the density has increased by a given amount (``deltadens``, 0.03 kg m-3) with respect
to the surface. The array must have a depth coordinate with a ``positive`` attribute.

.. GENERATED FROM PYTHON SOURCE LINES 64-81

.. code-block:: Python


    mld_temp = mixed_layer_depth(temp, method="deltatemp")
    mld_dens = mixed_layer_depth(sigma0, method="deltadens")
    print(float(mld_temp.mean()), float(mld_dens.mean()))

    fig, axes = plot_fields(
        {"Temperature criterion": mld_temp, "Density criterion": mld_dens},
        ncols=2,
        figsize=(9, 4),
        cmap=cmocean.cm.deep,
        vmin=0,
        vmax=150,
        extend="max",
        map_kw={"land": True},
    )
    plot_minimap(ds, parent=axes[0], loc="lower left", size=0.25)




.. image-sg:: /tutorials/dynamics/images/sphx_glr_plot_mixed_layer_001.png
   :alt: Temperature criterion, Density criterion
   :srcset: /tutorials/dynamics/images/sphx_glr_plot_mixed_layer_001.png
   :class: sphx-glr-single-img


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

 .. code-block:: none

    46.87445068359375 40.362239837646484

    <GeoAxes: >



.. GENERATED FROM PYTHON SOURCE LINES 82-85

Both criteria give the same patterns, with mixed layers of a few tens of meters that deepen
along the fronts and the eddies of the stream. The density criterion is a bit shallower on
average, since it also accounts for the salinity.

.. GENERATED FROM PYTHON SOURCE LINES 87-91

Check on a profile
------------------

On a profile, we see where the criterion is met. We choose a point north of the stream.

.. GENERATED FROM PYTHON SOURCE LINES 91-106

.. code-block:: Python


    point = dict(lat=39.0, lon=-66.0, method="nearest")
    fig, axes = plt.subplots(1, 2, figsize=(7, 4.5), sharey=True, constrained_layout=True)
    for ax, var, mld, label in (
        (axes[0], temp, mld_temp, "Temperature [°C]"),
        (axes[1], sigma0, mld_dens, "Potential density anomaly [kg m⁻³]"),
    ):
        prof = var.sel(**point)
        ax.plot(prof, prof.depth, "o-", ms=3)
        ax.axhline(float(mld.sel(**point)), color="C3", ls="--", label="Mixed layer depth")
        ax.set_xlabel(label)
    axes[0].set_ylim(300, 0)
    axes[0].set_ylabel("Depth [m]")
    axes[0].legend()




.. image-sg:: /tutorials/dynamics/images/sphx_glr_plot_mixed_layer_002.png
   :alt: plot mixed layer
   :srcset: /tutorials/dynamics/images/sphx_glr_plot_mixed_layer_002.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <matplotlib.legend.Legend object at 0x738c02f4c2f0>



.. GENERATED FROM PYTHON SOURCE LINES 107-113

Isotherms
---------

:func:`xoa.interp.isoslice` interpolates an array where another one crosses a value.
With the depth as the interpolated array, we get the depth of an isotherm.
Where the isotherm is above the surface, the result is meaningless and masked.

.. GENERATED FROM PYTHON SOURCE LINES 113-118

.. code-block:: Python


    depth = temp.depth.broadcast_like(temp)
    z18 = isoslice(depth, temp, 18.0, "depth").where(temp.isel(depth=0) > 18)
    z18.attrs.update(long_name="Depth of the 18 degC isotherm", units="m")








.. GENERATED FROM PYTHON SOURCE LINES 119-120

We can also do the other way round, to get the temperature at a given depth.

.. GENERATED FROM PYTHON SOURCE LINES 120-134

.. code-block:: Python


    t200 = isoslice(temp, depth, 200.0, "depth")
    t200.attrs.update(long_name="Temperature at 200 m", units="degC")

    fig, axes = plot_fields(
        [
            (z18, {"cmap": cmocean.cm.deep, "vmin": 0, "vmax": 500}),
            (t200, {"cmap": cmocean.cm.thermal}),
        ],
        ncols=2,
        figsize=(9, 4),
        map_kw={"land": True},
    )




.. image-sg:: /tutorials/dynamics/images/sphx_glr_plot_mixed_layer_003.png
   :alt: plot mixed layer
   :srcset: /tutorials/dynamics/images/sphx_glr_plot_mixed_layer_003.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 135-137

The 18 degC isotherm is deeper than 400 m in the warm waters south of the stream and it
rises sharply across it, which is also visible on the temperature at 200 m.

.. GENERATED FROM PYTHON SOURCE LINES 139-144

Section across the stream
-------------------------

On a meridional section, we draw the temperature with a few isotherms and the mixed
layer depth.

.. GENERATED FROM PYTHON SOURCE LINES 144-164

.. code-block:: Python


    sec = temp.sel(lon=-66.0, method="nearest")
    fig, ax = plt.subplots(figsize=(8, 4), constrained_layout=True)
    sec.plot.contourf(
        x="lat",
        y="depth",
        yincrease=False,
        ylim=(1000, 0),
        levels=np.arange(4, 29, 2),
        cmap=cmocean.cm.thermal,
        ax=ax,
    )
    sec.plot.contour(
        x="lat", y="depth", yincrease=False, levels=[12, 18], colors="k", linewidths=1, ax=ax
    )
    mld_temp.sel(lon=-66.0, method="nearest").plot(ax=ax, color="w", lw=2, label="Mixed layer depth")
    ax.set_ylim(1000, 0)
    ax.set_ylabel("Depth [m]")
    ax.legend(loc="lower left")
    ax.set_title("Temperature at 66W")



.. image-sg:: /tutorials/dynamics/images/sphx_glr_plot_mixed_layer_004.png
   :alt: Temperature at 66W
   :srcset: /tutorials/dynamics/images/sphx_glr_plot_mixed_layer_004.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    Text(0.5, 1.0, 'Temperature at 66W')




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

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


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

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

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

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

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

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

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


.. only:: html

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

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