Extraction¶
xarray-native extremes extraction — the preprocessing that turns a raw
spatiotemporal series into the sample an EVT model actually expects. Inputs
are xr.DataArrays; array-valued results preserve coordinates, dimensions,
and metadata, while fully reduced results (constant_threshold,
quantile_threshold reduced over all dimensions, estimate_extremal_index on
1-D data) come back as plain floats.
The two routes through this module mirror the two EVT paradigms: block maxima feed a GEV, and threshold exceedances feed a GPD.
Block maxima¶
Take the maximum over fixed blocks (usually years) and model those with a GEV.
Simple and robust, but it discards all but one observation per block —
r_largest_block_maxima recovers some of that lost information by keeping the
top \(r\) order statistics, and sliding_block_maxima trades independence for a
larger sample.
Extraction utilities for extreme values on xarray data.
Block maxima, threshold selection, and declustering — the three standard preprocessing steps for extreme value analysis on spatiotemporal data.
temporal_block_maxima(da: xr.DataArray, freq: str, time_dim: str = 'time', min_periods: int | None = None, keep_time: bool = False) -> xr.DataArray
¶
Extract temporal block maximum values from an xarray DataArray.
Uses time-based resampling to compute maximum values over temporal blocks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input data array |
required |
freq
|
str
|
Frequency string for temporal grouping (e.g., 'YS' for annual, 'MS' for monthly, '7D' for weekly, '3h' for 3-hourly) |
required |
time_dim
|
str
|
Name of the time dimension |
'time'
|
min_periods
|
int
|
Minimum number of observations required for a valid maximum. If None, all blocks are used regardless of missing data. |
None
|
keep_time
|
bool
|
If True, attach a |
False
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Temporal block maximum values. When |
Examples:
>>> # Monthly maxima with at least 20 observations per month
>>> monthly_max = temporal_block_maxima(da, 'MS', min_periods=20)
>>> # Annual maxima labelled with the day each maximum occurred
>>> am = temporal_block_maxima(da, 'YS', keep_time=True)
>>> am['time_of_max'] # actual timestamps, NaT for empty blocks
Source code in src/xtremax/extraction/block_maxima.py
spatial_block_maxima(da: xr.DataArray, block_size: int | dict[Hashable, int], dims: Hashable | Sequence[Hashable] = None, min_periods: int | None = None, boundary: str = 'trim', keep_coords: bool = False) -> xr.DataArray
¶
Extract spatial block maximum values from an xarray DataArray.
Uses coarsening to compute maximum values over spatial blocks of fixed size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input data array |
required |
block_size
|
int or dict
|
Size of spatial blocks. If int, uses same size for all specified dims. If dict, maps dimension names to block sizes (e.g., {'x': 10, 'y': 10}) |
required |
dims
|
Hashable or Sequence[Hashable]
|
Dimension(s) to coarsen. If None and block_size is int, raises error. If None and block_size is dict, uses dict keys. |
None
|
min_periods
|
int
|
Minimum number of valid observations required within each block. If None, computes maximum even with missing data. |
None
|
boundary
|
str
|
How to handle boundaries. Options: 'trim', 'pad', 'exact' |
'trim'
|
keep_coords
|
bool
|
If True, attach a |
False
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Spatial block maximum values with reduced resolution. When
|
Examples:
>>> # 5x5 blocks along lat/lon dimensions
>>> spatial_max = spatial_block_maxima(da, 5, dims=['lat', 'lon'])
>>> # Require at least 50 valid points per block
>>> spatial_max = spatial_block_maxima(
... da, {'x': 10, 'y': 10}, min_periods=50
... )
>>> # 5x5 blocks, keeping the (lat, lon) of each block's maximum
>>> sm = spatial_block_maxima(da, 5, dims=['lat', 'lon'], keep_coords=True)
>>> sm['lat_of_max'], sm['lon_of_max']
Source code in src/xtremax/extraction/block_maxima.py
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 | |
sliding_block_maxima(da: xr.DataArray, window_size: int, dim: str = 'time', stride: int = 1, min_periods: int | None = None, center: bool = False, keep_time: bool = False) -> xr.DataArray
¶
Extract block maxima using a sliding window approach.
Sliding windows provide overlapping blocks, which helps: - Avoid sensitivity to arbitrary block boundaries - Increase the number of block maxima for better statistical estimation - Capture extreme events that might span fixed block boundaries
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input data array |
required |
window_size
|
int
|
Size of the sliding window (number of observations) |
required |
dim
|
str
|
Dimension along which to slide the window |
'time'
|
stride
|
int
|
Step size between windows. stride=1 gives fully overlapping windows, stride=window_size gives non-overlapping blocks (equivalent to coarsen) |
1
|
min_periods
|
int
|
Minimum number of valid observations required for a valid maximum. If None, defaults to window_size. |
None
|
center
|
bool
|
If True, set the window labels at the center of the window |
False
|
keep_time
|
bool
|
If True, attach a |
False
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Sliding block maximum values. When |
Examples:
>>> # 365-day sliding window with daily stride
>>> sliding_max = sliding_block_maxima(da, window_size=365, stride=1)
>>> # Non-overlapping 30-day blocks (equivalent to fixed blocks)
>>> block_max = sliding_block_maxima(da, window_size=30, stride=30)
>>> # 90-day window with 7-day stride (weekly updates)
>>> weekly_max = sliding_block_maxima(da, window_size=90, stride=7)
>>> # Track the day each window maximum actually occurred
>>> sm = sliding_block_maxima(da, window_size=30, keep_time=True)
>>> sm['time_of_max']
Source code in src/xtremax/extraction/block_maxima.py
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 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 | |
r_largest_block_maxima(da: xr.DataArray, block_size: int | str, r: int = 3, dim: str = 'time', min_periods: int | None = None, keep_time: bool = False) -> xr.DataArray
¶
Extract r-largest order statistics from each block.
Instead of just the maximum, extract the r largest values from each block. This provides more information for extreme value analysis and can improve statistical efficiency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input data array |
required |
block_size
|
int or str
|
Size of blocks. If int, number of elements. If str, frequency string. |
required |
r
|
int
|
Number of largest values to extract from each block |
3
|
dim
|
str
|
Dimension along which to compute order statistics |
'time'
|
min_periods
|
int
|
Minimum number of observations required in a block |
None
|
keep_time
|
bool
|
If True, attach a |
False
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Array with r-largest values from each block, with new dimension 'order'.
For integer |
Examples:
>>> # Top 5 values from 100-element blocks
>>> block_r_largest = r_largest_block_maxima(da, 100, r=5)
>>> # ... and the day each of the 3 largest occurred
>>> rl = r_largest_block_maxima(da, 'YS', r=3, keep_time=True)
>>> rl['time_of_max']
Notes
The r-largest order statistics model is useful when you want to use more information than just the block maximum for fitting extreme value distributions.
Source code in src/xtremax/extraction/block_maxima.py
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 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 | |
declustered_block_maxima(da: xr.DataArray, threshold: float, min_separation: int, dim: str = 'time', method: str = 'runs', keep_time: bool = False) -> xr.DataArray
¶
Extract declustered block maxima by identifying independent extreme events.
Declustering removes temporal dependence in extremes by ensuring sufficient separation between events. This is crucial for extreme value theory which assumes independence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input data array |
required |
threshold
|
float
|
Threshold value for identifying extreme events |
required |
min_separation
|
int
|
Minimum separation (in time steps) between independent events |
required |
dim
|
str
|
Dimension along which to decluster |
'time'
|
method
|
str
|
Declustering method:
- 'runs': Select maximum from each exceedance run, merging runs
whose below-threshold gap is shorter than |
'runs'
|
keep_time
|
bool
|
If True, attach a |
False
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Declustered block maxima with reduced temporal dependence. |
Examples:
>>> # Extract independent storm maxima (3-day separation)
>>> storm_max = declustered_block_maxima(
... da, threshold=100, min_separation=3, method='runs'
... )
>>> # Heat wave maxima with 7-day separation
>>> heatwave_max = declustered_block_maxima(
... da, threshold=35, min_separation=7, method='separation'
... )
Notes
The runs method identifies continuous periods above threshold and takes the maximum from each run. The separation method ensures peaks are separated by at least min_separation time steps.
Source code in src/xtremax/extraction/block_maxima.py
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | |
Threshold selection¶
Peaks-over-threshold keeps every exceedance above \(u\), so the threshold choice is the bias–variance tradeoff: too low and the GPD asymptotics fail, too high and you run out of data. A constant threshold is only defensible for stationary data — under trends or seasonality, use the time-varying variants so the exceedance rate stays roughly constant.
Extraction utilities for extreme values on xarray data.
Block maxima, threshold selection, and declustering — the three standard preprocessing steps for extreme value analysis on spatiotemporal data.
constant_threshold(da: xr.DataArray, threshold: float) -> float
¶
Return a constant threshold value.
This is the simplest threshold selection method, using a fixed value across all times and locations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input data array (included for API consistency) |
required |
threshold
|
float
|
Constant threshold value |
required |
Returns:
| Type | Description |
|---|---|
float
|
The threshold value |
Examples:
Source code in src/xtremax/extraction/threshold.py
quantile_threshold(da: xr.DataArray, quantile: float, dim: Hashable | Sequence[Hashable] | None = None) -> float | xr.DataArray
¶
Calculate threshold based on a percentile of the data.
Common choices are 0.95 (95th percentile) or 0.99 (99th percentile). Higher quantiles result in fewer but more extreme exceedances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input data array |
required |
quantile
|
float
|
Quantile value between 0 and 1 (e.g., 0.95 for 95th percentile) |
required |
dim
|
Hashable or Sequence[Hashable]
|
Dimension(s) over which to compute quantile. If None, computes over all dimensions returning a scalar. |
None
|
Returns:
| Type | Description |
|---|---|
float or DataArray
|
Threshold value(s) |
Examples:
>>> # 99th percentile, computed separately for each location
>>> thresh = quantile_threshold(da, 0.99, dim='time')
Source code in src/xtremax/extraction/threshold.py
rolling_threshold(da: xr.DataArray, quantile: float, window_size: int = 15, time_dim: str = 'time', center: bool = True, min_periods: int | None = None) -> xr.DataArray
¶
Calculate time-varying threshold using a rolling window.
Uses a rolling window to compute a threshold that varies smoothly over time. Useful for removing short-term variations while preserving longer-term trends.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input data array with time dimension |
required |
quantile
|
float
|
Quantile value between 0 and 1 |
required |
window_size
|
int
|
Size of rolling window (in time steps) for computing the threshold |
15
|
time_dim
|
str
|
Name of the time dimension |
'time'
|
center
|
bool
|
If True, set window labels at center of window |
True
|
min_periods
|
int
|
Minimum number of observations required in window. If None, uses window_size. Windows with fewer valid observations (e.g. at the series edges) return NaN. |
None
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Time-varying threshold values with smooth temporal variation.
Positions whose window holds fewer than |
Examples:
>>> # Rolling 15-day 95th percentile threshold
>>> thresh = rolling_threshold(da, 0.95, window_size=15)
>>> # Rolling 30-day 99th percentile threshold
>>> thresh = rolling_threshold(da, 0.99, window_size=30)
>>> # Non-centered window (past values only)
>>> thresh = rolling_threshold(da, 0.95, window_size=30, center=False)
Notes
Rolling window approach provides smoother temporal variation than groupby methods. Good for removing high-frequency variations while keeping the seasonal cycle.
Source code in src/xtremax/extraction/threshold.py
seasonal_threshold(da: xr.DataArray, quantile: float = 0.95, time_dim: str = 'time') -> xr.DataArray
¶
Calculate seasonal threshold (backward compatibility wrapper).
This is a convenience wrapper around temporal_threshold with groupby='time.season'. For more control, use temporal_threshold directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input data array |
required |
quantile
|
float
|
Quantile value between 0 and 1 |
0.95
|
time_dim
|
str
|
Name of the time dimension |
'time'
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Seasonal threshold values |
Examples:
See Also
temporal_threshold : More flexible temporal grouping rolling_threshold : Smooth rolling window threshold
Source code in src/xtremax/extraction/threshold.py
temporal_threshold(da: xr.DataArray, quantile: float, groupby: str = 'time.season', time_dim: str = 'time', method: str = 'quantile') -> xr.DataArray
¶
Calculate time-varying threshold based on temporal grouping.
Computes threshold separately for each temporal group (season, month, year, week, dayofyear, etc.) using groupby operations. More flexible than rolling window approach.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input data array with time dimension |
required |
quantile
|
float
|
Quantile value between 0 and 1 (e.g., 0.95 for 95th percentile) |
required |
groupby
|
str
|
Grouping specification. Common options:
- 'time.season' : seasonal (DJF, MAM, JJA, SON)
- 'time.month' : monthly (1-12)
- 'time.year' : annual
- 'time.dayofyear' : day of year (1-365/366)
- 'time.hour' : hour of day
(For week-of-year grouping, precompute an isocalendar week
coordinate; the |
'time.season'
|
time_dim
|
str
|
Name of the time dimension |
'time'
|
method
|
str
|
Aggregation method: 'quantile', 'mean', 'median', 'max', 'min' |
'quantile'
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Time-varying threshold values, aligned with original time coordinate |
Examples:
>>> # Seasonal 95th percentile thresholds
>>> thresh = temporal_threshold(da, 0.95, groupby='time.season')
>>> # Monthly 99th percentile thresholds
>>> thresh = temporal_threshold(da, 0.99, groupby='time.month')
>>> # Day-of-year thresholds (smooth seasonal cycle)
>>> thresh = temporal_threshold(da, 0.95, groupby='time.dayofyear')
>>> # Day-of-year mean thresholds
>>> thresh = temporal_threshold(da, 0.9, groupby='time.dayofyear', method='mean')
Notes
The function groups data by the specified temporal accessor (e.g., month), computes the threshold for each group, then broadcasts back to the original time coordinate. This is useful for capturing regular temporal patterns in the tail distribution.
For day-of-year grouping, this gives a smooth seasonal cycle of thresholds. For month/season, this gives discrete jumps between periods.
Source code in src/xtremax/extraction/threshold.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 | |
Declustering & the extremal index¶
Raw exceedances arrive in clusters — one storm produces several consecutive threshold crossings — which violates the independence the GPD likelihood assumes. Declustering reduces each cluster to one peak; the extremal index \(\theta \in (0, 1]\) quantifies how much clustering there was (\(\theta = 1\) means none).
Extraction utilities for extreme values on xarray data.
Block maxima, threshold selection, and declustering — the three standard preprocessing steps for extreme value analysis on spatiotemporal data.
decluster_runs(da: xr.DataArray, threshold: float | xr.DataArray, dim: str = 'time', reduction: str = 'max', min_separation: int = 1) -> xr.DataArray
¶
Decluster exceedances using the runs method.
Identifies runs of exceedances and applies a reduction function to each run. This ensures temporal independence by treating each cluster as a single event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input data array |
required |
threshold
|
float or DataArray
|
Threshold value(s) |
required |
dim
|
str
|
Dimension along which to identify runs |
'time'
|
reduction
|
str
|
Reduction function to apply to each run: 'max', 'mean', 'sum', 'min' |
'max'
|
min_separation
|
int
|
Runs-declustering separation parameter r: two exceedances
belong to the same cluster when fewer than |
1
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Array with the same shape as |
Examples:
>>> # Maximum value from each exceedance cluster
>>> declustered = decluster_runs(da, threshold=100, reduction='max')
>>> # Merge exceedances separated by gaps of fewer than 3 steps
>>> declustered = decluster_runs(da, threshold=100, min_separation=3)
Notes
The runs method identifies periods where values exceed the
threshold, merging exceedances whose below-threshold gap is shorter
than min_separation into one cluster, and extracts one
representative value per cluster. The reduction is applied to the
cluster's exceedance values only — intra-cluster below-threshold
samples do not contribute.
Source code in src/xtremax/extraction/decluster.py
decluster_separation(da: xr.DataArray, threshold: float | xr.DataArray, min_separation: int, dim: str = 'time') -> xr.DataArray
¶
Decluster by enforcing minimum separation between peaks.
Identifies peaks above threshold and ensures they are separated by at least min_separation time steps. When peaks are too close, keeps the larger one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input data array |
required |
threshold
|
float or DataArray
|
Threshold value(s) |
required |
min_separation
|
int
|
Minimum separation (in time steps) between independent peaks |
required |
dim
|
str
|
Dimension along which to enforce separation |
'time'
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Declustered peak values |
Examples:
>>> # Peaks separated by at least 3 days
>>> declustered = decluster_separation(da, threshold=100, min_separation=3)
>>> # Storm events with 7-day minimum separation
>>> storms = decluster_separation(da, threshold=95, min_separation=7)
Notes
This method first identifies all local maxima above threshold, then iteratively removes peaks that are too close to larger peaks.
Plateaus (runs of equal consecutive values) count as a single peak
when the values adjacent to the entire run are strictly lower — the
peak is stamped at the run's first sample. Quantized observational
data (rounded gauges, integer records) hit this case routinely;
requiring strict inequality between adjacent samples used to drop
such events entirely, while a naive adjacent-sample tie-break would
also mark rising shelves (e.g. [0, 5, 5, 6]) as peaks.
Source code in src/xtremax/extraction/decluster.py
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 | |
estimate_extremal_index(da: xr.DataArray, threshold: float | xr.DataArray, dim: str = 'time', method: str = 'runs', min_separation: int = 1) -> float | xr.DataArray
¶
Estimate the extremal index (theta), a measure of clustering.
The extremal index θ ∈ [0, 1] measures the degree of clustering in extremes: - θ = 1: no clustering (independent extremes) - θ < 1: clustering present (dependent extremes) - θ = 0: complete clustering (perfect dependence)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input data array |
required |
threshold
|
float or DataArray
|
Threshold value for identifying extremes |
required |
dim
|
str
|
Dimension along which to estimate clustering |
'time'
|
method
|
str
|
Estimation method: 'runs' or 'intervals' |
'runs'
|
min_separation
|
int
|
Runs parameter r: exceedances separated by fewer than
|
1
|
Returns:
| Type | Description |
|---|---|
float or DataArray
|
Extremal index estimate (between 0 and 1). For 1-D input a scalar
|
Examples:
>>> # Estimate clustering strength
>>> theta = estimate_extremal_index(da, threshold=100)
>>> print(f"Extremal index: {theta:.3f}")
>>> # theta ≈ 0.7 suggests moderate clustering
>>> # Use high threshold (99th percentile)
>>> from xtremax.extraction.threshold import quantile_threshold
>>> thresh = quantile_threshold(da, 0.99)
>>> theta = estimate_extremal_index(da, thresh)
Notes
The runs estimator uses: θ = (number of clusters) / (number of exceedances)
A smaller θ indicates more clustering. Counting is performed
independently per non-dim slice so cluster labels from different
slices cannot collide.
Source code in src/xtremax/extraction/decluster.py
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 335 | |
Quantile-regression thresholds¶
A threshold that follows a covariate-driven trend, fitted by quantile regression rather than taken as a fixed quantile — the right tool when sea level rise or warming shifts the whole distribution under you.
These require scikit-learn and are only exported when the
xtremax[threshold] extra is installed:
Quantile regression utilities for extremes thresholding.
Provides two layers:
-
XarrayQuantileRegressor— a thin sklearn-compatible wrapper aroundsklearn.linear_model.QuantileRegressorthat accepts and returnsxr.DataArrayobjects, preserving coordinates through fit → predict. -
quantile_regression_threshold— domain-specific function that builds the feature matrix (numeric time, optional covariates) and delegates to the regressor, returning a time-varying threshold suitable for peak-over-threshold analysis.
Example¶
import xarray as xr, numpy as np, pandas as pd da = xr.DataArray( ... np.random.default_rng(0).standard_normal(200), ... dims="time", ... coords={"time": pd.date_range("2000", periods=200, freq="D")}, ... ) threshold = quantile_regression_threshold(da, quantile=0.95, time_dim="time")
XarrayQuantileRegressor(quantile: float = 0.5, alpha: float = 0.0, solver: str = 'highs', fit_intercept: bool = True)
¶
Bases: BaseEstimator, RegressorMixin
Quantile regressor that operates on :class:xr.DataArray inputs.
Thin wrapper around :class:sklearn.linear_model.QuantileRegressor.
Both fit and predict expect DataArray objects; coordinate
metadata on the leading dimension is preserved through the round-trip.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quantile
|
float
|
Target quantile ∈ (0, 1). |
0.5
|
alpha
|
float
|
L1 regularisation strength. |
0.0
|
solver
|
str
|
Solver forwarded to |
'highs'
|
fit_intercept
|
bool
|
Whether the sklearn estimator should fit its own intercept.
Set to |
True
|
Source code in src/xtremax/extraction/quantile_regression.py
coef_: np.ndarray
property
¶
Regression coefficients (delegates to the inner model).
intercept_: float
property
¶
Intercept (delegates to the inner model).
fit(X: xr.DataArray, y: xr.DataArray) -> XarrayQuantileRegressor
¶
Fit the quantile regression model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(DataArray, shape(n_samples) or (n_samples, n_features))
|
Feature matrix. |
required |
y
|
(DataArray, shape(n_samples))
|
Target values. |
required |
Returns:
| Type | Description |
|---|---|
self
|
|
Source code in src/xtremax/extraction/quantile_regression.py
predict(X: xr.DataArray) -> xr.DataArray
¶
Predict quantile values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
DataArray
|
Feature matrix (same schema as training X). |
required |
Returns:
| Type | Description |
|---|---|
DataArray
|
Predicted quantile values with the leading dimension's coordinates preserved from X. |
Source code in src/xtremax/extraction/quantile_regression.py
quantile_regression_threshold(da: xr.DataArray, quantile: float, time_dim: str, covariates: xr.DataArray | None = None, *, alpha: float = 0.0, solver: str = 'highs') -> xr.DataArray
¶
Estimate a time-varying threshold via linear quantile regression.
Fits the model
.. math::
Q_{\tau}(y \mid t, \mathbf{z}) = \beta_0
+ \beta_1 t + \boldsymbol{\beta}_z^\top \mathbf{z}
where t is numeric time and z are optional covariates, then returns the fitted quantile surface evaluated at the observed times. The result is suitable as a non-stationary threshold for peak-over-threshold (POT) extreme value analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Response variable (1-D along time_dim). |
required |
quantile
|
float
|
Target quantile τ ∈ (0, 1), e.g. 0.95 for the 95th percentile. |
required |
time_dim
|
str
|
Name of the time dimension in da. |
required |
covariates
|
DataArray
|
Additional covariates aligned along time_dim. |
None
|
alpha
|
float
|
L1 regularisation passed to the regressor (0 = unregularised). |
0.0
|
solver
|
str
|
LP solver, forwarded to |
'highs'
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Fitted threshold values with the same coords as da. |
Examples:
>>> # 95th-percentile linear-trend threshold
>>> threshold = quantile_regression_threshold(da, 0.95, "time")
>>> # With a covariate (e.g., sea-surface temperature)
>>> threshold = quantile_regression_threshold(
... da, 0.99, "time", covariates=sst
... )