---
title: "Case study: extreme daily rainfall in São Paulo"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Case study: extreme daily rainfall in São Paulo}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

<!-- This file is precomputed: edit case-study.Rmd.orig and run
     vignettes/precompute.R; do not edit case-study.Rmd by hand. -->



This vignette is a complete analysis of real data with **margEVT**: the
daily rainfall at the São Paulo – Mirante de Santana weather station, with
the El Niño–Southern Oscillation (ENSO) and the weather of the previous day
as covariates. It covers every step of the package, from declustering to
walk-forward validation, and asks three practical questions:

1. How high can daily rainfall get in São Paulo, for return periods of 10
   to 100 years?
2. How much does ENSO change that answer?
3. How rare were the largest days in the record, such as 10 February 2020?

The introductory vignette (`vignette("margEVT")`) explains the model with
simulated data; here the emphasis is on the decisions a real analysis
requires.


``` r
library(margEVT)
```

## Data

`sp_mirante` contains daily summaries from the automatic station A701 of
the Brazilian National Institute of Meteorology (INMET), from July 2006 to
December 2025, with the monthly Multivariate ENSO Index (MEI.v2) of NOAA.
It was built with the **rmet** package, which downloads, quality-controls
and summarizes INMET data (`?sp_mirante` documents every step).


``` r
data(sp_mirante)
str(sp_mirante)
#> 'data.frame':	7100 obs. of  9 variables:
#>  $ date                     : Date, format: "2006-07-25" "2006-07-26" ...
#>  $ year                     : int  2006 2006 2006 2006 2006 2006 2006 2006 2006 2006 ...
#>  $ precip_mm                : num  NA 0.4 0 0 9 7.8 8.2 0.4 0.2 0 ...
#>  $ temp_max_c               : num  NA 27.5 28.2 29.4 24 12.9 15.9 15.2 15.4 19.8 ...
#>  $ temp_mean_c              : num  NA 21.2 21.4 23.2 16.7 ...
#>  $ humid_rel_mean_pct       : num  NA 63.1 63.1 68.5 NA ...
#>  $ pressure_station_mean_hpa: num  NA 925 925 924 925 ...
#>  $ wind_gust_max_ms         : num  NA 10.1 8.4 9.1 11.5 7.1 6.3 5.5 5.4 5.9 ...
#>  $ MEI                      : num  0.22 0.22 0.22 0.22 0.22 0.22 0.22 0.59 0.59 0.59 ...
colSums(is.na(sp_mirante))
#>                      date                      year                 precip_mm 
#>                         0                         0                        68 
#>                temp_max_c               temp_mean_c        humid_rel_mean_pct 
#>                        56                        56                        62 
#> pressure_station_mean_hpa          wind_gust_max_ms                       MEI 
#>                        48                        48                         0
```

Missing values are few (68 days of
precipitation, under 1% of the record). Every function that works with whole
years of covariates (approaches B and C, the risk over a horizon and the
walk-forward validation) needs a complete daily calendar, so we keep every
day and:

* treat the missing precipitation days as days without an exceedance (a
  conservative choice that can only miss events, never create them);
* fill the short gaps of the covariates by linear interpolation.

The covariates are the MEI and three variables of the *previous* day, so
that every covariate is known before the day being modelled: the mean
relative humidity, the change in station pressure over the day, and the
maximum temperature. They are standardized, so that a coefficient is the
effect of one standard deviation. A linear time trend, in decades and equal
to zero at the end of the record, lets the data decide whether the extremes
changed over the period. We start in 2007, the first complete year.


``` r
fill <- function(x) approx(seq_along(x), x, seq_along(x), rule = 2)$y
std  <- function(x) (x - mean(x)) / sd(x)
lag1 <- function(x) c(NA, head(x, -1))

d <- sp_mirante
d$prec_raw <- ifelse(is.na(d$precip_mm), 0, d$precip_mm)
RH <- fill(d$humid_rel_mean_pct)
P  <- fill(d$pressure_station_mean_hpa)
TX <- fill(d$temp_max_c)
d$RH_lag1   <- lag1(RH)
d$dP_lag1   <- lag1(c(NA, diff(P)))
d$Tmax_lag1 <- lag1(TX)
d <- d[d$year >= 2007, ]
for (v in c("RH_lag1", "dP_lag1", "Tmax_lag1")) d[[v]] <- std(d[[v]])
d$trend <- as.numeric(d$date - as.Date("2025-12-31")) / 3652.5
d <- cbind(d, seasonal_harmonics(as.integer(format(d$date, "%j"))))
range(table(d$year))
#> [1] 365 366
```

