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


Accumulating statistics in time
===============================

In this tutorial, we show how to:

* accumulate temporal statistics step by step and check them against a manual computation,
* get volume statistics that are automatically weighted by the layer thicknesses and
  the grid cell sizes, whose weights are far from homogeneous,
* stop the accumulation and restart it from a file.

The data are synthetic: a temperature that is linear with depth, on sigma layers
over a sloping bottom, whose thickness varies with time.

The concepts are explained in the :ref:`indepth.stataccum` guide.
See also: :ref:`sphx_glr_tutorials_graphics_plot_taylor_diagram.py`.

.. GENERATED FROM PYTHON SOURCE LINES 21-23

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

.. GENERATED FROM PYTHON SOURCE LINES 23-53

.. code-block:: Python


    import os
    import tempfile

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

    from xoa.grid import get_dx_dy, get_dz
    from xoa.stats import StatAccum

    plt.rcParams.update({"font.size": 9, "axes.titlesize": 10, "axes.titleweight": "bold"})

    nt, nz, ny, nx = 10, 20, 12, 30
    time = np.array("2020-01-01", dtype="M8[h]") + np.arange(nt) * 6
    lon = xr.DataArray(np.linspace(-6, -4, nx), dims="x", attrs={"units": "degrees_east"})
    lat = xr.DataArray(np.linspace(30, 60, ny), dims="y", attrs={"units": "degrees_north"})
    bathy = 20 + 180 * (lon - lon[0]) / (lon[-1] - lon[0])
    tide = xr.DataArray(1 + 0.1 * np.sin(np.arange(nt)), dims="time", coords={"time": time})
    sigma = xr.DataArray((np.arange(nz) + 0.5) / nz, dims="nz")

    # The depth of the layers varies in space and time
    z = (-bathy * tide * sigma).transpose("time", "nz", "x")
    z.attrs.update(units="m", positive="up")
    temp = 15 + 0.05 * z + 0.1 * (lat - 45)
    temp = temp.transpose("time", "nz", "y", "x").rename("temp")
    temp.attrs.update(long_name="Sea temperature", units="degC")
    temp = temp.assign_coords(z=z, lon=lon, lat=lat)
    temp_ref = (temp + 0.5).rename("temp_ref")








.. GENERATED FROM PYTHON SOURCE LINES 54-61

Accumulating step by step
-------------------------

The data are appended in five chunks of two time steps, as if they were
produced along a run. Nothing but the moments is kept between two calls.
After each chunk, we get the statistics at a given point, and we compare them
with a manual computation on all the time steps available so far.

.. GENERATED FROM PYTHON SOURCE LINES 61-86

.. code-block:: Python


    point = dict(nz=-1, y=0, x=-1)
    sa = StatAccum()
    steps, tmean, tstd = [], [], []
    for i in range(0, nt, 2):
        sa.append(temp.isel(time=slice(i, i + 2)))
        stats = sa.get_stats(["tmean", "tstd"]).isel(point)
        steps.append(sa.nt)
        tmean.append(float(stats.tmean))
        tstd.append(float(stats.tstd))

    series = temp.isel(point).values
    manual_mean = [series[:n].mean() for n in steps]
    manual_std = [series[:n].std() for n in steps]
    np.testing.assert_allclose(tmean, manual_mean)
    np.testing.assert_allclose(tstd, manual_std)

    fig, axes = plt.subplots(1, 2, figsize=(9, 3), sharex=True)
    for ax, acc, man, name in zip(axes, (tmean, tstd), (manual_mean, manual_std), ("mean", "std")):
        ax.plot(steps, man, "o-", label="Manual")
        ax.plot(steps, acc, "x--", ms=10, label="StatAccum")
        ax.set_title(f"Temporal {name}")
        ax.set_xlabel("Number of accumulated time steps")
    ax.legend()




.. image-sg:: /tutorials/evaluation/images/sphx_glr_plot_stataccum_001.png
   :alt: Temporal mean, Temporal std
   :srcset: /tutorials/evaluation/images/sphx_glr_plot_stataccum_001.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <matplotlib.legend.Legend object at 0x738c04f7d400>



.. GENERATED FROM PYTHON SOURCE LINES 87-89

The accumulated statistics match the manual ones at each step,
although the data of the previous steps are not used anymore.

.. GENERATED FROM PYTHON SOURCE LINES 91-99

Volume statistics
-----------------

We now reduce all the spatial dimensions at each time step. Statistics are weighted
by the layer thicknesses, which :func:`~xoa.grid.get_dz` deduces from the ``z`` coordinate,
and by the grid cell sizes, which :func:`~xoa.grid.get_dx_dy` deduces from the longitudes
and latitudes. These are the weights that :class:`~xoa.stats.StatAccum` computes internally.
They are very heterogeneous, as shown below.

.. GENERATED FROM PYTHON SOURCE LINES 99-114

.. code-block:: Python


    dz = get_dz(temp)
    dx, dy = get_dx_dy(temp)
    weights = dz * dx * dy

    fig, axes = plt.subplots(1, 3, figsize=(9, 2.5))
    dz.isel(time=0).plot(ax=axes[0], x="x", y="nz")
    axes[0].set_title("Layer thickness (m)")
    (dx * dy).isel(x=0).plot(ax=axes[1])
    axes[1].set_title("Cell area (m2)")
    weights.isel(time=0, y=0).plot(ax=axes[2], x="x", y="nz")
    axes[2].set_title("Cell volume (m3)")
    fig.tight_layout()
    print("Weights range over a factor", float(weights.max() / weights.min()))




