#!/usr/bin/env python3 """compare_bench_bug_fix.py Compare hourly global totals in CCTM_EMIS_DIAG from two MPAS-CMAQ runs that differ only in one line of centralized_io_module.F (r_interpolate_var_3d_mpas): "without" : original code (no NEXTIME before retrieve_time_dep_gridded_data) "with" : one line added: call nextime (loc_jdate, loc_jtime, loc_tstep) For each species it prints, per hour: without, with : global totals in CCTM_EMIS_DIAG without-without01 (rel.) : relative change from the 01:00 value (without the line) with-with01 (rel.) : relative change from the 01:00 value (with the line) input : global total of the gridded emission input (per-area units are multiplied by areaCell) without/input, with/input : ratios *_norm : (DIAG/input) normalised by hour 00 It also prints (with - without) and (input[h] - input[01]). If the gridded emissions stay at their 01:00 values without the line, these two columns agree, because the point-source and inline parts are the same in both runs. Note: CCTM_EMIS_DIAG is the sum of all streams (gridded, point sources, inline biogenic/soil/sea-spray, etc.), so DIAG/input is not exactly 1. Usage: python3 compare_bench_bug_fix.py \ --without /CCTM_EMIS_DIAG_20170101.nc \ --with /CCTM_EMIS_DIAG_20170101.nc \ --grid x1.40962.init.20170101.nc \ --from-log \ --species SO2 NO CO """ import argparse import glob import os import re import sys import numpy as np from netCDF4 import Dataset def xtimes(ds): if "xtime" in ds.variables: v = ds.variables["xtime"] v.set_auto_mask(False) v.set_auto_chartostring(False) out = [] for row in np.atleast_2d(np.asarray(v[:])): s = b"".join(row.tolist()) if row.dtype.kind == "S" else bytes(row.astype(np.uint8).tolist()) out.append(s.replace(b"\x00", b"").decode(errors="replace").strip()) return out if "TFLAG" in ds.variables: tf = ds.variables["TFLAG"][:, 0, :] return [f"{d:07d}:{t:06d}" for d, t in tf] return None def per_area(units): u = (units or "").replace(" ", "").lower() return any(k in u for k in ("/m2", "m-2", "m^-2", "/m**2")) def time_totals(ds, var, area): """Global total for each time step; per-area units are multiplied by areaCell.""" v = ds.variables[var] v.set_auto_mask(False) dims = v.dimensions data = np.asarray(v[:], dtype=np.float64) data = np.where(np.abs(data) > 1e30, 0.0, data) # drop fill values tdim = next((i for i, d in enumerate(dims) if d.lower() in ("time", "tstep")), 0) data = np.moveaxis(data, tdim, 0) rest = [d for i, d in enumerate(dims) if i != tdim] units = getattr(v, "units", "") if per_area(units): if area is None: sys.exit(f"{var} has per-area units '{units}'; pass --grid with areaCell") ax = rest.index("nCells") + 1 shape = [1] * data.ndim shape[ax] = area.size data = data * area.reshape(shape) units += " x areaCell" return data.reshape(data.shape[0], -1).sum(axis=1), units def emis_files_from_log(path): """Collect 'setenv GR_EMIS_xxx ' lines from the run log (existing files only).""" out = [] pat = re.compile(r"setenv\s+GR_EMIS_\d+\s+(\S+)") with open(path, errors="replace") as f: for line in f: m = pat.search(line) if m and m.group(1) not in out and os.path.exists(m.group(1)): out.append(m.group(1)) return out def find_var(ds, sp): if sp in ds.variables: return sp return next((k for k in ds.variables if k.upper() == sp.upper()), None) def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--without", required=True, help="CCTM_EMIS_DIAG from the run without the line") ap.add_argument("--with", dest="with_", required=True, help="CCTM_EMIS_DIAG from the run with the line") ap.add_argument("--grid", help="file with areaCell (init / restart / grid)") ap.add_argument("--emis-files", nargs="*", default=[], help="gridded emission files (glob allowed)") ap.add_argument("--from-log", help="run log; GR_EMIS_xxx files are taken from 'setenv' lines") ap.add_argument("--species", nargs="+", default=["SO2"]) a = ap.parse_args() area = None if a.grid: with Dataset(a.grid) as g: area = np.asarray(g.variables["areaCell"][:], dtype=np.float64) wo, wi = Dataset(a.without), Dataset(a.with_) for lab, ds in (("without the line", wo), ("with the line", wi)): t = xtimes(ds) if t: print(f"times ({lab}): " + ", ".join(t)) efiles = [] for p in a.emis_files: efiles += [q for q in (sorted(glob.glob(p)) or [p]) if os.path.exists(q)] if a.from_log: efiles += [p for p in emis_files_from_log(a.from_log) if p not in efiles] if efiles: print(f"\ngridded emission input files ({len(efiles)}):") for p in efiles: print(" ", p) for sp in a.species: vo, vi = find_var(wo, sp), find_var(wi, sp) if vo is None or vi is None: print(f"\n[{sp}] not found in CCTM_EMIS_DIAG") continue Do, units = time_totals(wo, vo, area) Di, _ = time_totals(wi, vi, area) n = min(len(Do), len(Di)) I = None if efiles: I, used = np.zeros(n), 0 for p in efiles: with Dataset(p) as e: ve = find_var(e, sp) if ve is None: continue tot, _ = time_totals(e, ve, area) m = min(n, len(tot)) I[:m] += tot[:m] used += 1 if used == 0: I = None print(f"\n[{sp}] EMIS_DIAG units: {units}") hdr = f"{'h':>3} {'without':>12} {'with':>12} {'wo-wo01':>10} {'wi-wi01':>10} {'with-without':>13}" if I is not None: hdr += f" {'input':>12} {'in-in01':>12} {'wo/input':>9} {'wi/input':>9} {'wo_norm':>8} {'wi_norm':>8}" print(hdr) for h in range(n): ro = (Do[h] - Do[1]) / Do[1] if n > 1 and Do[1] else np.nan ri = (Di[h] - Di[1]) / Di[1] if n > 1 and Di[1] else np.nan line = f"{h:3d} {Do[h]:12.5e} {Di[h]:12.5e} {ro:10.2e} {ri:10.2e} {Di[h] - Do[h]:13.5g}" if I is not None and I[h] and I[0]: line += (f" {I[h]:12.5e} {I[h] - I[1]:12.5g} {Do[h] / I[h]:9.4f} {Di[h] / I[h]:9.4f}" f" {(Do[h] / I[h]) / (Do[0] / I[0]):8.4f} {(Di[h] / I[h]) / (Di[0] / I[0]):8.4f}") print(line) if __name__ == "__main__": main()