--- title: "Fixed-radius concentration analysis" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Fixed-radius concentration analysis} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( fig.path = "figures/fixed-radius-concentration-", collapse = TRUE, comment = "#>" ) ``` ## Motivation Fixed-radius concentration can be formulated as a weighted circle-placement problem: given point locations with associated weights and a disk of fixed radius, find the centre of the disk that maximises the total weight enclosed. This is a classical spatial optimisation problem from computational geometry. In its simplest form, the question is: where can I place a 200 metre circle so that the total insured value inside that circle is as large as possible? In an exposure portfolio, the point weights might represent insured value, population, asset value, infrastructure value, or another quantity observed at point locations. Insurance concentration analysis is one practical application: the same fixed-radius problem can be interpreted as finding the largest local accumulation of insured value. The package does not impose a probabilistic model. It computes deterministic spatial aggregates from observed point locations and values. The workflows and parameter choices shown in this vignette are illustrative examples of the computational building blocks, not a prescribed methodology or process for any particular organisation. ## Example portfolio The examples below use the included `Groningen` data. The same functions can be applied to larger portfolios. ```{r} library(spatialrisk) portfolio <- Groningen portfolio <- portfolio[, c("lon", "lat", "amount")] head(portfolio) ``` The `amount` column is the value to be accumulated within each radius. In an insurance application this could represent an insured amount, exposure measure, or another portfolio value. The 200 metre radius used below is illustrative; the relevant radius depends on the analytical or reporting context. ## Quick example: find the largest concentration The main applied workflow is `concentration_hotspot()`. It takes point-level exposure data, a value column, and a radius, and returns the circle centre with the largest fixed-radius sum. ```{r} hotspot <- concentration_hotspot( portfolio, value = "amount", radius = 200, cell_size = 100, progress = FALSE ) hotspot ``` The reported `amount_sum` is the sum of `amount` within 200 metres of the selected centre. The default `method = "continuous"` searches for a centre that may lie anywhere in space, not only on an observed building location. ```{r hotspot-map, eval = requireNamespace("mapview", quietly = TRUE)} plot(hotspot) ``` ## Understanding the result A hotspot result contains two main components: - `hotspots`: the selected centre coordinates and the fixed-radius sum; - `contributing_points`: the observations inside the selected hotspot radius. ```{r} hotspot$hotspots head(hotspot$contributing_points[, c("id", "data_row", "lon", "lat", "amount", "amount_sum")]) ``` This separation between the hotspot centre and the contributing observations is important in applied insurance work. It allows the result to be inspected, mapped, and reconciled with the underlying portfolio. The `data_row` column identifies the row in the original input data. ## Inspecting contributing locations The observations assigned to the selected hotspot are stored directly in the hotspot object. This is the safest way to audit the reported hotspot, because it uses the exact contributing observations returned by the search. ```{r} head(hotspot$contributing_points) nrow(hotspot$contributing_points) sum(hotspot$contributing_points$amount) ``` The lower-level function `points_within_radius()` applies the same local inclusion rule around a specified centre. It is useful for checking a known or externally specified location. ```{r} known_centre_points <- points_within_radius( portfolio, lon_center = 6.5549, lat_center = 53.1942, radius = 200 ) head(known_centre_points) nrow(known_centre_points) sum(known_centre_points$amount) ``` The returned data contains the observations that contribute to this specified local fixed-radius sum. This makes the aggregate traceable back to the underlying policies or locations. ## Calculating sums at specified locations The same operation can be repeated for several target locations with `radius_sum()`. Here, the target locations are the first five observations in the portfolio. ```{r} targets <- portfolio[1:5, c("lon", "lat")] target_sums <- radius_sum( targets = targets, reference = portfolio, value = "amount", radius = 200, progress = FALSE, result_col = "amount_200m" ) target_sums ``` The `targets` and `reference` arguments are separated deliberately. This makes it possible to evaluate concentration at existing policy locations, at externally specified coordinates, or at candidate centres created in a custom workflow. In this sense, `points_within_radius()` and `radius_sum()` are supporting functions: they provide transparency and flexibility around the main hotspot search. ## Continuous vs observed centres The maximum fixed-radius circle does not generally need to be centred on one of the insured locations. This distinction matters because a circle placed between several buildings may cover a larger total value than any circle centred exactly on a building. `spatialrisk` therefore distinguishes two useful search strategies: - `method = "continuous"`: the centre may lie anywhere in space; - `method = "observed"`: candidate centres are limited to observed point locations. The observed-points method is fast and deterministic, and is useful as a benchmark. It can, however, miss a higher concentration when the best circle centre lies between buildings. ```{r} hotspot_continuous <- concentration_hotspot( portfolio, value = "amount", radius = 200, cell_size = 100, progress = FALSE ) hotspot_observed <- concentration_hotspot( portfolio, value = "amount", radius = 200, method = "observed", progress = FALSE ) rbind( continuous = hotspot_continuous$hotspots, observed = hotspot_observed$hotspots ) ``` In this example the continuous hotspot has a higher `amount_sum` than the observed-points hotspot. The example should be read as a demonstration of the methodological distinction: restricting centres to observed locations changes the optimisation problem. ```{r hotspot-method-comparison, eval = requireNamespace("mapview", quietly = TRUE)} plot(hotspot_continuous) plot(hotspot_observed) ``` The original grid-refinement workflow remains available with `method = "grid"`. In that method, `grid_spacing` controls the local grid refinement. For the default `method = "continuous"`, `grid_spacing` is only used if the local pair-refinement subset is too large and the function falls back to grid refinement. ## Multiple hotspots The argument `n_hotspots` gives the number of hotspots to return. When `n_hotspots > 1`, hotspots are selected sequentially: after the first hotspot has been found, its contributing observations are removed before the next hotspot is searched for. This gives non-overlapping hotspot assignments. ```{r} hotspot_top2 <- concentration_hotspot( portfolio, value = "amount", radius = 200, cell_size = 100, progress = FALSE, n_hotspots = 2 ) hotspot_top2$hotspots ``` The first hotspot addresses the single-circle maximum concentration problem. The second hotspot is the largest hotspot in the remaining portfolio after removing the observations assigned to the first hotspot. This greedy procedure is useful for reporting several distinct local accumulations, but it should not be interpreted as a globally optimal joint placement of several circles. ```{r hotspot-top2-map, eval = requireNamespace("mapview", quietly = TRUE)} plot(hotspot_top2) ``` ## How the search works The high-level hotspot workflow can also be run step by step. This is useful when the intermediate candidate selection needs to be inspected before the final hotspot is optimised. The state supplied to `optimize_hotspot()` determines where geometric candidate centres are generated. A prepared state has not been screened and therefore represents the full active portfolio as the candidate-generation universe. A state returned by `select_candidates()` represents the screened candidate regions. In either case, retained candidate centres are evaluated against the complete active portfolio: candidate selection does not create a subportfolio for scoring. Conceptually, the search has four stages: - coarse spatial screening identifies promising regions; - candidate regions are retained using an automatically estimated lower bound; - candidate centres are generated or refined within those regions; - exact fixed-radius totals are maintained for candidate centres and the best result is returned. ```{r} model <- prepare_spatialrisk(portfolio, value = "amount", radius = 200, cell_size = 100) model <- select_candidates(model, progress = FALSE) step_hotspot <- optimize_hotspot(model, n_hotspots = 2, progress = FALSE) step_hotspot$hotspots ``` For small validation problems, candidate screening can be omitted deliberately. The direct route evaluates observed centres and the valid pairwise circle-intersection centres generated from the complete active portfolio. The screened route is the normal continuous search used by `concentration_hotspot()`. ```{r} validation_portfolio <- portfolio[1:200, ] validation_model <- prepare_spatialrisk( validation_portfolio, value = "amount", radius = 200, cell_size = 100 ) # Full geometric reference search full <- optimize_hotspot(validation_model, progress = FALSE) # Screened continuous search screened <- validation_model |> select_candidates(progress = FALSE) |> optimize_hotspot(progress = FALSE) full$hotspots screened$hotspots ``` The full route has pairwise computational cost and is intended for small portfolios, diagnostics, and methodological validation. It does not silently switch to grid refinement when the number of points exceeds `max_refinement_points`; instead, it warns that the requested complete search may be expensive. Calling `plot(model)` after `prepare_spatialrisk()` but before candidate selection shows the rasterised portfolio sum per cell. After `select_candidates()`, `plot(model)` shows the centre cells retained by screening. The cell colours still show the original focal sums; `model$candidates$cells$point_upper_bound` contains the tighter point-based bounds for the default continuous search. ```{r workflow-plots, eval = requireNamespace("mapview", quietly = TRUE)} prepared <- prepare_spatialrisk(portfolio, value = "amount", radius = 200, cell_size = 100) plot(prepared) selected <- select_candidates(prepared, progress = FALSE) plot(selected) ``` The lower bound can also be supplied explicitly, for example `select_candidates(model, threshold = 1000)`. When `threshold = NULL`, the automatic lower bound is deliberately conservative. The function takes the five highest cells from the focal raster and evaluates a 10 by 10 regular trial grid across each cell. These 500 evaluations use the same projected Euclidean geometry and complete active portfolio as the final search; trial coordinates on shared cell edges need not be unique. The best feasible concentration becomes the lower bound. For continuous search with non-negative values, focal cells above this lower bound undergo a second, point-based bound calculation described below. The five highest surviving point bounds seed another trial grid; the best actually attained portfolio sum can raise, but never lower, the threshold. Only cells whose point bound is at least the resulting threshold remain candidates. The candidate map is therefore an inspection view of where the next hotspot may be found, not a fixed list of final hotspots. When `n_hotspots > 1`, the search is repeated. After the first hotspot has been found, its contributing observations are removed from the remaining portfolio and the screening, candidate selection, and refinement steps are run again for the next hotspot. This is why a candidate map that currently shows, for example, five focal cells can still lead to ten hotspots when `optimize_hotspot(model, n_hotspots = 10)` is used: the five cells describe the first search iteration only. The default continuous method uses terra rasterisation and focal sums for the screening step. It then refines all candidate areas above the lower bound by evaluating observed local points and the circle centres implied by local point pairs. The point-to-cell assignment created during preparation is reused to retrieve points from nearby raster cells, rather than scanning the complete portfolio separately for every focal candidate cell. For the common single-hotspot search, the retained local point sets are combined and Rcpp traverses the pair geometry once as a streaming angular sweep. The sweep maintains conservative interval totals over all active neighbours, including the distance slack used by point-level scoring, without materialising all centres. Candidate angles remain those of the original radius-circle intersections. Grouping nearby events does not merge or move their pair-derived centre coordinates. Only centres whose interval bound can match or improve the current best receive a confirming indexed radius evaluation; signed weights bypass this upper-bound preselection. The numerical safeguards accommodate rounding but do not constitute a formal floating-point optimality certificate. Runtime therefore depends strongly on local pair density, not only on the total portfolio size. If the local refinement subset is larger than `max_refinement_points`, the function falls back to grid refinement for that iteration. Grid refinement and fallback use the same projected coordinates, closed-radius membership test, and complete active portfolio as continuous scoring. Only the candidate-centre search changes. The `refinement_methods` attribute of a continuous result reports `"pair_intersections"` or `"grid"`; grid fallback has no global-optimality guarantee. The focal moving window is deliberately wider than the requested radius by one raster-cell diagonal. Consequently, with non-negative values, the focal sum is an upper bound for the exact radius sum of every centre located in that cell: all source cells that could contribute to such a centre are included. The automatically estimated threshold is a lower bound obtained from a feasible preliminary centre. A raster cell whose focal upper bound is below that threshold cannot contain a better centre and need not be refined. For each surviving centre cell $C$, a tighter bound is $$ V(C) = \sum_i w_i\,\mathbf{1}\{d(p_i,C)\leq r\}, $$ where $d(p_i,C)$ is the minimum distance from the point to the closed cell rectangle. If a point can lie within a radius-$r$ disk centred anywhere in $C$, it must contribute to this bound. The reverse need not hold for all points simultaneously, so $V(C)$ remains an upper bound, not an attainable hotspot value. Unlike the focal sum, it does not include the full weight of a neighbouring cell merely because its boundary can be reached. The implementation uses the stored terra cell assignments to retrieve nearby active points in one batch and allows for radius-scoring and floating-point tolerances at cell edges. Cells with $V(C)