"""Build one intake-esm catalog for the new-obs "cases" used as MDTF model cases (WK / MJO_suite obs).
Scans /cases////...nc (symlinks into /data/) and
writes /esm_catalog_newobs.{csv,json} with the same columns as the CESM timeslice catalogs
(esm_catalog_CESM_timeslice_mdtfv3.v43.*). The path column keeps the symlink path, which contains the case name
(MDTF matches cases by name in the path). Rerun it after adding files.
Usage: python build_catalog.py [base]
"""
import csv
import glob
import json
import os
import sys
from datetime import datetime, timezone
import netCDF4
import numpy as np
CATALOG = "esm_catalog_newobs"
REALM = {"atm": "atmos", "lnd": "land", "ocn": "ocean", "ice": "seaIce"}
COLUMNS = ["activity_id", "assoc_files", "institution_id", "member_id", "realm", "variable_id",
"table_id", "source_id", "source_type", "cell_methods", "cell_measures", "experiment_id",
"variant_label", "grid_label", "units", "time_range", "chunk_freq", "standard_name",
"long_name", "frequency", "file_name", "path"]
def time_range(ds):
t = ds.variables["time"]
dates = netCDF4.num2date(np.asarray(t[[0, -1]]), t.units, getattr(t, "calendar", "standard"))
return "-".join(d.strftime("%Y%m%d:000000") for d in dates)
def row(path):
comp, freq = path.split(os.sep)[-3:-1]
var = os.path.basename(path).split(".")[-3]
with netCDF4.Dataset(path) as ds:
v = ds.variables[var]
r = dict.fromkeys(COLUMNS, "")
r.update(activity_id="CESM", institution_id="NCAR", realm=REALM.get(comp, comp),
variable_id=var, cell_methods="time: mean", units=getattr(v, "units", ""),
time_range=time_range(ds), standard_name=getattr(v, "standard_name", ""),
long_name=getattr(v, "long_name", ""), frequency=freq, path=path)
return r
def main():
base = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
files = sorted(f for f in glob.glob(os.path.join(base, "cases", "*", "*", "*", "*.nc"))
if os.path.basename(f).startswith(f.split(os.sep)[-4] + ".") and os.path.exists(f))
rows = [row(f) for f in files]
stem = os.path.join(base, CATALOG)
with open(stem + ".csv", "w", newline="") as fh:
w = csv.DictWriter(fh, fieldnames=COLUMNS)
w.writeheader()
w.writerows(rows)
header = {
"esmcat_version": "0.0.1",
"attributes": [{"column_name": c, "vocabulary": ""} for c in COLUMNS],
"assets": {"column_name": "path", "format": "netcdf", "format_column_name": None},
"aggregation_control": {
"variable_column_name": "variable_id",
"groupby_attrs": ["activity_id", "institution_id", "experiment_id", "frequency",
"member_id", "realm"],
"aggregations": [{"type": "union", "attribute_name": "variable_id", "options": {}}],
},
"id": CATALOG,
"description": "New observations for MDTF Wheeler_Kiladis and MJO_suite, in CESM variable names",
"title": None,
"last_updated": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"catalog_file": os.path.basename(stem + ".csv"),
}
with open(stem + ".json", "w") as fh:
json.dump(header, fh, indent=2)
for r in rows:
print(r["variable_id"], r["frequency"], r["time_range"], r["path"])
print(f"wrote {stem}.csv/.json ({len(rows)} rows)")
if __name__ == "__main__":
main()