dapper.met package

Subpackages

Submodules

dapper.met.cmip_utils module

CMIP6 utilities (Pangeo / intake-esm)

Design goals: - Separate search/listing of available datasets from sampling. - Cache the catalog so repeated searches don’t re-parse the JSON. - Support fast “dataset-first” sampling: open each remote zarr once, then compute means for many AOIs.

Typical workflow:

col = open_cmip6_catalog() df_all = search_cmip6(params, col=col) df_use = dedupe_latest(df_all) df_use = filter_complete(df_use, required_vars=params[“variables”]) df_use = df_use[df_use[“source_id”].isin([…])] # optional hard filter out = sample_bbox_means_for_aois(df_use, aois={…}, out_csv=…)

dapper.met.cmip_utils.bounds_from_geojson(path)[source]
Return type:

tuple[tuple[float, float], tuple[float, float]]

Parameters:

path (str | Path)

Read a polygon GeoJSON/shapefile and return:

lat_bounds = (lat_min, lat_max) lon_bounds = (lon_min, lon_max)

Requires geopandas.

dapper.met.cmip_utils.dedupe_latest(df)[source]

Deduplicate by keeping the latest ‘version’ (if present) for each dataset key.

In the Pangeo CMIP6 catalog, duplicates often exist for the same (model, experiment, member, table, grid, variable) with different versions.

Return type:

DataFrame

Parameters:

df (DataFrame)

dapper.met.cmip_utils.download_pangeo(df, dir_out, lat=None, lon=None, lat_bounds=None, lon_bounds=None, polygon_path=None)[source]

Download CMIP6 data from Pangeo to NetCDF, with optional spatial subsetting.

Note: only one of (lat/lon), (lat_bounds/lon_bounds), or (polygon_path) should be provided.

Parameters:
  • df (DataFrame)

  • dir_out (str | Path)

  • lat (float | None)

  • lon (float | None)

  • lat_bounds (tuple[float, float] | None)

  • lon_bounds (tuple[float, float] | None)

  • polygon_path (str | Path | None)

dapper.met.cmip_utils.filter_complete(df, required_vars, group_cols=None)[source]

Keep only dataset groups that contain all required variables.

Return type:

DataFrame

Parameters:
  • df (DataFrame)

  • required_vars (Sequence[str])

  • group_cols (Sequence[str] | None)

By default, completeness is enforced per:

(source_id, experiment_id, member_id, table_id, grid_label)

This prevents “mixing” variables from different grids/members/experiments.

dapper.met.cmip_utils.find_available_data(params, col=None)[source]

Backwards-compatible wrapper around the new search/filter approach.

Note

  • This is now fast because open_cmip6_catalog is cached.

  • It enforces completeness across all requested variables.

Return type:

DataFrame

Parameters:

params (dict)

dapper.met.cmip_utils.open_cmip6_catalog(url='https://storage.googleapis.com/cmip6/pangeo-cmip6.json')[source]

Open (and cache) the Pangeo CMIP6 intake-esm catalog.

Important

  • intake-esm registers its plugin into intake, so you open via intake.open_esm_datastore(…).

Parameters:

url (str)

dapper.met.cmip_utils.sample_bbox_means_for_aois(df, aois, out_csv=None, time_min=None, time_max=None, show_progress=True, *, out_dir=None, chunk_format='parquet', resume=True, return_df=True, fail_log=None, retries=3, retry_backoff=1.0)[source]
Dataset-first sampler (pattern you wanted):
  • Loop over datasets (rows of df), open each zarr once

  • For that dataset, compute bbox-mean time series for each AOI

Crash-resilient mode (recommended):
  • Set out_dir=… to write ONE chunk file per dataset row as you go.

  • If resume=True, already-written chunks are skipped on rerun.

  • If return_df=True, the function returns the concatenation of all chunks in out_dir (including chunks from prior runs).

Notes

  • “dataset” here is a single (model, experiment, member, table, grid, variable) zarr store.

  • Parquet append to a single file is intentionally avoided; parquet is much happier as a directory of files.

Parameters:
  • df (DataFrame) – output of search_cmip6/find_available_data (ideally deduped + filtered).

  • aois (dict[str, tuple[tuple[float, float], tuple[float, float]]]) – dict mapping aoi_id -> ((lat_min, lat_max), (lon_min, lon_max)).

  • out_csv (str | Path | None) – optional final combined CSV to write (built from in-memory output or by reading chunks).

  • time_min/time_max – optional ISO-like strings for time slicing.

  • show_progress (bool) – use tqdm if available.

  • out_dir (str | Path | None) – directory to write chunk outputs (recommended for long runs).

  • chunk_format (str) – ‘parquet’ (default) or ‘csv’. If parquet engine is missing, it falls back to csv automatically.

  • resume (bool) – if True and out_dir provided, skip dataset rows that already have chunk output.

  • return_df (bool) – if True, return concatenated dataframe (reads chunks if out_dir provided).

  • fail_log (str | Path | None) – optional path to a log file for failures; failures are logged and the run continues.

  • retries (int) – number of attempts per dataset row on transient errors.

  • retry_backoff (float) – base backoff seconds (exponential) between retries.

  • time_min (str | None)

  • time_max (str | None)

