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

.. only:: html

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

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


Compare Hycom3d with a GDP drifter
==================================

In this tutorial, we show how to:

* decode dataset so that it is easy to access generic coordinates and variables,
* compute depths from layer thicknesses,
* interpolate currents from U and V positions to T position on an arakawa C grid,
* perform a 4D interpolation with a variable depth coordinate to random positions,
* make an horizontal slice of a 4D variable with a variable depth coordinate.

The concepts are explained in the :ref:`indepth.meta` guide.
See also: :ref:`sphx_glr_tutorials_evaluation_plot_mercator_argo.py`, :ref:`sphx_glr_tutorials_vertical_plot_croco_section.py`.

.. GENERATED FROM PYTHON SOURCE LINES 18-20

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

.. GENERATED FROM PYTHON SOURCE LINES 20-38

.. code-block:: Python


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

    import xoa
    import xoa.geo as xgeo
    import xoa.meta as xmeta
    from xoa.core.plot import add_quiverkey, get_quiverkey_value
    from xoa.grid import dz2depth, shift
    from xoa.plot import plot_double_minimap, plot_flow
    from xoa.regrid import grid2loc, regrid1d

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








.. GENERATED FROM PYTHON SOURCE LINES 39-40

Set the internal Hycom naming specifications as the current ones

.. GENERATED FROM PYTHON SOURCE LINES 40-44

.. code-block:: Python

    hycom_cfg_file = xoa.get_meta_config_file("hycom")
    print(hycom_cfg_file)
    xmeta.set_meta_specs(hycom_cfg_file)





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

 .. code-block:: none

    /home/docs/checkouts/xoa/conda/develop/lib/python3.15/site-packages/xoa/meta/configs/hycom.cfg

    <xoa.meta.set_meta_specs object at 0x738bf9a14e20>



.. GENERATED FROM PYTHON SOURCE LINES 45-50

Note that, since this file is internal, you can do it simply with::

       xmeta.set_meta_specs("hycom")

Here is what these CF specifications contain

.. GENERATED FROM PYTHON SOURCE LINES 50-54

.. code-block:: Python


    with open(hycom_cfg_file) as f:
        print(f.read())





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

 .. code-block:: none

    [register]
    name=hycom

        [[attrs]]
        nsigma = "[0-9]?"

    [sglocator]
    name_format="{root}_{loc}"
    valid_locations=u,v

    [vertical]
    positive=down
    type=dz

    [data_vars]

        [[u]]
        loc=u
            [[[add_coords_loc]]]
            lon=True
            lat=True
            x=True
            y=True

        [[v]]
        loc=v
            [[[add_coords_loc]]]
            lon=True
            lat=True
            x=True
            y=True

        [[bathy]]
        name=bathymetry
        add_loc=True

        [[dz]]
        name=h

    [coords]

        [[x]]
        name=X

        [[y]]
        name=Y

        [[depth]]
        name=lev





.. GENERATED FROM PYTHON SOURCE LINES 55-57

Note that most of these specifications are not needed to decode the dataset, i.e to find
known variables and coordinates, since the default specifications help for that.

.. GENERATED FROM PYTHON SOURCE LINES 59-72

Read and decode the datasets
----------------------------

Hycom velocities
~~~~~~~~~~~~~~~~

U and V are stored in separate files at U and V locations on the Hycom Arakawa C-Grid.
We choose to rename the dataset contents so that we can use generic names to access it.
We call for that the :meth:`~xarray.Dataset.xoa.decode` accessor method.
Note that the staggered grid location is automatically appended to horizontal
coordinates and dimensions of the U and V velocity components since they are
placed at U and V locations. This prevent any conflict with the bathymetry and
layer thickness horizontal coordinates and dimensions, which point to the T location.

.. GENERATED FROM PYTHON SOURCE LINES 74-75

U velocity component

.. GENERATED FROM PYTHON SOURCE LINES 75-78

.. code-block:: Python

    u_hycom = xoa.open_data_sample("MODELS/HYCOM/hycom.gdp.u.nc").xoa.decode().u.squeeze(drop=True)
    print(u_hycom)





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

 .. code-block:: none

    <xarray.DataArray 'u' (time: 50, depth: 6, y_u: 11, x_u: 13)> Size: 172kB
    [42900 values with dtype=float32]
    Coordinates:
      * time     (time) datetime64[ns] 400B 2021-03-01 ... 2021-03-25T12:00:00
      * depth    (depth) int32 24B 1 2 3 4 5 6
        lon_u    (y_u, x_u) float32 572B ...
        lat_u    (y_u, x_u) float32 572B ...
    Dimensions without coordinates: y_u, x_u
    Attributes:
        long_name:      Vitesse u
        units:          m/s
        standard_name:  sea_water_x_velocity




