Skip to content

Where points fall

When the locations themselves are the data, test complete spatial randomness with Clark–Evans, Ripley's K and L, and quadrat counts.

Advanced ~15 min11 steps

What runs in CodeSplash

You will be able to

  • State what complete spatial randomness assumes
  • Read a Clark–Evans ratio and a Ripley L envelope as clustered or regular
  • Explain why edges and global envelopes matter

Read first

01

The locations are the data

Read

So far each site carried a value. Now nothing is measured except where things are: trees, cells, stores, crimes.

The reference is complete spatial randomnessComplete spatial randomnessPoints placed independently and uniformly over the window, the usual null for point patterns. (CSR): each point lands anywhere in the window with equal chance, independently of the others. Against that, a pattern can be clustered, with points closer together than chance, or regular, with points kept apart.

02

Nearest neighbors

Predict

Predict first

The Clark–EvansClark–Evans ratioMean nearest-neighbor distance over what random points would give; below 1 clustered, above 1 regular. ratio divides the mean nearest-neighbor distance by the value expected under CSR:

R=dˉE[dˉ],E[dˉ]≈12λR = \frac{\bar d}{E[\bar d]}, \qquad E[\bar d] \approx \frac{1}{2\sqrt{\lambda}}

Biological cells can't overlap, so each keeps its distance from the next. What do you expect for RR?

R below 1R close to 1R above 1
Reveal

Above 1: RR = 1.56, p < .001. Clustered redwood seedlings go the other way: RR = 0.58, p = .005 from simulated patterns.

03

The edge problem

Read

A point near the boundary has neighbors you can't see outside the window, so its nearest-neighbor distance is too long.

On 80 random points, ignoring this gives RR = 1.036. Donnelly's correction raises the expected distance and gives RR = 0.987, p = .831.

04

Every distance at once

Read

Nearest neighbors only see the smallest scale. Ripley's KRipley's K and LHow many other points lie within distance r of a typical point, against what random points would give. L(r) = r under randomness. counts how many other points lie within distance rr, for every rr:

L(r)=K(r)/πL(r) = \sqrt{K(r)/\pi}

Under CSR, L(r)=rL(r) = r. So L(r)−rL(r) - r above zero means more neighbors than chance at that distance, and below zero means fewer.

05

Read the curve

Predict

Predict first

At short distances, which way does L(r)−rL(r) - r go for the cells, whose points keep apart?

Above zeroBelow zeroOn zero
Reveal

Below zero: the largest deviation is −0.085 at rr = 0.11, with p = .010.

The redwoods go the other way: 0.051 at rr = 0.06, p = .010.

06

Global, not pointwise

Read

Comparing the curve with an envelope at each distance separately is one test per distance, so somewhere the curve is likely to poke out by chance.

A global envelope sets one band for the whole range. Its width comes from the maximum deviation across all distances in each simulated pattern.

Ripley's L envelope testRecorded · Python and R agreeRecorded 2026-11-17 · 23 values compared
R

T = 0.0509, p = .010, n = 62

T
0.0509
p
.010
Distance of largest gap
0.0645

Plots

62 pointsHow do two numeric variables move together?
View data
xy
0.3600−0.0800
0.4400−0.1000
0.4800−0.0800
0.4800−0.1400
0.5000−0.1000
0.7600−0.1400
0.7800−0.1200
0.7800−0.1600
0.8400−0.0800
0.8600−0.1800
0.9000−0.0800
0.9000−0.1000
0.9000−0.1600
0.9000−0.2000
0.1800−0.4000
0.1800−0.3800
0.2000−0.4200
0.6000−0.3400
0.6200−0.3400
0.6400−0.3600
0.6400−0.2800
0.6800−0.3200
0.6800−0.2400
0.7000−0.2800
0.7200−0.2600
0.1000−0.5800
0.1200−0.5800
0.1200−0.6200
0.1400−0.5800
0.1800−0.5600
0.1800−0.5400
0.2000−0.5200
0.2000−0.5000
0.2200−0.4600
0.2400−0.4800
0.5200−0.5800
0.5000−0.6000
0.5800−0.5800
0.9400−0.5200
0.9600−0.5400
0.2200−0.8000
0.2200−0.8400
0.2600−0.7000
0.4400−0.7600
0.4800−0.7800
0.5000−0.7600
0.9000−0.7600
0.9000−0.7800
0.4800−0.6800
0.5200−0.6600
0.5600−0.6400
0.9990−0.8400
0.4400−0.8200
0.4800−0.8200
0.3400−0.8400
0.3800−0.8400
0.2600−0.8600
0.4000−0.8600
0.2800−0.8600
0.7400−0.9000

