Ocean Stats

[1]:
%load_ext autoreload
%autoreload 2
[2]:
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yaml, os
import nc_time_axis, cftime
from datetime import datetime
import getpass
import xarray as xr
from mom6_tools.stats import extract_time_series, ocean_stats
from mom6_tools.m6toolbox import cime_xmlquery, genBasinMasks
from mom6_tools.MOM6grid import MOM6grid
Basemap module not found. Some regional plots may not function properly
[3]:
# Make the graphs a bit prettier, and bigger
plt.style.use('ggplot')
pd.set_option('display.width', 5000)
pd.set_option('display.max_columns', 60)
plt.rcParams['figure.figsize'] = (15, 5)
plt.rcParams.update({'font.size': 18})
[4]:
# Read in the yaml file
diag_config_yml_path = "diag_config.yml"
diag_config_yml = yaml.load(open(diag_config_yml_path,'r'), Loader=yaml.Loader)
[5]:
caseroot = diag_config_yml['Case']['CASEROOT']
casename = cime_xmlquery(caseroot, 'CASE')
DOUT_S = cime_xmlquery(caseroot, 'DOUT_S')
rundir = cime_xmlquery(caseroot, 'RUNDIR')

if DOUT_S:
  OUTDIR = cime_xmlquery(caseroot, 'DOUT_S_ROOT')+'/ocn/hist/'
else:
  OUTDIR = cime_xmlquery(caseroot, 'RUNDIR')

print('Rundir directory is:', rundir)
print('Casename is:', casename)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Cell In[5], line 2
      1 caseroot = diag_config_yml['Case']['CASEROOT']
----> 2 casename = cime_xmlquery(caseroot, 'CASE')
      3 DOUT_S = cime_xmlquery(caseroot, 'DOUT_S')
      4 rundir = cime_xmlquery(caseroot, 'RUNDIR')

File ~/checkouts/readthedocs.org/user_builds/mom6-tools/envs/latest/lib/python3.10/site-packages/mom6_tools/m6toolbox.py:47, in cime_xmlquery(caseroot, varname)
     45 """run CIME's xmlquery for varname in the directory caseroot, return the value"""
     46 try:
---> 47   value = subprocess.check_output(
     48       ["./xmlquery", "-N", "--value", varname],
     49       stderr=subprocess.STDOUT,
     50       cwd=caseroot,
     51   )
     52 except subprocess.CalledProcessError:
     53   value = subprocess.check_output(
     54       ["./xmlquery", "--value", varname], stderr=subprocess.STDOUT, cwd=caseroot
     55   )

File ~/.asdf/installs/python/3.10.20/lib/python3.10/subprocess.py:421, in check_output(timeout, *popenargs, **kwargs)
    418         empty = b''
    419     kwargs['input'] = empty
--> 421 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
    422            **kwargs).stdout

File ~/.asdf/installs/python/3.10.20/lib/python3.10/subprocess.py:503, in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    500     kwargs['stdout'] = PIPE
    501     kwargs['stderr'] = PIPE
--> 503 with Popen(*popenargs, **kwargs) as process:
    504     try:
    505         stdout, stderr = process.communicate(input, timeout=timeout)

File ~/.asdf/installs/python/3.10.20/lib/python3.10/subprocess.py:971, in Popen.__init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, user, group, extra_groups, encoding, errors, text, umask, pipesize)
    967         if self.text_mode:
    968             self.stderr = io.TextIOWrapper(self.stderr,
    969                     encoding=encoding, errors=errors)
--> 971     self._execute_child(args, executable, preexec_fn, close_fds,
    972                         pass_fds, cwd, env,
    973                         startupinfo, creationflags, shell,
    974                         p2cread, p2cwrite,
    975                         c2pread, c2pwrite,
    976                         errread, errwrite,
    977                         restore_signals,
    978                         gid, gids, uid, umask,
    979                         start_new_session)
    980 except:
    981     # Cleanup if the child failed starting.
    982     for f in filter(None, (self.stdin, self.stdout, self.stderr)):