`seasonal_harmonics()` builds the annual cycle (`cos1`, `sen1`, `cos2`,
`sen2`) from the day of the year, with the same convention that the
package uses when it rebuilds whole years of covariates later.

## Threshold and clustering


``` r
u <- 35
plot(d$date, d$prec_raw, type = "h", col = "grey40",
     xlab = "", ylab = "Daily rainfall (mm)")
abline(h = u, col = "firebrick", lty = 2)
```

<div class="figure">
<img src="case-study-series-1.png" alt="plot of chunk series" width="100%" />
<p class="caption">plot of chunk series</p>
</div>

We use $u = 35$ mm, close to the 97% quantile of the daily totals, which
leaves 210 exceedances in 19
years. In a full study the threshold would be checked with mean residual
life and parameter stability plots (packages **extRemes** or **mev**) and the
results compared over a range of thresholds.

Heavy rain often lasts more than one day, so exceedances come in clusters,
which the Poisson process does not allow for. The extremal index $\theta$,
the reciprocal of the mean cluster size, measures this:


``` r
extremal_index(d$prec_raw, u)
#>       theta  n_clusters  run_length 
#>   0.5745261 118.0000000  11.0000000
d$prec <- decluster(d$prec_raw, u)
c(exceedances = sum(d$prec_raw > u), clusters = sum(d$prec > u))
#> exceedances    clusters 
#>         210         118
```

`decluster()` keeps the largest value of each cluster and sets the others
to the threshold. We fit the model to `prec` and keep `prec_raw` for the
validation.

## A stationary model first

A model with only the seasonal cycle is the natural reference:


``` r
fit0 <- fit_nhpp(prec ~ cos1 + sen1 + cos2 + sen2, data = d, threshold = u,
                 penalty = "none", verbose = FALSE)
fit0
#> -- nhpp_fit --------------------------------------
#>   Threshold    : 35
#>   Penalty      : none
#>   Lambda       : 0
#>   Alpha        : 0.5
#>   Converged    : TRUE
#>   nllh (raw)   : 356.7629
#>   nllh (pen)   : 356.7629
#>   obs/year     : 365.25
#>   Active params: 7 of 7
#>   Coefficients (non-zero):
#>    mu.(Intercept)           mu.cos1           mu.sen1           mu.cos2 
#>          68.61816          19.20650           8.23738           0.52687 
#>           mu.sen2 sigma.(Intercept)    xi.(Intercept) 
#>           1.85476           2.88006          -0.15374
```

## The covariate model

The formula interface works like `glm()`: the first formula is for the
location, `scale` and `shape` take one-sided formulas, and `free` lists
covariates that are never penalized (here, the annual cycle). Every
weather covariate is a candidate in the location and in the scale, and the
trend in the location (a trend in the scale is hard to identify with 19
years and would compete with the covariates for the same variation). The
adaptive LASSO selects them, with the penalty chosen by BIC, and
`refit = TRUE` refits the selected model without penalty, so that the
coefficients are free of the LASSO shrinkage.