First 60 of 62 rows.

L(r) against 99 random patternsAt what distances are points more clustered or more regular than random?
View data
L(r)Pointwise highGlobal highPointwise lowGlobal lowDistance r
000.02340−0.02340
00.01300.02540−0.02150.0020
00.01300.02730−0.01950.0039
00.01830.02930−0.01760.0059
00.01830.03130−0.01560.0078
00.02250.03320−0.01370.0098
00.02590.03520−0.01170.0117
00.02590.03710−0.00980.0137
00.02590.03910−0.00780.0156
00.02900.04100−0.00590.0176
00.02950.04300−0.00390.0195
0.03890.03200.04490−0.00200.0215
0.03890.03620.0469000.0234
0.03890.03670.048800.00200.0254
0.03890.03780.050800.00390.0273
0.05950.03970.052700.00590.0293
0.05950.04610.05470.01830.00780.0313
0.05950.04850.05660.01830.00980.0332
0.05950.05130.05860.01830.01170.0352
0.05950.05150.06050.02250.01370.0371
0.05950.05350.06250.02250.01560.0391
0.06990.05460.06450.02300.01760.0410
0.06990.05900.06640.02590.01950.0430
0.09170.06360.06840.02640.02150.0449
0.09170.06520.07030.02940.02340.0469
0.09170.06650.07230.03430.02540.0488
0.09170.06670.07420.03430.02730.0508
0.09170.06930.07620.03670.02930.0527
0.09170.07290.07810.03890.03130.0547
0.09880.07680.08010.04100.03320.0566
0.09880.07790.08200.04300.03520.0586
0.10540.08000.08400.04300.03710.0605
0.10540.08150.08590.04680.03910.0625
0.11530.08290.08790.04920.04100.0645
0.11530.08290.08980.05000.04300.0664
0.11530.08700.09180.05310.04490.0684
0.11530.08800.09380.05560.04690.0703
0.12240.09010.09570.05790.04880.0723
0.12240.09080.09770.05950.05080.0742
0.12240.09170.09960.06270.05270.0762
0.12240.09360.10160.06450.05470.0781
0.12580.09360.10350.06700.05660.0801
0.12580.09500.10550.06920.05860.0820
0.13170.09670.10740.06980.06050.0840
0.13490.09900.10940.07270.06250.0859
0.13490.10000.11130.07410.06450.0879
0.13920.10270.11330.07530.06640.0898
0.13920.10530.11520.07640.06840.0918
0.13920.10670.11720.07750.07030.0938
0.13920.11010.11910.08040.07230.0957
0.13920.11170.12110.08040.07420.0977
0.13920.11320.12300.08170.07620.0996
0.14870.11530.12500.08360.07810.1016
0.15220.11690.12700.08560.08010.1035
0.15220.11940.12890.08810.08200.1055
0.15220.12210.13090.08930.08400.1074
0.15560.12500.13280.09250.08590.1094
0.15560.12710.13480.09520.08790.1113
0.15670.13090.13670.09680.08980.1133
0.15670.13260.13870.09920.09180.1152

First 60 of 129 rows.

Assumptions

  • Observation window known — The window is the rectangle you stated.
  • Constant intensity — Density that varies across the window mimics clustering between points. These tests cannot tell the two apart.
  • Distances fixed in advance — Pointwise envelopes do not control error over the whole range; use the global test's p.

L(r) with its envelopes

