Interpolate a meridional section of CROCO outputs to regular heights#

In this tutorial, we show how to:

  • compute the z heights from s-coordinates,

  • easily find the name of variables and coordinates,

  • interpolate a 3D field with varying heights to regular heights,

  • compute the mixed layer depth from temperature.

The concepts are explained in the Vertical coordinates: z and depth guide. See also: Inspect and manipulate horizontal and vertical grids, Rossby number on the sigma levels of a CROCO simulation.

Initialisations#

Import needed modules.

import cmocean  # noqa
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

import xoa
import xoa.meta as xmeta
from xoa.plot import add_colorbar, plot_section
from xoa.regrid import regrid1d
from xoa.thermdyn import mixed_layer_depth

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

Register the internal CROCO naming specifications

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

You can provide your own configuration file.

In this way, the xoa.meta module will recognise the CROCO netcdf names. It would be equivalent to force loading name specs with xoa.meta.set_meta_specs(xoa.get_meta_config_file(“croco”)).

Read the model#

This sample is a meridional extraction of a full 3D CROCO output.

sample_file = xoa.get_data_sample("MODELS/CROCO/SOUTH-AFRICA/croco.south-africa.meridional.nc")
print(sample_file)
ds = xr.open_dataset(sample_file)
print(ds)
/home/docs/.cache/xoa/MODELS/CROCO/SOUTH-AFRICA/croco.south-africa.meridional.nc
<xarray.Dataset> Size: 48kB
Dimensions:     (time: 1, s_w: 33, eta_rho: 56, xi_rho: 1, s_rho: 32, auxil: 4,
                 xi_u: 1, eta_v: 55)
Coordinates: (12/13)
  * time        (time) float64 8B 2.592e+06
  * s_w         (s_w) float32 132B -1.0 -0.9688 -0.9375 ... -0.0625 -0.03125 0.0
  * eta_rho     (eta_rho) float32 224B 6.0 7.0 8.0 9.0 ... 58.0 59.0 60.0 61.0
  * xi_rho      (xi_rho) float32 4B 131.0
    lat_rho     (eta_rho, xi_rho) float32 224B ...
    lat_v       (eta_v, xi_rho) float32 220B ...
    ...          ...
    lon_v       (eta_v, xi_rho) float32 220B ...
  * s_rho       (s_rho) float32 128B -0.9844 -0.9531 ... -0.04688 -0.01562
  * xi_u        (xi_u) float32 4B 131.5
    lat_u       (eta_rho, xi_u) float32 224B ...
    lon_u       (eta_rho, xi_u) float32 224B ...
  * eta_v       (eta_v) float32 220B 6.5 7.5 8.5 9.5 ... 57.5 58.5 59.5 60.5
Dimensions without coordinates: auxil
Data variables: (12/23)
    AKt         (time, s_w, eta_rho, xi_rho) float32 7kB ...
    Cs_r        (s_rho) float32 128B ...
    Cs_w        (s_w) float32 132B ...
    Vtransform  float32 4B ...
    angle       (eta_rho, xi_rho) float32 224B ...
    el          float32 4B ...
    ...          ...
    time_step   (time, auxil) int32 16B ...
    u           (time, s_rho, eta_rho, xi_u) float32 7kB ...
    v           (time, s_rho, eta_v, xi_rho) float32 7kB ...
    w           (time, s_rho, eta_rho, xi_rho) float32 7kB ...
    xl          float32 4B ...
    zeta        (time, eta_rho, xi_rho) float32 224B ...
Attributes: (12/57)
    type:           ROMS history file
    title:          BENGUELA TEST MODEL
    date:
    rst_file:       CROCO_FILES/croco_rst.nc
    his_file:       CROCO_FILES/croco_his.nc
    avg_file:       CROCO_FILES/croco_avg.nc
    ...             ...
    v_sponge:       0.0
    sponge_expl:    Sponge parameters : extent (m) & viscosity (m2.s-1)
    SRCS:           main.F step.F read_inp.F timers_roms.F init_scalars.F ini...
    CPP-options:    REGIONAL BENGUELA_VHR MPI OBC_EAST OBC_WEST OBC_NORTH OBC...
    history:        Tue Mar 31 16:26:24 2020: ncks -O -d time,30 -d xi_rho,13...
    NCO:            4.4.2

Compute heights from s-coordinates#

Decode the dataset according to the CF conventions:

  1. Find sigma terms

  2. Compute the z_rho and z_w heights, that are negative in the ocean

  3. Assign them as coordinates

Note that the decode_sigma subaccessor of the xoa accessor calls the xoa.sigma.decode_cf_sigma() function.