``` r
fit <- fit_nhpp(
  prec ~ cos1 + sen1 + cos2 + sen2 + MEI + RH_lag1 + dP_lag1 + Tmax_lag1 + trend,
  data = d, threshold = u,
  scale = ~ MEI + RH_lag1 + dP_lag1 + Tmax_lag1,
  free  = ~ cos1 + sen1 + cos2 + sen2,
  penalty = "lasso", lambda = "bic", penalty_weights = "adaptive",
  refit = TRUE, verbose = FALSE)
summary(fit)
#> -- nhpp_fit summary --------------------------------------
#>   Threshold      : 35
#>   Penalty        : lasso
#>   Lambda         : mu=0.078639, sigma=0.078639, xi=0.078639
#>   Weights        : adaptive: mle
#>   Alpha          : 1
#>   Penalize shape : TRUE
#>   obs/year       : 365.25
#>   Converged      : TRUE
#>   KKT violation  : 7.88e-07 (per exceedance)
#>   nllh (raw)     : 337.5997
#>   nllh (pen)     : 338.0620
#>   Exceedances    : 118 | BIC: 737.218
#> 
#>   Active coefficients (13 of 16):
#>                   Estimate
#> mu.(Intercept)    70.73806
#> mu.cos1           12.18823
#> mu.sen1            6.25638
#> mu.cos2            2.80776
#> mu.sen2            3.41338
#> mu.MEI             9.06927
#> mu.RH_lag1         5.60279
#> mu.Tmax_lag1      10.27378
#> sigma.(Intercept)  2.86162
#> sigma.MEI          0.16256
#> sigma.RH_lag1     -0.19850
#> sigma.dP_lag1      0.27256
#> xi.(Intercept)    -0.29068
#> 
#>   Shrunk to zero : mu.dP_lag1, mu.trend, sigma.Tmax_lag1
active_covariates(fit)
#> [1] "MEI"       "RH_lag1"   "Tmax_lag1" "dP_lag1"
```


``` r
plot(fit, type = "path")
```

<div class="figure">
<img src="case-study-path-1.png" alt="plot of chunk path" width="100%" />
<p class="caption">plot of chunk path</p>
</div>

The path shows the coefficients as the penalty decreases, and the BIC curve
marks the selected penalty. The solution is certified by the
Karush-Kuhn-Tucker conditions of the penalized problem (`fit$kkt`).

The covariate model improves on the stationary one, with a BIC lower by
9.7:


``` r
c(stationary = BIC(fit0), covariates = BIC(fit))
#> stationary covariates 
#>   746.9205   737.2184
```

### How stable is the selection?

With 19 years and about 120 cluster maxima, the selected set can depend on
the specification. `update()` refits the same call with one change: here,
the trend is also allowed in the scale.


``` r
fit_alt <- update(fit, scale = ~ MEI + RH_lag1 + dP_lag1 + Tmax_lag1 + trend)
active_covariates(fit_alt)
#> [1] "RH_lag1" "dP_lag1"
c(main = BIC(fit), trend_in_scale = BIC(fit_alt))
#>           main trend_in_scale 
#>       737.2184       733.3226
```

The alternative specification selects a smaller model and reaches a
similar, even slightly lower, BIC. The two models describe the data about
equally well, so the ENSO effect in the main model is plausible but not
firmly established by this record: the analysis below uses the main model
to illustrate the package, and its ENSO results should be read as
illustrative. A longer record, or repeated-sample inclusion frequencies,
would be needed to settle the question.

Wald intervals, conditional on the selected model:


``` r
round(confint(fit), 3)
#>                    2.5 % 97.5 %
#> mu.(Intercept)    64.019 77.457
#> mu.cos1            3.408 20.968
#> mu.sen1           -0.475 12.988
#> mu.cos2           -3.771  9.386
#> mu.sen2           -3.500 10.327
#> mu.MEI             2.233 15.906
#> mu.RH_lag1        -2.130 13.336
#> mu.Tmax_lag1       2.571 17.976
#> sigma.(Intercept)  2.707  3.016
#> sigma.MEI          0.012  0.314
#> sigma.RH_lag1     -0.364 -0.033
#> sigma.dP_lag1      0.129  0.416
#> xi.(Intercept)    -0.440 -0.141
```

## Diagnostics

By the time-rescaling theorem, the interarrival residuals are standard
exponential under a correct model, and the magnitude residuals check the
fitted tail. The bands are exact pointwise 95% bands.


``` r
op <- par(mfrow = c(1, 2), cex.main = 0.8)
plot(fit, type = "qq", residuals = "interarrival")
plot(fit, type = "qq", residuals = "magnitude")
```

<div class="figure">
<img src="case-study-qq-1.png" alt="plot of chunk qq" width="100%" />
<p class="caption">plot of chunk qq</p>
</div>

