--- title: "Events in time: contagion, trends and operations" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Events in time: contagion, trends and operations} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} # the vignette runs in full in GitHub CI and for the package tarball (NOT_CRAN), # on r-universe (MY_UNIVERSE), on the package website (IN_PKGDOWN) and in an # interactive session; when CRAN re-builds it in its check, none of these is set # and only this chunk runs if (!interactive() && !any(nzchar(Sys.getenv(c("NOT_CRAN", "MY_UNIVERSE", "IN_PKGDOWN"))))) { knitr::knit_exit() } knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 6.5, fig.height = 4, fig.align = "center", dpi = 72) options(width = 88) set.seed(1) library(crimlab) ``` Self-exciting processes, trends, change points, survival, forecasts and the other methods for events in time. Each section is one help page: what the function is for, the example of its help page as it runs, and the plot of its result where the package draws one. `?name` gives the arguments and the value in full. # Time, contagion and operations ## Hawkes process: self-exciting event times `hwkfit()`: Fits a self-exciting (Hawkes) point process to event times, such as the times of shootings, burglaries or calls for service, by maximum likelihood: a background rate and, on top of it, a rise in the rate after each event that dies away with the time since. The fitted branching ratio `eta` is the expected number of events each event triggers; it says how much of the record is contagion rather than background. ```{r hwkfit} x <- hwksim(c(a0 = log(0.5), eta = 0.5, beta = 2), 200, seed = 1) fit <- hwkfit(x$t, 200) fit hwkfit(x$t, 200, kernel = c("exp", "lomax"))$cmp ``` ## Hawkes process: time-rescaling residuals `hwkres()`: Transforms event times by the compensator of a Hawkes process, Lambda(t) = \int_0^t lambda: under the model the gaps tau_i = Lambda(t_i) - Lambda(t_{i-1}) (with t_0 = 0) are independent standard exponentials, so `u = 1 - exp(-tau)` are uniform on [0, 1]. The Kolmogorov-Smirnov test compares `u` with the uniform, with R's exact p-value below 100 events without ties and the limiting distribution otherwise, as `stats::ks.test()` does. `plot()` draws the uniform quantile plot with the test's 95% band. ```{r hwkres} x <- hwksim(c(a0 = log(0.5), eta = 0.5, beta = 2), 200, seed = 1) r <- hwkres(hwkfit(x$t, 200)) r plot(r) ``` ```{r hwkres-plot} plot(r) ``` ## Hawkes process: simulation `hwksim()`: Simulates a Hawkes process on [0, hor] by its branching construction (Hawkes and Oakes 1974): background events from the baseline (by thinning for the `"cycle"` baseline), and from each event a Poisson number, mean `eta`, of offspring at lags drawn from the kernel, and so on over the generations. With `win` the process is in space and time: background events fall uniformly in the rectangle, the baseline is then per unit area, and each offspring lands at a normal offset (standard deviation `sigma`) from its parent; offspring outside the window or past `hor` are not recorded and have no offspring of their own. ```{r hwksim} hwksim(c(a0 = log(0.2), eta = 0.6, beta = 1), 50, seed = 2) hwksim(c(a0 = log(0.01), eta = 0.5, beta = 1), 50, win = c(0, 10, 0, 10), sigma = 0.5, seed = 2) ``` ## Trend in a series: rate ratio, Mann-Kendall and Theil-Sen `trndrr()`: Measures the trend in a short series of counts (admissions, incidents or placements per year) three ways. The Poisson log-linear model \log mu_t = b_0 + b_1 (x_t - \bar x) + \log e_t gives the rate ratio per unit of `x`, `exp(b1)` (0.85: a fall of 15% a period), with the exposure `expo` as offset so that the trend is in the rate; when the Pearson dispersion (over `n - 2`) is above 1.5 the interval and p-value are the quasi-Poisson ones (standard error times the square root of the dispersion, the t distribution on `n - 2` degrees of freedom). The fit takes the steps of `stats::glm()`. Mann-Kendall's rank test and the Theil-Sen slope (the median of the pairwise slopes, with Sen's distribution-free interval) make no distributional assumption; the p-value is exact over every ordering of the observed values up to 8 periods (ties kept) and normal with the tie and continuity corrections beyond. Negating the series negates S, so rises and falls are treated alike (`proof("trndrr")`). `yoy` holds the change on the period before, and with `seas` the totals by season are tested for equality (chi-square). Given the counts of one cycle with each season once (incidents by month of the year, by day of the week or by hour of the day), that test is the one that the counts are spread evenly over the cycle, as `chisq.test(y)`. ```{r trndrr} y <- c(402, 377, 390, 368, 331, 310, 305) trndrr(y, 2017:2023) # a rate: counts over a growing population trndrr(c(20, 25, 30, 33), expo = c(1000, 1500, 2500, 2600))$rr # equal totals by quarter? trndrr(c(5, 9, 7, 4, 6, 10, 8, 5), seas = rep(1:4, 2))$seas ``` ```{r trndrr-plot} res <- trndrr(y, 2017:2023) plot(res) ``` ## Change point: a step in a series and Pettitt's test `stpcp()`: Asks whether a series moved to a new level, and where. The step scan takes every split after period `k` with at least `minseg` periods on each side, and the largest between-segment sum of squares T_k = k (n - k) / n (\bar y_a - \bar y_b)^2; its p-value comes from the same maximum over reorderings of the series (every ordering when n! is at most `nperm`, giving an exact p-value; otherwise `nperm` random ones, (1 + #{T* >= T}) / (1 + nperm)), so it is a test of a step anywhere, not of the best split alone. Pettitt's rank test takes the split with the largest |U_t|, U_t = sum_{i <= t < j} sign(y_j - y_i), with its approximate p-value 2 \exp(-6 K^2 / (n^3 + n^2)). Both assume exchangeable periods under no change: a steady trend can read as a step. ```{r stpcp} stpcp(c(100, 104, 98, 60, 63, 58), x = 2018:2023) stpcp(c(100, 104, 98, 101, 97, 60, 63, 58, 61, 59), nperm = 999, seed = 1) ``` ## CUSUM surveillance of counts `cusrv()`: Watches a series of counts for a rise above what is expected: the cumulative sum s_t = \max(0, s_{t-1} + z_t - k) of the standardised excess z_t raises an alarm where s_t >= h. The expected counts are given (`expd`), or are the mean of the counts before `start`, the first period watched. `z` is `(y - m) / sqrt(m)` (`"std"`), Rossi's transform (y - 3 m + 2 sqrt(y m)) / (2 sqrt(m)) (`"rossi"`), Anscombe's `1.5 (y^(2/3) - m^(2/3)) / m^(1/6)` (`"anscombe"`) or the count itself (`"none"`, for `k` and `h` on the count scale). With `reset` the sum starts again from 0 after an alarm. ```{r cusrv} y <- c(10, 12, 9, 11, 10, 13, 19, 22, 25, 12) cusrv(y, start = 6) cusrv(y, expd = rep(11, 10), trans = "rossi", reset = TRUE) ``` ## Correlation of two series, at lags `xcser()`: Correlates two series period by period: Pearson's r with Fisher's interval and the t-test p-value of `stats::cor.test()`, and the cross-correlations at lags -K..K as `stats::ccf()` estimates them (lag `k` is the correlation of `x[t + k]` with `y[t]`; the default `K` is `ccf()`'s, floor(10 log10(n / 2))). Two named series are matched by name (the periods both have, in the order of `x`), so counts from two sources for the same years line up whatever years each covers. With `dif` the changes from one period to the next are correlated instead of the levels: two series that both trend correlate in level whether or not they move together. Every correlation lies in [-1, 1] (Cauchy-Schwarz, `proof("xcser")`). ```{r xcser} a <- c("2019" = 120, "2020" = 98, "2021" = 105, "2022" = 130, "2023" = 141) b <- c("2018" = 50, "2019" = 61, "2020" = 44, "2021" = 52, "2022" = 66, "2023" = 70) xcser(a, b) xcser(a, b, dif = TRUE)$cor ``` ```{r xcser-plot} res <- xcser(a, b) plot(res) ``` ## Kaplan-Meier survival and recurrence `kmrec()`: Estimates the share still without an event at each time since the start (release, placement, a case opening, the last incident at a place) by Kaplan-Meier, by group, with Greenwood's standard error and the log-scale interval of `survival::survfit()` (its default), each group's median (where the curve sits at exactly 1/2, halfway to its next fall, as `survfit()` does), and the log-rank test between groups (`survival::survdiff()`). Each product step is a factor in [0, 1], so the curve starts at most 1 and never rises (`proof("kmrec")`). ```{r kmrec} kmrec(c(3, 8, 8, 12, 20, 24), event = c(1, 1, 0, 1, 0, 1), grp = c("a", "a", "a", "b", "b", "b")) # repeat incidents at three places, watched to day 100 kmrec(c(2, 9, 30, 5, 70, 11, 12, 13), unit = rep(c("p", "q", "r"), c(3, 2, 3)), end = 100)$med ``` ```{r kmrec-plot} res <- kmrec(c(3, 8, 8, 12, 20, 24), event = c(1, 1, 0, 1, 0, 1), grp = c("a", "a", "a", "b", "b", "b")) plot(res) ``` ## Split-population (cure) model of recidivism `spcure()`: Asks two questions that an ordinary survival model runs together: what share of people released will ever be reconvicted, and how soon those who are reconvicted fail. A Kaplan-Meier curve of time to reconviction levels off well above 0: many released people never fail, however long they are followed. Schmidt and Witte (1989) model this with a split population: each person would eventually fail with chance delta = 1 / (1 + exp(-x'gamma)) (the `"fail"` part), and the time to failure of those who would fail follows a distribution with scale exp(x'beta) (the `"time"` part): a Weibull with a common shape, an exponential, or a lognormal (log time normal with mean x'beta and a common standard deviation `sigma`). A person followed to time `t` without failing contributes 1 - delta + delta S(t), one who failed at `t` contributes delta f(t). The parameters are estimated by maximum likelihood (quasi-Newton steps with the analytic gradient) with standard errors from the inverse of the Hessian. ```{r spcure} set.seed(10) n <- 600 prior <- rbinom(n, 1, 0.4) fail <- rbinom(n, 1, plogis(-0.5 + 1.2 * prior)) tt <- ifelse(fail == 1, rweibull(n, 1.3, 300), Inf) cens <- runif(n, 365, 1500) r <- spcure(pmin(tt, cens), as.numeric(tt <= cens), data.frame(prior)) r ``` ```{r spcure-plot} plot(r) ``` ## Hypercube queue of patrol units `hypq()`: Larson's hypercube model of patrol cars: calls arrive from each atom (beat, reporting area) at rate `lam` and go to the first free unit in the atom's order of preference; each unit serves at rate `mu`. The state is the set of busy units, 2^n states for `n` units, and the stationary distribution is found exactly. From it come each unit's workload (the share of time busy), the share of calls each unit answers from each atom, the probability that every unit is busy (a lost call, or with `queue = "wait"` a call that waits; Larson's infinite-line model, the queue lumped into the all-busy state), the mean queue and wait, and with travel times the mean response travel time. Whatever the orders, the number of busy units follows Erlang's loss or delay system. The noisy-OR chance that patrols detect an event is `nordet()`. ```{r hypq} pref <- rbind(c(1, 2, 3), c(2, 1, 3), c(3, 2, 1), c(3, 1, 2)) tt <- matrix(c(2, 5, 8, 6, 3, 7, 9, 6, 2, 7, 8, 3), 3) hypq(c(0.4, 0.7, 0.3, 0.6), pref, mu = 1.5, tt = tt) ``` ```{r hypq-plot} res <- hypq(c(0.4, 0.7, 0.3, 0.6), pref, mu = 1.5, tt = tt) plot(res) ``` ## Square-root law of response distance `sqrtlw()`: Kolesar and Blum's square-root law: with available units spread like a random (Poisson) pattern over a region of area `area`, the mean distance from a call to the nearest available unit is c sqrt{A / (u (1 - b))} for `units` u of which a share `busy` b is busy; c = 1/2 in straight lines and sqrt{2 pi} / 4 \approx 0.627 on a rectangular street grid. Quadrupling the units halves the distance and scaling area and units together leaves it unchanged (`proof("sqrtlw")`). The busy share can come from `hypq()`'s workloads. ```{r sqrtlw} sqrtlw(100, 4) sqrtlw(100, 8, busy = 0.3, metric = "grid", speed = 0.5) ``` ## Hot-spot dynamics: the Short-D'Orsogna-Brantingham model `sdbsim()`: Simulates the model of residential burglary of Short et al. (2008) on an `n` by `n` grid of houses that wraps at its edges. Each site has an attractiveness `a0 + b`; `b` rises by `theta` with every burglary there, spreads to the four neighbours at rate `eta` and decays at rate `omega`, so that burglaries draw further burglaries (repeat and near-repeat victimisation). In the `"agent"` model offenders (`rho`, whole numbers per site) burgle with probability 1 - e^{-(a_0 + b) dt} and leave, or else move to a neighbouring site chosen in proportion to its attractiveness; new offenders arrive at `gam` per site per unit time. In the `"pde"` model the densities follow the continuum limit, b_t = (eta D / z) Delta b - omega b + epsilon D rho A and rho_t = (D / z)(Delta rho - 2 \nabla \cdot (rho \nabla A / A)) - rho A + gamma with A = a_0 + b, by explicit Euler steps on a grid of spacing `dx`; `sup` marks sites where policing suppresses crime (no burglaries there). The step must satisfy dt <= z dx^2 / (4 dif max(1, eta)). ```{r sdbsim} s <- sdbsim(20, 50, a0 = 1 / 30, omega = 1 / 15, eta = 0.03, gam = 0.02, theta = 0.5, seed = 1) s p <- sdbsim(16, 200, mode = "pde", eps = 2, dt = 0.05, rho = matrix(0.07, 16, 16)) range(p$b) ``` ```{r sdbsim-plot} plot(p) ``` ## Hot-spot threshold of the Short-D'Orsogna-Brantingham model `sdbthr()`: The continuum model of `sdbsim()` has one uniform steady state, \bar b = epsilon D gamma / omega, \bar A = a_0 + \bar b, \barrho = gamma / \bar A. Linearised about it, a disturbance of wavenumber-squared k evolves by a 2 by 2 matrix whose trace is negative at every k and whose determinant is P k^2 - Q k + R, R = omega \bar A > 0: a mode grows exactly when the determinant is negative. So hot spots form when Q > 0, that is 3 epsilon D \barrho > omega + eta \bar A (repeat victimisation outweighs decay and spreading), and Q^2 > 4 P R; the fastest-growing mode is near k^* = Q / (2 P). Without reinforcement (`eps = 0`) the uniform state is stable at every wavelength (`proof("sdbthr")`). `z` places the lattice's neighbour count on both diffusion terms, as `sdbsim()` does (`z = 1` is the continuum form). ```{r sdbthr} sdbthr(a0 = 1, omega = 1, eps = 2, dif = 1, gam = 1, eta = 0.01) sdbthr(a0 = 1, omega = 1, eps = 0, dif = 1, gam = 1, eta = 0.01)$unstable ``` ## ETAS: a self-exciting process with marks and the Omori law `etasf()`: Fits the temporal epidemic-type aftershock sequence (ETAS) model of Ogata (1988) to event times with marks (a magnitude, the number of victims, the severity of an incident): ```{r etasf} x <- hwksim(c(log(0.3), 0.5, 0.6, 1), 800, kernel = "lomax", seed = 5) etasf(x$t, 800) ``` ## Multivariate Hawkes process: types that excite each other `mvhwk()`: Fits a multivariate Hawkes process with exponential kernels to event times of several types (offence types, gangs, areas): ```{r mvhwk} a <- hwksim(c(log(0.3), 0.3, 1), 400, seed = 1) b <- hwksim(c(log(0.2), 0.4, 1), 400, seed = 2) d <- rbind(data.frame(t = a$t, type = "a"), data.frame(t = b$t, type = "b")) d <- d[order(d$t), ] mvhwk(d$t, d$type, 400) ``` ## Space-time Hawkes process `sthwk()`: Fits the self-exciting point process of crime in space and time of Mohler et al. (2011): ```{r sthwk} s <- hwksim(c(log(0.02), 0.5, 1), 100, win = c(0, 10, 0, 10), sigma = 0.3, seed = 3) f <- sthwk(s$t, s$x, s$y, 100, win = c(0, 10, 0, 10)) f sthwk(s$t, s$x, s$y, 100, win = c(0, 10, 0, 10), par = f$par, at = data.frame(t = 50, x = 5, y = 5))$lam ``` ## Aoristic weights `aorwt()`: Spreads each event known only to have happened in an interval [from, to) with uniform density over that interval and counts each instant in the bin of its local clock time (Ratcliffe 2002): with the defaults, the 168 hours of the week from Sunday 00:00. A change of clock (daylight saving) moves the remaining time to the right hours: skipped hours get nothing and a repeated hour gets both. Missing values follow stated rules: an event with no `from` is left out; with no `to`, a reversed interval or one shorter than `lo` seconds, its whole weight goes to the start's bin; one of at least `hi` seconds is spread evenly over all bins. ```{r aorwt} f <- as.POSIXct(c("2024-03-04 22:00", "2024-03-05 09:30"), tz = "UTC") t <- as.POSIXct(c("2024-03-05 02:00", "2024-03-05 10:30"), tz = "UTC") a <- aorwt(f, t, bw = 3600, nb = 24, origin = 0) a$tot ``` # Counts over time and across categories ## ARIMA(1,1,1) forecast of a count series `arimfc()`: Fits ARIMA(1,1,1) to a series of counts (monthly incidents, calls for service, admissions) by exact maximum likelihood, the Kalman filter on the state-space form with the conditional-sum-of-squares fit as its start, as `stats::arima()` does by default, and forecasts `h` periods ahead with their standard errors. AIC is -2 \log L + 2(k + 1); BIC is \mathrm{AIC} + (k + 1)(\log n - 2), k the ARMA coefficients. ```{r arimfc} # 48 simulated months of counts set.seed(1) y <- rpois(48, 50 + 10 * sin(1:48 / 6)) arimfc(y, h = 6)$fc ``` ## Seasonal ARIMA forecast with a hold-out check `sarfc()`: Fits SARIMA(p,d,q)(P,D,Q)_s (by the method of `arimfc()`) to all but the last `h` values of a count series, forecasts those `h`, and scores the forecasts against them: the mean absolute percentage error (each error over the larger of the count and 1) and the root mean square error. The model must difference the series once at least (`order[2]` or `seasonal[2]` above 0), so it has no mean. ```{r sarfc} set.seed(1) y <- rpois(60, 50 + 10 * sin(2 * pi * (1:60) / 12)) sarfc(y, h = 6)[c("mape", "rmse")] ``` ## Ornstein-Uhlenbeck (Langevin) fit and simulation of a count series `ousim()`: Treats a daily count series as a noisy mean-reverting intensity, dX_t = theta (mu - X_t) dt + sigma dW_t: theta, mu and sigma from the least-squares regression of the first differences on the lagged values (theta = -b, at least 10^{-6}, mu = -a/b, sigma the residual standard deviation), then `npath` Euler-Maruyama paths of `days / dt` steps from the last value. Draws come from `seed`, as `set.seed()` takes it. ```{r ousim} set.seed(1) y <- rpois(200, 20) ousim(y, npath = 20, days = 30)$q ``` ## Fokker-Planck evolution of a count density `fpdens()`: The density of the Ornstein-Uhlenbeck process fitted as in `ousim()`, evolved by the Fokker-Planck equation \partial_t p = -\partial_x (theta (mu - x) p) + \frac{1}{2} sigma^2 \partial_x^2 p, here with the drift taken outside the derivative as in the explicit scheme used: central differences on `ngrid` points from 0 to 1.5 times the largest count plus 1, `nstep` steps of 0.05, edges copied from their neighbours, the density kept non-negative and of total 1. It starts as a normal curve at the last count with standard deviation sigma + 1. The stationary variance is sigma^2 / (2 theta). ```{r fpdens} set.seed(1) f <- fpdens(rpois(200, 20)) f$peak ``` ## Lotka-Volterra rates of a yearly count series `lvfit()`: Treats yearly counts as the prey x(t) and their three-year trailing mean as a stand-in predator y(t) (an enforcement series can take its place) in \dot x = alpha x - beta x y, \dot y = delta x y - gamma y: alpha is the median log growth of x plus 0.05, gamma minus the median log growth of y plus 0.05, beta = alpha / \mathrm{median}(y), delta = gamma / \mathrm{median}(x), and the linearised cycle has period 2pi / sqrt{alphagamma} (D'Orsogna and Perc 2015, section 3.4). The rates describe the series; they are not a fitted dynamical model. ```{r lvfit} lvfit(c(410, 455, 430, 470, 520, 498, 515), year = 2017:2023)$period ``` ## Correlation of counts per unit between categories `catcor()`: Counts the events of each category (offence type, call type) by unit (neighbourhood, beat, district), over the union of the units with a 0 where a category has none, and gives the Pearson correlations of those counts between every pair of categories: whether the same places score high on both. ```{r catcor} # simulated events of three categories in 20 areas set.seed(1) a <- sprintf("%02d", 1:20) u <- list(theft = sample(a, 200, TRUE), assault = sample(a, 80, TRUE), fraud = sample(a, 50, TRUE)) catcor(u)$r ```