Skip to content

Internals

For contributors, not end users

This page documents the internal modules used by GeoBayesianNetwork and the data sources. Normal users interact exclusively with the public API described in GeoBayesianNetwork, InferenceResult, and the Sources pages.

Grid module (grid.py)

GridSpec dataclass

Describes the spatial grid that all inputs are aligned to.

from_params classmethod

from_params(crs, resolution, extent)

Build a GridSpec from explicit parameters.

Parameters

crs: Target CRS as EPSG string (e.g. "EPSG:32632") or WKT. resolution: Pixel size in the units of crs. extent: (xmin, ymin, xmax, ymax) in the units of crs.

extent_wgs84

extent_wgs84()

Return the bounding box in WGS84 (lon_min, lat_min, lon_max, lat_max).

Points along all four grid edges are transformed, not just the corners, because straight edges in a projected CRS are curved in lon/lat. If the grid contains a pole (e.g. polar stereographic), the box extends to that pole and spans all longitudes. A grid crossing the antimeridian is not split; it gets a box spanning nearly -180..180 degrees longitude.

align_to_grid

align_to_grid(data, grid, resampling='bilinear')

Reproject and resample data to match grid.

Returns a (H, W) float32 array. Pixels that fall outside data's extent are filled with NaN.

resampling is one of :data:RESAMPLING_METHODS:

  • "bilinear" interpolates between the four source pixels around each destination pixel centre. A NaN among them gives NaN.
  • "nearest" takes the source pixel under the destination pixel centre.
  • "mode", "average", "min" and "max" aggregate over the source pixels that fall within each destination pixel, ignoring NaN. A destination pixel is NaN only when none of them has data. Where the source is coarser than the grid, a destination pixel lies within a single source pixel and these methods give the same result as "nearest".

A source with crs=None must either be a single value (ConstantSource), which is broadcast, or already match the grid shape (pre-aligned ArraySource), which is returned as-is. Any other crs=None shape raises ValueError. A source that already matches the target grid is returned as-is. resampling does not apply to either case.

Discretization module (discretize.py)

DiscretizationSpec dataclass

Maps continuous values to BN state labels via breakpoints.

Example

DiscretizationSpec([0, 10, 30, 90], ["flat", "moderate", "steep"]) produces: - value < 10 → "flat" (index 0) - 10 ≤ value < 30 → "moderate" (index 1) - value ≥ 30 → "steep" (index 2)

The first and last breakpoints define the valid range [first, last] (inclusive). They do not affect the bin boundaries; out_of_range controls what happens to values outside them:

  • "clip" (default): values below the range go to the first state, values above it go to the last state.
  • "nan": values outside the range are treated as NoData (index -1).

discretize_array

discretize_array(array, spec)

Return an integer index array (H, W) matching each pixel to a state.

NaN pixels are mapped to -1 (sentinel for NoData). With spec.out_of_range == "nan", values outside [breakpoints[0], breakpoints[-1]] are mapped to -1 as well.

Inference module (inference.py)

run_inference

run_inference(model, evidence_state_grids, evidence_state_names, query_nodes, query_state_names, ve=None)

Run batched pixel-wise inference.

A pixel with NoData (index -1) in some inputs is solved with the inputs it has. A query node is NaN there only when a missing input is d-connected to it given the observed inputs (see :func:make_blanked_by).

Parameters

model: A fitted pgmpy BayesianNetwork. evidence_state_grids: Mapping from evidence node name to (H, W) int16 array of state indices, -1 for NoData. evidence_state_names: Mapping from evidence node name to its ordered list of state labels. query_nodes: Nodes whose posterior distributions are requested. query_state_names: Mapping from query node name to its ordered list of state labels. ve: Pre-built :class:pgmpy.inference.VariableElimination engine. If None (default) a new one is created from model. Pass a cached instance to avoid recreating it on every call when the model does not change.

Returns

Mapping from query node name to a (H, W, n_states) float32 array.

build_conditional_table

build_conditional_table(model, evidence_nodes, query_nodes, ve=None, max_table_cells=_MAX_TABLE_CELLS)

Compute P(query | evidence) for all evidence combinations at once.