``` r
par(op)
```

The magnitude residuals follow the line, so the fitted tail describes the
sizes of the cluster maxima well. The interarrival residuals bend below the
line at the upper end: long waits between events are rarer than the model
predicts, a sign that some clustering is left after declustering (rainy
spells longer than the runs found by `decluster()`). This kind of
misspecification is not included in the bootstrap intervals below, and a
study focused on return levels would check it against other declustering
rules.


``` r
plot(fit, type = "fitted")
```

<div class="figure">
<img src="case-study-intensity-1.png" alt="plot of chunk intensity" width="100%" />
<p class="caption">plot of chunk intensity</p>
</div>

The fitted location follows the annual cycle, with the wet summer peak,
and moves from day to day with the covariates; the scale varies mostly
with the weather of the previous day.

## Conditional levels: what ENSO does

Approach A fixes the covariates for a whole year. Holding the weather of
the previous day at its average and varying only the MEI gives the levels
of a typical La Niña, neutral and El Niño year:


``` r
base <- list(RH_lag1 = 0, dP_lag1 = 0, Tmax_lag1 = 0, trend = 0)
enso <- list(LaNina  = modifyList(base, list(MEI = -1.5)),
             Neutral = modifyList(base, list(MEI = 0)),
             ElNino  = modifyList(base, list(MEI = 1.5)))
rl_A <- marginalize(fit, d, TRs = c(2, 10, 50, 100), approaches = "A",
                    scenarios = enso)
rl_table(rl_A)
#>   approach scenario      T2      T10      T50     T100
#> 1        A   LaNina 65.0433  85.3264  97.6137 101.5706
#> 2        A  Neutral 79.2549 103.9473 118.5305 123.3564
#> 3        A   ElNino 93.9914 124.5544 141.9390 147.6844
```

These are *conditional* levels: each answers "how high, if the whole year
had this ENSO state and average weather". They are useful to compare
states, but none of them is the return level of an actual year, in which
ENSO and the daily weather vary.

## Marginal levels: integrating the covariates out

The marginal return level averages the annual non-exceedance probability
over the years the covariates can produce. Approach B draws those years
from a vector autoregressive (VAR) generator fitted to the covariates;
approach C resamples the observed years.


``` r
gen <- fit_var_generator(fit, d, lag_max = 7)
gen
#> VAR(3) covariate generator
#>   Covariates      : MEI, RH_lag1, Tmax_lag1, dP_lag1
#>   Seasonal model  : 2 harmonics, period 365.25
#>   Spectral radius : 0.9982 (stable)
sims <- simulate_covariates(gen, n_mc = 1000, seed = 1)
```

The generator removes the seasonal cycle of each covariate, selects the VAR
order by the Schwarz criterion and checks stability (spectral radius below
one).


``` r
rl <- marginalize(fit, d, TRs = c(2, 5, 10, 25, 50, 100),
                  approaches = c("A", "B", "C"),
                  scenarios = enso["Neutral"], mc_sample = sims,
                  n_boot = 1000, seed = 1)
rl_table(rl)
#>   approach            scenario      T2      T5      T10      T25      T50
#> 1        A             Neutral 79.2549 95.4403 103.9473 112.8967 118.5305
#> 2        B       parametric_mc 81.1172 99.4088 110.1608 122.6592 131.3873
#> 3        C empirical_bootstrap 80.6106 99.1681 110.2060 123.1591 132.2366
#>       T100
#> 1 123.3564
#> 2 139.7486
#> 3 140.8787
plot(rl)
```

<div class="figure">
<img src="case-study-marginal-1.png" alt="plot of chunk marginal" width="100%" />
<p class="caption">plot of chunk marginal</p>
</div>

B and C, two different laws for the covariates, give close marginal levels.
The conditional level at the neutral state is lower, and the gap grows with
the return period: because the covariates also act on the scale, the
years with an unusual ENSO state or unusual weather contribute more to the
upper tail than the average year suggests. This gap does not shrink with
more data; it comes from the definition of the level, not from estimation
error.

### How rare were the largest days?

