Weights store¶
Remapping weights depend only on the source grid, the HEALPix target and the method, so grid-doctor computes them once and reuses them. Every weight file has one name, derived from what it describes, and lives in a weights store: a local (POSIX) directory. Callers only choose the store's root; everything below it is grid-doctor's layout.
Getting weights¶
cached_weights is the usual entry point.
It returns a local weight file, looking it up in this order:
- the store,
- the local cache (weights computed while the store was read-only),
- otherwise the weights are computed into the store, or into the local cache when the store is read-only.
import grid_doctor as gd
weights_file = gd.cached_weights(ds, level=9) # default store
weights_file = gd.cached_weights(ds, level=9, store="/work/ab1234/weights")
pyramid = gd.create_healpix_pyramid(ds, max_level=9, weights_path=weights_file)
regrid_to_healpix and
create_healpix_pyramid use the
default store when no weights_path is given, so this is enough to
compute the weights once and reuse them afterwards:
The default store is the GRID_DOCTOR_WEIGHTS_STORE environment
variable, or $XDG_CACHE_HOME/grid-doctor/weights (~/.cache/grid-doctor/weights) when it is unset. To compute into an
explicit file instead, use
compute_healpix_weights(weights_path=...).
Only these choices select a weight file: the source grid, the HEALPix
level and the method. Options such as ignore_unmapped, large_file,
nproc or prefer_offline change how weights are computed, not the
weights themselves. With ignore_unmapped=False, a file found in the store
is still checked: it fails if it leaves HEALPix cells unmapped.
Nested and ring order¶
Weight files are nested; their order is recorded in the
grid_doctor_order attribute. Ring and nested weights differ only in how
the HEALPix cells are numbered, so ring order is chosen when the weights
are applied, and one file serves both:
ds_ring = gd.apply_weight_file(ds, weights_file, nest=False)
pyramid = gd.create_healpix_pyramid(ds, max_level=9, weights_path=weights_file, nest=False)
The target rows are then renumbered in memory (see
nested_to_ring); no ESMF run and
no second file are needed.
Sharing weights¶
Point several users or jobs at the same directory to share weights, e.g.
GRID_DOCTOR_WEIGHTS_STORE=/work/ab1234/weights. Files are written
atomically, so readers never see a partial file. A directory you cannot
write to is used read-only: missing weights are computed into your local
cache instead.
Only local directories and in-memory filesystems (memory://, for tests)
are supported for now.
grid-doctor does not manage permissions: directories and weight files are
created as the user's umask, or the directory's default ACL, allows. A
store shared between users needs a default ACL on its root, set once by
whoever administers it, e.g. for the group ab1234:
Every directory and file created below the root then inherits it,
whatever each user's umask. A PermissionError on a shared store
therefore points at the store's setup, not at grid-doctor.
The same grid is recognised whatever its conventions: coordinates in
radians or degrees, longitudes in 0..360 or [-180, 180) and differing
variable names all lead to the same weight file.
Layout¶
Weight files are stored under Hive-style directories, followed by the digest of the source grid:
<root>/version=1/grid=healpix/ellipsoid=sphere/level=9/method=conservative/<digest>.nc
<root>/version=1/grid=healpix/ellipsoid=wgs84/level=9/method=conservative/<digest>.nc
Tools such as pyarrow, DuckDB or Polars read the directory names as
columns. One grid has the same digest at every level and method, so
WeightsStore.find lists all
targets of a grid, or all grids of a target:
from grid_doctor.weights import WeightsStore
store = WeightsStore("/work/ab1234/weights")
store.find(level=9, method="conservative")
Each file also records its identity (source digest, level, indexing scheme, ellipsoid, method, grid-doctor and layout version), the ESMF version and the number of unmapped HEALPix cells as global attributes, so a store can be checked from the files alone.
Source digest¶
The file name is the SHA-256 digest of the source grid's geometry. It depends only on the cells and their order, so other tools can compute the same digest and share weight files with grid-doctor:
- Coordinates. Take the cell-centre latitude and longitude and, if present, the cell-vertex latitude and longitude, in degrees.
- Quantise. Round every value to integer micro-degrees,
round(value * 1_000_000)(round half to even). Wrap longitudes into[-180_000_000, 180_000_000), so180and-180are equal. Missing vertices (NaN) become-2**63. - Dimensions. Number the dimensions by first appearance, in the
order of step 4. A regular grid has
laton(0,)andlonon(1,). An unstructured grid has both on(0,), and its vertices on(0, 1). - Hash. For centre latitude, centre longitude, vertex latitude and
vertex longitude in that order, add
dims=<dims>;shape=<shape>;(Python tuple notation, e.g.dims=(0, 1);shape=(2, 2);), followed by the integers as little-endian 64-bit values in C (row-major) order.
Variable names, dtypes, units (radians are converted first) and the
longitude convention do not change the digest. Cell order does, because
it defines the columns of the weight matrix. Vertex coordinates are hashed
instead of a node/connectivity list (face_nodes): they describe the same
cells and need no shared node numbering between tools.
API¶
cached_weights(ds, level=None, *, method='conservative', source_units='auto', store=None, ellipsoid=None, **kwargs)
¶
Return a local HEALPix weight file, reusing it through a store.
Weights are identified by their
WeightsDescription: the
normalised source geometry, the HEALPix target and the method. The
lookup is done by
WeightsStore.fetch_or_compute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ds
|
Dataset
|
Source dataset whose grid geometry defines the weights. |
required |
level
|
int | None
|
HEALPix level. Derived from the grid resolution when omitted. |
None
|
method
|
RemapMethod
|
Weight-generation method. Supported values are |
'conservative'
|
source_units
|
SourceUnits
|
Unit convention of the source coordinates. |
'auto'
|
store
|
WeightsStore | str | Path | None
|
Weights store, or its location (see
|
None
|
ellipsoid
|
Ellipsoid | None
|
Ellipsoid of the HEALPix target, |
None
|
**kwargs
|
Unpack[WeightOptions]
|
Any additional keyword arguments for
|
{}
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the local NetCDF weight file. |
Examples:
Source code in grid_doctor/weights.py
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 | |
WeightsStore(location=None, *, cache_dir=None, read_only=None)
¶
Store of HEALPix weight files, laid out by WeightsRef.
Callers pass a root; everything below it is grid-doctor's layout. The
root is a local (POSIX) directory, or an in-memory fsspec filesystem
(memory://, mainly for tests). ESMF and the weight readers need
local files, so files of in-memory stores are copied once into a local
cache that mirrors the same layout.
Args:
location: Root of the store: a local path, a file:// or
memory:// URL, or an fsspec mapper of either. Defaults to
grid_doctor.config.weights_store
(environment variable GRID_DOCTOR_WEIGHTS_STORE), else
$XDG_CACHE_HOME/grid-doctor/weights.
cache_dir: Local directory for copies of in-memory weights and for
weights computed while the store is read-only. Defaults to
$XDG_CACHE_HOME/grid-doctor/weights.
read_only: Forbid publish.
When omitted, local stores are read-only if their directory is
not writable.
Raises: ValueError: For filesystems other than local and in-memory ones.
Examples:
Source code in grid_doctor/weights.py
url_root
property
¶
URL of the store root.
url(item)
¶
local_path(item)
¶
Return where the local copy of a weight file lives.
The file itself for local stores, its place in the local cache for in-memory ones. The file need not exist.
Source code in grid_doctor/weights.py
exists(item)
¶
fetch(item)
¶
Return a local path to the weight file, downloading it if needed.
Raises: FileNotFoundError: If the store does not hold the file.
Source code in grid_doctor/weights.py
publish(desc, local_file)
¶
Store local_file as the weights of desc and return its reference.
Readers never see a partial file: local stores write a temporary file and rename it.
Raises: PermissionError: If the store is read-only.
Source code in grid_doctor/weights.py
fetch_or_compute(desc, compute)
¶
Return a local copy of the weights of desc, computing them if needed.
Looks for the local copy, then the store; otherwise calls
compute(path) and publishes the result to a writable in-memory
store. Weights for a read-only store are computed into and kept in
cache_dir only.
The store holds nested-order weights, so compute must write those, whatever the indexing scheme of desc.
Source code in grid_doctor/weights.py
find(**filters)
¶
List the weight files whose reference fields match filters.
Args:
**filters: Field values of WeightsRef,
e.g. level, method or key.
Raises: TypeError: For unknown filter names.
Examples:
Source code in grid_doctor/weights.py
WeightsDescription(source, target, method)
dataclass
¶
Description of the weights of a remapping problem.
Two descriptions are equal when they describe the same source
geometry (by digest),
target and method.
Attributes: source: Source description. target: HEALPix target grid. method: Remapping method.
ref
property
¶
WeightsRef under which these weights are stored.
Weight files are nested; ring order is chosen when the weights
are applied (see
apply_weight_file), so
both indexing schemes share one reference.
describe_source(source, *, grid=None, source_kind='auto', source_units='auto', spectral_transform_command=None, workdir=None)
¶
Describe a source for HEALPix weight generation.
Normalises the source geometry and classifies the grid. The mesh and the weight-file metadata are built lazily, so describing a source to look its weights up does not mesh it.
Args:
source: Source dataset or source path. A path is mainly
useful for spectral inputs that need an external transform.
grid: Optional grid dataset that supplies geometry when the
data file itself only contains values on dimensions such
as cell.
source_kind: Explicit source representation. Use "auto"
to infer it from the available coordinates.
source_units: Angular unit convention of the source
coordinates, used to normalise the geometry to degrees.
spectral_transform_command: External command used when
source_kind="spectral". The command may use
{input} and {output} placeholders.
workdir: Working directory for the spectral transform;
a temporary directory when omitted.
Raises:
ValueError: When the geometry cannot be normalised (see
normalise_dataset). In particular, cell centres with
NaN coordinates (masked grids) are rejected.
Source code in grid_doctor/weights.py
SourceDescription(dataset, geometry, kind)
dataclass
¶
Resolved description of the source representation.
Built by describe_source
and consumed by the weight-generation entry point and
WeightsDescription.
Two descriptions are equal when their
digest is, i.e. when
they describe the same normalised geometry.
Attributes:
dataset: Materialised gridpoint dataset used for weight
generation.
geometry: Normalised geometry dataset (degrees, longitudes in
[-180, 180)) the mesh is built from.
kind: Source representation class.
The source mesh and everything derived from it are built lazily on first access, so describing a source to look its weights up is cheap.
source_mesh
property
¶
Source mesh stored as compact node/connectivity arrays.
source_dims
property
¶
Source dimensions in flattening order.
looks_global
cached
property
¶
Whether the source appears to cover the whole sphere (diagnostic only).
ignore_unmapped
property
¶
Recommended default for ESMF unmapped handling; always True.
The HEALPix target tiles the whole sphere, so a source that does
not (masked, regional, polar gaps) leaves destination cells
without overlap. They must become missing values rather than abort
weight generation; callers can pass ignore_unmapped=False to
require full coverage. A source that looks global yet leaves cells
unmapped may point at a grid problem (see looks_global).
metadata
cached
property
¶
Source attributes to persist into the weight file.
digest
cached
property
¶
Hash (sha256 hex digest) of the normalised source geometry.
Independent of the target and the method, so one grid has one digest at every level, indexing scheme and method.
WeightsRef(method, level, key, grid=GRID_MAPPING_NAME, ellipsoid='sphere', version=WEIGHTS_VERSION)
dataclass
¶
Reference to a weight file, as a Hive-style relative path.
Lowercase throughout. One name=value directory per entry of
HIERARCHY, followed by the
source digest as file name::
version=1/grid=healpix/ellipsoid=sphere/level=10/method=conservative/<key>.nc
Every part that changes the weights is a directory, so the path is
unique per weight file and the fields used for searching can be read
from a listing without opening files. version is the version of the
path scheme itself. Files hold nested-order weights; ring order is a
renumbering of their rows when they are applied, so it needs no file
of its own.
Attributes:
method: Remapping method.
level: HEALPix level.
key: Source digest (sha256 hex digest); see
SourceDescription.digest.
grid: Target grid; always "healpix".
ellipsoid: Ellipsoid of the HEALPix cell vertices, lowercased
("sphere" or "wgs84").
version: Version of the path scheme.
HIERARCHY = ('version', 'grid', 'ellipsoid', 'level', 'method')
class-attribute
¶
Directory levels, outermost first.
path
property
¶
Relative (store-root) path of the weight file.
__post_init__()
¶
Lowercase every string field, so one set of weights has one path, and validate them.
Raises: ValueError: If a field cannot appear in a weight reference.
Source code in grid_doctor/weights.py
parse(path)
classmethod
¶
Parse a relative weight file path, the inverse of path.
Raises: ValueError: If path does not follow the layout.
Source code in grid_doctor/weights.py
nested_to_ring(cells, level)
¶
Return the ring-order numbers of nested HEALPix cells (0-based) at level.
Weight files are stored in nested order; their rows are renumbered with this when ring order is wanted, instead of computing the weights again.
Source code in grid_doctor/weights.py
ring_to_nested(cells, level)
¶
Return the nested-order numbers of ring HEALPix cells (0-based) at level.
Source code in grid_doctor/weights.py
local_weights_dir()
¶
Local directory holding weight files in the WeightsRef layout.
$XDG_CACHE_HOME/grid-doctor/weights, where XDG_CACHE_HOME
defaults to ~/.cache. Generated weights land here by default and
remote WeightsStores download
into it, so one set of weights has one local path.
Source code in grid_doctor/weights.py
check_coverage(path)
¶
Raise when weight file path leaves HEALPix target cells unmapped.
Repeats the check of ignore_unmapped=False for weights that were
generated (and stored) with unmapped cells ignored. Files without the
unmapped-cells attribute (older files) pass.
Raises: ValueError: If the file records unmapped target cells.