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

.. only:: html

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

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


Find variables whatever their names
===================================

In this tutorial, we show how to:

* access the same quantity in datasets that name it differently,
* write a function once and apply it to several models,
* decode datasets to generic names and encode them back,
* use the naming specifications of a model.

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

.. GENERATED FROM PYTHON SOURCE LINES 18-20

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

.. GENERATED FROM PYTHON SOURCE LINES 20-39

.. code-block:: Python


    import cmocean
    import xarray as xr

    import xoa
    from xoa import meta
    from xoa.coords import get_tdim, get_zdim
    from xoa.plot import plot_fields

    xr.set_options(display_style="text")

    paths = {
        "GLORYS": "MODELS/CMEMS-GLORYS/glorys_gulfstream_3d.nc",
        "IBI": "MODELS/CMEMS-IBI/ibi-argo-7900573.nc",
        "HYCOM": "MODELS/HYCOM/hycom.gdp.u.nc",
        "CROCO": "MODELS/CROCO/SOUTH-AFRICA/croco.south-africa.surf.nc",
    }
    datasets = {name: xoa.open_data_sample(path) for name, path in paths.items()}








.. GENERATED FROM PYTHON SOURCE LINES 40-44

Same quantity, different names
------------------------------

Each model has its own names for the variables and the coordinates.

.. GENERATED FROM PYTHON SOURCE LINES 44-48

.. code-block:: Python


    for name, ds in datasets.items():
        print(f"{name:7}", list(ds.data_vars)[:6], list(ds.coords)[:4])





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

 .. code-block:: none

    GLORYS  ['thetao', 'so', 'uo', 'vo', 'zos'] ['depth', 'latitude', 'longitude', 'time']
    IBI     ['so', 'thetao', 'uo', 'vo', 'zos'] ['depth', 'latitude', 'longitude', 'time']
    HYCOM   ['lon', 'lat', 'u'] ['lev', 'time']
    CROCO   ['AKt', 'Cs_r', 'Cs_w', 'Vtransform', 'angle', 'el'] ['eta_rho', 'eta_v', 'lat_rho', 'lat_u']




.. GENERATED FROM PYTHON SOURCE LINES 49-51

The ``xoa`` accessor searches a dataset for a quantity from its generic name, like
``"u"`` or ``"lon"``, by scanning the names and the attributes of the arrays.

.. GENERATED FROM PYTHON SOURCE LINES 51-57

.. code-block:: Python


    for name, ds in datasets.items():
        print(
            f"{name:7} u -> {ds.xoa.get('u').name:3} sal -> {getattr(ds.xoa.get('sal'), 'name', None)}"
        )





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

 .. code-block:: none

    GLORYS  u -> uo  sal -> so
    IBI     u -> uo  sal -> so
    HYCOM   u -> u   sal -> None
    CROCO   u -> u   sal -> salt




.. GENERATED FROM PYTHON SOURCE LINES 58-65

A function that works with any model
------------------------------------

Since the search relies on the generic names, a function does not need to know
which model it is applied to. Here we map the surface speed of the two CMEMS models,
and :func:`xoa.coords.get_zdim` and :func:`xoa.coords.get_tdim` find the vertical and time
dimensions.

.. GENERATED FROM PYTHON SOURCE LINES 65-80

.. code-block:: Python



    def get_surface_speed(ds):
        u, v = ds.xoa.get("u"), ds.xoa.get("v")
        speed = (u**2 + v**2) ** 0.5
        speed = speed.isel({get_zdim(speed): 0, get_tdim(speed): 0}, drop=True)
        speed.attrs.update(long_name="Surface current speed", units="m s-1")
        return speed


    speeds = {name: get_surface_speed(datasets[name]) for name in ("GLORYS", "IBI")}
    fig, axes = plot_fields(
        speeds, ncols=2, figsize=(9, 4), cmap=cmocean.cm.speed, map_kw={"land": True}
    )




.. image-sg:: /tutorials/meta/images/sphx_glr_plot_naming_001.png
   :alt: GLORYS, IBI
   :srcset: /tutorials/meta/images/sphx_glr_plot_naming_001.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 81-91

Naming specifications
---------------------

The specifications that are used are inferred from the dataset or set by the user.
Some come with xoa for a few models, like Mercator for the CMEMS products,
which know their own names. :meth:`~xarray.Dataset.xoa.decode` renames the arrays to their
generic names and completes their attributes, and :meth:`~xarray.Dataset.xoa.encode` gives back
the specialized names.
The accessor reads the specifications when it is first used on a dataset,
so we open the dataset within the context.

.. GENERATED FROM PYTHON SOURCE LINES 91-98

.. code-block:: Python


    with meta.set_meta_specs("mercator"):
        ds = xoa.open_data_sample(paths["GLORYS"])
        decoded = ds.xoa.decode()
        print(list(ds.data_vars), "->", list(decoded.data_vars))
        print(list(decoded.xoa.encode().data_vars))





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

 .. code-block:: none

    ['thetao', 'so', 'uo', 'vo', 'zos'] -> ['temp', 'sal', 'u', 'v', 'ssh']
    ['thetao', 'so', 'uo', 'vo', 'zos']




.. GENERATED FROM PYTHON SOURCE LINES 99-100

The attributes are completed with the conventional ones.

.. GENERATED FROM PYTHON SOURCE LINES 100-103

.. code-block:: Python


    print(decoded.temp.attrs["standard_name"], "|", decoded.temp.attrs["long_name"])





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

 .. code-block:: none

    sea_water_potential_temperature | Temperature




.. GENERATED FROM PYTHON SOURCE LINES 104-106

The names of CROCO are explicit about the grid location: ``u`` lives on the ``u`` points,
with its own longitudes and latitudes. They are known by the ``croco`` specifications.

.. GENERATED FROM PYTHON SOURCE LINES 106-113

.. code-block:: Python


    with meta.set_meta_specs("croco"):
        croco = xoa.open_data_sample(paths["CROCO"])
        print(croco.xoa.get_meta_specs().name)
        print(croco.xoa.get("u").dims, croco.xoa.get("v").dims)
        print(list(croco.xoa.decode().data_vars)[-6:])





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

 .. code-block:: none

    croco
    ('time', 's_rho', 'eta_rho', 'xi_u') ('time', 's_rho', 'eta_v', 'xi_rho')
    ['time_step', 'u', 'v', 'w', 'xl', 'ssh']




.. GENERATED FROM PYTHON SOURCE LINES 114-119

Your own specifications
-----------------------

For a model that is not known by xoa, you write the naming specifications yourself,
as a dict or a configuration file: see :ref:`sphx_glr_tutorials_meta_plot_naming_specs.py`.

.. GENERATED FROM PYTHON SOURCE LINES 121-123

Using specifications registers them, which changes how the next datasets are decoded.
Since the other tutorials share this session, we restore the initial state.

.. GENERATED FROM PYTHON SOURCE LINES 123-125

.. code-block:: Python


    meta.reset_cache(memory=True)








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

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


.. _sphx_glr_download_tutorials_meta_plot_naming.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/meta/plot_naming.ipynb
        :alt: Launch binder
        :width: 150 px

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

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

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

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

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

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


.. only:: html

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

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