`annual_prob()` gives the probability, in each year of covariates, that the
annual maximum stays below a level. Averaging over the observed years gives
the marginal exceedance probability of the record's largest days:


``` r
years <- unique(d$year)
blocks <- lapply(years, function(y) head(d[d$year == y, ], 365))
obs_max <- tapply(d$prec_raw, d$year, max)
top <- sort(obs_max, decreasing = TRUE)[1:3]
p_exc <- sapply(top, function(z) 1 - mean(annual_prob(fit, z, blocks)))
data.frame(year = names(top), max_mm = as.numeric(top),
           return_period = round(1 / p_exc))
#>      year max_mm return_period
#> 2020 2020  140.8           101
#> 2025 2025  125.6            30
#> 2019 2019  105.0             7
```

The day of 10 February 2020 has an estimated return period of about a
century. That is unusual for a record of 19 years, but not
implausible: the probability that at least one year in 19
exceeds a level with that return period is
17%.

### Scenarios for the covariate law

Approach B accepts several ensembles at once. As an illustration (not a
projection), we shift the simulated MEI by half a unit, a world in which
El Niño-like conditions are more frequent:


``` r
stopifnot("MEI" %in% names(sims[[1]]))
shifted <- lapply(sims, function(b) { b$MEI <- b$MEI + 0.5; b })
rl_scen <- marginalize(fit, d, TRs = c(10, 50, 100), approaches = "B",
                       mc_sample = list(historical = sims, shifted = shifted))
rl_table(rl_scen)
#>   approach   scenario      T10      T50     T100
#> 1        B historical 110.1608 131.3873 139.7486
#> 2        B    shifted 116.3377 139.0063 147.9681
```

## Risk over a planning horizon

A drainage structure is designed for decades, not for one year.
`horizon_risk()` gives the probability that a level is exceeded at least
once over the horizon, using whole trajectories of years, here 30 years
resampled from the record, 300 times:


``` r
set.seed(1)
traj <- replicate(300, blocks[sample(length(blocks), 30, replace = TRUE)],
                  simplify = FALSE)
hr <- horizon_risk(fit, z = c(100, 120, 140, 160), trajectories = traj)
hr
#> Exceedance risk over a horizon of 30 years (300 trajectories)
#>    z prob_exceed     se_mc expected_years   wait
#>  100     0.99833 7.102e-05         5.7738  5.205
#>  120     0.79009 3.274e-03         1.5242 15.570
#>  140     0.27575 3.363e-03         0.3212 25.776
#>  160     0.05563 9.886e-04         0.0572 29.184
plot(hr)
```

<div class="figure">
<img src="case-study-horizon-1.png" alt="plot of chunk horizon" width="100%" />
<p class="caption">plot of chunk horizon</p>
</div>

`design_life_level()` inverts the question: the level exceeded with a
given probability during the 30 years (Rootzén and Katz, 2013).


``` r
design_life_level(fit, traj, prob = c(0.5, 0.1))
#>   prob horizon      DLL     se_mc
#> 1  0.5      30 130.5462 0.1550702
#> 2  0.1      30 153.1445 0.1953937
```

## Uncertainty

`bootstrap_nhpp()` refits the selected model on parametric bootstrap
samples and returns percentile intervals for the marginal levels and for
every coefficient. Each replicate has its own random-number stream, so the
results do not depend on the number of cores.