<xarray.DataArray 'z_rho' (time: 1, s_rho: 32, eta_rho: 56, xi_rho: 1)> Size: 14kB
array([[[[-4.47877110e+03],
         [-4.45341971e+03],
         [-4.43332704e+03],
         ...,
         [-7.38942221e+01],
         [-7.34145067e+01],
         [-7.34091375e+01]],

        [[-4.10998820e+03],
         [-4.08677643e+03],
         [-4.06837911e+03],
         ...,
         [-7.04949884e+01],
         [-7.00423304e+01],
         [-7.00372638e+01]],

        [[-3.70399833e+03],
         [-3.68314549e+03],
         [-3.66661727e+03],
         ...,
...
         ...,
         [-4.29529272e+00],
         [-4.27484202e+00],
         [-4.27461272e+00]],

        [[-1.00794918e+01],
         [-1.00480588e+01],
         [-1.00177861e+01],
         ...,
         [-2.57388434e+00],
         [-2.56165088e+00],
         [-2.56151371e+00]],

        [[-3.17876268e+00],
         [-3.15406668e+00],
         [-3.12913607e+00],
         ...,
         [-8.56901999e-01],
         [-8.52836074e-01],
         [-8.52790485e-01]]]], shape=(1, 32, 56, 1))
Coordinates:
  * time     (time) float64 8B 2.592e+06
  * s_rho    (s_rho) float32 128B -0.9844 -0.9531 -0.9219 ... -0.04688 -0.01562
  * eta_rho  (eta_rho) float32 224B 6.0 7.0 8.0 9.0 10.0 ... 58.0 59.0 60.0 61.0
  * xi_rho   (xi_rho) float32 4B 131.0
    lat_rho  (eta_rho, xi_rho) float32 224B -37.67 -37.61 ... -34.03 -33.96
    lon_rho  (eta_rho, xi_rho) float32 224B 18.83 18.83 18.83 ... 18.83 18.83
    z_rho    (time, s_rho, eta_rho, xi_rho) float64 14kB -4.479e+03 ... -0.8528
Attributes:
    long_name:      Ocean s roms coordinate at rho point at RHO location
    Vtransform:     2
    standard_name:  altitude_at_rho_location
    units:          m
    positive:       up

Find coordinate names from CF conventions#

The z_rho was assigned as coordinates at the previous stage. We use the xoa accessor to easily access the temperature, latitude and z arrays. The default configuration exposes shortcuts for some variables and coordinates as shown in accessors.

temp = ds.xoa.temp.squeeze()
temp = temp.where(temp != 0)  # convert zeros to nans
lat_name = temp.xoa.lat.name

Interpolate at regular heights#

We interpolate the temperature array from irregular to regular heights.

Let’s create the output heights.

z = xr.DataArray(
    np.linspace(ds.z_rho.values.min(), ds.z_rho.values.max(), 1000), name="z", dims="z"
)

Let’s interpolate the temperature with xoa.regrid.regrid1d().

tempz = regrid1d(temp, z, extrap="top")

Compute the mixed layer depths#

The mixed layer depths are computed here as the depth at which the temperature is deltatemp lower than the surface temperature, thanks to the xoa.thermdyn.mixed_layer_depth() function.

Plots#

Plot the full section with xoa.plot.plot_section(), that finds the depths and labels the axes from the meta-data.

def plot_both(axs, **extra):
    """Plot the original and the interpolated sections with a shared colorbar"""
    kw = dict(levels=np.arange(0, 23), x="lat", add_colorbar=False, **extra)
    for ax, field in zip(axs, (temp, tempz)):
        mappable = plot_section(field, ax=ax, method="contourf", cmap="cmo.thermal", **kw)
        plot_section(field, ax=ax, method="contour", colors="k", linewidths=0.3, **kw)
        ax.set_xlabel("Latitude [°N]")
        ax.set_ylabel("Height [m]")
    axs[0].set_title("Original")
    axs[1].set_title("Interpolated")
    add_colorbar(mappable, axs, da=temp)
    return mappable


fig, axs = plt.subplots(
    ncols=2, sharex=True, sharey=True, figsize=(9, 3.4), constrained_layout=True
)
plot_both(axs)
Original, Interpolated
<matplotlib.contour.QuadContourSet object at 0x738c04f6ead0>

Plot a zoom near the surface and add the mixed layer depth isoline.

fig, axs = plt.subplots(ncols=2, sharex=True, sharey=True, figsize=(9, 3), constrained_layout=True)
plot_both(axs)
axs[0].plot(mld[lat_name], mld, color="k", linewidth=2, linestyle="--")
axs[1].plot(mldz[lat_name], mldz, color="k", linewidth=2, linestyle="--")
axs[0].set_ylim(-300, 0)
Original, Interpolated
(-300.0, 0.0)

Et voilà!

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

Gallery generated by Sphinx-Gallery