<jupyter_start><jupyter_text>Assess the error associated with using annual-mean tendencies to calculate WMTThis is motivated by the advent of OM4_highres and the call for diagnostics. Is it sufficient to have the tendencies output as an annual mean, or do they need to be monthly or higher?<jupyter_code># Import packages
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
from xhistogram.xarray import histogram
from xgcm import Grid
# Don't display filter warnings
import warnings
warnings.filterwarnings("ignore")
# Set figure font size
plt.rcParams.update({'font.size':14})
# Load data on native grid
rootdir = '/archive/gam/MOM6-examples/ice_ocean_SIS2/Baltic_OM4_025/1yr/'
gridname = 'native'
prefix = '19000101.ocean_'
# Diagnostics were saved into different files
suffixs = ['1900','heat','salt']
ds = xr.Dataset()
for suffix in suffixs:
    filename = prefix+gridname+'_'+suffix+'*.nc'
    dsnow = xr.open_mfdataset(rootdir+filename)
    ds = xr.merge([ds,dsnow])
gridname = '19000101.ocean_static.nc'
grid = xr.open_dataset(rootdir+gridname).squeeze()

# Specify the diffusive tendency terms
processes=['boundary forcing','vertical diffusion','neutral diffusion',
           'frazil ice','internal heat']
terms = {}
terms['heat'] = {'boundary forcing':'boundary_forcing_heat_tendency',
         'vertical diffusion':'opottempdiff',
         'neutral diffusion':'opottemppmdiff',
         'frazil ice':'frazil_heat_tendency',
         'internal heat':'internal_heat_heat_tendency'}
colors = {}
colors['heat'] = {'boundary forcing':'tab:blue',
         'vertical diffusion':'tab:orange',
         'neutral diffusion':'tab:green',
         'frazil ice':'tab:red',
         'internal heat':'tab:purple'}
# Specify the tracer range and bin widths (\delta\lambda) for the calculation
delta_l = 0.2
lmin = -2
lmax = 10
bins = np.arange(lmin,lmax,delta_l)
# Specify constants for the reference density and the specific heat capacity
rho0 = 1035.
Cp = 3992.
G_monthly = xr.Dataset()
for process in processes:
    term = terms['heat'][process]
    nanmask = np.isnan(ds[term])
    G_monthly[process] = histogram(ds['temp'].where(~nanmask).squeeze(),
                        bins=[bins],
                        dim=['xh','yh','zl'],
                        weights=(
                            rho0*(ds[term]/(Cp*rho0)
                                 )*grid['areacello']
                        ).where(~nanmask).squeeze()
                          )/np.diff(bins)
G_yearly = xr.Dataset()
for process in processes:
    term = terms['heat'][process]
    nanmask = np.isnan(ds[term].mean('time'))
    G_yearly[process] = histogram(ds['temp'].mean('time').where(~nanmask).squeeze(),
                        bins=[bins],
                        dim=['xh','yh','zl'],
                        weights=(
                            rho0*(ds[term].mean('time')/(Cp*rho0)
                                 )*grid['areacello']
                        ).where(~nanmask).squeeze()
                          )/np.diff(bins)
# Plot the time-mean transformation
fig, ax = plt.subplots(figsize=(12,8))
total_monthly = xr.zeros_like(G_monthly[processes[0]].mean('time'))
total_yearly = xr.zeros_like(G_yearly[processes[0]])
for process in processes:
    ax.plot(G_monthly['temp_bin'],G_monthly[process].mean('time'),label=process,color=colors['heat'][process])
    ax.plot(G_yearly['temp_bin'],G_yearly[process],linestyle='--',color=colors['heat'][process])
    total_monthly += G_monthly[process].mean('time')
    total_yearly += G_yearly[process]
ax.plot(G['temp_bin'],total_monthly,color='k',label='TOTAL')
ax.plot(G['temp_bin'],total_yearly,linestyle='--',color='k')
ax.legend(loc='lower left')
ax.set_xlabel('Temperature [$^\circ C$]')
ax.set_ylabel('Transformation [$kg\,s^{-1}$]');<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14756671899529042, 'fraction_numerical': 0.0141287284144427, 'mean_word_length': 3.3942528735632185, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '490256', 'license': 'MIT', 'n_tokens_mistral': 1296, 'n_tokens_neox': 1209, 'n_words': 251, 'path': 'notebooks/calc_wmt_timeaveraging_error.ipynb', 'repo_name': 'gmacgilchrist/wmt_bgc', 'size': '3822'}