``` r
b <- bootstrap_nhpp(fit, d, TRs = c(10, 50, 100), R = 200, approach = "C",
                    marginalize_args = list(n_boot = 500, seed = 1),
                    cores = max(1L, parallel::detectCores() - 1L),
                    verbose = FALSE)
b
#> Conditional parametric bootstrap | R = 200 | 95% percentile intervals | occurrence: fixed
#> 
#> Return levels (approach C):
#>   TR RL_est  CI_low CI_high n_ok
#>   10 109.46  94.911  121.02  200
#>   50 131.18 106.419  148.02  200
#>  100 139.73 110.752  157.97  200
#> 
#> Coefficients:
#>          parameter estimate   CI_low  CI_high p_zero n_ok
#>     mu.(Intercept) 70.73806 60.13975 76.85486  0.000  200
#>            mu.cos1 12.18823  7.84744 19.75455  0.000  200
#>            mu.sen1  6.25638  1.17179 10.66644  0.000  200
#>            mu.cos2  2.80776 -2.87101  7.19898  0.000  200
#>            mu.sen2  3.41338 -2.09556  6.15399  0.000  200
#>             mu.MEI  9.06927  3.35168 16.14833  0.005  200
#>         mu.RH_lag1  5.60279 -1.75519 13.96009  0.020  200
#>         mu.dP_lag1  0.00000 -5.73391  5.66466  0.195  200
#>       mu.Tmax_lag1 10.27378  0.77777 15.46465  0.000  200
#>           mu.trend  0.00000 -6.68035  1.08169  0.220  200
#>  sigma.(Intercept)  2.86162  2.46927  2.95380  0.000  200
#>          sigma.MEI  0.16256  0.02442  0.32800  0.010  200
#>      sigma.RH_lag1 -0.19850 -0.45860  0.02802  0.030  200
#>      sigma.dP_lag1  0.27256  0.11229  0.45379  0.000  200
#>    sigma.Tmax_lag1  0.00000 -0.30635  0.06952  0.540  200
#>     xi.(Intercept) -0.29068 -0.50000 -0.19563  0.000  200
```

The intervals are conditional on the selected model and on the observed
number and timing of exceedances (`occurrence = "simulated"` also
resamples them), so they understate the real uncertainty. With 19 years
of data, the 100-year level is an extrapolation, and the width of its
interval shows it. The lower end of the shape interval sits at the bound
$\xi = -1/2$ (`shape_lower`): some bootstrap samples push the tail towards
a short upper limit, and the bound keeps them in the region where maximum
likelihood is regular.

## Walk-forward validation

`backtest()` refits the model on the first years only (declustering and
adaptive weights included), computes return levels from those years, and
counts how often the annual maxima of the following years exceed them.


``` r
bt <- backtest(fit, d, varname = "prec_raw", TRs = c(2, 5),
               window_years = 3, min_train_years = 10, n_boot = 500,
               approaches = "C",
               decluster = function(y) decluster(y, u), verbose = FALSE)
bt
#> Walk-forward backtest: 9 validation years
#> 
#> Exceedance rates (binomial comparison with 1/T):
#>  approach TR expected observed n_exceedances n_total p_value not_rejected
#>         C  2      0.5   0.6667             6       9  0.5078         TRUE
#>         C  5      0.2   0.3333             3       9  0.3960         TRUE
#> 
#> Tail-conditional PIT, Kolmogorov-Smirnov (exploratory):
#>  approach n D_statistic p_value not_rejected
#>         C 9      0.2652  0.4732         TRUE
```

Approach B can be validated in the same way (`approaches = c("B", "C")`),
but here a VAR fitted to only ten years, with the slowly varying MEI, is
too close to non-stationarity for its trajectories to be simulated; with
the full record it is stable, as shown above.

With only nine validation years, the test can detect gross failures but
not small biases; longer records (for example the conventional INMET
station at the same site, which starts in the 1960s) would give a more
demanding test.

## Summary

* The adaptive LASSO kept a small set of physically sensible covariates:
  ENSO and the humidity, pressure change and temperature of the previous
  day; with 19 years, the selection is sensitive to the specification.
* In the main model, ENSO changes the conditional 10-year level
  substantially between La Niña and El Niño years.
* The marginal levels from the VAR generator (B) and from the observed
  years (C) agree, and both are above the conditional level of an average
  year, increasingly so at long return periods.
* The largest day of the record (10 February 2020) has a return period of
  about a century under the fitted model, rare but plausible in 19 years.
* The diagnostics show some residual clustering between events, a
  limitation to keep in mind when reading the intervals.

## Reproducibility


``` r
packageVersion("margEVT")
#> [1] '0.7.0'
sessionInfo()$R.version$version.string
#> [1] "R version 4.6.2 (2026-10-29 ucrt)"
```

## References

Rootzén, H. and Katz, R. W. (2013). Design life level: quantifying risk in
a changing climate. *Water Resources Research*, 49(9), 5964--5972.