.. image-sg:: /tutorials/evaluation/images/sphx_glr_plot_stataccum_002.png
   :alt: Layer thickness (m), Cell area (m2), Cell volume (m3)
   :srcset: /tutorials/evaluation/images/sphx_glr_plot_stataccum_002.png
   :class: sphx-glr-single-img


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

 .. code-block:: none

    Weights range over a factor 21.052945444216608




.. GENERATED FROM PYTHON SOURCE LINES 115-119

We accumulate the volume statistics and compare the mean with a manual weighted
computation. We also compare with an unweighted mean, where thin layers on the shelf
count as much as thick ones in the open ocean, and cells at high latitudes
as much as the others.

.. GENERATED FROM PYTHON SOURCE LINES 119-136

.. code-block:: Python


    sa = StatAccum(spatial=True)
    sa.append(temp, temp_ref)
    stats = sa.get_stats()
    print(stats)

    manual = (temp * weights).sum(["nz", "y", "x"]) / weights.sum(["nz", "y", "x"])
    xr.testing.assert_allclose(stats.smean0, manual, check_dim_order=False)
    unweighted = StatAccum(temporal=False, spatial=True, weights=False).append(temp).get_stats()

    fig, ax = plt.subplots(figsize=(6, 3))
    manual.plot(ax=ax, label="Manual weighted", lw=4, alpha=0.4)
    stats.smean0.plot(ax=ax, label="StatAccum weighted", ls="--")
    unweighted.smean.plot(ax=ax, label="Unweighted")
    ax.legend()
    ax.set_title("Volume mean of the temperature")




.. image-sg:: /tutorials/evaluation/images/sphx_glr_plot_stataccum_003.png
   :alt: Volume mean of the temperature
   :srcset: /tutorials/evaluation/images/sphx_glr_plot_stataccum_003.png
   :class: sphx-glr-single-img


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

 .. code-block:: none

    <xarray.Dataset> Size: 986kB
    Dimensions:  (nz: 20, x: 30, y: 12, time: 10)
    Coordinates:
        z        (nz, x) float64 5kB -0.5 -0.6552 -0.8103 ... -182.9 -188.9 -195.0
        lon      (x) float64 240B -6.0 -5.931 -5.862 -5.793 ... -4.138 -4.069 -4.0
        lat      (y) float64 96B 30.0 32.73 35.45 38.18 ... 51.82 54.55 57.27 60.0
      * time     (time) datetime64[s] 80B 2020-01-01 ... 2020-01-03T06:00:00
    Dimensions without coordinates: nz, x, y
    Data variables: (12/34)
        tcount   (nz, y, x) float64 58kB 10.0 10.0 10.0 10.0 ... 10.0 10.0 10.0 10.0
        tmean0   (nz, y, x) float64 58kB 13.47 13.47 13.46 ... 7.176 6.868 6.559
        tvar0    (nz, y, x) float64 58kB 2.702e-06 4.639e-06 ... 0.3859 0.411
        tstd0    (nz, y, x) float64 58kB 0.001644 0.002154 ... 0.6212 0.6411
        tmin0    (nz, y, x) float64 58kB 13.47 13.46 13.46 ... 6.45 6.118 5.785
        tmax0    (nz, y, x) float64 58kB 13.48 13.47 13.46 ... 8.232 7.959 7.685
        ...       ...
        sbias    (time) float64 80B 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5
        scrms    (time) float64 80B 1.066e-14 1.599e-14 ... 5.152e-14 3.908e-14
        srms     (time) float64 80B 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5
        scov     (time) float64 80B 6.54 7.538 7.622 6.702 ... 7.312 7.721 7.019
        scorr    (time) float64 80B 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
        savail   (time) float64 80B 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0

    Text(0.5, 1.0, 'Volume mean of the temperature')



.. GENERATED FROM PYTHON SOURCE LINES 137-142

Stop and restart
----------------

The accumulation can be interrupted at any time and resumed later, for instance
from one job of a long simulation to the next.

.. GENERATED FROM PYTHON SOURCE LINES 142-152

.. code-block:: Python


    path = os.path.join(tempfile.mkdtemp(), "stats.nc")
    part = StatAccum(spatial=True)
    part.append(temp.isel(time=slice(0, 4)), temp_ref.isel(time=slice(0, 4)))
    part.dump(path)

    part = StatAccum.from_file(path)
    part.append(temp.isel(time=slice(4, None)), temp_ref.isel(time=slice(4, None)))
    xr.testing.assert_allclose(part.get_stats(), stats)








.. GENERATED FROM PYTHON SOURCE LINES 153-155

The restarted accumulator gives the same statistics as the uninterrupted one.
Times already accumulated are refused, or skipped with ``on_overlap="skip"``.

.. GENERATED FROM PYTHON SOURCE LINES 155-159

.. code-block:: Python


    fig, ax = plt.subplots(figsize=(6, 3))
    part.get_stats().tmean0.isel(y=0, x=-1).plot(ax=ax, y="z", yincrease=False)
    ax.set_title("Temporal mean in the deepest column")



.. image-sg:: /tutorials/evaluation/images/sphx_glr_plot_stataccum_004.png
   :alt: Temporal mean in the deepest column
   :srcset: /tutorials/evaluation/images/sphx_glr_plot_stataccum_004.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    Text(0.5, 1.0, 'Temporal mean in the deepest column')




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

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


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

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

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

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

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

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

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


.. only:: html

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

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