rK(r)L(r)Pointwise lowPointwise highGlobal lowGlobal high
00000−0.02340.0234
0.00590000.0183−0.01760.0293
0.01170000.0259−0.01170.0352
0.01760000.0290−0.00590.0410
0.02340.00480.038900.036200.0469
0.02930.01110.059500.03970.00590.0527
0.03520.01110.05950.01830.05130.01170.0586
0.04100.01530.06990.02300.05460.01760.0645
0.04690.02640.09170.02940.06520.02340.0703
0.05270.02640.09170.03670.06930.02930.0762
0.05860.03070.09880.04300.07790.03520.0820
0.06450.04180.11530.04920.08290.04100.0879
0.07030.04180.11530.05560.08800.04690.0938
0.07620.04710.12240.06270.09170.05270.0996
0.08200.04970.12580.06920.09500.05860.1055
0.08790.05710.13490.07410.10000.06450.1113
0.09380.06080.13920.07750.10670.07030.1172
0.09960.06080.13920.08170.11320.07620.1230
0.10550.07270.15220.08810.11940.08200.1289
0.11130.07610.15560.09520.12710.08790.1348
0.11720.08220.16180.10300.13290.09380.1406
0.12300.08890.16820.10630.13880.09960.1465
0.12890.10070.17910.11130.14420.10550.1523
0.13480.10340.18140.11730.15080.11130.1582
0.14060.10500.18280.12570.15500.11720.1641
0.14650.11640.19250.13320.16280.12300.1699
0.15230.12060.19600.13840.16790.12890.1758
0.15820.12240.19740.14350.17420.13480.1816
0.16410.12850.20220.14940.18050.14060.1875
0.16990.13190.20490.15540.18410.14650.1934
0.17580.13370.20630.16150.19110.15230.1992
0.18160.13880.21020.16970.19640.15820.2051
0.18750.14310.21340.17410.20340.16410.2109
0.19340.15170.21970.17830.21090.16990.2168
0.19920.15530.22230.18340.21630.17580.2227
0.20510.15860.22470.19080.22190.18160.2285
0.21090.16320.22790.19650.22730.18750.2344
0.21680.17140.23350.20430.23290.19340.2402
0.22270.17430.23560.20960.23820.19920.2461
0.22850.18650.24360.21540.24510.20510.2520

First 40 of 43 rows.

  • Window area 1; isotropic edge correction; global test over distances up to 0.25 from 99 uniform patterns.
