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


Write your own naming specifications
====================================

In this tutorial, we show how to:

* declare that your names are known quantities, with a dict or a configuration file,
* use the specifications temporarily or for a given dataset,
* register them so that they are inferred from the names of a dataset,
* assign them to a dataset once and for all.

The use of the specifications is shown in :ref:`sphx_glr_tutorials_meta_plot_naming.py`
and the concepts are explained in the :ref:`indepth.meta` guide.
The configuration files are read with :mod:`xoa.cfgm`, see
:ref:`sphx_glr_tutorials_config_plot_cfgm.py`.

.. GENERATED FROM PYTHON SOURCE LINES 20-22

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

.. GENERATED FROM PYTHON SOURCE LINES 22-33

.. code-block:: Python


    import pathlib
    import tempfile

    import xarray as xr

    import xoa
    from xoa import meta

    xr.set_options(display_style="text")





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

 .. code-block:: none


    <xarray.core.options.set_options object at 0x738c41642ad0>



.. GENERATED FROM PYTHON SOURCE LINES 34-36

A dataset with names that are not known by default: ``T_surf`` is a temperature and
``mylon`` is a longitude.

.. GENERATED FROM PYTHON SOURCE LINES 36-47

.. code-block:: Python



    def make_dataset():
        return xr.Dataset(
            {"T_surf": ("n", [10.0, 11.0, 12.0], {"units": "degC"})},
            coords={"mylon": ("n", [1.0, 2.0, 3.0])},
        )


    print(make_dataset().xoa.get("temp"))





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

 .. code-block:: none

    None




.. GENERATED FROM PYTHON SOURCE LINES 48-55

With a dict
-----------

Each item of the specifications is a generic name, here ``temp`` and ``lon``, that is declared
in a section of data variables or of coordinates, with its alternative names.
The specifications are set for the content of a ``with`` block, and the accessor reads them
when it is first used on a dataset.

.. GENERATED FROM PYTHON SOURCE LINES 55-64

.. code-block:: Python


    specs = {
        "data_vars": {"temp": {"alt_names": ["T_surf"]}},
        "coords": {"lon": {"alt_names": ["mylon"]}},
    }
    with meta.set_meta_specs(specs):
        ds = make_dataset()
        print(ds.xoa.get("temp").name, ds.xoa.get("lon").name)





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

 .. code-block:: none

    T_surf mylon




.. GENERATED FROM PYTHON SOURCE LINES 65-73

With a configuration file
-------------------------

The same specifications are written in a configuration file, which is better for a model
that you use often. The ``name`` is the specialized name and
:meth:`~xarray.Dataset.xoa.decode` renames the arrays to the generic names and completes their
attributes. The ``register`` section gives a name to the specifications, which is needed to
recall them. We write the file in a temporary directory.

.. GENERATED FROM PYTHON SOURCE LINES 73-97

.. code-block:: Python


    content = """
    [register]
    name=mymodel

    [data_vars]
        [[temp]]
        name=T_surf
        [[sal]]
        name=S_surf

    [coords]
        [[lon]]
        name=mylon
    """
    path = pathlib.Path(tempfile.mkdtemp()) / "mymodel.cfg"
    path.write_text(content)

    with meta.set_meta_specs(str(path)):
        ds = make_dataset()
        decoded = ds.xoa.decode()
        print(list(ds.variables), "->", list(decoded.variables))
        print(list(decoded.xoa.encode().variables))





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

 .. code-block:: none

    ['T_surf', 'mylon'] -> ['temp', 'lon']
    /home/docs/checkouts/xoa/conda/develop/lib/python3.15/site-packages/xoa/meta/__init__.py:241: XoaWarning: Unknown registration name for Meta specs: mymodel
      exceptions.xoa_warn(msg)
    ['temp', 'lon']




.. GENERATED FROM PYTHON SOURCE LINES 98-101

Internal specifications, like the ones of CROCO, are files like this one, and
:func:`xoa.get_meta_config_file` gives their path if you want to start from one of them.
The other sections are described in :ref:`appendix.meta.sections`.

.. GENERATED FROM PYTHON SOURCE LINES 101-104

.. code-block:: Python


    print(xoa.get_meta_config_file("croco"))





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

 .. code-block:: none

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




.. GENERATED FROM PYTHON SOURCE LINES 105-111

Registering them
----------------

Registered specifications are recalled by their name and are candidates when
the ones that match a dataset are looked for, so that :class:`~xoa.meta.set_meta_specs` is not
needed any more. The ones that know the most names of a dataset are inferred.

.. GENERATED FROM PYTHON SOURCE LINES 111-120

.. code-block:: Python


    meta.register_meta_specs(str(path))
    print(meta.is_registered_meta_specs("mymodel"))

    ds = make_dataset()
    print(meta.infer_meta_specs(ds, named=True).name)
    print(ds.xoa.get("temp").name)
    print(list(ds.xoa.decode().variables))





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

 .. code-block:: none

    True
    mymodel
    T_surf
    ['temp', 'lon']




.. GENERATED FROM PYTHON SOURCE LINES 121-126

Assigning them
--------------

To avoid the inference, assign the specifications to the dataset: this sets
the ``meta_specs`` encoding of its arrays, that is saved with the file.

.. GENERATED FROM PYTHON SOURCE LINES 126-131

.. code-block:: Python


    meta.assign_meta_specs(ds, "mymodel")
    print(ds.T_surf.encoding)
    print(meta.get_meta_specs(ds.T_surf).name)





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

 .. code-block:: none

    {'meta_specs': 'mymodel'}
    mymodel




.. GENERATED FROM PYTHON SOURCE LINES 132-134

Registering changes how the next datasets are decoded. Since the other tutorials share
this session, we restore the initial state.

.. GENERATED FROM PYTHON SOURCE LINES 134-137

.. code-block:: Python


    meta.reset_cache(memory=True)
    print(meta.is_registered_meta_specs("mymodel"))




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

 .. code-block:: none

    False





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

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


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

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

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

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

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

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

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


.. only:: html

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

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