"""IMERG Final V07B daily precipitation on the 1 deg OLR CDR grid, for one year, as CESM PRECT (m s-1). Source: NCAR GDEX d734000, gpm_3imergdf_v07/YYYY/MM/3B-DAY.MS.MRG.3IMERG.YYYYMMDD-S000000-E235959.V07B.nc4 (2000-06-01 .. 2025-09-30), variable 'precipitation' (combined microwave-IR, mm/day, dims time, lon, lat). Regridding: each 1x1 deg cell is the area-weighted mean of the 10x10 IMERG 0.1 deg cells inside it (the grids nest exactly); missing IMERG cells are left out of the mean, and a 1 deg cell with no valid IMERG cell is missing. Longitudes are shifted from -180..180 to 0..360. Output: yearly/imerg/imerg_.nc Usage: python imerg_daily_year.py YEAR [NDAYS for testing]. Written 2026-11-05. """ import datetime as dt import glob import os import sys import netCDF4 import numpy as np BASE = "/glade/work/bundy/mdtf/obs_wk_mjo" SRC = "/glade/campaign/collections/gdex/data/d734000/gpm_3imergdf_v07" FILL = 1.0e20 def main(): year = int(sys.argv[1]) ndays = int(sys.argv[2]) if len(sys.argv) > 2 else None out = f"{BASE}/yearly/imerg/imerg_{year}.nc" if ndays is not None: out = os.environ.get("TEST_OUT", f"imerg_test_{year}.nc") if os.path.exists(out): sys.exit(f"{out} exists, nothing to do") files = sorted(glob.glob(f"{SRC}/{year}/*/3B-DAY.MS.MRG.3IMERG.{year}*-S000000-E235959.V07B.nc4"))[:ndays] days = [dt.datetime.strptime(os.path.basename(f).split(".")[4][:8], "%Y%m%d").date() for f in files] if any((b - a).days != 1 for a, b in zip(days, days[1:])): sys.exit("days are not consecutive") # area weights of the 0.1 deg cells by latitude, in blocks of 10 edges = np.radians(np.linspace(-90, 90, 1801)) wl = (np.sin(edges[1:]) - np.sin(edges[:-1])).reshape(180, 10) # [lat1, sub] pr = np.full((len(days), 180, 360), FILL, dtype="f4") nmiss = 0 for i, f in enumerate(files): with netCDF4.Dataset(f) as nc: nc.set_auto_mask(False) lat = nc.variables["lat"][:] lon = nc.variables["lon"][:] if not (abs(lat[0] + 89.95) < 1e-4 and abs(lon[0] + 179.95) < 1e-4 and len(lat) == 1800 and len(lon) == 3600): sys.exit(f"{f}: unexpected grid") a = np.asarray(nc.variables["precipitation"][0], dtype="f8").T # (lat, lon) ok = a > -9000.0 a = np.where(ok, a, 0.0).reshape(180, 10, 360, 10) w = ok.reshape(180, 10, 360, 10) * wl[:, :, None, None] num = (a * w).sum(axis=(1, 3)) den = w.sum(axis=(1, 3)) m = np.where(den > 0, num / np.where(den > 0, den, 1) / 86400.0 / 1000.0, FILL) # mm/day -> m s-1 nmiss += int((den == 0).sum()) pr[i] = np.roll(m, 180, axis=1) # lon -180..180 -> 0..360 (cell 0 becomes 0..1 E) if i % 30 == 0: print(f"{dt.datetime.now():%H:%M:%S} {days[i]}", flush=True) tmp = out + ".tmp" with netCDF4.Dataset(tmp, "w") as o: o.createDimension("time", None) o.createDimension("lat", 180) o.createDimension("lon", 360) o.createDimension("nbnd", 2) t = o.createVariable("time", "f8", ("time",)) t.units, t.calendar, t.standard_name, t.axis = "days since 1970-01-01", "proleptic_gregorian", "time", "T" t.bounds = "time_bnds" base = dt.date(1970, 1, 1) t[:] = [(d - base).days + 0.5 for d in days] tb = o.createVariable("time_bnds", "f8", ("time", "nbnd")) tb[:] = [[(d - base).days, (d - base).days + 1] for d in days] la = o.createVariable("lat", "f4", ("lat",)) la.units, la.standard_name, la.axis = "degrees_north", "latitude", "Y" la[:] = np.arange(-89.5, 90.0) lo = o.createVariable("lon", "f4", ("lon",)) lo.units, lo.standard_name, lo.axis = "degrees_east", "longitude", "X" lo[:] = np.arange(0.5, 360.0) x = o.createVariable("PRECT", "f4", ("time", "lat", "lon"), zlib=True, complevel=1, fill_value=FILL) x.units, x.standard_name, x.cell_methods = "m s-1", "precipitation_rate", "time: mean" x.long_name = "Total precipitation rate (IMERG Final V07B daily 'precipitation', mm/day / 86400 / 1000)" x[:] = pr o.source = ("NASA GPM IMERG Final Run V07B daily (3B-DAY), NCAR GDEX d734000; 0.1 deg cells area-averaged " "onto the 1x1 deg NOAA OLR CDR grid") os.rename(tmp, out) print(f"DONE {out}: {len(days)} days {days[0]}..{days[-1]}, all-missing 1 deg cells: {nmiss}", flush=True) if __name__ == "__main__": main()