The exact R script · R R version 4.5.1 (2025-06-13)
# Point patterns (Clark–Evans, Ripley's K and L envelopes)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.points 1.0.1 · spec bdfc18810b498cd7
# Dataset: sp_redwood (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/sp_redwood.parquet", col_select = c("x", "y")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x", "y")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("x", "y"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Point patterns against complete spatial randomness: Clark & Evans (1954) with Donnelly's (1978) correction, and
# Ripley's K (1977) and Besag's L with an envelope of uniform patterns from the shared random stream.
X <- "x"
Y <- "y"
test <- "ripley"  # ripley | clark_evans
coordinates <- "planar"  # planar | lonlat
n_sim <- as.integer(99)
alpha <- 0.05
seed <- 42
pr <- cs_spp_project(df[[X]], df[[Y]], coordinates)
px <- pr$x
py <- pr$y
n <- length(px)
wc <- cs_spp_project(c(0, 1), c(-1, 0), coordinates)
w <- cs_spp_window(px, py, "custom", wc$x[1], wc$x[2], wc$y[1], wc$y[2], names = c(X, Y))
intensity <- n / w$area
values <- list()
tables <- list()
charts <- list()
if (test == "clark_evans") {
  correction <- "donnelly"  # donnelly | none
  calibration <- "normal"  # normal | simulation
  alternative <- "two_sided"  # two_sided | less | greater
  res <- cs_spp_clark_evans(px, py, w, correction, calibration, alternative, n_sim, seed)
  statistic <- res$R
  p <- res$p
  test_label <- "Clark–Evans test"
  test_symbol <- "R"
  pattern <- if (statistic < 1) "The points are closer together than random points, a clustered pattern." else "The points are further apart than random points, a regular pattern."
  values <- c(values, list(z = res$z, p_analytic = res$p_analytic, mean_nn = res$mean_nn, expected_nn = res$expected_nn, se_nn = res$se_nn,
                           n_sim = if (calibration == "simulation") n_sim else 0L))
  detail <- sprintf("R = %.3f (mean nearest-neighbor distance %.4g, expected %.4g), %s", statistic, res$mean_nn, res$expected_nn, cs_fmt_p(p))
  statistics <- list(list(key = "statistic", label = "R", value = statistic), list(key = "z", label = "z", value = res$z), list(key = "p", label = "p", value = p, format = "p"),
                     list(key = "mean_nn", label = "Mean nearest-neighbor distance", value = res$mean_nn))
  how <- paste0(if (correction == "donnelly") "Donnelly's edge-corrected mean and standard error" else "no edge correction",
                if (calibration == "simulation") "; p from simulated random patterns" else "; normal approximation")
} else {
  correction <- "isotropic"  # isotropic | translation | none
  global_stat <- "mad"  # mad | dclf
  rmax <- NULL
  r <- cs_spp_r_grid(w, n, rmax, as.integer(129))
  res <- cs_spp_ripley_envelope(px, py, w, r, correction, global_stat, n_sim, alpha, seed)
  statistic <- res$T
  p <- res$p
  test_label <- "Ripley's L envelope test"
  test_symbol <- "T"
  pattern <- if (res$dev_at_max > 0) {
    sprintf("The largest gap is above randomness near distance %.3g: points cluster at that scale.", res$r_at_max)
  } else {
    sprintf("The largest gap is below randomness near distance %.3g: points keep apart at that scale.", res$r_at_max)
  }
  values <- c(values, list(T = res$T, band = res$band, r_max = r[length(r)], r_at_max = res$r_at_max, dev_at_max = res$dev_at_max,
                           L_at_rmax = res$L[length(r)], K_at_rmax = res$K[length(r)], n_sim = n_sim, level = res$level))
  detail <- if (global_stat == "mad") sprintf("largest |L(r) − r| = %.4g at distance %.3g, %s", res$T, res$r_at_max, cs_fmt_p(p)) else sprintf("integrated squared gap %.4g, %s", res$T, cs_fmt_p(p))
  statistics <- list(list(key = "statistic", label = "T", value = statistic), list(key = "p", label = "p", value = p, format = "p"),
                     list(key = "r_at_max", label = "Distance of largest gap", value = res$r_at_max))
  how <- sprintf("%s edge correction; global test over distances up to %.3g from %d uniform patterns", correction, r[length(r)], n_sim)
  step <- max(1L, length(r) %/% 33L)
  idx <- seq(1L, length(r), by = step)
  tables[[1]] <- list(key = "curve", title = "L(r) with its envelopes", columns = list(
    list(key = "r", label = "r", type = "number"), list(key = "K", label = "K(r)", type = "number"), list(key = "L", label = "L(r)", type = "number"),
    list(key = "lo", label = "Pointwise low", type = "number"), list(key = "hi", label = "Pointwise high", type = "number"),
    list(key = "lo_global", label = "Global low", type = "number"), list(key = "hi_global", label = "Global high", type = "number")),
    rows = lapply(idx, function(k) list(r = r[k], K = res$K[k], L = res$L[k], lo = res$lo[k], hi = res$hi[k], lo_global = res$lo_global[k], hi_global = res$hi_global[k])))
  charts[[1]] <- cs_chart("envelope", "ripley-envelope", sprintf("L(r) against %d random patterns", n_sim), list(
    r = cs_col("Distance r", r), L = cs_col("L(r)", res$L), lo = cs_col("Pointwise low", res$lo), hi = cs_col("Pointwise high", res$hi),
    lo_global = cs_col("Global low", res$lo_global), hi_global = cs_col("Global high", res$hi_global)), controls = list(alpha = alpha))
}
charts <- c(list(cs_chart("points", "scatter", sprintf("%d points", n), list(x = cs_col(X, as.numeric(df[[X]])), y = cs_col(Y, as.numeric(df[[Y]]))))), charts)

