Matched Filter¶
Pure-NumPy matched-filter family for hyperspectral retrieval (CH₄ / CO₂ / arbitrary trace gases). Each piece — background mean, covariance, target spectrum, scoring — is a separate Operator so the algebra is composable.
- Core scoring:
MatchedFilter,MatchedFilterPixel,MatchedFilterSNR - Background statistics:
EstimateMean,EstimateCovEmpirical,EstimateCovLowRank,EstimateCovShrunkStreamingBackground— Welford accumulator + shrunk covariance across many cubesAdaptiveWindowBackground/ApplyAdaptiveMF— sliding-window local mean + diagonal variance, scored per pixel withα = tᵀΛ⁻¹(x − μ) / (tᵀΛ⁻¹t),Λ = diag(σ² + ridge)GMMClusterBackground/ApplyClusterMF— cluster-conditional background- Target construction:
LinearTargetFromObs,NonlinearTargetFromObs - Composed:
ColumnEnhancement— mean → cov → target → MF in one operator - Result containers:
NumpyLinearOperator(dense covariance withsolve),AdaptiveBackground,ClusterBackground,StreamingBackgroundResult,WelfordAccumulator - Post-processing:
DetectionThreshold,ValidateMFInputs - Array primitives (no GeoArray):
apply_image,apply_pixel,apply_adaptive_mf,matched_filter_snr,estimate_mean,estimate_cov_empirical,estimate_cov_shrunk,estimate_cov_lowrank,shrink_covariance,detection_threshold,validate_mf_inputs
Covariance shrinkage ("ledoit_wolf", the default, and "oas") reproduces
sklearn.covariance.ledoit_wolf / sklearn.covariance.oas: the shrinkage intensity is identical on
the same centred samples, and because this package uses the 1/(n − 1) sample covariance the shrunk
matrix is exactly n/(n − 1) times sklearn's (matched-filter scores are invariant to that scale).
Ledoit-Wolf needs the sample fourth moment m₄ = mean‖xₖ − x̄‖⁴: estimate_cov_shrunk computes it
from the pixels, StreamingBackground streams it through WelfordAccumulator.m4, and a direct
shrink_covariance(method="ledoit_wolf", ...) call must pass fourth_moment=.
geoops.matched_filter
¶
Composable pure-NumPy matched-filter operators.
AdaptiveBackground
dataclass
¶
Local per-pixel background statistics from square-window filtering.
Produced by adaptive_window_background. The covariance model is
diagonal: only per-band local variances are stored.
Attributes:
| Name | Type | Description |
|---|---|---|
mean |
Float[ndarray, 'c h w']
|
Per-pixel local mean cube, shaped like the input
|
variance |
Float[ndarray, 'c h w']
|
Per-pixel local (diagonal, unbiased) variance cube,
shaped like the input |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
AdaptiveWindowBackground
¶
Bases: Operator
Per-pixel local mean and diagonal variance over a square window.
Accepts a GeoArray or plain np.ndarray 3-D cube and returns
an AdaptiveBackground (a pair of statistic cubes, not a carrier).
Nodata pixels (non-finite or equal to the input's fill value in any
band) carry no window weight and are NaN in both cubes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window
|
int
|
Side length of the square window; positive odd
integer. Default |
7
|
pad_mode
|
str
|
Boundary mode forwarded to
:func: |
'reflect'
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
ApplyAdaptiveMF
¶
Bases: Operator
Apply a matched filter against per-pixel local window statistics.
Scores each pixel with α = tᵀΛ⁻¹(x − μ) / (tᵀΛ⁻¹t) where μ and
Λ = diag(σ² + ridge) are the pixel's own local mean and diagonal
variance from :class:AdaptiveWindowBackground (see
:func:geoops.matched_filter._src.array.apply_adaptive_mf).
Accepts a GeoArray or plain np.ndarray 3-D cube and returns
the score map as the same carrier kind. Nodata pixels (non-finite or
equal to the input's fill value in any band) and pixels whose window
statistics are undefined hold NaN (fill_value=NaN).
The background is supplied at apply time as a runtime input so the
config (target, ridge, axis) stays hydra-/YAML-safe; pair
it with :class:AdaptiveWindowBackground in a pipeline::
bg = AdaptiveWindowBackground(window=7)(gt)
scores = ApplyAdaptiveMF(target=t)(gt, bg)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
ndarray
|
Target signature |
required |
ridge
|
float
|
Non-negative variance floor added to every local |
0.0
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
ApplyClusterMF
¶
Bases: Operator
Apply a matched filter dispatched by per-pixel cluster label.
Accepts a GeoArray or plain np.ndarray cube and returns the
score map as the same carrier kind. Nodata pixels (non-finite or
equal to the input's fill value in any band, or labelled -1)
hold NaN (fill_value=NaN).
The cluster background is supplied at apply time as a runtime input
so the operator config (target, axis) is hydra-/YAML-safe and
fully describes the operator's init-time state. Pair this operator
with :class:GMMClusterBackground in a pipeline to wire the cluster
state through dataflow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
ndarray
|
Target signature |
required |
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
ClusterBackground
dataclass
¶
Cluster labels with per-cluster matched-filter background statistics.
Produced by gmm_cluster_background and consumed by
apply_cluster_mf, which scores each pixel against the statistics
of its own cluster.
Attributes:
| Name | Type | Description |
|---|---|---|
labels |
Int[ndarray, 'h w']
|
Integer cluster-label map over the cube's spatial shape;
values index into |
means |
Float[ndarray, 'k c']
|
Per-cluster mean spectra, shaped |
cov_ops |
tuple[NumpyLinearOperator, ...]
|
Per-cluster |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
ColumnEnhancement
¶
Bases: Operator
Convenience trace-gas column-enhancement matched-filter composite.
Chains :class:EstimateMean, a covariance estimator, an optional
:class:LinearTargetFromObs, and :class:MatchedFilter into one
call. With obs_model=None the target defaults to a uniform unit
spectrum. Accepts a GeoArray or plain np.ndarray cube and
returns the enhancement score map as the same carrier kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gas
|
str
|
Gas label recorded in the config (e.g. |
'CH4'
|
sensor
|
str
|
Sensor label recorded in the config (e.g. |
'EMIT'
|
obs_model
|
Any | None
|
Optional callable observation model used to derive a
linearised target; a uniform target is used when |
None
|
mean_method
|
MeanMethod
|
Background-mean estimator. Default |
'median'
|
cov_method
|
CovShrinkageMethod | Literal['lowrank']
|
Covariance estimator — |
'ledoit_wolf'
|
target_pattern
|
str
|
Perturbation pattern for target linearisation. |
'uniform'
|
rank
|
int | None
|
Rank for |
None
|
tikhonov
|
float | None
|
Tikhonov regulariser for |
None
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 | |
DetectionThreshold
¶
Bases: Operator
Gaussian false-alarm score threshold.
Graph source: computed from its configuration alone. An optional
input is accepted and ignored, so it can close a Sequential;
it returns the scalar score
threshold whose exceedance probability under the Gaussian no-target
null equals false_alarm_rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
false_alarm_rate
|
float
|
Desired false-alarm probability, strictly between 0 and 1. |
required |
cov_op
|
NumpyLinearOperator | ndarray
|
Background covariance as a |
required |
target
|
ndarray
|
Target signature |
required |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
EstimateCovEmpirical
¶
Bases: Operator
Estimate an empirical covariance operator.
Accepts a GeoArray or plain np.ndarray cube and returns a
NumpyLinearOperator (not a carrier) wrapping the (c, c) sample
covariance. Nodata pixels (non-finite or equal to the input's fill
value in any band) are ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
ndarray | None
|
Optional precomputed mean spectrum |
None
|
ridge
|
float
|
Optional Tikhonov ridge added to the diagonal. |
0.0
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
EstimateCovLowRank
¶
Bases: Operator
Estimate a low-rank-plus-Tikhonov covariance operator.
Accepts a GeoArray or plain np.ndarray cube and returns a
NumpyLinearOperator (not a carrier) approximating the covariance
by its top-rank eigenpairs plus a Tikhonov diagonal. Nodata
pixels (non-finite or equal to the input's fill value in any band)
are ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
ndarray | None
|
Optional precomputed mean spectrum |
None
|
rank
|
int
|
Number of leading eigenpairs kept. |
10
|
tikhonov
|
float
|
Diagonal regulariser added after the low-rank reconstruction. |
0.001
|
seed
|
int | None
|
Seed for the randomized range finder; the default
|
0
|
n_oversamples
|
int
|
Extra random probe vectors beyond |
10
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
EstimateCovShrunk
¶
Bases: Operator
Estimate a diagonal-target shrinkage covariance operator.
Accepts a GeoArray or plain np.ndarray cube and returns a
NumpyLinearOperator (not a carrier) wrapping the covariance shrunk
toward a scaled-identity target. Nodata pixels (non-finite or equal
to the input's fill value in any band) are ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
ndarray | None
|
Optional precomputed mean spectrum |
None
|
method
|
CovShrinkageMethod
|
Shrinkage-intensity estimator, |
'ledoit_wolf'
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
EstimateMean
¶
Bases: Operator
Estimate a spectral background mean vector from a cube.
Accepts a ``GeoArray`` or plain ``np.ndarray`` cube and returns the
plain ``(c,)`` mean spectrum (a vector, not a carrier). See
:func:geoops.matched_filter._src.array.estimate_mean for the
estimator details. Nodata pixels (non-finite or equal to the input's
fill value in any band) are ignored.
Args:
method: Mean estimator — ``"mean"``, ``"median"``, ``"trimmed"``,
or ``"huber"``.
trim_proportion: Fraction cut from each tail for
``method="trimmed"``.
huber_c: Huber tuning constant for ``method="huber"``.
dim: Name of the band dim (default ``"band"``); its position is read
from the carrier's dims.
axis: Deprecated: the band axis position. ``-3`` maps to
``dim="band"``; removed in the next minor release.
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
GMMClusterBackground
¶
Bases: Operator
Estimate clustered background statistics with a NumPy GMM backend.
Runs the deterministic diagonal-GMM clustering (k-means initialised)
of :func:geoops.matched_filter._src.array.gmm_cluster_background.
Accepts a GeoArray or plain np.ndarray cube and returns a
ClusterBackground (labels plus per-cluster statistics, not a
carrier), typically wired into :class:ApplyClusterMF. Nodata pixels
(non-finite or equal to the input's fill value in any band) are left
out of the fit and labelled -1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_clusters
|
int
|
Number of mixture components. |
required |
cov_estimator
|
Literal['empirical', 'ledoit_wolf', 'oas']
|
Per-cluster covariance estimator —
|
'ledoit_wolf'
|
seed
|
int | None
|
Seed for the clustering; fixed seeds give reproducible backgrounds. |
0
|
bayesian
|
bool
|
If |
False
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
LinearTargetFromObs
¶
Bases: Operator
Finite-difference tangent-linear target from an observation model.
Perturbs the background state by a small scaled pattern, pushes both
states through obs_model, and divides the response difference by
the perturbation size — a per-band linearised (Jacobian-action)
target signature (c,). Accepts a GeoArray or plain
np.ndarray cube and returns a plain vector (not a carrier).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obs_model
|
Any
|
Callable mapping a state cube to a spectral response (either a per-band vector or a cube that is averaged over space). Must be callable. |
required |
vmr_background
|
ndarray | None
|
Optional explicit background state; the incoming
cube is used when |
None
|
pattern
|
str | ndarray
|
Perturbation pattern — |
'uniform'
|
pixel
|
tuple[int, int] | None
|
Spatial index of the impulse for |
None
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 | |
MatchedFilter
¶
Bases: Operator
Per-pixel matched-filter score map.
Computes y = (x - mu)^T Sigma^-1 t / (t^T Sigma^-1 t) for every
pixel spectrum and returns a single-band score map. Accepts either a
GeoArray (georeferencing preserved on the output) or a plain
np.ndarray (plain array returned) — the math is metadata-free.
Fitted operator (see Fitted operators in the concepts guide):
- :meth:
fitestimates the background statistics the constructor left unset (meanand / orcov_op) withmean_method/cov_methodand stores the full background inmean_/cov_op_(supplied components are copied through unchanged); - :meth:
transformscores a cube with that background without mutating the operator; - calling the operator fits the missing statistics once, on the first
call (
fit_on_call=False), or estimates them from each cube without storing anything (fit_on_call=True, a per-scene background). Neither path writes fitted arrays intoget_config().
Nodata pixels (non-finite or equal to the input's fill value in any
band) are left out of the fit and hold NaN in the score map,
which declares fill_value=NaN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
ndarray | None
|
Background mean spectrum |
None
|
cov_op
|
NumpyLinearOperator | ndarray | None
|
Background covariance as a |
None
|
target
|
ndarray | None
|
Target signature |
None
|
fit_on_call
|
bool
|
Estimate mean and covariance from every cube the operator is called on (a per-scene background, ignoring any supplied or fitted statistics) instead of fitting the missing ones once. |
False
|
mean_method
|
MeanMethod
|
Mean estimator used when fitting. Default
|
'median'
|
cov_method
|
CovMethod
|
Covariance estimator used when fitting —
|
'ledoit_wolf'
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
mean_ |
ndarray | None
|
Background mean from :meth: |
cov_op_ |
NumpyLinearOperator | ndarray | None
|
Background covariance from :meth: |
Examples:
>>> mf = MatchedFilter(target=t).fit(background_scene)
>>> scores = mf(scene) # reuses the fitted background
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | |
fit(gt)
¶
Estimate the unset background statistics from the valid pixels of gt.
Returns:
| Type | Description |
|---|---|
Self
|
This operator, for chaining. |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
transform(gt)
¶
Score gt against the fitted (or supplied) background.
Raises:
| Type | Description |
|---|---|
ValueError
|
If no background is available yet or |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
MatchedFilterPixel
¶
Bases: Operator
Single-pixel matched-filter score.
Scalar counterpart of :class:MatchedFilter: scores one pixel
spectrum (any 1-D array-like) against fixed background statistics
and returns a float.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
ndarray
|
Background mean spectrum |
required |
cov_op
|
NumpyLinearOperator | ndarray
|
Background covariance as a |
required |
target
|
ndarray
|
Target signature |
required |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
MatchedFilterSNR
¶
Bases: Operator
Theoretical detection SNR amplitude * sqrt(t^T Sigma^-1 t).
Graph source: computed from its configuration alone. An optional
input is accepted and ignored, so it can close a Sequential;
it returns the scalar
matched-filter output SNR for the configured amplitude, background
covariance, and target.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amplitude
|
float
|
Target amplitude. |
required |
cov_op
|
NumpyLinearOperator | ndarray
|
Background covariance as a |
required |
target
|
ndarray
|
Target signature |
required |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
NonlinearTargetFromObs
¶
Bases: Operator
Finite-amplitude target from a callable observation model.
Like :class:LinearTargetFromObs but with a caller-chosen finite
perturbation amplitude and no division by it: the returned
(c,) signature is the raw response difference, which retains the
observation model's nonlinearity at that amplitude. Accepts a
GeoArray or plain np.ndarray cube and returns a plain
vector (not a carrier).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obs_model
|
Any
|
Callable mapping a state cube to a spectral response. Must be callable. |
required |
vmr_background
|
ndarray | None
|
Optional explicit background state; the incoming
cube is used when |
None
|
amplitude
|
float
|
Finite perturbation amplitude. Default |
1.0
|
pattern
|
str | ndarray
|
Perturbation pattern — |
'uniform'
|
pixel
|
tuple[int, int] | None
|
Spatial index of the impulse for |
None
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 | |
NumpyLinearOperator
dataclass
¶
Dense NumPy linear operator with a small solve interface.
Wraps a square (covariance) matrix behind the minimal interface the
matched-filter kernels need — shape and solve — so callers
don't depend on how the operator is represented. The matrix is
coerced to a float ndarray at construction.
Attributes:
| Name | Type | Description |
|---|---|---|
matrix |
Float[ndarray, 'c c']
|
Square |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
shape
property
¶
Matrix shape (c, c).
solve(rhs)
¶
Solve matrix @ x = rhs for x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rhs
|
Float[ndarray, ' c']
|
Right-hand-side vector with one entry per band. |
required |
Returns:
| Type | Description |
|---|---|
Float[ndarray, ' c']
|
The solution vector |
Raises:
| Type | Description |
|---|---|
LinAlgError
|
If the matrix is singular. |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
StreamingBackground
¶
Bases: Operator
Aggregate mean/covariance across an iterable of cubes.
Streams every cube through a WelfordAccumulator and returns a
StreamingBackgroundResult (mean vector plus covariance operator,
not a carrier). Cubes may be GeoArray or plain np.ndarray
and can be mixed freely. Nodata pixels (non-finite or equal to each
cube's fill value in any band) are not accumulated.
The cubes iterable is supplied at apply time (runtime dataflow) so the
operator config remains hydra-/YAML-serialisable: cov_kind and
axis fully describe the operator's init-time state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cov_kind
|
Literal['empirical', 'shrunk']
|
|
'shrunk'
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
StreamingBackgroundResult
dataclass
¶
Mean and covariance operator estimated from streamed cubes.
Attributes:
| Name | Type | Description |
|---|---|---|
mean |
Float[ndarray, ' c']
|
Background mean spectrum |
cov_op |
NumpyLinearOperator
|
Background |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
ValidateMFInputs
¶
Bases: Operator
Fail-fast pass-through validator for matched-filter inputs.
Raises ValueError early for an all-zero target, a singular
covariance, or a non-positive filter gain; otherwise returns its
runtime input unchanged (whatever its type), so it can be inserted
anywhere in a pipeline as a guard.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cov_op
|
NumpyLinearOperator | ndarray
|
Background covariance as a |
required |
target
|
ndarray
|
Target signature |
required |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
WelfordAccumulator
dataclass
¶
Streaming mean/covariance accumulator using Chan-Welford updates.
Accumulates first and second moments over batches of spectra without
holding them all in memory, using the numerically stable pairwise
(Chan et al.) merge of Welford statistics. Feed sample batches with
update (or combine partial accumulators with merge) and read the
result off mean / covariance.
Attributes:
| Name | Type | Description |
|---|---|---|
count |
int
|
Number of samples absorbed so far. |
mean |
Float[ndarray, ' c']
|
Running mean spectrum |
m2 |
Float[ndarray, 'c c']
|
Running centred sum-of-products matrix |
m3 |
Float[ndarray, ' c']
|
Running centred third-moment vector
|
m4 |
float
|
Running centred fourth moment |
Merging two accumulators A, B with pooled mean x̄ and
offsets δ_X = x̄_X − x̄ (all sums centred, so Σ d = 0)::
M2 = Σ_X [M2_X + n_X δ_X δ_Xᵀ]
M3 = Σ_X [M3_X + tr(M2_X) δ_X + 2 M2_X δ_X + n_X ‖δ_X‖² δ_X]
M4 = Σ_X [M4_X + 4 δ_Xᵀ M3_X + 4 δ_Xᵀ M2_X δ_X
+ 2 ‖δ_X‖² tr(M2_X) + n_X ‖δ_X‖⁴]
which follows from expanding ‖d + δ‖² with d = x − x̄_X.
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | |
covariance(*, ddof=1, ridge=0.0)
¶
Return the sample covariance matrix of the absorbed samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ddof
|
int
|
Delta degrees of freedom; the default |
1
|
ridge
|
float
|
Optional Tikhonov ridge added to the diagonal to keep the matrix invertible. |
0.0
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, 'c c']
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
empty(n_features)
classmethod
¶
Create an empty accumulator for n_features spectral bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_features
|
int
|
Number of bands |
required |
Returns:
| Type | Description |
|---|---|
WelfordAccumulator
|
A zero-count accumulator ready for |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
from_values(values)
classmethod
¶
Create an accumulator from a batch of sample rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Float[ndarray, 'n c']
|
Sample rows shaped |
required |
Returns:
| Type | Description |
|---|---|
WelfordAccumulator
|
An accumulator holding the batch's exact mean and centred |
WelfordAccumulator
|
sum-of-products. Rows with a non-finite value are skipped. |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
merge(other)
¶
Merge another accumulator into this one in place.
Uses the pairwise Chan update, so merging accumulators built from disjoint batches is exact (equivalent to a single pass over the concatenated samples).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
WelfordAccumulator
|
Accumulator over the same number of bands. |
required |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
update(values)
¶
Absorb a batch of samples into the running statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Float[ndarray, 'n c']
|
Sample rows shaped |
required |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
apply_adaptive_mf(cube, *, background, target, ridge=0.0, axis=-3)
¶
Apply a matched filter against a local diagonal-covariance background.
Scores every pixel against its own window statistics from
adaptive_window_background: local mean μ(r) and diagonal
covariance Λ(r) = diag(σ²(r) + ridge). With the same amplitude
normalisation as apply_image (the Manolakis MF with Σ → Λ(r))::
α(r) = tᵀ Λ(r)⁻¹ (x(r) − μ(r)) / (tᵀ Λ(r)⁻¹ t)
= Σ_c t_c (x_c − μ_c) / σ²_c / Σ_c t_c² / σ²_c
i.e. the per-pixel maximum-likelihood target amplitude under an
independent-band Gaussian background. The window includes the pixel
itself, so a strong target slightly biases its own μ and σ².
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Float[ndarray, 'c h w']
|
Spectral cube, canonically |
required |
background
|
AdaptiveBackground
|
Local statistics from |
required |
target
|
Float[ndarray, ' c']
|
Target signature |
required |
ridge
|
float
|
Non-negative variance floor added to every |
0.0
|
axis
|
int
|
Position of the spectral axis. Default |
-3
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, 'h w']
|
Score map with the cube's spatial shape; |
Float[ndarray, 'h w']
|
its local mean, or its local variance is non-finite, or where a |
Float[ndarray, 'h w']
|
band's |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the background shapes differ from the cube's, the
target length disagrees with the band count, |
Examples:
>>> import numpy as np
>>> cube = np.random.default_rng(0).normal(size=(3, 8, 8))
>>> bg = adaptive_window_background(cube, window=3)
>>> apply_adaptive_mf(cube, background=bg, target=np.ones(3)).shape
(8, 8)
>>> apply_adaptive_mf(
... cube, background=bg, target=np.array([1.0, 0.0, 0.0]), ridge=1e-6
... ).shape
(8, 8)
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 | |
apply_image(cube, *, mean, cov_op, target, axis=-3)
¶
Apply a matched filter over a hyperspectral image cube.
The covariance system is solved once for the target and reused for
every pixel, so the per-pixel work is a single dot product. See
apply_pixel for the scalar kernel and its formula.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Float[ndarray, 'c h w']
|
Spectral cube, canonically |
required |
mean
|
Float[ndarray, ' c']
|
Background mean spectrum |
required |
cov_op
|
NumpyLinearOperator | Float[ndarray, 'c c']
|
Background covariance as a |
required |
target
|
Float[ndarray, ' c']
|
Target signature |
required |
axis
|
int
|
Position of the spectral axis. Default |
-3
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, 'h w']
|
Matched-filter score map with the cube's spatial shape (e.g. |
Float[ndarray, 'h w']
|
|
Float[ndarray, 'h w']
|
non-finite band. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If vector lengths disagree with the band count, or the target/covariance pair produces a non-positive filter denominator. |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
apply_pixel(pixel, *, mean, cov_op, target)
¶
Score one pixel spectrum with the matched filter.
Computes the maximum-likelihood target-amplitude estimate
.. math::
\alpha \;=\; \frac{(x - \mu)^\top \Sigma^{-1} t}
{t^\top \Sigma^{-1} t}
for a single spectrum x. See apply_image for whole cubes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pixel
|
Float[ndarray, ' c']
|
Pixel spectrum |
required |
mean
|
Float[ndarray, ' c']
|
Background mean spectrum |
required |
cov_op
|
NumpyLinearOperator | Float[ndarray, 'c c']
|
Background covariance as a |
required |
target
|
Float[ndarray, ' c']
|
Target signature |
required |
Returns:
| Type | Description |
|---|---|
float
|
The scalar matched-filter score (estimated target amplitude). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If vector lengths disagree with the band count, or the target/covariance pair produces a non-positive filter denominator. |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
detection_threshold(*, false_alarm_rate, cov_op, target)
¶
Return the score threshold for a Gaussian false-alarm rate.
Under the no-target null hypothesis the matched-filter score is
zero-mean Gaussian with standard deviation
:math:1 / \sqrt{t^\top \Sigma^{-1} t}, so thresholding scores at
:math:\Phi^{-1}(1 - \text{FAR}) / \sqrt{t^\top \Sigma^{-1} t}
yields the requested false-alarm probability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
false_alarm_rate
|
float
|
Desired false-alarm probability, strictly between 0 and 1. |
required |
cov_op
|
NumpyLinearOperator | Float[ndarray, 'c c']
|
Background covariance as a |
required |
target
|
Float[ndarray, ' c']
|
Target signature |
required |
Returns:
| Type | Description |
|---|---|
float
|
The scalar score threshold. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
estimate_cov_empirical(cube, *, mean=None, ridge=0.0, axis=-3)
¶
Estimate an empirical covariance operator from a cube.
Computes the standard ddof=1 sample covariance of the vectorised
pixel spectra, optionally centred on a caller-supplied (e.g. robust)
mean and regularised with a diagonal ridge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Float[ndarray, 'c h w']
|
Spectral cube, canonically |
required |
mean
|
Float[ndarray, ' c'] | None
|
Optional precomputed mean spectrum |
None
|
ridge
|
float
|
Optional Tikhonov ridge added to the diagonal to keep the matrix invertible for near-degenerate backgrounds. |
0.0
|
axis
|
int
|
Position of the spectral axis. Default |
-3
|
Returns:
| Type | Description |
|---|---|
NumpyLinearOperator
|
|
NumpyLinearOperator
|
of the valid pixels (pixels with any non-finite band are |
NumpyLinearOperator
|
ignored). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
estimate_cov_lowrank(cube, *, mean=None, rank=10, tikhonov=0.001, seed=0, n_oversamples=10, axis=-3)
¶
Estimate a low-rank-plus-Tikhonov dense covariance operator.
Approximates the empirical covariance by its top-rank eigenpairs
— found with a randomized range finder (Halko et al. 2011) followed
by an SVD of the projected matrix — and adds a Tikhonov diagonal, so
the result is the dense, well-conditioned matrix
U_k S_k U_k^T + tikhonov * I. Useful when the band count is
large and the background is dominated by a few spectral modes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Float[ndarray, 'c h w']
|
Spectral cube, canonically |
required |
mean
|
Float[ndarray, ' c'] | None
|
Optional precomputed mean spectrum |
None
|
rank
|
int
|
Number of leading eigenpairs kept. Must be positive; values above the band count are truncated to it. |
10
|
tikhonov
|
float
|
Diagonal regulariser added after the low-rank
reconstruction; keeps the operator invertible even though
the low-rank part is singular for |
0.001
|
seed
|
int | None
|
Seed for the randomized range finder. The default
|
0
|
n_oversamples
|
int
|
Extra random probe vectors beyond |
10
|
axis
|
int
|
Position of the spectral axis. Default |
-3
|
Returns:
| Type | Description |
|---|---|
NumpyLinearOperator
|
|
NumpyLinearOperator
|
low-rank covariance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
estimate_cov_shrunk(cube, *, mean=None, method='ledoit_wolf', axis=-3)
¶
Estimate a scaled-identity-target shrinkage covariance operator.
Forms the ddof=1 empirical covariance S of the vectorised
spectra and blends it toward the scaled-identity target
F = tr(S)/c · I with a data-driven intensity s (see
shrink_covariance) — the standard fix when the pixel count is small
relative to the band count. The Ledoit-Wolf intensity needs the
sample fourth moment, which is computed here from the sample matrix,
so the intensity equals sklearn.covariance.ledoit_wolf /
sklearn.covariance.oas on the same centred samples and the
returned matrix is exactly n/(n − 1) times sklearn's (sklearn
uses the 1/n scatter; this package uses 1/(n − 1)). The
matched-filter score is invariant to that scale.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Float[ndarray, 'c h w']
|
Spectral cube, canonically |
required |
mean
|
Float[ndarray, ' c'] | None
|
Optional precomputed mean spectrum |
None
|
method
|
CovShrinkageMethod
|
Shrinkage-intensity estimator, |
'ledoit_wolf'
|
axis
|
int
|
Position of the spectral axis. Default |
-3
|
Returns:
| Type | Description |
|---|---|
NumpyLinearOperator
|
|
NumpyLinearOperator
|
of the valid pixels (pixels with any non-finite band are |
NumpyLinearOperator
|
ignored). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import numpy as np
>>> cube = np.random.default_rng(0).normal(size=(4, 5, 5))
>>> estimate_cov_shrunk(cube).shape
(4, 4)
>>> estimate_cov_shrunk(cube, method="oas").shape
(4, 4)
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
estimate_mean(cube, *, method='mean', trim_proportion=0.1, huber_c=1.345, axis=-3)
¶
Estimate a per-band background mean spectrum from a cube.
Robustness matters for matched filtering: sparse bright targets
(plumes, panels) bias the plain mean toward the target itself, so
the median, trimmed, or huber estimators usually give a
cleaner background.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Float[ndarray, 'c h w']
|
Spectral cube, canonically |
required |
method
|
MeanMethod
|
Mean estimator — |
'mean'
|
trim_proportion
|
float
|
Fraction cut from each tail for
|
0.1
|
huber_c
|
float
|
Huber tuning constant in robust z-score units for
|
1.345
|
axis
|
int
|
Position of the spectral axis. Default |
-3
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, ' c']
|
Mean spectrum with one entry per band, fitted on valid pixels |
Float[ndarray, ' c']
|
only (pixels with any non-finite band are ignored). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
matched_filter_snr(*, amplitude, cov_op, target)
¶
Return the theoretical matched-filter detection SNR.
For a target of amplitude a in Gaussian background noise with
covariance :math:\Sigma, the matched-filter output SNR is
:math:a \sqrt{t^\top \Sigma^{-1} t}.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amplitude
|
float
|
Target amplitude |
required |
cov_op
|
NumpyLinearOperator | Float[ndarray, 'c c']
|
Background covariance as a |
required |
target
|
Float[ndarray, ' c']
|
Target signature |
required |
Returns:
| Type | Description |
|---|---|
float
|
The scalar SNR. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the target/covariance pair produces a non-positive filter gain. |
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
shrink_covariance(empirical, *, method, n_samples, fourth_moment=None)
¶
Shrink an empirical covariance toward a scaled-identity target.
Returns the convex combination (1 − s)·S + s·F with target
F = μ·I, μ = tr(S)/p, where S is the ddof=1 sample
covariance of n samples in p bands and the intensity
s ∈ [0, 1] is estimated from the data. Both estimators reproduce
scikit-learn exactly: with the 1/n scatter Sₙ = S·(n − 1)/n
(sklearn's empirical_covariance), s is sklearn's shrinkage
and the result is n/(n − 1) times sklearn's shrunk matrix (the
intensity is scale-free, the target scales with S).
-
"ledoit_wolf"(Ledoit & Wolf 2004, sklearn'sledoit_wolf_shrinkage), withdₖ = xₖ − x̄the centred samples andm₄ = (1/n) Σₖ ‖dₖ‖⁴::δ² = ‖Sₙ − μₙ I‖²_F (distance to target) β̄² = (1/n²) Σₖ ‖dₖdₖᵀ − Sₙ‖²_F = (m₄ − ‖Sₙ‖²_F) / n s = min(β̄², δ²) / δ² (0 when δ² = 0)
β̄² is the sample variance of the entries of Sₙ; it needs the
fourth moment m₄, which cannot be recovered from S alone.
-
"oas"(Chen et al. 2010, as implemented bysklearn.covariance.oas)::s = min(1, (tr(S²) + tr(S)²) / ((n + 1)·(tr(S²) − tr(S)²/p)))
sklearn omits the 2/p terms of Chen et al. Eq. 23,
((1 − 2/p)·tr(S²) + tr(S)²) / ((n + 1 − 2/p)·(…)); they vanish
for large p and are omitted here too so the two agree exactly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
empirical
|
Float[ndarray, 'c c']
|
|
required |
method
|
CovShrinkageMethod
|
Shrinkage-intensity estimator. |
required |
n_samples
|
int
|
Number of samples used to form |
required |
fourth_moment
|
float | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, 'c c']
|
The shrunk |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import numpy as np
>>> x = np.random.default_rng(0).normal(size=(30, 4))
>>> d = x - x.mean(axis=0)
>>> s = d.T @ d / 29
>>> m4 = float(np.mean(np.sum(d * d, axis=1) ** 2))
>>> shrink_covariance(s, method="ledoit_wolf", n_samples=30,
... fourth_moment=m4).shape
(4, 4)
>>> shrink_covariance(s, method="oas", n_samples=30).shape
(4, 4)
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 | |
validate_mf_inputs(*, cov_op, target)
¶
Raise ValueError for degenerate target/covariance pairs.
Checks, in order: the target has at least one non-zero entry, the
covariance system is solvable, and the resulting filter gain
:math:t^\top \Sigma^{-1} t is finite and positive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cov_op
|
NumpyLinearOperator | Float[ndarray, 'c c']
|
Background covariance as a |
required |
target
|
Float[ndarray, ' c']
|
Target signature |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the target is all-zero, the covariance is singular, or the filter gain is non-positive. |