Return type:

DataFrame

Returns:

Combined long-format dataframe, unless return_df=False (then returns empty dataframe).

dapper.met.cmip_utils.search_cmip6(params, col=None)[source]

Search the CMIP6 catalog and return the raw matches dataframe.

params keys (all optional):

experiment: list[str] -> experiment_id table: str|list[str] -> table_id variables: list[str] -> variable_id ensemble: str|list[str] -> member_id models: list[str] -> source_id grid: str|list[str] -> grid_label

Return type:

DataFrame

Returns:

pd.DataFrame of the intake-esm matches (metadata only).

Parameters:

params (dict)

dapper.met.exporter module

Meteorological data export pipelines.

class dapper.met.exporter.Exporter(adapter, src_path, *, domain, out_dir=None, calendar='noleap', dtime_resolution_hrs=1, dtime_units='days', dformat='BYPASS', append_attrs=None, chunks=None, include_vars=None, exclude_vars=None, clip_to_full_years=None)[source]

Bases: object

Source-agnostic meteorological exporter.

Ingests time-sharded CSVs for all sites/cells, preprocesses each shard with a pluggable adapter, stages per-gid parquet files, and writes packed (int16) ELM MET NetCDFs. The layout follows domain.mode:

  • "cellset": <out_dir>/MET/<file>.nc per variable with dims ('DTIME', 'lat', 'lon'), one global packing, and a single DTIME axis shared by every point (sparse lat/lon axes are allowed).

  • "sites": <out_dir>/<gid>/MET/<file>.nc per variable with dims ('n', 'DTIME') (n=1), per-site packing, and a per-site DTIME axis.

Each MET directory also gets a zone_mappings.txt.

All dataset-specific logic (file discovery, unit conversions, renaming to ELM short names) lives in the adapter (see dapper.met.adapters.base.BaseAdapter).

Parameters:
  • adapter (BaseAdapter) – Source adapter (e.g. ERA5Adapter).

  • src_path (str or pathlib.Path) – Input location passed to adapter.discover_files.

  • domain (Domain) – Sites/cells to export; gid links CSV rows to cells.

  • out_dir (str or pathlib.Path, optional) – Output root. Defaults to domain.run_dir (requires domain.path_out).

  • calendar (str, default "noleap") – DTIME calendar; Feb 29 is dropped for no-leap aliases.

  • dtime_resolution_hrs (float, default 1) – Target DTIME step in hours (fractions allowed).

  • dtime_units ({"days", "hours"}, default "days") – Units of the numeric DTIME coordinate.

  • dformat ({"BYPASS", "DATM_MODE"}, default "BYPASS") – ELM forcing format passed to the adapter.

  • append_attrs (dict, optional) – Extra global attributes for every file. Exporter provenance (domain_mode, pack_scope, export_start_year, …) is added without overriding user keys, except domain_mode, pack_scope, clip_to_full_years and the export years, which always win.

  • chunks (tuple[int, ...], optional) – Explicit NetCDF chunk sizes; auto-chunked when omitted.

  • include_vars (Iterable[str], optional) – Allow/block lists of ELM short names applied after preprocessing. Meta columns gid, time, LATIXY, LONGXY and zone are kept.

  • exclude_vars (Iterable[str], optional) – Allow/block lists of ELM short names applied after preprocessing. Meta columns gid, time, LATIXY, LONGXY and zone are kept.

  • clip_to_full_years (bool or None, optional) – Clip the discovered year range to complete calendar years (raises if none). None keeps the adapter default (True for ERA5).

Notes

Temporary parquet shards are written under <out_dir>/.dapper_tmp and removed at the end of run().

run(*, pack_scope=None, filename=None, overwrite=False)[source]

Run the MET export for this exporter’s Domain.

The output layout is derived from Domain.mode:
  • sites: writes <run_dir>/<gid>/MET/{prefix_}{var}.nc and a per-site zone_mappings.txt (always zone=01, id=1).

  • cellset: writes <run_dir>/MET/{prefix_}{var}.nc and a single zone_mappings.txt covering all locations (zones taken from df_loc, default 1).

Parameters:
  • pack_scope (str | None) – Optional packing strategy override. Defaults to per-site for sites and global for cellset outputs.

  • filename (str | None) – Optional filename template for output NetCDF files. Supports two formats: - Template with {var} placeholder: ‘ERA5_{var}_1950-2025_z01’ generates ‘ERA5_TBOT_1950-2025_z01.nc’ - Simple prefix (legacy): ‘prefix’ generates ‘prefix_TBOT.nc’ If omitted, the default is ‘<driver>_<var>_<start>-<end>_z01.nc’. The ‘.nc’ extension is added automatically.

  • overwrite (bool) – If True, clears existing MET outputs before writing.

Return type:

None

dapper.met.temporal module