Instead of one VE query per evidence combination (prod(n_states) calls), the joint P(query, e_1, ..., e_k) is computed with a single VE query per query node and normalised along the query axis. The result is a lookup table identical in shape to the one built by :meth:~geobn.GeoBayesianNetwork.precompute.

Parameters

model: A fitted pgmpy DiscreteBayesianNetwork. evidence_nodes: Evidence node names; their order defines the table axes. query_nodes: Nodes whose conditional distributions are tabulated. ve: Optional pre-built VariableElimination engine. max_table_cells: If the total number of table cells (summed over query nodes) exceeds this bound, None is returned and the caller should fall back to per-combination queries.

Returns

Mapping from query node to a float32 array of shape (n_states_0, ..., n_states_k, n_query_states), or None if the table would exceed max_table_cells (or a query node is itself an evidence node). Evidence combinations with zero prior probability yield NaN rows.

run_inference_from_table

run_inference_from_table(table, node_order, evidence_state_grids, blanked_by=None)

Map pixel-wise discrete evidence to precomputed probabilities via fancy indexing.

This is the zero-pgmpy fast path used after :meth:~geobn.GeoBayesianNetwork.precompute. Probabilities are read from a lookup table using numpy advanced indexing — O(H×W) rather than running pgmpy per unique evidence combination.

For a pixel with NoData in some inputs, a query node that blanked_by does not list is independent of those inputs given the observed ones, so every table row over the missing inputs' states holds the same posterior (or NaN where that state combination is impossible). The first row without NaN is used; if there is none, the observed evidence itself has probability zero and the result is NaN.

Parameters

table: Mapping from query node name to a numpy array of shape (n_states_0, n_states_1, ..., n_states_k, n_query_states) where the first k axes correspond to the k nodes in node_order. node_order: Evidence node names in the order matching the table axes. evidence_state_grids: Mapping from node name to an int array of state indices, -1 for NoData. All arrays have the same shape, e.g. (H, W) or (K,). blanked_by: Function from a set of missing input nodes to the query nodes it makes NaN, as returned by :func:make_blanked_by. Without it, any missing input makes every query node NaN.

Returns

Mapping from query node name to a float32 array of the grids' shape plus a trailing n_states axis.

make_blanked_by

make_blanked_by(model, evidence_nodes, query_nodes)

Return a function giving the query nodes a set of missing inputs blanks.

A query node is blanked when any missing input is d-connected to it given the inputs that are observed. Results are memoised per missing set.

blank_masks

blank_masks(evidence_state_grids, node_order, query_nodes, blanked_by=None)

Where each query node is NaN because an input it depends on is missing.

Returns one bool array per query node, shaped like the state grids. Without blanked_by, any missing input blanks every query node.

shannon_entropy

shannon_entropy(probs)

Compute per-pixel Shannon entropy (bits) from a probability array.

Parameters

probs: (..., n_states) array of probabilities.

Returns

(...) array of entropy values.

Types (_types.py)

RasterData

Bases: NamedTuple

Internal raster representation — never exposes rasterio objects.

I/O helpers (_io.py)

write_geotiff

write_geotiff(array, crs, transform, path, nodata=float('nan'), descriptions=None)

Write a multi-band float32 GeoTIFF.

Parameters

array: (bands, H, W) float32 array. crs: CRS as EPSG string or WKT. transform: Affine pixel-to-world transform. path: Output file path. nodata: NoData value written into the file metadata. descriptions: Optional band descriptions, one per band.

Disk cache utilities (sources/_cache.py)

Each entry is a {hash16}.npy array beside a {hash16}.json sidecar holding crs, transform and fetched_at (unix seconds). Entries written without fetched_at are dated by the array file's modification time.

_make_cache_path

_make_cache_path(cache_dir, key)

_cache_age

_cache_age(cache_path)

Return the age of a cache entry in seconds, or None if it has none.

The age comes from fetched_at in the JSON sidecar. Entries written without it fall back to the array file's modification time.

_load_cached

_load_cached(cache_path, ttl=None)

Return cached RasterData, or None if absent, corrupt or older than ttl.

Parameters

cache_path: Path of the .npy array file; its .json sidecar sits alongside. ttl: Maximum age in seconds. None (the default) never expires.

_save_cached

_save_cached(cache_path, data, validators=None)