File ~/.asdf/installs/python/3.10.20/lib/python3.10/subprocess.py:1863, in Popen._execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, gid, gids, uid, umask, start_new_session)
   1861     if errno_num != 0:
   1862         err_msg = os.strerror(errno_num)
-> 1863     raise child_exception_type(errno_num, err_msg, err_filename)
   1864 raise child_exception_type(err_msg)

FileNotFoundError: [Errno 2] No such file or directory: '/glade/work/gmarques/cesm.cases/G/g.e30_a07c_cesm.GJRAv4.TL319_t232_wgx3_hycom1_N75.2025.130/'
[6]:
# create an empty class object
class args:
  pass

args.rundir = rundir
args.casename = casename
args.caseroot = caseroot
args.OUTDIR = OUTDIR
args.nw = 6
args.static = casename+diag_config_yml['Fnames']['static']
args.native = casename+diag_config_yml['Fnames']['native']
args.geom =   casename+diag_config_yml['Fnames']['geom']
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[6], line 5
      2 class args:
      3   pass
----> 5 args.rundir = rundir
      6 args.casename = casename
      7 args.caseroot = caseroot

NameError: name 'rundir' is not defined
[7]:
# read grid info
geom_file = OUTDIR+'/'+args.geom
if os.path.exists(geom_file):
  grd = MOM6grid(OUTDIR+'/'+args.static, geom_file, xrformat=True)
else:
  grd = MOM6grid(OUTDIR+'/'+args.static, xrformat=True)

try:
  depth = grd.depth_ocean.values
except:
  depth = grd.deptho.values

try:
  area = grd.area_t.where(grd.wet > 0)
except:
  area = grd.areacello.where(grd.wet > 0)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[7], line 2
      1 # read grid info
----> 2 geom_file = OUTDIR+'/'+args.geom
      3 if os.path.exists(geom_file):
      4   grd = MOM6grid(OUTDIR+'/'+args.static, geom_file, xrformat=True)

NameError: name 'OUTDIR' is not defined
[8]:
# remove Nan's, otherwise genBasinMasks won't work
# Get masking for different regions
depth[np.isnan(depth)] = 0.0
basin_code = genBasinMasks(grd.geolon.values, grd.geolat.values, depth, xda=True)

#select a few basins, namely, Global, MedSea,BalticSea,HudsonBay Arctic,
# Pacific, Atlantic, Indian, Southern, LabSea and BaffinBay
basins = basin_code.isel(region=[0,4,5,6,7,8,9,10,11,12,13])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[8], line 3
      1 # remove Nan's, otherwise genBasinMasks won't work
      2 # Get masking for different regions
----> 3 depth[np.isnan(depth)] = 0.0
      4 basin_code = genBasinMasks(grd.geolon.values, grd.geolat.values, depth, xda=True)
      6 #select a few basins, namely, Global, MedSea,BalticSea,HudsonBay Arctic,
      7 # Pacific, Atlantic, Indian, Southern, LabSea and BaffinBay

NameError: name 'depth' is not defined

Integrated T & S

[9]:
variables = ['thetaoga','soga','opottempmint','somint']
ds = extract_time_series(args.native, variables, area, args)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[9], line 2
      1 variables = ['thetaoga','soga','opottempmint','somint']
----> 2 ds = extract_time_series(args.native, variables, area, args)

AttributeError: type object 'args' has no attribute 'native'
[10]:
%matplotlib inline

for v in ds.data_vars:
    fig, ax = plt.subplots()
    ds[v].plot(ax=ax)
    ax.set_title('')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[10], line 3
      1 get_ipython().run_line_magic('matplotlib', 'inline')
----> 3 for v in ds.data_vars:
      4     fig, ax = plt.subplots()
      5     ds[v].plot(ax=ax)

NameError: name 'ds' is not defined
[11]:
stats = ocean_stats(args)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[11], line 1
----> 1 stats = ocean_stats(args)