.. GENERATED FROM PYTHON SOURCE LINES 79-80

V velocity component

.. GENERATED FROM PYTHON SOURCE LINES 80-82

.. code-block:: Python

    v_hycom = xoa.open_data_sample("MODELS/HYCOM/hycom.gdp.v.nc").xoa.decode().v.squeeze(drop=True)








.. GENERATED FROM PYTHON SOURCE LINES 83-84

Layer thicknesses dataset

.. GENERATED FROM PYTHON SOURCE LINES 84-87

.. code-block:: Python

    hycom = xoa.open_data_sample("MODELS/HYCOM/hycom.gdp.h.nc").xoa.decode().squeeze(drop=True)
    print(hycom)





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

 .. code-block:: none

    <xarray.Dataset> Size: 174kB
    Dimensions:  (y: 11, x: 13, time: 50, depth: 6)
    Coordinates:
        lon      (y, x) float32 572B ...
        lat      (y, x) float32 572B ...
      * time     (time) datetime64[ns] 400B 2021-03-01 ... 2021-03-25T12:00:00
      * depth    (depth) int32 24B 1 2 3 4 5 6
    Dimensions without coordinates: y, x
    Data variables:
        bathy    (y, x) float32 572B ...
        dz       (time, depth, y, x) float32 172kB ...
    Attributes: (12/26)
        history:                   Fri Apr  9 12:15:22 2021: ncrcat -d X,472,508,...
        Conventions:               COARDS
        nhybrd:                    20
        nsigma:                    19
        kapref:                    2
        hybflg:                    0
        ...                        ...
        dp00ft:                    [1.15 1.15 1.15 1.15 1.15 1.15 1.15 1.15 1.15 ...
        dp00xt:                    [21.874 21.414 21.414 13.197  7.85   3.85   4....
        ds00t:                     [3.555 3.026 3.026 1.547 0.828 0.828 0.968 0.8...
        ds00ft:                    [1.15 1.15 1.15 1.15 1.15 1.15 1.15 1.15 1.15 ...
        ds00xt:                    [21.874 21.414 21.414  7.197  3.85   3.85   4....
        nco_openmp_thread_number:  1




.. GENERATED FROM PYTHON SOURCE LINES 88-91

We now compute the depths from the layer thicknesses at the T location
thanks to the :func:`xoa.grid.dz2depth` function:
we integrate from a null SSH and interpolate the depth from W locations to T locations.

.. GENERATED FROM PYTHON SOURCE LINES 91-94

.. code-block:: Python


    hycom.coords["depth"] = dz2depth(hycom.dz, centered=True)








.. GENERATED FROM PYTHON SOURCE LINES 95-99

Then we interpolate the velocity components to the T location with
the :func:`xoa.grid.shift` function.
The call to :meth:`reloc <xoa.meta.MetaSpecs.reloc>` helps removing the
staggered grid location prefixes.

.. GENERATED FROM PYTHON SOURCE LINES 99-105

.. code-block:: Python


    ut_hycom = shift(u_hycom, {"x": "left", "y": "left"}).xoa.reloc(u=False)
    vt_hycom = shift(v_hycom, {"x": "left", "y": "left"}).xoa.reloc(v=False)
    hycom["u"] = ut_hycom.assign_coords(**hycom.coords)
    hycom["v"] = vt_hycom.assign_coords(**hycom.coords)








.. GENERATED FROM PYTHON SOURCE LINES 106-107

So, finally we obtain:

.. GENERATED FROM PYTHON SOURCE LINES 107-110

.. code-block:: Python


    print(hycom)





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

 .. code-block:: none

    <xarray.Dataset> Size: 689kB
    Dimensions:  (y: 11, x: 13, time: 50, depth: 6)
    Coordinates:
        lon      (y, x) float32 572B ...
        lat      (y, x) float32 572B ...
      * time     (time) datetime64[ns] 400B 2021-03-01 ... 2021-03-25T12:00:00
        depth    (time, depth, y, x) float32 172kB 1.511 1.511 1.51 ... 20.09 20.06
    Dimensions without coordinates: y, x
    Data variables:
        bathy    (y, x) float32 572B ...
        dz       (time, depth, y, x) float32 172kB 3.021 3.021 3.02 ... 5.216 5.209
        u        (time, depth, y, x) float32 172kB 0.03078 0.02984 ... 0.1292 0.1364
        v        (time, depth, y, x) float32 172kB 0.0497 0.07527 ... 0.0498 0.05054
    Attributes: (12/26)
        history:                   Fri Apr  9 12:15:22 2021: ncrcat -d X,472,508,...
        Conventions:               COARDS
        nhybrd:                    20
        nsigma:                    19
        kapref:                    2
        hybflg:                    0
        ...                        ...
        dp00ft:                    [1.15 1.15 1.15 1.15 1.15 1.15 1.15 1.15 1.15 ...
        dp00xt:                    [21.874 21.414 21.414 13.197  7.85   3.85   4....
        ds00t:                     [3.555 3.026 3.026 1.547 0.828 0.828 0.968 0.8...
        ds00ft:                    [1.15 1.15 1.15 1.15 1.15 1.15 1.15 1.15 1.15 ...
        ds00xt:                    [21.874 21.414 21.414  7.197  3.85   3.85   4....
        nco_openmp_thread_number:  1




.. GENERATED FROM PYTHON SOURCE LINES 111-115

GDP drifter
~~~~~~~~~~~

The drifter comes as a `csv` file and we read it as :class:`pandas.DataFrame` instance.

.. GENERATED FROM PYTHON SOURCE LINES 115-121

.. code-block:: Python


    csv_name = xoa.get_data_sample("OBS/DRIFTERS/gdp-6203641.csv")
    drifter = pd.read_csv(
        csv_name, header=0, skiprows=[1], parse_dates=[0], index_col=0, usecols=[2, 3, 4, 5, 6, 7]
    )








.. GENERATED FROM PYTHON SOURCE LINES 122-123

Since the sampling is not that nice, we resample it to 3-hour intervals.

.. GENERATED FROM PYTHON SOURCE LINES 123-126

.. code-block:: Python


    drifter = drifter.resample("3h").mean()








.. GENERATED FROM PYTHON SOURCE LINES 127-128

We switch to default naming conventions for the drifter.

.. GENERATED FROM PYTHON SOURCE LINES 128-132

.. code-block:: Python


    xmeta.set_meta_specs("default")






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

 .. code-block:: none


    <xoa.meta.set_meta_specs object at 0x738c03e8fd10>



.. GENERATED FROM PYTHON SOURCE LINES 133-134

We convert it to and :class:`xarray.Dataset`, fix the time coordinate and decode it.

.. GENERATED FROM PYTHON SOURCE LINES 134-137

.. code-block:: Python


    drifter = drifter.to_xarray().assign_coords(time=drifter.index.values).xoa.decode()








.. GENERATED FROM PYTHON SOURCE LINES 138-139

We drop missing values.

.. GENERATED FROM PYTHON SOURCE LINES 139-142

.. code-block:: Python


    drifter = drifter.where(~drifter.lon.isnull() & ~drifter.lat.isnull(), drop=True)








.. GENERATED FROM PYTHON SOURCE LINES 143-144

We add a constant depth of 15 m.

.. GENERATED FROM PYTHON SOURCE LINES 144-151

.. code-block:: Python


    drifter.coords["depth"] = (
        "time",
        np.full(drifter.sizes["time"], 15.0),
        {"standard_name": "ocean_depth", "units": "m", "positive": "down"},
    )








.. GENERATED FROM PYTHON SOURCE LINES 152-153

Here is what we obtain.

.. GENERATED FROM PYTHON SOURCE LINES 153-156

.. code-block:: Python


    print(drifter)





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

 .. code-block:: none

    <xarray.Dataset> Size: 9kB
    Dimensions:  (time: 159)
    Coordinates:
      * time     (time) datetime64[us] 1kB 2021-03-03T18:00:00 ... 2021-03-24T09:...
        lat      (time) float64 1kB 44.68 44.72 44.72 44.72 ... 44.72 44.71 44.71
        lon      (time) float64 1kB -2.544 -2.583 -2.592 ... -2.523 -2.514 -2.505
        depth    (time) float64 1kB 15.0 15.0 15.0 15.0 15.0 ... 15.0 15.0 15.0 15.0
    Data variables:
        sst      (time) float64 1kB 13.09 12.79 12.77 12.78 ... 12.56 12.53 12.61
        slp      (time) float64 1kB 1.027e+03 1.024e+03 ... 1.025e+03 1.026e+03
        lon360   (time) float64 1kB 357.5 357.4 357.4 357.4 ... 357.5 357.5 357.5




.. GENERATED FROM PYTHON SOURCE LINES 157-161

Compute and interpolate velocities
----------------------------------

We compute the drifter velocity components

.. GENERATED FROM PYTHON SOURCE LINES 161-170

.. code-block:: Python


    drifter["u"] = (
        drifter.lon.differentiate("time", datetime_unit="s") * xgeo.EARTH_RADIUS * np.pi / 180
    )
    drifter["u"] *= np.cos(np.radians(drifter.lat.values))
    drifter["v"] = (
        drifter.lat.differentiate("time", datetime_unit="s") * xgeo.EARTH_RADIUS * np.pi / 180
    )








.. GENERATED FROM PYTHON SOURCE LINES 171-172

We make a 4D linear interpolation the Hycom velocity to the drifter positions with :func:`xoa.interp.grid2loc`.

.. GENERATED FROM PYTHON SOURCE LINES 172-176

.. code-block:: Python


    uloc = grid2loc(hycom["u"], drifter)
    vloc = grid2loc(hycom["v"], drifter)








.. GENERATED FROM PYTHON SOURCE LINES 177-180

Instead of just showing the velocities along the drifter positions,
we can plot the mean model velocities over the same period as a background.
So we interpolate them at 15 m with :func:`xoa.regrid.regrid1d` and compute a time average.

.. GENERATED FROM PYTHON SOURCE LINES 180-185

.. code-block:: Python


    d15 = xr.DataArray([15.0], dims="depth", name="depth")
    uh15 = regrid1d(hycom["u"], d15).squeeze(drop=True).mean(dim="time")
    vh15 = regrid1d(hycom["v"], d15).squeeze(drop=True).mean(dim="time")








.. GENERATED FROM PYTHON SOURCE LINES 186-193

Plot
----

The geographic extent is easily computed with the :func:`xoa.geo.get_extent` function.
The background currents are plotted with the :func:`xoa.plot.plot_flow` function.
A reference arrow with a round value is added with :func:`xoa.core.plot.get_quiverkey_value`
and :func:`xoa.core.plot.add_quiverkey`, and a minimap with :func:`xoa.plot.plot_double_minimap`.

.. GENERATED FROM PYTHON SOURCE LINES 193-232

.. code-block:: Python


    pmerc = ccrs.Mercator()
    pcarr = ccrs.PlateCarree()
    fig, ax = plt.subplots(
        figsize=(6.5, 6.5),
        subplot_kw={"facecolor": "teal", "projection": pmerc},
        constrained_layout=True,
    )

    ax.gridlines(draw_labels=True, dms=True)
    ax.set_extent(xgeo.get_extent(uh15))
    kwqv = dict(scale_units="dots", scale=0.1 / 20, units="dots", transform=pcarr)
    plot_flow(uh15, vh15, axes=ax, transform=pcarr, color="w", alpha=(0.3, 1), linewidth=0.6)
    qv = ax.quiver(
        uloc.lon.values,
        uloc.lat.values,
        uloc.values,
        vloc.values,
        color="w",
        width=2,
        label="Model",
        **kwqv,
    )
    ax.plot(drifter.lon.values, drifter.lat.values, '-', color="C1", transform=pcarr, lw=0.5)
    ax.quiver(
        drifter.lon.values,
        drifter.lat.values,
        drifter.u.values,
        drifter.v.values,
        color="C1",
        label="Drifter",
        width=2,
        **kwqv,
    )
    qvalue = get_quiverkey_value(np.hypot(uloc, vloc))
    add_quiverkey(ax, qv, qvalue, r"$m\,s^{-1}$", pos=(0.0, 1.07))
    plt.legend()
    plot_double_minimap(drifter, parent=ax, loc="lower left", size=0.15, regional_ax="right")




.. image-sg:: /tutorials/evaluation/images/sphx_glr_plot_hycom_gdp_001.png
   :alt: plot hycom gdp
   :srcset: /tutorials/evaluation/images/sphx_glr_plot_hycom_gdp_001.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    (<GeoAxes: >, <GeoAxes: >)



.. GENERATED FROM PYTHON SOURCE LINES 233-237

The discrepancies between the lagrangian and mean eulerian currents highlight
the variability due to the mesocale activity.
The differences between the observed and modeled currents are partly due to
the lack of data assimilation in the model.


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

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


.. _sphx_glr_download_tutorials_evaluation_plot_hycom_gdp.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/evaluation/plot_hycom_gdp.ipynb
        :alt: Launch binder
        :width: 150 px

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

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

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

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

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

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


.. only:: html

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

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