# %% Assumptions
custom_window <- TRUE
assumptions <- list(
  list(key = "window_known", label = "Observation window known", status = if (custom_window) "pass" else "info",
       detail = if (custom_window) {
         "The window is the rectangle you stated."
       } else {
         "The window is the points' bounding box, slightly too small, which makes patterns look more regular. State the searched rectangle if you know it."
       }),
  list(key = "homogeneous", label = "Constant intensity", status = "info",
       detail = "Density that varies across the window mimics clustering between points. These tests cannot tell the two apart."),
  list(key = "range_fixed", label = "Distances fixed in advance", status = "info",
       detail = if (test == "ripley") "Pointwise envelopes do not control error over the whole range; use the global test's p." else "Clark–Evans looks only at nearest neighbors, so it can miss a pattern at larger scales.")
)

# %% Result
verdict <- if (p < alpha) pattern else "The points are compatible with complete spatial randomness at this scale."
summary <- sprintf("%s for %d points: %s. %s", test_label, n, detail, verdict)
values <- c(values, list(statistic = statistic, p = p, n = n, area = w$area, intensity = intensity, missing_share = if (n_input > 0) n_dropped / n_input else 0,
                         test_label = test_label, test_symbol = test_symbol, pattern = pattern))
for (key in c("z", "p_analytic", "mean_nn", "expected_nn", "se_nn", "T", "band", "r_max", "r_at_max", "dev_at_max", "L_at_rmax", "K_at_rmax", "level")) if (is.null(values[[key]])) values[[key]] <- NA_real_  # only some options produce these
cs_publish(list(
  method = "spatial.points",
  methodVersion = "1.0.1",
  title = test_label,
  engine = cs_engine_info("stats"),
  n = n,
  summary = summary,
  apa = sprintf("%s = %.3g, %s, n = %d", test_symbol, statistic, cs_fmt_p(p), n),
  statistics = statistics,
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Window area %.4g; %s.", w$area, how)),
  values = values,
  charts = charts
))
Python

T = 0.0509, p = .010, n = 62

T
0.0509
p
.010
Distance of largest gap
0.0645

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Observation window known — The window is the rectangle you stated.
  • Constant intensity — Density that varies across the window mimics clustering between points. These tests cannot tell the two apart.
  • Distances fixed in advance — Pointwise envelopes do not control error over the whole range; use the global test's p.

L(r) with its envelopes

rK(r)L(r)Pointwise lowPointwise highGlobal lowGlobal high
00000−0.02340.0234
0.00590000.0183−0.01760.0293
0.01170000.0259−0.01170.0352
0.01760000.0290−0.00590.0410
0.02340.00480.038900.036200.0469
0.02930.01110.059500.03970.00590.0527
0.03520.01110.05950.01830.05130.01170.0586
0.04100.01530.06990.02300.05460.01760.0645
0.04690.02640.09170.02940.06520.02340.0703
0.05270.02640.09170.03670.06930.02930.0762
0.05860.03070.09880.04300.07790.03520.0820
0.06450.04180.11530.04920.08290.04100.0879
0.07030.04180.11530.05560.08800.04690.0938
0.07620.04710.12240.06270.09170.05270.0996
0.08200.04970.12580.06920.09500.05860.1055
0.08790.05710.13490.07410.10000.06450.1113
0.09380.06080.13920.07750.10670.07030.1172
0.09960.06080.13920.08170.11320.07620.1230
0.10550.07270.15220.08810.11940.08200.1289
0.11130.07610.15560.09520.12710.08790.1348
0.11720.08220.16180.10300.13290.09380.1406
0.12300.08890.16820.10630.13880.09960.1465
0.12890.10070.17910.11130.14420.10550.1523
0.13480.10340.18140.11730.15080.11130.1582
0.14060.10500.18280.12570.15500.11720.1641
0.14650.11640.19250.13320.16280.12300.1699
0.15230.12060.19600.13840.16790.12890.1758
0.15820.12240.19740.14350.17420.13480.1816
0.16410.12850.20220.14940.18050.14060.1875
0.16990.13190.20490.15540.18410.14650.1934
0.17580.13370.20630.16150.19110.15230.1992
0.18160.13880.21020.16970.19640.15820.2051
0.18750.14310.21340.17410.20340.16410.2109
0.19340.15170.21970.17830.21090.16990.2168
0.19920.15530.22230.18340.21630.17580.2227
0.20510.15860.22470.19080.22190.18160.2285
0.21090.16320.22790.19650.22730.18750.2344
0.21680.17140.23350.20430.23290.19340.2402
0.22270.17430.23560.20960.23820.19920.2461
0.22850.18650.24360.21540.24510.20510.2520

