Skip to content

API reference

Top level

synapse_sr.super_resolve

super_resolve(src, model='flash', weights=None, device=None, **kwargs)

One call: load (once, then cached) a model and super-resolve src.

model is "flash" (default: fast on any machine), "pro" (highest detail, best on a GPU) or a registered name; weights / device go to from_pretrained; every other keyword goes to :meth:Pro.super_resolve (tile, batch, scl, progress ...).

synapse_sr.Pro

Pro(model: SynapseProX5, op: S2Forward, device: Union[str, device] = 'cpu', meta: Optional[dict] = None)

SYNAPSE Pro super-resolution model (Sentinel-2 10 m -> 2.0 m RGBN).

The output is x_hat = x_base + P_N(delta): a deterministic, observation-consistent baseline plus a learned correction restricted to the null space of the Sentinel-2 forward operator, so the network can add structure the sensor could not observe but cannot change what it did observe.

Use :meth:from_pretrained to construct.

from_pretrained classmethod

from_pretrained(name: str = registry.DEFAULT, weights: Optional[PathLike] = None, device: Optional[Union[str, device]] = None) -> Pro

Load a SYNAPSE Pro checkpoint.

Parameters:

Name Type Description Default
name str

Registered model name (see synapse_sr/pretrained/*.json). Its checkpoint is downloaded once into the cache ($SYNAPSE_CACHE or ~/.cache/synapse) and its SHA-256 verified on every load.

DEFAULT
weights Optional[PathLike]

Path to a local .safetensors checkpoint. Skips the registry and the network entirely (air-gapped use).

None
device Optional[Union[str, device]]

"cuda", "cpu", "cuda:1" ... Defaults to CUDA when available.

None

super_resolve

super_resolve(src: Union[PathLike, ndarray], band_names: Optional[Sequence[str]] = None, scl: Optional[Union[PathLike, ndarray]] = 'auto', nodata: Optional[float] = None, offset: Optional[float] = None, tile: Optional[int] = None, halo: Optional[int] = None, context: bool = True, batch: Optional[int] = None, progress: Union[bool, str, Callable[[int, int], None]] = 'auto', discrepancy: Optional[float] = None, tta: bool = False, restore_mean: Optional[bool] = None) -> Result

Super-resolve one Sentinel-2 scene.

Parameters:

Name Type Description Default
src Union[PathLike, ndarray]

GeoTIFF path, a (C, H, W) numpy array or torch tensor, or an xarray.DataArray with a band coordinate (for example a single time step of a cubo cube), in L2A DN or reflectance. Accepted band layouts: the 10 model bands (B04 B03 B02 B08 B05 B06 B07 B8A B11 B12), the 12-band L2A order, the 13-band L1C order, or any stack whose band_names (or GeoTIFF band descriptions) include the 10 model bands.

required
band_names Optional[Sequence[str]]

Names of the channels of src; overrides GeoTIFF descriptions.

None
scl Optional[Union[PathLike, ndarray]]

Sentinel-2 scene classification (path or (h, w) array, 10 m or 20 m); classes 0, 1, 3, 8, 9 and 10 are masked. "auto" (default) uses <input>_scl.tif next to a GeoTIFF input when it exists; None disables masking.

'auto'
nodata Optional[float]

Input NoData value; defaults to the GeoTIFF's. All-zero pixels are always masked.

None
offset Optional[float]

Added to DN before dividing by 10000 (-1000 for L2A processing baseline 04.00 and later). None (default) reads the GeoTIFF BOA_ADD_OFFSET tag, else 0. Ignored for reflectance input.

None
discrepancy Optional[float]

How closely the physics baseline fits the measurement, in units of the Sentinel-2 L2A noise level. Pro defaults to 0.5 (tight fit, the most recovered detail); Flash to 4 (a looser fit that absorbs forward-model error, with fewer spurious edges). 4 on Pro reproduces 0.4.0.

None
tile Optional[int]

Source-pixel tile size and context halo. By default the largest tile (and batch) that fits the free GPU memory, or a 6 GB RAM budget on CPU, is chosen: larger tiles waste less computation on the halo.

None
halo Optional[int]

Source-pixel tile size and context halo. By default the largest tile (and batch) that fits the free GPU memory, or a 6 GB RAM budget on CPU, is chosen: larger tiles waste less computation on the halo.

None
batch Optional[int]

Tiles processed together (default: as many as fit the free GPU memory, up to 8; 1 on CPU).

None
progress Union[bool, str, Callable[[int, int], None]]

"auto" (default) shows a live progress bar in terminals and notebooks and stays silent when output is piped or logged; True / False force it on / off; a callable f(done, total) receives the tile count instead. SYNAPSE_SR_QUIET=1 silences everything.

'auto'
context bool

Carry the six native 20 m bands (B05 B06 B07 B8A B11 B12) onto the output grid by pixel replication, so red-edge and SWIR indices (NDRE, NDBI, NBR, MNDWI) are available. They are NOT super-resolved.

True
restore_mean Optional[bool]

Make every 10 m pixel's mean reflectance equal the measurement with a smooth (bicubic) correction that adds no fine structure; it is counted in x_base, not prior. On by default for Flash (lower spectral and reflectance error, higher detail correlation); off by default for Pro, whose tight fit already matches the measurement.

None

Returns:

Type Description
Result

2.0 m RGBN image with error-scale map, support classes, validity mask, consistency and the observed / inferred decomposition.

save_pretrained

save_pretrained(path: PathLike) -> PathLike

Write model and operator to a single .safetensors file loadable with weights=.

to

to(device: Union[str, device]) -> Pro

Move the model and operator to another device, in place.

synapse_sr.Flash

Flash(model: SynapseProX5, op: S2Forward, device: Union[str, device] = 'cpu', meta: Optional[dict] = None)

Bases: Pro

SYNAPSE Flash: the same observation-consistent pipeline as :class:Pro (x_base + P_N(delta)) with a 0.6 M-parameter convolutional detail network instead of the Mamba network. No sequence scan, so it is fast on CPUs, laptops, integrated graphics and Apple silicon. Its body was initialised from SEN2SR-Lite (ESAOpenSR, CC0-1.0) and fine-tuned for the x5 null-space task.

from_pretrained classmethod

from_pretrained(name: str = registry.DEFAULT_FLASH, weights: Optional[PathLike] = None, device: Optional[Union[str, device]] = None) -> Flash

Load a SYNAPSE Flash checkpoint; arguments as :meth:Pro.from_pretrained.

synapse_sr.Result dataclass

Result(image: ndarray, confidence: ndarray, consistency: dict, gsd: float, metadata: dict = dict(), profile: Optional[dict] = None, support: Optional[ndarray] = None, valid: Optional[ndarray] = None, x_base: Optional[ndarray] = None, prior: Optional[ndarray] = None, context: Optional[ndarray] = None, calibration: Optional[dict] = None)

Output of :meth:synapse_sr.Pro.super_resolve.

Attributes:

Name Type Description
image ndarray

(4, 5H, 5W) float32 surface reflectance, bands B04 B03 B02 B08, on the output grid.

confidence ndarray

(4, 5H, 5W) predicted absolute error scale in reflectance. A learned estimate, not calibrated.

consistency dict

Per-band RMS(A(image) - y) / tau_b on the fully supported block, where A is the nominal Sentinel-2 forward model and tau_b the band's noise level.

gsd float

Output grid spacing in metres (2.0 for Sentinel-2 input).

metadata dict

Processing details: scan backend, precision, tiling, regularisation weights, support thresholds.

profile Optional[dict]

Input rasterio profile when the input was a GeoTIFF, else None.

support Optional[ndarray]

(5H, 5W) uint8: 2 HIGH (observation-determined), 1 MEDIUM, 0 LOW (prior-dominated) or invalid input.

valid Optional[ndarray]

(5H, 5W) bool, False where the input was NoData, cloud, cloud shadow, cirrus or saturated.

x_base Optional[ndarray]

(4, 5H, 5W) the observation-determined baseline.

prior Optional[ndarray]

(4, 5H, 5W) structure contributed by the learned prior; x_base + prior == image.

context Optional[ndarray]

(6, 5H, 5W) float16 B05 B06 B07 B8A B11 B12 replicated from their native 20 m grid (not super-resolved), or None.

calibration Optional[dict]

The checkpoint's calibrated error model (coefficients, noise levels, conformal quantiles), used by :meth:uncertainty and :meth:interval; None when the checkpoint ships without one.

summary

summary(print_: bool = True) -> dict

Key facts about the run: size, backend, per-band consistency, support fractions, time. Prints a formatted table (Rich) unless print_=False; always returns them as a dict.

show

show(what=('image', 'support'), figsize=None)

Quick matplotlib look at the result: any of "image" (true colour), "x_base" (the observation-determined baseline), "prior" (learned detail), "support", "uncertainty", "ndvi". Requires matplotlib.

indices

indices() -> dict

Application indices on the output grid, NaN where the input was invalid.

From the super-resolved bands: NDVI, SAVI, EVI, GNDVI (vegetation / crops) and NDWI (water). With 20 m context: NDRE (crop stress), NDBI (built-up), NBR (burn severity) and MNDWI (water / flood); these carry the 20 m spatial detail of their red-edge / SWIR band. Reflectance below zero (possible in L2A over dark water and shadow) is treated as zero; normalised differences are NaN where both bands are essentially dark (sum below 0.002) and lie in [-1, 1] elsewhere; EVI is clipped to [-1, 1].

ndvi

ndvi() -> np.ndarray

NDVI from the super-resolved B08 and B04, NaN where the input was invalid.

band

band(name: str) -> np.ndarray

One band by name: B04 B03 B02 B08 (super-resolved) or a 20 m context band (replicated).

uncertainty

uncertainty() -> np.ndarray

Expected absolute error per pixel and band (reflectance), (4, 5H, 5W), from the checkpoint's calibrated error model: log|error| regressed on the learned error scale, the prior's magnitude relative to sensor noise, local edge strength and variance, brightness, NDVI and band, fitted against a held-out HR reference.

interval

interval(level: float = 0.9) -> np.ndarray

Calibrated error half-width (reflectance), (4, 5H, 5W): with probability level the reference value lies within image +/- half-width. Levels 0.80, 0.90 and 0.95 are calibrated by split conformal prediction on held-out HR reference data; see the model card for the measured coverage.

rgb

rgb(percentiles=(2, 98), gamma: float = 1.0) -> np.ndarray

(5H, 5W, 3) uint8 true-colour quicklook (B04 B03 B02), percentile-stretched jointly.

to_xarray

to_xarray()

xarray.DataArray (band, y, x) with coordinates when the input was georeferenced. Requires xarray.

save

save(path, with_confidence: bool = True, cog: bool = False)

Write a float32 GeoTIFF (or .npz when the input was an array).

Bands: B04 B03 B02 B08, then ERRSCALE_* x4 and SUPPORT unless with_confidence=False. Invalid pixels are written as NaN. cog=True writes a Cloud-Optimised GeoTIFF (internal tiles and overviews) that web maps, QGIS and cloud storage can stream.

Applications

synapse_sr.change

change(before: Result, after: Result, index: str = 'ndvi', threshold: Optional[float] = None, min_support: int = 1) -> Change

Change map between two results on the same grid (e.g. before / after a flood, fire or earthquake).

index: one of CHANGE_INDICES. threshold defaults to 0.2 for normalised indices and 0.03 reflectance for brightness. Pixels invalid on either date, or prior-dominated (support < min_support) on either date, are excluded from mask and reported through reliable, so detected change rests on observed evidence.

synapse_sr.Change dataclass

Change(delta: ndarray, mask: ndarray, reliable: ndarray, index: str, threshold: float, gsd: float)

Output of :func:change. delta = after - before of the chosen index; mask = |delta| > threshold on reliable pixels; reliable = valid on both dates and not prior-dominated on either.

synapse_sr.boundaries

boundaries(r: Result, kind: str = 'field', sigma: float = 1.0) -> np.ndarray

Boundary strength in [0, 1] on the output grid: "field" (NDVI edges: crop parcels), "water" (NDWI edges: shorelines, flood fronts) or "urban" (brightness edges: buildings, roads). Scaled by the 99th percentile; NaN where the input was invalid.

synapse_sr.fetch_sentinel2

fetch_sentinel2(lat: float, lon: float, start: str, end: str, size_m: float = 2000.0, out: Optional[str] = None, max_cloud: float = 20.0, api: str = EARTH_SEARCH) -> str

Download the least-cloudy Sentinel-2 L2A scene over a point into a SYNAPSE-ready GeoTIFF.

Parameters:

Name Type Description Default
lat float

Centre of the area, WGS84 degrees.

required
lon float

Centre of the area, WGS84 degrees.

required
start str

Date range, "YYYY-MM-DD".

required
end str

Date range, "YYYY-MM-DD".

required
size_m float

Edge length of the square area in metres (on the scene's UTM grid).

2000.0
out Optional[str]

Output path; defaults to s2_<item id>.tif in the current directory.

None
max_cloud float

Maximum scene cloud cover in percent.

20.0
api str

STAC API root; default Element 84 Earth Search.

EARTH_SEARCH

Returns:

Type Description
str

Path of the 10-band GeoTIFF (B04 B03 B02 B08 B05 B06 B07 B8A B11 B12, named bands, 10 m grid, 20 m bands nearest-resampled). The scene classification layer is written next to it as *_scl.tif and the radiometric offset is stored in the BOA_ADD_OFFSET tag, which :meth:Pro.super_resolve applies automatically.

Lower level

These are stable, but most users do not need them.

synapse_sr.io.sentinel2.select_bands

select_bands(arr, names=None)

(C, H, W) array -> (10, H, W) in INPUT_BANDS order.

names: band names of arr's channels (e.g. GeoTIFF descriptions). Without names, 10-, 12- and 13-channel stacks are interpreted as INPUT_BANDS, the L2A 12-band and the L1C 13-band orders respectively.

synapse_sr.io.sentinel2.to_reflectance

to_reflectance(arr, scale=10000.0, offset=0.0)

DN -> reflectance: (DN + offset) / scale. L2A processing baseline >= 04.00 uses offset -1000.

synapse_sr.models.scan.backend

backend(u)

'fused' (mamba-ssm CUDA kernel), else 'triton' (CUDA GPU with Triton, self-tested once), else 'pytorch'.

Environment variables

Variable Effect
SYNAPSE_CACHE weight cache directory (default ~/.cache/synapse)
SYNAPSE_SR_DISABLE_FUSED 1 ignores an installed mamba-ssm kernel
SYNAPSE_SR_DISABLE_TRITON 1 skips the Triton scan kernel on CUDA
SYNAPSE_SR_QUIET 1 silences progress bars and summaries everywhere