{ "cells": [ { "cell_type": "markdown", "id": "c485e8fa", "metadata": {}, "source": [ "# Distance-based statistics in `pointpats`\n", "\n", "This notebook provides an introduction to the\n", "**distance-based statistics** available in `pointpats`, focusing on:\n", "\n", "- Ripley’s **G** (nearest-neighbor) function\n", "- Ripley’s **F** (empty-space) function\n", "- Ripley’s **K** and **L** functions (inter-event distances)\n", "- Simulation-based **envelopes** using `g_test` and `k_test`\n", "\n", "We will:\n", "\n", "1. Construct two toy point patterns in the unit square: one **CSR** (completely\n", " spatially random) and one **clustered**.\n", "2. Compare their distance-based statistics using the functional API:\n", " `f`, `g`, `k`, and `l`.\n", "3. Use `g_test` and `k_test` to generate Monte Carlo simulation envelopes\n", " under CSR and visualize departures from complete spatial randomness.\n", "\n", "This notebook is designed to live in the `docs/user-guide/` folder and be\n", "executed automatically as part of the `pointpats` documentation build.\n", "\n", "## 1. Setup and imports\n", "\n", "We work in the unit square `[0, 1] × [0, 1]` and simulate patterns using\n", "the random distributions in `pointpats.random`." ] }, { "cell_type": "code", "execution_count": null, "id": "5747bcbe", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "from pointpats import PointPattern, f, g, g_test, k, k_test, l, random\n", "\n", "# Make results reproducible\n", "np.random.seed(12345)\n", "\n", "# Unit square hull encoded as [xmin, ymin, xmax, ymax]\n", "hull = np.array([0.0, 0.0, 1.0, 1.0])\n", "hull" ] }, { "cell_type": "markdown", "id": "f74d9e8f", "metadata": {}, "source": [ "## 2. Constructing example point patterns\n", "\n", "We construct two patterns within the same hull:\n", "\n", "- a **CSR** pattern from a homogeneous Poisson process; and\n", "- a **clustered** pattern from a Poisson cluster process.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "3d12eeab", "metadata": {}, "outputs": [], "source": [ "n_points = 200\n", "\n", "# CSR pattern: homogeneous Poisson process in the hull\n", "coords_csr = random.poisson(hull, size=n_points)\n", "pp_csr = PointPattern(coords_csr)\n", "\n", "# Clustered pattern: Poisson cluster process\n", "coords_cluster = random.cluster_poisson(\n", " hull,\n", " size=n_points,\n", " n_seeds=5,\n", ")\n", "pp_cluster = PointPattern(coords_cluster)\n", "\n", "pp_csr.n, pp_cluster.n" ] }, { "cell_type": "markdown", "id": "c4241430", "metadata": {}, "source": [ "### Helper: plotting point patterns\n", "\n", "We will reuse a simple helper to visualize point patterns in their hull." ] }, { "cell_type": "code", "execution_count": null, "id": "a77ea131", "metadata": {}, "outputs": [], "source": [ "def plot_pattern(points, hull, ax=None, title=None):\n", " \"\"\"Plot a 2D point pattern inside a rectangular hull.\n", "\n", " Parameters\n", " ----------\n", " points : array-like of shape (n, 2)\n", " Point coordinates.\n", " hull : array-like of length 4\n", " Bounding box [xmin, ymin, xmax, ymax].\n", " ax : matplotlib.axes.Axes, optional\n", " Axis to plot on.\n", " title : str, optional\n", " Plot title.\n", " \"\"\"\n", " points = np.asarray(points)\n", "\n", " if ax is None:\n", " fig, ax = plt.subplots(figsize=(4, 4))\n", "\n", " xmin, ymin, xmax, ymax = hull\n", " ax.scatter(points[:, 0], points[:, 1], s=10, alpha=0.7)\n", " ax.set_xlim(xmin, xmax)\n", " ax.set_ylim(ymin, ymax)\n", " ax.set_aspect(\"equal\", adjustable=\"box\")\n", " ax.set_xlabel(\"x\")\n", " ax.set_ylabel(\"y\")\n", " if title:\n", " ax.set_title(title)\n", "\n", " return ax\n", "\n", "\n", "fig, axes = plt.subplots(1, 2, figsize=(8, 4))\n", "plot_pattern(coords_csr, hull, ax=axes[0], title=\"CSR (Poisson)\")\n", "plot_pattern(coords_cluster, hull, ax=axes[1], title=\"Clustered\")\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "b4dc3fc8", "metadata": {}, "source": [ "## 3. Distance-based summary functions: F, G, K, L\n", "\n", "`pointpats` provides a functional API for distance-based statistics.\n", "Each function takes `coordinates` and returns a pair `(support, values)`:\n", "\n", "```python\n", "support, G_vals = g(coordinates)\n", "support, F_vals = f(coordinates, hull=hull)\n", "support, K_vals = k(coordinates)\n", "support, L_vals = l(coordinates, linearized=True)\n", "```\n", "\n", "- **G(d)**: nearest-neighbor distribution from events to events.\n", "- **F(d)**: empty-space function from random locations to events\n", " (requires a hull when distances are not precomputed).\n", "- **K(d)**: cumulative inter-event distance function.\n", "- **L(d)**: scaled and shifted version of K; for CSR, linearized L\n", " should be close to zero across distances." ] }, { "cell_type": "code", "execution_count": null, "id": "f494e7bc", "metadata": {}, "outputs": [], "source": [ "# G: nearest-neighbor distribution\n", "support_g_csr, G_csr = g(coords_csr)\n", "support_g_cluster, G_cluster = g(coords_cluster)\n", "\n", "# F: empty-space function (needs hull when distances=None)\n", "support_f_csr, F_csr = f(coords_csr, hull=hull)\n", "support_f_cluster, F_cluster = f(coords_cluster, hull=hull)\n", "\n", "# K: inter-event distance function\n", "support_k_csr, K_csr = k(coords_csr)\n", "support_k_cluster, K_cluster = k(coords_cluster)\n", "\n", "# L: linearized version of K\n", "support_l_csr, L_csr = l(coords_csr, linearized=True)\n", "support_l_cluster, L_cluster = l(coords_cluster, linearized=True)\n", "\n", "(support_g_csr.shape, support_k_csr.shape)" ] }, { "cell_type": "markdown", "id": "c7ba6b75", "metadata": {}, "source": [ "### 3.1 Comparing G and F\n", "\n", "We first compare the G and F functions for the CSR and clustered patterns.\n", "Clustering tends to increase the probability of short distances, which is\n", "reflected differently in G and F." ] }, { "cell_type": "code", "execution_count": null, "id": "bfdad630", "metadata": {}, "outputs": [], "source": [ "fig, axes = plt.subplots(1, 2, figsize=(10, 4))\n", "\n", "# G function\n", "ax = axes[0]\n", "ax.plot(support_g_csr, G_csr, label=\"CSR\", lw=2)\n", "ax.plot(support_g_cluster, G_cluster, label=\"Clustered\", lw=2)\n", "ax.set_xlabel(\"distance\")\n", "ax.set_ylabel(\"G(d)\")\n", "ax.set_title(\"Ripley's G function\")\n", "ax.legend()\n", "\n", "# F function\n", "ax = axes[1]\n", "ax.plot(support_f_csr, F_csr, label=\"CSR\", lw=2)\n", "ax.plot(support_f_cluster, F_cluster, label=\"Clustered\", lw=2)\n", "ax.set_xlabel(\"distance\")\n", "ax.set_ylabel(\"F(d)\")\n", "ax.set_title(\"Ripley's F function\")\n", "ax.legend()\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "a4e52fb0", "metadata": {}, "source": [ "### 3.2 Comparing K and L\n", "\n", "Under complete spatial randomness (CSR) with intensity `lambda`, we expect:\n", "\n", "- `K(d)` to grow like `pi * d^2`.\n", "- `L(d)` (linearized) to be close to zero.\n", "\n", "Departures above zero in L suggest clustering, while departures below zero\n", "suggest inhibition (regularity)." ] }, { "cell_type": "code", "execution_count": null, "id": "fdea0ce1", "metadata": {}, "outputs": [], "source": [ "fig, axes = plt.subplots(1, 2, figsize=(10, 4))\n", "\n", "# K function\n", "ax = axes[0]\n", "ax.plot(support_k_csr, K_csr, label=\"CSR\", lw=2)\n", "ax.plot(support_k_cluster, K_cluster, label=\"Clustered\", lw=2)\n", "ax.set_xlabel(\"distance\")\n", "ax.set_ylabel(\"K(d)\")\n", "ax.set_title(\"Ripley's K function\")\n", "ax.legend()\n", "\n", "# L function\n", "ax = axes[1]\n", "ax.axhline(0.0, color=\"k\", ls=\"--\", lw=1, label=\"CSR expectation\")\n", "ax.plot(support_l_csr, L_csr, label=\"CSR\", lw=2)\n", "ax.plot(support_l_cluster, L_cluster, label=\"Clustered\", lw=2)\n", "ax.set_xlabel(\"distance\")\n", "ax.set_ylabel(\"L(d)\")\n", "ax.set_title(\"Ripley's L function (linearized)\")\n", "ax.legend()\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "5c171ed7", "metadata": {}, "source": [ "## 4. Simulation envelopes with `g_test` and `k_test`\n", "\n", "The functional API (`f`, `g`, `k`, `l`) gives a single curve for a given\n", "pattern. To assess whether this curve is consistent with CSR, `pointpats`\n", "provides test functions like `g_test` and `k_test` that:\n", "\n", "1. Simulate many CSR patterns in the same hull.\n", "2. Compute the statistic for each simulation.\n", "3. Return the observed statistic, the simulated statistics, and Monte Carlo\n", " p-values at each distance.\n", "\n", "We will apply `g_test` and `k_test` to the **clustered** pattern and visualize\n", "the simulation envelopes." ] }, { "cell_type": "code", "execution_count": null, "id": "d74a1211", "metadata": {}, "outputs": [], "source": [ "n_sims = 199\n", "\n", "g_cluster = g_test(\n", " coords_cluster,\n", " hull=hull,\n", " keep_simulations=True,\n", " n_simulations=n_sims,\n", ")\n", "\n", "k_cluster = k_test(\n", " coords_cluster,\n", " hull=hull,\n", " keep_simulations=True,\n", " n_simulations=n_sims,\n", ")\n", "\n", "g_cluster.support.shape, g_cluster.simulations.shape, k_cluster.simulations.shape" ] }, { "cell_type": "markdown", "id": "6c4128d8", "metadata": {}, "source": [ "### Helper: plotting simulation envelopes\n", "\n", "We define a small helper that takes a test result and produces a two-panel\n", "plot showing:\n", "\n", "- the observed function and a simulation envelope; and\n", "- the point pattern used in the test." ] }, { "cell_type": "code", "execution_count": null, "id": "fcc769bd", "metadata": {}, "outputs": [], "source": [ "def plot_envelope(test_result, coordinates, name=\"G\"):\n", " \"\"\"Plot simulation envelopes and the observed distance function.\n", "\n", " Parameters\n", " ----------\n", " test_result : namedtuple\n", " Result from g_test, k_test, etc. Must have attributes\n", " `support`, `statistic`, and `simulations`.\n", " coordinates : array-like of shape (n, 2)\n", " The point pattern being tested.\n", " name : str, default \"G\"\n", " Name of the statistic, used for labels and titles.\n", " \"\"\"\n", " support = test_result.support\n", " observed = test_result.statistic\n", " sims = test_result.simulations\n", "\n", " fig, axes = plt.subplots(\n", " 1,\n", " 2,\n", " figsize=(10, 3),\n", " gridspec_kw={\"width_ratios\": (2, 1)},\n", " )\n", "\n", " # Left: simulation envelope + observed\n", " ax = axes[0]\n", "\n", " # All simulations as faint lines\n", " ax.plot(support, sims.T, color=\"0.8\", alpha=0.1)\n", "\n", " # 95% envelope\n", " lower = np.percentile(sims, 2.5, axis=0)\n", " upper = np.percentile(sims, 97.5, axis=0)\n", " ax.fill_between(\n", " support,\n", " lower,\n", " upper,\n", " color=\"0.9\",\n", " alpha=0.7,\n", " label=\"95% envelope\",\n", " )\n", "\n", " # Observed\n", " ax.plot(support, observed, lw=2, label=\"observed\")\n", "\n", " ax.set_xlabel(\"distance\")\n", " ax.set_ylabel(f\"{name}(d)\")\n", " ax.set_title(f\"Ripley's {name} with CSR envelope\")\n", " ax.legend()\n", "\n", " # Right: the pattern itself\n", " ax = axes[1]\n", " coords = np.asarray(coordinates)\n", " ax.scatter(coords[:, 0], coords[:, 1], s=10, alpha=0.7)\n", " xmin, ymin, xmax, ymax = hull\n", " ax.set_xlim(xmin, xmax)\n", " ax.set_ylim(ymin, ymax)\n", " ax.set_xticks([])\n", " ax.set_yticks([])\n", " ax.set_aspect(\"equal\", adjustable=\"box\")\n", " ax.set_title(\"Pattern\")\n", "\n", " fig.tight_layout()\n", " plt.show()\n", "\n", "\n", "plot_envelope(g_cluster, coords_cluster, name=\"G\")" ] }, { "cell_type": "code", "execution_count": null, "id": "0caf89eb", "metadata": {}, "outputs": [], "source": [ "plot_envelope(k_cluster, coords_cluster, name=\"K\")" ] }, { "cell_type": "markdown", "id": "8039d778", "metadata": {}, "source": [ "In these plots, departures of the observed curve outside the simulation\n", "envelope indicate scales (distances) where the clustered pattern is unlikely\n", "to have arisen under CSR.\n", "\n", "For example, if the observed G curve lies above the envelope at short\n", "distances, that suggests an excess of close neighbors, consistent with\n", "clustering. If it lies below, that suggests inhibition or regular spacing.\n", "\n", "## 5. Recap\n", "\n", "In this notebook, we have:\n", "\n", "- Constructed **CSR** and **clustered** point patterns in a simple\n", " rectangular window.\n", "- Used the functional API (`f`, `g`, `k`, `l`) to compute distance-based\n", " statistics directly from coordinate arrays.\n", "- Compared how **G**, **F**, **K**, and **L** respond to CSR vs clustering.\n", "- Used `g_test` and `k_test` to generate **simulation envelopes** under CSR\n", " and visualize departures from complete spatial randomness.\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.3" } }, "nbformat": 4, "nbformat_minor": 5 }