First 40 of 43 rows.

  • Window area 1; isotropic edge correction; global test over distances up to 0.25 from 99 uniform patterns.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Point patterns (Clark–Evans, Ripley's K and L envelopes)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.points 1.0.1 · spec bdfc18810b498cd7
# Dataset: sp_redwood (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import spatial_points as spp

# %% Data
df = pd.read_parquet("tests/parity/fixtures/sp_redwood.parquet", columns=["x", "y"])
n_input = len(df)
df = df.dropna(subset=["x", "y"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["x", "y"])  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Point patterns against complete spatial randomness: Clark & Evans (1954) with Donnelly's (1978) correction, and
# Ripley's K (1977) and Besag's L with an envelope of uniform patterns from the shared random stream.
X = "x"
Y = "y"
test = "ripley"  # ripley | clark_evans
coordinates = "planar"  # planar | lonlat
n_sim = int(99)
alpha = 0.05
seed = 42
px, py = spp.project(df[X].to_numpy(dtype=float), df[Y].to_numpy(dtype=float), coordinates)
n = px.size
wx0, wy0 = spp.project(np.array([0, 1]), np.array([-1, 0]), coordinates)
w = spp.window(px, py, "custom", wx0[0], wx0[1], wy0[0], wy0[1], names=(X, Y))
intensity = n / w["area"]
values = {}
tables = []
charts = []
statistics = []
if test == "clark_evans":
    correction = "donnelly"  # donnelly | none
    calibration = "normal"  # normal | simulation
    alternative = "two_sided"  # two_sided | less | greater
    res = spp.clark_evans(px, py, w, correction, calibration, alternative, n_sim, seed)
    statistic, p = res["R"], res["p"]
    test_label, test_symbol = "Clark–Evans test", "R"
    if statistic < 1:
        pattern = "The points are closer together than random points, a clustered pattern."
    else:
        pattern = "The points are further apart than random points, a regular pattern."
    values.update({"z": res["z"], "p_analytic": res["p_analytic"], "mean_nn": res["mean_nn"], "expected_nn": res["expected_nn"], "se_nn": res["se_nn"],
                   "n_sim": n_sim if calibration == "simulation" else 0})
    detail = f"R = {statistic:.3f} (mean nearest-neighbor distance {res['mean_nn']:.4g}, expected {res['expected_nn']:.4g}), {cs.fmt_p(p)}"
    statistics = [{"key": "statistic", "label": "R", "value": statistic}, {"key": "z", "label": "z", "value": res["z"]}, {"key": "p", "label": "p", "value": p, "format": "p"},
                  {"key": "mean_nn", "label": "Mean nearest-neighbor distance", "value": res["mean_nn"]}]
    how = ("Donnelly's edge-corrected mean and standard error" if correction == "donnelly" else "no edge correction") + ("; p from simulated random patterns" if calibration == "simulation" else "; normal approximation")
else:
    correction = "isotropic"  # isotropic | translation | none
    global_stat = "mad"  # mad | dclf
    rmax = None
    r = spp.r_grid(w, n, rmax, int(129))
    res = spp.ripley_envelope(px, py, w, r, correction, global_stat, n_sim, alpha, seed)
    statistic, p = res["T"], res["p"]
    test_label, test_symbol = "Ripley's L envelope test", "T"
    if res["dev_at_max"] > 0:
        pattern = f"The largest gap is above randomness near distance {res['r_at_max']:.3g}: points cluster at that scale."
    else:
        pattern = f"The largest gap is below randomness near distance {res['r_at_max']:.3g}: points keep apart at that scale."
    values.update({"T": res["T"], "band": res["band"], "r_max": float(r[-1]), "r_at_max": res["r_at_max"], "dev_at_max": res["dev_at_max"],
                   "L_at_rmax": float(res["L"][-1]), "K_at_rmax": float(res["K"][-1]), "n_sim": n_sim, "level": res["level"]})
    detail = f"largest |L(r) − r| = {res['T']:.4g} at distance {res['r_at_max']:.3g}, {cs.fmt_p(p)}" if global_stat == "mad" else f"integrated squared gap {res['T']:.4g}, {cs.fmt_p(p)}"
    statistics = [{"key": "statistic", "label": "T", "value": statistic}, {"key": "p", "label": "p", "value": p, "format": "p"},
                  {"key": "r_at_max", "label": "Distance of largest gap", "value": res["r_at_max"]}]
    how = f"{correction} edge correction; global test over distances up to {float(r[-1]):.3g} from {n_sim} uniform patterns"
    step = max(1, r.size // 33)
    idx = np.arange(0, r.size, step)
    tables.append({"key": "curve", "title": "L(r) with its envelopes", "columns": [
        {"key": "r", "label": "r", "type": "number"}, {"key": "K", "label": "K(r)", "type": "number"}, {"key": "L", "label": "L(r)", "type": "number"},
        {"key": "lo", "label": "Pointwise low", "type": "number"}, {"key": "hi", "label": "Pointwise high", "type": "number"},
        {"key": "lo_global", "label": "Global low", "type": "number"}, {"key": "hi_global", "label": "Global high", "type": "number"}],
        "rows": [{"r": float(r[k]), "K": float(res["K"][k]), "L": float(res["L"][k]), "lo": float(res["lo"][k]), "hi": float(res["hi"][k]),
                  "lo_global": float(res["lo_global"][k]), "hi_global": float(res["hi_global"][k])} for k in idx]})
    charts.append(cs.chart("envelope", "ripley-envelope", f"L(r) against {n_sim} random patterns", {
        "r": cs.col("Distance r", r), "L": cs.col("L(r)", res["L"]), "lo": cs.col("Pointwise low", res["lo"]), "hi": cs.col("Pointwise high", res["hi"]),
        "lo_global": cs.col("Global low", res["lo_global"]), "hi_global": cs.col("Global high", res["hi_global"])}, controls={"alpha": alpha}))
charts.insert(0, cs.chart("points", "scatter", f"{n} points", {"x": cs.col(X, df[X].to_numpy(dtype=float)), "y": cs.col(Y, df[Y].to_numpy(dtype=float))}))

# %% Assumptions
assumptions = [
    {"key": "window_known", "label": "Observation window known", "status": "pass" if True else "info",
     "detail": ("The window is the rectangle you stated." if True
                else "The window is the points' bounding box, slightly too small, which makes patterns look more regular. State the searched rectangle if you know it.")},
    {"key": "homogeneous", "label": "Constant intensity", "status": "info",
     "detail": "Density that varies across the window mimics clustering between points. These tests cannot tell the two apart."},
    {"key": "range_fixed", "label": "Distances fixed in advance", "status": "info",
     "detail": "Pointwise envelopes do not control error over the whole range; use the global test's p." if test == "ripley" else "Clark–Evans looks only at nearest neighbors, so it can miss a pattern at larger scales."},
]

# %% Result
if p < alpha:
    verdict = pattern
else:
    verdict = "The points are compatible with complete spatial randomness at this scale."
summary = f"{test_label} for {n} points: {detail}. {verdict}"
values.update({"statistic": statistic, "p": p, "n": n, "area": w["area"], "intensity": intensity, "missing_share": n_dropped / n_input if n_input else 0.0,
               "test_label": test_label, "test_symbol": test_symbol, "pattern": pattern})
for key in ["z", "p_analytic", "mean_nn", "expected_nn", "se_nn", "T", "band", "r_max", "r_at_max", "dev_at_max", "L_at_rmax", "K_at_rmax", "level"]:  # only some options produce these
    values.setdefault(key, None)
cs.publish({
    "method": "spatial.points",
    "methodVersion": "1.0.1",
    "title": test_label,
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"{test_symbol} = {statistic:.3g}, {cs.fmt_p(p)}, n = {n}",
    "statistics": statistics,
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Window area {w['area']:.4g}; {how}."],
    "values": values,
    "charts": charts,
})

With 99 simulations, the smallest possible p is 1/1001/100. On the random points, the same test gives p = .840.

07

Counting in a grid

Predict

Predict first

Quadrat countsQuadrat countsCounts in a grid of equal cells, compared with what random points would give. are the plain version: split the window into equal cells and compare counts with what's expected. The variance-to-mean ratio is near 1 under CSR.

Clustered points pile up in a few cells. Where does their ratio land?

Above 1About 1Below 1
Reveal

Above 1. Redwoods: ratio 2.82, p = .005.

Cells lean below 1: ratio 0.54, p = .170, with little evidence. The result depends on the grid, and a coarse grid can miss what Clark–Evans finds.

08

Choosing a test and a mechanism

Reflect

Crimes cluster in a city. But people cluster too: if the population isn't spread evenly, crimes would cluster without any contagion.

For a point pattern you know, what could make its intensity vary across the window? Would the CSR null answer the question you care about, or do you need a null that follows that intensity?

09

Check your understanding

Checkpoint

Check yourself

A Clark–Evans test gives R=0.6R = 0.6 with a small p-value. What does that suggest?

Show the answer

Answer: a

RR below 1 means nearest neighbors are closer than expected, so the pattern is clustered. Attraction is only one possible cause: varying intensity gives the same result.

Check yourself

Why use a global envelope rather than a pointwise one?

Show the answer

Answer: c

A global envelope controls the error over the whole range of rr. It needs a fixed range, chosen before you look.

Check yourself

A pattern has intensity λ=100\lambda = 100 points per unit area. What mean nearest-neighbor distance does 1/(2λ)1/(2\sqrt{\lambda}) give under CSR?

Show the answer

Answer: 0.05

1/(2100)=1/20=0.051/(2\sqrt{100}) = 1/20 = 0.05, before any edge correction.

Check yourself

A 4 × 4 grid of quadrats gives a chi-square test of equal counts. How many degrees of freedom does it have?

Show the answer

Answer: 15

16−1=1516 - 1 = 15: the number of cells minus one, because the total is fixed.

Check yourself

Quadrat counts give a variance-to-mean ratio well above 1. What does that suggest?

Show the answer

Answer: a

Under CSR the counts are close to Poisson, so the ratio is near 1. Above 1 means more variation than that, and below 1 means less.

Check yourself

You try 3 × 3, 4 × 4 and 5 × 5 grids, and only 4 × 4 is significant. What should you do?

Show the answer

Answer: b

The result depends on the grid. Trying several and reporting the best is shopping for a p-value, and Ripley's L doesn't need a grid at all.

10

Do it in CodeSplash

In the app

Pick Ripley's K and L with an envelope or Clark–Evans. Under Observation window, use a Stated rectangle if you know the study area: the bounding box of the points is smaller than the true window and makes them look more spread out.

This script reproduces the uncorrected ratio and Donnelly's expected distance, 0.0587.

Python
import numpy as np
import pandas as pd

d = pd.read_csv("sp_guide_points.csv").to_numpy()
n, area, perimeter = len(d), 1.0, 4.0

dist = np.linalg.norm(d[:, None] - d[None, :], axis=2)
np.fill_diagonal(dist, np.inf)
mean_nn = dist.min(axis=1).mean()

csr = 0.5 * np.sqrt(area / n)
donnelly = csr + (0.0514 + 0.041 / np.sqrt(n)) * perimeter / n
print(mean_nn / csr, donnelly, mean_nn / donnelly)
R
d <- as.matrix(read.csv("sp_guide_points.csv"))
n <- nrow(d); area <- 1; perimeter <- 4

dist <- as.matrix(dist(d))
diag(dist) <- Inf
mean_nn <- mean(apply(dist, 1, min))

csr <- 0.5 * sqrt(area / n)
donnelly <- csr + (0.0514 + 0.041 / sqrt(n)) * perimeter / n
c(mean_nn / csr, donnelly, mean_nn / donnelly)
11

Recap

Recap
  • Complete spatial randomness is the reference: equal chance everywhere, with independent points.
  • Clark–Evans looks at nearest neighbors; Ripley's L looks at every distance; quadrats count in a grid.
  • Correct for edges, and use a global envelope over a range you fixed in advance.
  • Clustering is compatible with attraction and with intensity that varies across the window.

Concepts in this lesson