File ~/checkouts/readthedocs.org/user_builds/mom6-tools/envs/latest/lib/python3.10/site-packages/mom6_tools/stats.py:483, in ocean_stats(args)
    478 header = ["Step", "Day","Truncs", "Energy/Mass",
    479         "Maximum CFL", "Mean Sea Level",
    480         "Total Mass", "Mean Salin", "Mean Temp",
    481        "Frac Mass Err", "Salin Err", "Temp Err"]
    482 # ocean.stats is not archived, so it should be read from RUNDIR
--> 483 df = pd.read_csv(args.rundir+'/ocean.stats',  delimiter=',',
    484                usecols=(0,1,2,3,4,5,6,7,8,9,10,11),skiprows=(0,1),
    485                names=header)
    487 # remove characters from each column
    488 for var in header[3::]:

AttributeError: type object 'args' has no attribute 'rundir'

Truncations

[12]:
stats.Truncs.plot()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[12], line 1
----> 1 stats.Truncs.plot()

NameError: name 'stats' is not defined

Maximum finite-volume CFL

[13]:
stats.max_CFL_trans.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[13], line 1
----> 1 stats.max_CFL_trans.plot();

NameError: name 'stats' is not defined

Maximum finite-difference CFL

[14]:
stats.max_CFL_lin.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[14], line 1
----> 1 stats.max_CFL_lin.plot();

NameError: name 'stats' is not defined

Maximum CFL

[15]:
stats.MaximumCFL.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[15], line 1
----> 1 stats.MaximumCFL.plot();

NameError: name 'stats' is not defined

Energy/Mass

[16]:
stats.EnergyMass.plot()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[16], line 1
----> 1 stats.EnergyMass.plot()

NameError: name 'stats' is not defined

Mean Sea Level

[17]:
stats.MeanSeaLevel.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[17], line 1
----> 1 stats.MeanSeaLevel.plot();

NameError: name 'stats' is not defined

Total Mass

[18]:
stats.TotalMass.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[18], line 1
----> 1 stats.TotalMass.plot();

NameError: name 'stats' is not defined

Mean Salinity

[19]:
stats.MeanSalin.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[19], line 1
----> 1 stats.MeanSalin.plot();

NameError: name 'stats' is not defined

Mean Temperature

[20]:
stats.MeanTemp.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[20], line 1
----> 1 stats.MeanTemp.plot();

NameError: name 'stats' is not defined

Total Energy

[21]:
stats.En.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[21], line 1
----> 1 stats.En.plot();

NameError: name 'stats' is not defined

Available Potential Energy

[22]:
stats.APE.sum(axis=1,keep_attrs=True).plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[22], line 1
----> 1 stats.APE.sum(axis=1,keep_attrs=True).plot();

NameError: name 'stats' is not defined

Total Salt

[23]:
stats.Salt.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[23], line 1
----> 1 stats.Salt.plot();

NameError: name 'stats' is not defined

Total Salt Change between Entries

[24]:
stats.Salt_chg.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[24], line 1
----> 1 stats.Salt_chg.plot();

NameError: name 'stats' is not defined

Anomalous Total Salt Change

[25]:
stats.Salt_anom.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[25], line 1
----> 1 stats.Salt_anom.plot();

NameError: name 'stats' is not defined

Total Heat

[26]:
stats.Heat.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[26], line 1
----> 1 stats.Heat.plot();

NameError: name 'stats' is not defined

Total Heat Change between Entries

[27]:
stats.Heat_chg.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[27], line 1
----> 1 stats.Heat_chg.plot();

NameError: name 'stats' is not defined

Anomalous Total Heat Change

[28]:
stats.Heat_anom.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[28], line 1
----> 1 stats.Heat_anom.plot();

NameError: name 'stats' is not defined

Age

[29]:
stats.age.plot();
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[29], line 1
----> 1 stats.age.plot();

NameError: name 'stats' is not defined