Core Sources
ArraySource
ArraySource
Bases: DataSource
Wrap a numpy array that is already in memory.
This is the primary integration point for QGIS and other environments that manage rasters internally and cannot rely on file I/O.
If crs and transform are omitted, the array is treated as
pre-aligned to the BN's grid — align_to_grid will return it as-is
when its shape matches the target grid, just like ConstantSource
broadcasts when it has no spatial metadata.
Parameters
array:
2-D (H, W) array of values.
crs:
Optional CRS of the array, as an EPSG string or WKT.
transform:
Optional affine pixel-to-world transform.
valid_range:
Optional (lo, hi) tuple. Values outside this range become NaN.
Either bound may be None. The array passed in is left untouched.
resampling:
How the array is resampled onto the reference grid when it has a
crs and transform: "bilinear" (default), "nearest",
"mode", "average", "min" or "max". See
:class:~geobn.sources.DataSource.
Example — with CRS metadata (full georeferencing):
import numpy as np
from affine import Affine
slope = np.random.rand(100, 200).astype("float32") * 45.0
transform = Affine(0.01, 0, 10.0, 0, -0.01, 70.0)
source = geobn.ArraySource(slope, crs="EPSG:4326", transform=transform)
Example — pre-aligned array (no CRS needed):
# An array computed on the BN grid elsewhere, with the grid's shape,
# needs no CRS metadata.
snow_depth = my_snow_model(bn.fetch_raw(geobn.RasterSource("dem.tif")))
bn.set_input("snow_depth", geobn.ArraySource(snow_depth))
To compute an input from another source, a DerivedSource is usually the better fit:
it keeps the input lazy, so it is fetched only when needed and can be frozen.
ConstantSource
ConstantSource
Bases: DataSource
Broadcast a single scalar value across the entire domain.
The 1×1 sentinel array is recognised by align_to_grid and expanded to the reference grid shape, so no explicit spatial metadata is needed.
Parameters
value:
The scalar to broadcast.
valid_range:
Optional (lo, hi) tuple. Either bound may be None. A value
outside the range becomes NaN, and so covers the whole grid with
NoData.
Example:
# Apply a uniform 30 cm recent snowfall across the entire domain
source = geobn.ConstantSource(30.0)
bn.set_input("recent_snow", source)
RasterSource
RasterSource
Bases: DataSource
Read a local GeoTIFF file.
rasterio is used only to open the file and is discarded immediately; the returned RasterData contains only plain numpy/affine objects. Pixels matching the file's declared nodata value (or its mask) are returned as NaN.
Parameters
path:
Path to the GeoTIFF file.
valid_range:
Optional (lo, hi) tuple. Values outside this range become NaN.
Use it for files that encode missing data as an extreme number
without declaring it as nodata. Either bound may be None.
resampling:
How the file is resampled onto the reference grid: "bilinear"
(default), "nearest", "mode", "average", "min" or
"max". Use "mode" or "nearest" for class rasters such
as land cover. See :class:~geobn.sources.DataSource.
Example:
Example — a class raster:
# Most frequent class per grid pixel, so no in-between codes appear
source = geobn.RasterSource("land_cover.tif", resampling="mode")
bn.set_input("land_cover", source)
Example — masking undeclared sentinel values:
# A DTM that writes -9999 for sea without declaring it as nodata
source = geobn.RasterSource("dem_10m.tif", valid_range=(-500.0, 9000.0))
URLSource
URLSource
Bases: DataSource
Fetch a GeoTIFF from an HTTP/HTTPS URL and return it as plain data.
The file is streamed into an in-memory buffer so nothing is written to disk. rasterio is the only component that sees the raw bytes; the returned RasterData contains only numpy / affine objects.
Parameters
url:
HTTP/HTTPS URL pointing to a GeoTIFF file.
timeout:
HTTP request timeout in seconds.
cache_dir:
Optional path to a directory for caching the fetched raster on disk.
On a cache hit the HTTP request is skipped entirely.
cache_ttl:
Maximum age of a cache entry, as a :class:~datetime.timedelta or a
number of seconds. The default None never expires. When an
entry expires and the server sent an ETag or Last-Modified
header with it, the file is requested conditionally: if the server
answers that it is unchanged, the cached array is kept and its age
reset, and only a changed file is downloaded again.
valid_range:
Optional (lo, hi) tuple. Values outside this range become NaN.
Use it for files that encode missing data as an extreme number
without declaring it as nodata. Either bound may be None. The
cached array is the one the server sent, so changing the range
re-masks it without downloading again.
resampling:
How the file is resampled onto the reference grid: "bilinear"
(default), "nearest", "mode", "average", "min" or
"max". See :class:~geobn.sources.DataSource.
Supports optional disk caching.
Example:
source = geobn.URLSource(
"https://example.com/data/slope.tif",
cache_dir="cache/",
)
bn.set_input("slope_angle", source)
Add cache_ttl (a timedelta or seconds) for a file that is updated; an entry older than
the TTL is requested again. If the server sent an ETag or Last-Modified header with the
file, that request is conditional: a 304 Not Modified answer keeps the cached array and
resets its age, and only a changed file is downloaded.
PointGridSource
PointGridSource
Bases: DataSource
Sample a user-supplied callable over an N×N lat/lon grid.
Builds a regular grid of sample_points × sample_points WGS84 points
covering the inference bounding box, calls fn(lat, lon) at each point,
and assembles the results into a coarse EPSG:4326 raster.
This raster is then resampled to the reference grid, bilinearly unless
resampling says otherwise.
This is the generic primitive for any point-queryable data source (weather
APIs, elevation services, custom models). Pass a lambda or a regular
function as fn; return float("nan") or None for missing values.
Parameters
fn:
Callable with signature (lat: float, lon: float) -> float | None.
Return float("nan") or None for positions with no data.
sample_points:
Number of sample points per axis. Total API calls = sample_points².
Default is 5 (25 calls). Use 1 for a single-point broadcast (equivalent
to ConstantSource but fetched dynamically).
delay:
Seconds to sleep between successive calls. Default 0.05 s — enough to
be polite to most free REST APIs without slowing batch runs noticeably.
valid_range:
Optional (lo, hi) tuple. Either bound may be None. A sample
outside the range becomes NaN, for APIs that report missing data as a
magic number rather than null.
name:
Short identifier for this source, e.g. "wave_height". It is what
the disk cache is keyed on, together with the bounding box and
sample_points, because a callable cannot identify itself — two
sources built from the same factory are indistinguishable otherwise.
Required when cache_dir is set.
cache_dir:
Optional path to a directory for caching the sampled lattice on disk.
On a cache hit no calls to fn are made at all.
cache_ttl:
Maximum age of a cache entry, as a :class:~datetime.timedelta or a
number of seconds. An older entry is resampled. Forecasts are the
usual case for this, e.g. cache_ttl=timedelta(hours=6). The
default None never expires.
resampling:
How the sampled lattice is resampled onto the reference grid. The
lattice is coarser than the grid, so "bilinear" (default)
interpolates between samples, and every other method gives each
grid pixel the value of the sample cell it lies in. See
:class:~geobn.sources.DataSource.
PointGridSource is the generic primitive for any point-queryable data source.
Pass any callable that accepts (lat, lon) and returns a float.
Caching a forecast: pass cache_dir together with name, and cache_ttl for how long
a sampled lattice stays usable. On a hit fn is not called at all, which matters when each
call is an HTTP request — a 5×5 lattice is 25 of them.
name is what identifies the entry, because a callable cannot identify itself: two sources
built by the same factory are indistinguishable, so they would otherwise share one entry.
Passing cache_dir without name raises ValueError.
from datetime import timedelta
source = geobn.PointGridSource(
fn=sea_temperature,
sample_points=5,
name="sea_temp",
cache_dir="cache/",
cache_ttl=timedelta(hours=6),
)
Example — Open-Meteo precipitation:
import requests
import geobn
def fetch_precipitation(lat: float, lon: float) -> float:
"""Query Open-Meteo historical archive for daily precipitation."""
resp = requests.get(
"https://archive-api.open-meteo.com/v1/archive",
params={
"latitude": lat,
"longitude": lon,
"start_date": "2024-01-01",
"end_date": "2024-01-01",
"daily": "precipitation_sum",
"timezone": "UTC",
},
timeout=10,
)
resp.raise_for_status()
values = resp.json().get("daily", {}).get("precipitation_sum", [None])
v = values[0]
return float(v) if v is not None else float("nan")
source = geobn.PointGridSource(fn=fetch_precipitation, sample_points=5)
bn.set_input("precipitation", source)
Example — MET Norway ocean forecast:
import requests
def sea_temperature(lat: float, lon: float) -> float:
resp = requests.get(
"https://api.met.no/weatherapi/oceanforecast/2.0/complete",
params={"lat": lat, "lon": lon},
headers={"User-Agent": "my-app/1.0"},
timeout=10,
)
if resp.status_code == 422:
return float("nan") # outside ocean coverage
resp.raise_for_status()
ts = resp.json().get("properties", {}).get("timeseries", [])
if not ts:
return float("nan")
val = ts[0]["data"]["instant"]["details"].get("sea_water_temperature")
return float(val) if val is not None else float("nan")
source = geobn.PointGridSource(fn=sea_temperature, sample_points=5, delay=0.1)
bn.set_input("sea_temp", source)
MosaicSource
MosaicSource
Bases: DataSource
Combine several sources into one layer, best source first.
Each source is aligned to the reference grid, and the mosaic takes for every pixel the value of the first source that has data there. This covers the common case of a node whose data comes from layers of decreasing quality and increasing coverage: a local survey where it exists, a chart elsewhere, a regional model everywhere.
Alongside the values, the mosaic produces a provenance layer recording
which source supplied each pixel. Read both with
bn.fetch_raw(source, return_provenance=True).
Sources are fetched in order and only while pixels remain uncovered, so a lower-priority source is not fetched at all when the ones above it already cover the grid.
Parameters
sources:
The sources to combine, highest priority first. A source that covers
the whole grid, such as :class:~geobn.ConstantSource, is the usual
last entry.
names:
Optional labels for the provenance layer, one per source. They must
be unique. Without them the sources are labelled by class and
position, e.g. "RasterSource[0]".
on_error:
What to do when a source fails to fetch. "raise" (default)
propagates the error, so a mistyped path is not covered up by the
source below it. "skip" treats the source as having no data and
issues a :class:UserWarning naming it, for a layer that is optional
or sometimes unreachable.
valid_range:
Optional (lo, hi) tuple applied to the combined values, after the
sources have been merged. Pixels it masks are NaN in the values and
-1 in the provenance layer. A source can carry its own
valid_range as well, which applies before the merge and therefore
lets the next source fill in the pixels it masks.
fetch_with_provenance
Return the combined data together with the provenance layer.
Parameters
grid: Reference grid. Required: the sources have to be aligned to a common grid before they can be compared pixel by pixel.
Returns
tuple[RasterData, np.ndarray]
The mosaicked data, and an int16 array of the same shape holding
the index of the source each pixel came from, or -1 where no
source had data.
Each source is aligned to the reference grid before the merge, so they may differ in CRS,
resolution and extent. Each source is resampled with its own resampling method, and the
seam between two sources follows the resampled footprint of the higher-priority one. Sources are fetched in order and only
while pixels remain uncovered, so a remote source at the end of the list costs nothing
when the sources above it already cover the grid.
Example — a local survey over a regional model:
depth = geobn.MosaicSource(
[
geobn.RasterSource("multibeam_survey.tif"),
geobn.WCSSource(url=EMODNET_WCS, layer="emodnet:mean"),
],
names=["survey", "emodnet"],
)
bn.set_input("water_depth", depth)
Example — reading the provenance layer:
values, provenance = bn.fetch_raw(depth, return_provenance=True)
for index, name in enumerate(depth.names):
print(f"{name}: {(provenance == index).mean():.0%} of the grid")
print(f"no data: {(provenance == -1).mean():.0%}")
Example — a prior wherever the raster has nothing:
# ConstantSource covers the whole grid, so it is the natural last entry.
traffic = geobn.MosaicSource(
[geobn.RasterSource("ais_density.tif"), geobn.ConstantSource(2.0)],
names=["ais_density", "medium_traffic_prior"],
on_error="skip",
)
With on_error="skip" a source that cannot be fetched at all — a file that is not there,
an endpoint that is down — counts as having no data, and a UserWarning names it. The
default on_error="raise" propagates the error, so a mistyped path is not covered up by
the source below it.
A valid_range on the mosaic applies to the merged values, after a pixel has been taken
from a source. A valid_range on one of the sources applies before the merge, and
therefore lets the next source fill in the pixels it masks.
DerivedSource
DerivedSource
Bases: DataSource
Compute a layer from one or more other sources.
Each input source is aligned to the reference grid, and fn is called with the aligned arrays, one per source and in the same order. It returns one array of the same shape, which becomes this source's data::
depth = geobn.DerivedSource(
lambda z: np.where(z <= 0, -z, np.nan), # elevation → depth, land → NaN
geobn.WCSSource(url, layer="emodnet:mean"),
)
bn.set_input("water_depth", depth)
Nothing is fetched until the source is: the inputs are fetched and fn
runs when :meth:~geobn.GeoBayesianNetwork.infer or
:meth:~geobn.GeoBayesianNetwork.fetch_raw needs the data, so a derived
input can be frozen with :meth:~geobn.GeoBayesianNetwork.freeze like
any other. Derived sources can be nested, and :mod:geobn.terrain
builds on them for slope, aspect, roughness and TPI.
The source keeps no disk cache of its own. Give the input sources a
cache_dir to avoid downloading them again; fn runs on every fetch.
Parameters
fn:
Function taking one (H, W) float32 array per source and
returning an (H, W) array. NaN marks pixels without data, both in
the arrays passed in and in the one returned.
sources:
The input sources. Each is resampled onto the grid with its own
resampling method before fn sees it.
valid_range:
Optional (lo, hi) tuple applied to the result of fn*. Either
bound may be None.
Example — elevation to depth:
def depth_below_surface(elevation):
return np.where(elevation <= 0, -elevation, np.nan) # land → NaN
depth = geobn.DerivedSource(
depth_below_surface,
geobn.WCSSource(url=EMODNET_WCS, layer="emodnet:mean", cache_dir="cache/"),
)
bn.set_input("water_depth", depth)
Example — combining two sources:
# Snow load from depth (m) and density (kg/m³); both are aligned to the grid first.
load = geobn.DerivedSource(
lambda depth, density: depth * density * 9.81 / 1000, # kPa
geobn.RasterSource("snow_depth.tif"),
geobn.URLSource("https://example.com/snow_density.tif"),
)
bn.set_input("snow_load", load)
Example — building on a terrain helper:
def facing_north(aspect_deg):
return np.where(np.isnan(aspect_deg), np.nan, np.cos(np.radians(aspect_deg)))
bn.set_input("northness", geobn.DerivedSource(facing_north, geobn.terrain.aspect(dem)))
The function receives float32 arrays with NaN for missing data and must return an array
of the grid's shape. The inputs are resampled with their own resampling method. A derived
source keeps no disk cache of its own, so give remote inputs a cache_dir; the function
runs again on every fetch, and bn.freeze() keeps its discretised result between
infer() calls.