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.
A block is a frequency ("YS") or a number of steps (365). The lower tail takes temporal_block_minima. 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, declustering and exceedance counts — the standard preprocessing steps for extreme value analysis on spatiotemporal data.
temporal_block_maxima(da: xr.DataArray, freq: str | int, 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, or coarsening when the block is given as a number of steps.
Parameters¶
da : xr.DataArray
Input data array
freq : str or int
The block. A frequency string groups by time (e.g., 'YS' for annual,
'MS' for monthly, '7D' for weekly, '3h' for 3-hourly); an integer is a
number of time steps per block, counted from the first step, with a
trailing partial block dropped, and each block is labelled by its
first time.
time_dim : str, default 'time'
Name of the time dimension
min_periods : int, optional
Minimum number of observations required for a valid maximum.
If None, all blocks are used regardless of missing data.
keep_time : bool, default False
If True, attach a f"{time_dim}_of_max" coordinate holding the
original timestamp at which each block maximum occurred (rather than
only the resampled block label). Empty or min_periods-masked blocks
get NaT. Useful for plotting the maxima at the moment they actually
happened instead of at the block boundary.
Returns¶
xr.DataArray
Temporal block maximum values. When keep_time=True the result also
carries a f"{time_dim}_of_max" coordinate with the argmax timestamps.
Examples¶
Annual maxima¶
annual_max = temporal_block_maxima(da, 'YS')
Monthly maxima with at least 20 observations per month¶
monthly_max = temporal_block_maxima(da, 'MS', min_periods=20)
Seasonal maxima (3-month blocks)¶
seasonal_max = temporal_block_maxima(da, '3MS')
Maxima of blocks of 365 steps¶
yearly_max = temporal_block_maxima(da, 365)
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 packages/pyrox-xtreme/src/pyrox_xtreme/extraction/block_maxima.py
temporal_block_minima(da: xr.DataArray, freq: str | int, time_dim: str = 'time', min_periods: int | None = None, keep_time: bool = False) -> xr.DataArray
¶
Extract temporal block minimum values from an xarray DataArray.
The twin of temporal_block_maxima: the minimum over each temporal block,
for the lower tail (cold extremes, droughts, or the maxima of -da).
Parameters¶
da : xr.DataArray
Input data array
freq : str or int
The block: a frequency string (e.g., 'YS', 'MS', '7D'), or a number of
time steps per block, counted from the first step, with a trailing
partial block dropped, each labelled by its first time.
time_dim : str, default 'time'
Name of the time dimension
min_periods : int, optional
Minimum number of observations required for a valid minimum.
If None, all blocks are used regardless of missing data.
keep_time : bool, default False
If True, attach a f"{time_dim}_of_min" coordinate holding the
original timestamp at which each block minimum occurred.
Returns¶
xr.DataArray Temporal block minimum values.
Examples¶
Annual minima¶
annual_min = temporal_block_minima(da, 'YS')
Minima of blocks of 365 steps¶
yearly_min = temporal_block_minima(da, 365)
Source code in packages/pyrox-xtreme/src/pyrox_xtreme/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¶
da : xr.DataArray
Input data array
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})
dims : Hashable or Sequence[Hashable], optional
Dimension(s) to coarsen. If None and block_size is int,
raises error. If None and block_size is dict, uses dict keys.
min_periods : int, optional
Minimum number of valid observations required within each block.
If None, computes maximum even with missing data.
boundary : str, default 'trim'
How to handle boundaries. Options: 'trim', 'pad', 'exact'
keep_coords : bool, default False
If True, attach a f"{dim}_of_max" coordinate for each coarsened
dim holding the original coordinate at which each block maximum
occurred (i.e. where in the block the extreme is), rather than only the
coarsened block label. Empty / masked blocks get NaN.
Returns¶
xr.DataArray
Spatial block maximum values with reduced resolution. When
keep_coords=True the result also carries a f"{dim}_of_max"
coordinate per coarsened dim with the argmax locations.
Examples¶
10x10 spatial blocks¶
spatial_max = spatial_block_maxima(da, {'x': 10, 'y': 10})
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 packages/pyrox-xtreme/src/pyrox_xtreme/extraction/block_maxima.py
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 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 | |
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¶
da : xr.DataArray
Input data array
window_size : int
Size of the sliding window (number of observations)
dim : str, default 'time'
Dimension along which to slide the window
stride : int, default 1
Step size between windows. stride=1 gives fully overlapping windows,
stride=window_size gives non-overlapping blocks (equivalent to coarsen)
min_periods : int, optional
Minimum number of valid observations required for a valid maximum.
If None, defaults to window_size.
center : bool, default False
If True, set the window labels at the center of the window
keep_time : bool, default False
If True, attach a f"{dim}_of_max" coordinate holding the original
coordinate at which each window's maximum occurred (which can differ
from the window's own label). Windows whose maximum is masked — no valid
data, or fewer than min_periods observations — get NaN/NaT.
Returns¶
xr.DataArray
Sliding block maximum values. When keep_time=True the result also
carries a f"{dim}_of_max" coordinate with the argmax coordinates.
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 packages/pyrox-xtreme/src/pyrox_xtreme/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 463 464 465 466 467 468 | |
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¶
da : xr.DataArray
Input data array
block_size : int or str
Size of blocks. If int, number of elements. If str, frequency string.
r : int, default 3
Number of largest values to extract from each block
dim : str, default 'time'
Dimension along which to compute order statistics
min_periods : int, optional
Minimum number of observations required in a block
keep_time : bool, default False
If True, attach a f"{dim}_of_max" coordinate (with the same
order axis) holding the original coordinate at which each of the
r largest values occurred. Missing slots get NaN/NaT.
Returns¶
xr.DataArray
Array with r-largest values from each block, with new dimension 'order'.
For integer block_size, a trailing partial block (fewer than
block_size samples) is trimmed and does not contribute values.
When keep_time=True it also carries a f"{dim}_of_max" coordinate
over (..., order) with the timestamps of those r values.
Examples¶
3 largest values from each year¶
annual_r_largest = r_largest_block_maxima(da, 'YS', r=3)
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 packages/pyrox-xtreme/src/pyrox_xtreme/extraction/block_maxima.py
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 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 | |
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¶
da : xr.DataArray
Input data array
threshold : float
Threshold value for identifying extreme events
min_separation : int
Minimum separation (in time steps) between independent events
dim : str, default 'time'
Dimension along which to decluster
method : str, default 'runs'
Declustering method:
- 'runs': Select maximum from each exceedance run, merging runs
whose below-threshold gap is shorter than min_separation
- 'separation': Enforce minimum time separation between peaks
keep_time : bool, default False
If True, attach a f"{dim}_of_max" coordinate holding the original
timestamp at which each cluster's maximum occurred. The 'runs'
method otherwise labels the representative at the end of its run, so
this recovers the true peak time; for 'separation' the peaks already
sit at their original positions.
Returns¶
xr.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 packages/pyrox-xtreme/src/pyrox_xtreme/extraction/block_maxima.py
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 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 | |
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, declustering and exceedance counts — the 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¶
da : xr.DataArray Input data array (included for API consistency) threshold : float Constant threshold value
Returns¶
float The threshold value
Examples¶
Use a constant threshold of 100¶
thresh = constant_threshold(da, 100)
Source code in packages/pyrox-xtreme/src/pyrox_xtreme/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¶
da : xr.DataArray Input data array quantile : float Quantile value between 0 and 1 (e.g., 0.95 for 95th percentile) dim : Hashable or Sequence[Hashable], optional Dimension(s) over which to compute quantile. If None, computes over all dimensions returning a scalar.
Returns¶
float or xr.DataArray Threshold value(s)
Examples¶
95th percentile threshold¶
thresh = quantile_threshold(da, 0.95)
99th percentile, computed separately for each location¶
thresh = quantile_threshold(da, 0.99, dim='time')
Source code in packages/pyrox-xtreme/src/pyrox_xtreme/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¶
da : xr.DataArray Input data array with time dimension quantile : float Quantile value between 0 and 1 window_size : int, default 15 Size of rolling window (in time steps) for computing the threshold time_dim : str, default 'time' Name of the time dimension center : bool, default True If True, set window labels at center of window min_periods : int, optional 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.
Returns¶
xr.DataArray
Time-varying threshold values with smooth temporal variation.
Positions whose window holds fewer than min_periods valid
observations are NaN.
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 packages/pyrox-xtreme/src/pyrox_xtreme/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¶
da : xr.DataArray Input data array quantile : float, default 0.95 Quantile value between 0 and 1 time_dim : str, default 'time' Name of the time dimension
Returns¶
xr.DataArray Seasonal threshold values
Examples¶
95th percentile by season¶
thresh = seasonal_threshold(da, 0.95)
See Also¶
temporal_threshold : More flexible temporal grouping rolling_threshold : Smooth rolling window threshold
Source code in packages/pyrox-xtreme/src/pyrox_xtreme/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¶
da : xr.DataArray
Input data array with time dimension
quantile : float
Quantile value between 0 and 1 (e.g., 0.95 for 95th percentile)
groupby : str, default 'time.season'
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.week' accessor is deprecated.)
time_dim : str, default 'time'
Name of the time dimension
method : str, default 'quantile'
Aggregation method: 'quantile', 'mean', 'median', 'max', 'min'
Returns¶
xr.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')
Annual maximum¶
thresh = temporal_threshold(da, 0.95, groupby='time.year', method='max')
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 packages/pyrox-xtreme/src/pyrox_xtreme/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, declustering and exceedance counts — the 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¶
da : xr.DataArray
Input data array
threshold : float or xr.DataArray
Threshold value(s)
dim : str, default 'time'
Dimension along which to identify runs
reduction : str, default 'max'
Reduction function to apply to each run: 'max', 'mean', 'sum', 'min'
min_separation : int, default 1
Runs-declustering separation parameter r: two exceedances
belong to the same cluster when fewer than min_separation
consecutive below-threshold steps separate them. The default 1
reproduces classical contiguous runs (any single dip below the
threshold ends the run).
Returns¶
xr.DataArray
Array with the same shape as da. Run representatives are placed
at the last exceedance position of each run along dim and all
other positions are NaN. For multi-dimensional inputs, each
non-dim slice is declustered independently (so run IDs never
collide across slices).
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 packages/pyrox-xtreme/src/pyrox_xtreme/extraction/decluster.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 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 | |
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¶
da : xr.DataArray Input data array threshold : float or xr.DataArray Threshold value(s) min_separation : int Minimum separation (in time steps) between independent peaks dim : str, default 'time' Dimension along which to enforce separation
Returns¶
xr.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 packages/pyrox-xtreme/src/pyrox_xtreme/extraction/decluster.py
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 | |
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¶
da : xr.DataArray
Input data array
threshold : float or xr.DataArray
Threshold value for identifying extremes
dim : str, default 'time'
Dimension along which to estimate clustering
method : str, default 'runs'
Estimation method: 'runs' or 'intervals'
min_separation : int, default 1
Runs parameter r: exceedances separated by fewer than
min_separation consecutive below-threshold steps count as
the same cluster. The default 1 reproduces the classical
contiguous-runs estimator.
Returns¶
float or xr.DataArray
Extremal index estimate (between 0 and 1). For 1-D input a scalar
float. For inputs with additional dimensions, a DataArray of
per-slice estimates (one θ per batch row, e.g. per site).
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 pyrox_xtreme.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 packages/pyrox-xtreme/src/pyrox_xtreme/extraction/decluster.py
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 336 337 338 339 340 341 342 343 344 345 346 347 348 349 | |
Exceedances per block¶
The point-process view of peaks over threshold counts the exceedances of a threshold \(u\) in each block instead of keeping them: for independent exceedances the count of a block is Poisson with a mean proportional to its length. exceedance_counts gives the counts, exceedance_rate the fraction of observed values above \(u\) (the rate per time step), and exceedance_statistic summarises the exceedances of each block, for instance their mean or maximum. The threshold comes from the selectors above, and a block is a frequency or a number of steps, as for block maxima.
Extraction utilities for extreme values on xarray data.
Block maxima, threshold selection, declustering and exceedance counts — the standard preprocessing steps for extreme value analysis on spatiotemporal data.
exceedance_counts(da: xr.DataArray, threshold: float | xr.DataArray, block: str | int, time_dim: str = 'time') -> xr.DataArray
¶
Count the values above a threshold within each temporal block.
Parameters¶
da : xr.DataArray
Input data array. Missing values are not exceedances.
threshold : float or xr.DataArray
The threshold u; an array over the dimensions other than
time_dim (from quantile_threshold) gives each point its own.
block : str or int
A frequency string (e.g., 'YS', '7D'), or a number of time steps per
block as in temporal_block_maxima.
time_dim : str, default 'time'
Name of the time dimension.
Returns¶
xr.DataArray
The integer number of values > threshold in each block.
Examples¶
Exceedances of the 98th percentile in blocks of 5 steps¶
u = quantile_threshold(da, 0.98, dim='time') counts = exceedance_counts(da, u, 5)
Source code in packages/pyrox-xtreme/src/pyrox_xtreme/extraction/exceedances.py
exceedance_rate(da: xr.DataArray, threshold: float | xr.DataArray, block: str | int, time_dim: str = 'time') -> xr.DataArray
¶
The fraction of observed values above a threshold within each temporal block.
The empirical exceedance probability count / n per block, where n
is the number of non-missing values, which is the rate of a point process
per time step. Blocks without observations are NaN.
Parameters¶
da : xr.DataArray
Input data array.
threshold : float or xr.DataArray
The threshold, as in exceedance_counts.
block : str or int
A frequency string, or a number of time steps per block.
time_dim : str, default 'time'
Name of the time dimension.
Returns¶
xr.DataArray The rate, per time step, in each block.
Examples¶
u = quantile_threshold(da, 0.98, dim='time') rate = exceedance_rate(da, u, 'YS') # about 0.02 per day
Source code in packages/pyrox-xtreme/src/pyrox_xtreme/extraction/exceedances.py
exceedance_statistic(da: xr.DataArray, threshold: float | xr.DataArray, block: str | int, statistic: Callable[[np.ndarray], float] = np.mean, time_dim: str = 'time') -> xr.DataArray
¶
Summarise the values above a threshold within each temporal block.
Parameters¶
da : xr.DataArray
Input data array.
threshold : float or xr.DataArray
The threshold, as in exceedance_counts.
block : str or int
A frequency string, or a number of time steps per block.
statistic : callable, default numpy.mean
Reduces a 1-D array of the exceedances of one block (the values, not
the excesses over the threshold) to a float.
time_dim : str, default 'time'
Name of the time dimension.
Returns¶
xr.DataArray The statistic per block; NaN where a block has no exceedance.
Examples¶
u = quantile_threshold(da, 0.98, dim='time') mean_peak = exceedance_statistic(da, u, 5) worst = exceedance_statistic(da, u, 'YS', statistic=np.max)
Source code in packages/pyrox-xtreme/src/pyrox_xtreme/extraction/exceedances.py
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
pyrox-xtreme[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¶
quantile : float
Target quantile ∈ (0, 1).
alpha : float
L1 regularisation strength. 0 gives the classical
unregularised linear quantile regression (matching the default
behaviour of statsmodels.QuantReg).
solver : str
Solver forwarded to QuantileRegressor.
"highs" (the default) is robust for most problem sizes.
fit_intercept : bool
Whether the sklearn estimator should fit its own intercept.
Set to False if you supply a constant column yourself.
Source code in packages/pyrox-xtreme/src/pyrox_xtreme/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¶
X : xr.DataArray, shape (n_samples,) or (n_samples, n_features) Feature matrix. y : xr.DataArray, shape (n_samples,) Target values.
Returns¶
self
Source code in packages/pyrox-xtreme/src/pyrox_xtreme/extraction/quantile_regression.py
predict(X: xr.DataArray) -> xr.DataArray
¶
Predict quantile values.
Parameters¶
X : xr.DataArray Feature matrix (same schema as training X).
Returns¶
xr.DataArray Predicted quantile values with the leading dimension's coordinates preserved from X.
Source code in packages/pyrox-xtreme/src/pyrox_xtreme/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¶
da : xr.DataArray
Response variable (1-D along time_dim).
quantile : float
Target quantile τ ∈ (0, 1), e.g. 0.95 for the 95th percentile.
time_dim : str
Name of the time dimension in da.
covariates : xr.DataArray, optional
Additional covariates aligned along time_dim.
alpha : float
L1 regularisation passed to the regressor (0 = unregularised).
solver : str
LP solver, forwarded to QuantileRegressor.
Returns¶
xr.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 ... )