Temporal helpers used by Exporter and adapters. NetCDF I/O is handled in dapper.met.writers. This module is intentionally small.

dapper.met.temporal.create_dtime(df, calendar='standard', dtime_units='days', dtime_resolution_hrs=1.0, *, interval_end_vars=None, source_interval_hrs=None, target_start=None)[source]

Construct a numeric DTIME axis and align data onto it at an arbitrary cadence. Accepts fractional hours, e.g., 0.5 (30 min), 0.3 (18 min), 1.5 (90 min).

interval_end_vars identifies source fields whose timestamps label the end of an averaging/accumulation interval. These fields are relabeled to interval starts before calendar filtering or temporal resampling.

Parameters:
  • calendar (str)

  • dtime_units (str)

  • dtime_resolution_hrs (float)

  • source_interval_hrs (float | None)

dapper.met.temporal.get_start_end_years(csv_filepaths, calendar='standard', clip_to_full_years=True)[source]

Inspect CSVs (must contain a ‘date’ column) and return earliest/latest years present. By default, clip to full years and raise if none are present. When clip_to_full_years is False, return the min/max year in the data even when a boundary year is partial.

Parameters:
  • calendar (str)

  • clip_to_full_years (bool)

dapper.met.temporal.is_feb29(times)[source]

Boolean mask of Feb 29 entries in a 1D array-like of datetimes.

Return type:

ndarray

dapper.met.temporal.is_noleap_calendar(calendar='standard')[source]

Return True when calendar is any supported no-leap calendar alias.

Return type:

bool

Parameters:

calendar (str)

dapper.met.temporal.normalize_calendar(calendar='standard')[source]

Return a CF-compatible calendar name used consistently by dapper.

Return type:

str

Parameters:

calendar (str)

dapper.met.temporal.start_end_years_from_dates(date_values, calendar='standard', clip_to_full_years=True)[source]

Return the start/end years represented by a sequence of datetimes.

When clip_to_full_years is True, use the earliest/latest years that contain both Jan 1 and Dec 31. Raise when no complete calendar year is present; callers must explicitly disable clipping to export partial years.

Parameters:
  • calendar (str)

  • clip_to_full_years (bool)

dapper.met.validation module

PNG quicklooks of exported MET files.

dapper.met.validation.make_quicklooks(exporter=None, *, write_directory=None, mode=None, vars=None, gids=None, out_dir=None, max_vars=9)[source]

Create per-site PNG quicklooks of exported MET NetCDFs.

Parameters:
  • exporter (Exporter or None) – The Exporter used for run(...). Required for "cellset" outputs, where its df_loc_norm maps each gid onto the lat/lon axes.

  • write_directory (path-like or None) – Export output root. Defaults to the exporter’s group_dir.

  • mode ({"cellset", "sites"} or None) – Export layout; auto-detected from the NetCDFs when None.

  • vars (list[str] or None) – ELM short names to plot; defaults to DEFAULT_ELM_VARS.

  • gids (list[str] or None) – Subset of gids to plot; all when None.

  • out_dir (path-like or None) – Destination for PNGs. Defaults to <write_directory>/quicklooks.

  • max_vars (int) – Unused; kept for signature compatibility.

Return type:

None

dapper.met.writers module

Low-level netCDF4 writers for packed ELM MET files.

dapper.met.writers.append_met_netcdf(*, path_nc, var_name, data, indexers)[source]

Append data to variable var_name using indexers to select the region.

Notes

  • data should be float; netCDF4 will pack using var attrs (scale_factor/add_offset).

  • You can pass fewer indexers than dims; unspecified dims default to slice(None).

Parameters:
  • var_name (str)

  • indexers (dict[str, int | slice])

dapper.met.writers.initialize_met_netcdf(*, path_nc, var_name, dims, dim_lengths, dtime_name, dtime_vals, dtime_units, calendar, coord_specs, add_offset, scale_factor, dtype='i2', fill_value=32767, chunks, write_pattern='by_site', start_year=None, end_year=None, append_attrs=None, var_attrs=None, nc_format='NETCDF4_CLASSIC', zlib=True, shuffle=True, complevel=1)[source]
Create a NetCDF file with:
  • provided dims

  • numeric DTIME coord

  • ELM-readable start_year and end_year scalar variables

  • site/grid coords from coord_specs

  • packed int var with add_offset/scale_factor

If chunks is None, uses _compute_auto_chunks(…) tuned to write_pattern.

Parameters:
  • var_name (str)

  • dims (tuple[str, ...])

  • dim_lengths (dict[str, int])

  • dtime_name (str)

  • dtime_units (str)

  • calendar (str)

  • coord_specs (list[dict])

  • add_offset (float)

  • scale_factor (float)

  • chunks (tuple[int, ...] | None)

  • write_pattern (str)

  • start_year (int | None)

  • end_year (int | None)

  • append_attrs (dict | None)

  • var_attrs (dict | None)

  • nc_format (str)

  • zlib (bool)

  • shuffle (bool)

  • complevel (int)

Module contents

Meteorological forcing: adapters, exporter, and temporal helpers.