GeoBayesianNetwork
The primary user-facing class. Load a model file with geobn.load() (.bif,
.xmlbif, .xml, .net, .xdsl, .uai), attach data sources to evidence nodes,
configure discretization, and call infer().
Factory function
load
Load a Bayesian network from a file, dispatching on the extension.
Supported formats, all read with the readers that ship with pgmpy:
.bif— BIF, written by bnlearn and most exporters.xmlbif— XMLBIF, written by Weka and JavaBayes.net— Hugin NET, written by Hugin and GeNIe.xdsl— GeNIe XDSL, written by GeNIe / SMILE.uai— UAI competition format.xml— resolved from the file's root element (see below)
A .xml file is resolved from its root element: <BIF> is read as
XMLBIF, <smile> as GeNIe XDSL and <ANALYSISNOTEBOOK> as Microsoft
XBN. Any other root element raises :class:ValueError.
UAI files store no names: nodes come back as var_0, var_1, … and
states as integers, in file order. Loading one emits a
:class:UserWarning, and :meth:~GeoBayesianNetwork.set_input and
:meth:~GeoBayesianNetwork.set_discretization must use those names.
Netica .dne is not supported, because pgmpy has no reader for it.
Export to .net or .bif from Netica instead. To use any other
format, read it yourself and pass the model to
:class:GeoBayesianNetwork directly.
Parameters
path: Path to a Bayesian network file with one of the extensions above.
Returns
GeoBayesianNetwork
Ready to accept inputs via :meth:~GeoBayesianNetwork.set_input.
Raises
FileNotFoundError
If path does not exist.
ValueError
If the extension is not recognised, a .xml file's root element is
not one of the three above, the file cannot be parsed, or the parsed
model is not a valid discrete Bayesian network.
GeoBayesianNetwork class
GeoBayesianNetwork
A Bayesian network wired to geographic data sources.
Typical usage::
bn = geobn.load("model.bif")
bn.set_input("slope", geobn.RasterSource("slope.tif"))
bn.set_input("rainfall", geobn.ConstantSource(50.0))
bn.set_discretization("slope", [0, 10, 30, 90], ["flat", "moderate", "steep"])
bn.set_discretization("rainfall", [0, 25, 75, 200], ["low", "medium", "high"])
result = bn.infer(query=["fire_risk"])
result.to_geotiff("output/")
:func:load reads .bif, .xmlbif, .xml, .net, .xdsl and
.uai. A pgmpy model can also be wrapped directly, which covers models
built in code, fitted with pgmpy's estimators, or read with a pgmpy reader
that :func:load does not dispatch on::
from pgmpy.readwrite import XBNReader
model = XBNReader("model.dat").get_model()
bn = geobn.GeoBayesianNetwork(model)
Evidence on any node
Any node can take a source, not only the root nodes. Attach one to an intermediate node when a dataset measures it directly, and query any other node, including one of that node's parents::
bn.set_input("terrain_factor", geobn.RasterSource("exposure.tif"))
bn.set_discretization("terrain_factor", [0, 1, 2, 3], ["low", "medium", "high"])
result = bn.infer(query=["slope_angle"]) # P(slope | observed terrain)
Real-time / repeated inference
When only a subset of inputs change between calls (e.g. static terrain,
changing weather), use :meth:freeze to cache static node arrays::
bn.freeze("slope_angle", "aspect") # terrain is static
result = bn.infer(query=["avalanche_risk"]) # first call: fetches & caches terrain
# Subsequent calls re-process only weather inputs:
bn.set_input("recent_snow", geobn.ConstantSource(35.0))
result = bn.infer(query=["avalanche_risk"]) # terrain reused from cache
For maximum throughput, pre-run all evidence combinations once::
bn.precompute(query=["avalanche_risk"]) # one-time cost: all combos
result = bn.infer(query=["avalanche_risk"]) # O(H×W) numpy indexing, no pgmpy
set_input
Attach a data source to a BN evidence node.
Parameters
node:
Name of any node in the BN. Nodes with parents are allowed: attach
a source to an intermediate node when a dataset measures it
directly, rather than deriving it from the nodes that feed it.
Evidence on a child also lets :meth:infer return a posterior over
one of its parents.
source:
Any :class:~geobn.sources.DataSource subclass.
Notes
A node cannot be both an input and a query node; :meth:infer and
:meth:precompute raise :class:ValueError if one is.
Inputs on nodes with parents are not independent of each other, so they
can contradict the model. Observing a node together with its parent in
a combination the CPD gives probability zero leaves the posterior
undefined; those pixels get NaN and a :class:UserWarning, as with any
other impossible evidence.
fetch_raw
Fetch a data source using the BN's grid and return a plain numpy array.
Useful when you need the raw values to derive additional inputs — for
example, fetching a DEM to compute slope and aspect before registering
them via :meth:set_input. Requires :meth:set_grid to be called
first.
Parameters
source:
Any :class:~geobn.sources.DataSource to fetch. The source is
not registered as an input.
return_provenance:
Also return a layer saying where each pixel came from. For a
:class:~geobn.MosaicSource this is the index of the source that
supplied the pixel, into source.names. Any other source has
one layer, so every pixel that has data is 0.
Returns
np.ndarray
Float32 array of shape (H, W), aligned to the BN's grid.
NaN where the source has no data.
tuple[np.ndarray, np.ndarray]
With return_provenance=True, that array and an int16 array of
the same shape holding the source index per pixel, or -1 where
no source had data.
set_discretization
Define how continuous values for node are mapped to BN states.
Parameters
node:
Node name (must match an input node already registered via
:meth:set_input).
breakpoints:
Monotonically increasing list of len(labels) + 1 boundary
values. The interior values define the bin edges; the first and
last define the valid range [first, last] used by
out_of_range.
labels:
State names that exactly match the state names in the BN.
If omitted, state names are read from the BN node in their
definition order — the breakpoints must then produce exactly
as many bins as the node has states.
out_of_range:
What to do with values outside [breakpoints[0], breakpoints[-1]]:
- ``"clip"`` (default): assign them to the first or last state.
- ``"nan"``: treat them as NoData, so query nodes that depend on
this input get NaN probabilities at that pixel (or point).
suggest_breakpoints
Compute breakpoints for node from the values its source returns.
Fetches the source registered for node on the configured grid and
classifies its values, returning a list ready for
:meth:set_discretization::
bn.set_input("slope_angle", geobn.RasterSource("slope.tif"))
bn.set_discretization("slope_angle", bn.suggest_breakpoints("slope_angle"))
The breakpoints describe the data that was fetched. They fit the case where the model's conditional probabilities are authored alongside the breakpoints; a CPT elicited against fixed thresholds ("steep means over 30°") needs those thresholds, not ones derived from one raster.
Parameters
node:
Node with a source registered via :meth:set_input.
method:
"quantile" (default) for bins holding roughly equal numbers of
pixels, or "equal_interval" for bins of equal width. See
:mod:geobn.breakpoints.
n:
Number of bins. Defaults to the number of states node has in the
BN, which is what :meth:set_discretization expects.
bounds:
(lo, hi) for the outer breakpoints, which define the valid
range. Either side may be None to take that side from the
data, and the default None takes both. Pass the node's
physical range when later data may go beyond the values at hand.
Returns
list of float
n + 1 strictly increasing breakpoints.
Raises
RuntimeError If no grid is configured, since the source cannot be fetched without one. ValueError If node has no registered input, method is unknown, or the data cannot be split into n bins.
set_grid
Override the reference grid instead of deriving it from the first input.
Parameters
crs: Target CRS as EPSG string (e.g. "EPSG:32632") or WKT. resolution: Pixel size in CRS units. extent: (xmin, ymin, xmax, ymax) in CRS units.
freeze
Mark one or more input nodes as static.
On the first :meth:infer call after freezing, each frozen node is
fetched, aligned to the grid, and discretised normally; the resulting
integer index array is then cached in memory. On all subsequent calls
the cached array is reused, skipping fetch, alignment, and
discretisation for those nodes.
Calling :meth:freeze with a different set of nodes invalidates any
previously cached data.
Parameters
*node_names:
Names of input nodes whose data will not change between
:meth:infer calls.
precompute
Pre-run all evidence-state combinations and store a lookup table.
After :meth:precompute, subsequent :meth:infer calls for the same
query nodes bypass pgmpy entirely: probabilities are fetched from the
table via numpy fancy indexing — O(H×W) rather than O(n_unique_combos)
pgmpy queries.
One-time cost: a single pgmpy joint query per query node (the joint P(query, e_1, ..., e_k) is normalised into the conditional table). Only when the table would exceed the in-memory size bound does this fall back to one query per evidence combination.
Parameters
query:
BN node names to precompute posteriors for. Must match the
query passed to :meth:infer for the table path to activate.
Notes
State names are read directly from the BN's CPDs, so
:meth:set_discretization is not required before calling
:meth:precompute.
save_precomputed
Serialize the precomputed lookup table to a portable .npz file.
The file can be loaded on any machine with
:meth:load_precomputed — no pgmpy is required at load time.
Parameters
path:
Destination path. A .npz extension is appended automatically
if not already present (numpy behaviour).
Raises
RuntimeError
If :meth:precompute has not been called yet.
load_precomputed
Load a precomputed lookup table saved with :meth:save_precomputed.
After loading, :meth:infer uses the table path (O(H×W) numpy
indexing) without calling pgmpy.
The file records the model it was built from, and loading checks it against the current BN:
- The table's evidence nodes must be the current inputs. If they were registered in a different order, the table axes are reordered.
- The BN state names and a hash of the model (structure, states and CPD values) must match.
- Discretizations saved with the table are restored for inputs that have none set. An input whose discretization is already set must match the saved one.
Files written by older geobn versions carry none of this information. They still load, with a warning, and only the evidence nodes and array shapes are checked.
Parameters
path:
Path to the .npz file written by :meth:save_precomputed.
Raises
FileNotFoundError
If neither path nor path + .npz exists.
ValueError
If the table's evidence nodes, state names, model hash,
discretizations or array shapes do not match the current BN
configuration.
query_point
Posterior distributions for a single evidence point.
After :meth:precompute (or :meth:load_precomputed), this is a pure
numpy lookup in the precomputed table: no pgmpy inference runs, and
no grid or data sources are involved.
Parameters
evidence:
One value per input node (every node passed to :meth:set_input).
Values may be state names ("steep") or numbers, which are
discretized with the node's :meth:set_discretization spec.
A NaN value gives NaN probabilities for the query nodes that
depend on that input, as in :meth:infer.
query:
Query nodes to return. Defaults to the nodes passed to
:meth:precompute; must be a subset of them.
Returns
dict
{query_node: {state_name: probability}}.
Raises
RuntimeError If no precomputed table is available. ValueError On missing evidence, unknown state names, sequence-valued evidence, or a query node that was not precomputed.
Example
bn.precompute(query=["fire_risk"]) bn.query_point({"slope": 35.0, "rainfall": "high"}) {'fire_risk': {'low': 0.2, 'medium': 0.3, 'high': 0.5}}
query_batch
Posterior distributions for K evidence points at once.
Like :meth:query_point, but vectorized: a pure numpy lookup in the
precomputed table.
Parameters
evidence:
One entry per input node. An entry is either a sequence of K
values (list, tuple or array) or a single value that applies to
all K points. Values may be numbers (discretized with the node's
spec) or state names, but not both in one sequence. A NaN value
gives a NaN row for that point in the query nodes that depend on
that input.
query:
Query nodes to return. Defaults to the nodes passed to
:meth:precompute; must be a subset of them.
Returns
dict
{query_node: (K, n_states) float32 array} with state order
matching the BN definition.
Raises
RuntimeError If no precomputed table is available. ValueError On missing evidence, unknown state names, sequences of different lengths, or a query node that was not precomputed.
clear_cache
Invalidate all cached discrete arrays and the inference table.
Call this if a frozen input actually changes (e.g. you replaced the
terrain source), or after calling :meth:freeze with a different set
of nodes. The next :meth:infer call will re-fetch and re-cache all
frozen nodes.
infer
Run pixel-wise Bayesian inference and return probability rasters.
Parameters
query:
List of BN node names whose posterior distributions are requested.
These may be any nodes, including a parent of an observed node. A
node that is also an input raises :class:ValueError.
Returns
InferenceResult
Contains per-pixel probability arrays for each query node plus
Shannon entropy. Write to disk with .to_geotiff() or convert
to xarray with .to_xarray().
Notes
Where an input has no data, a query node is NaN only if that input is d-connected to it given the inputs that do have data. Query nodes the missing input cannot affect get their posterior from the other inputs.
If :meth:precompute has been called with the same query, this
method uses numpy fancy indexing instead of pgmpy queries. If
:meth:freeze has been called, cached discrete arrays are reused for
frozen nodes.
Real-time optimisation
For repeated inference with static terrain inputs or pre-computed state tables,
see the dedicated Real-time optimisation guide covering
freeze(), precompute(), and clear_cache().