mal_commonlib.data.mobility
Gravity-model mobility OD matrix builder + CSR binary writer.
Builds row-stochastic sparse origin-destination matrices for the ABM engine using a gravity model: P(i->j) ∝ H(j) * exp(-β * d(i,j)).
The output is a binary CSR file compatible with the C++
SparseOD::load_from_csr() reader in mobility_schedule.hpp.
1"""Gravity-model mobility OD matrix builder + CSR binary writer. 2 3Builds row-stochastic sparse origin-destination matrices for the ABM 4engine using a gravity model: P(i->j) ∝ H(j) * exp(-β * d(i,j)). 5 6The output is a binary CSR file compatible with the C++ 7``SparseOD::load_from_csr()`` reader in mobility_schedule.hpp. 8""" 9from __future__ import annotations 10 11import pathlib 12 13import numpy as np 14from scipy.signal import fftconvolve 15 16 17# --------------------------------------------------------------------------- 18# Gravity model 19# --------------------------------------------------------------------------- 20 21def build_gravity_od( 22 attractiveness: np.ndarray, 23 cell_size_km: float, 24 beta: float, 25 max_distance_km: float = 50.0, 26 sparsity_threshold: float = 5e-4, 27) -> tuple[np.ndarray, np.ndarray, np.ndarray, int, int]: 28 """Build a row-stochastic sparse OD matrix from a gravity model. 29 30 For each origin cell i the probability of moving to destination cell j is:: 31 32 P(i->j) ∝ H(j) × exp(-β × d(i,j)) 33 34 where H(j) is the attractiveness of j and d(i,j) is the Euclidean 35 distance between cell centres in km. 36 37 Rows are normalised so that Σ_j P(i->j) = 1, then entries with 38 P < *sparsity_threshold* are dropped and the kept entries are 39 renormalised so each row sums to 1.0 again (the C++ reader 40 validates row sums within ±0.01). 41 42 Implementation: the grid is regular, so d(i,j) depends only on the 43 offset (Δr, Δc). Row sums are computed with one FFT convolution and 44 entries are enumerated offset-by-offset with vectorised numpy ops — 45 O(K·N) with K = number of offsets inside the distance disk. No dense 46 N×N matrix is ever materialised; peak memory is O(nnz + N). 47 48 Args: 49 attractiveness: (H, W) array — destination attractiveness 50 (e.g. population for humans, livestock count for animals). 51 Negative / non-finite values (nodata) are treated as 0. 52 cell_size_km: side length of each grid cell in km. 53 beta: friction parameter — higher values keep people closer to home. 54 max_distance_km: hard distance cutoff; cells beyond this are excluded. 55 sparsity_threshold: minimum normalised probability to keep an entry. 56 57 Returns: 58 ``(row_ptr, col_idx, values, n_rows, n_cols)`` — CSR arrays where 59 each row sums to ~1.0, compatible with ``SparseOD::load_from_csr()``. 60 """ 61 grid = np.asarray(attractiveness, dtype=np.float64) 62 if grid.ndim != 2: 63 raise ValueError(f"attractiveness must be 2D, got shape {grid.shape}") 64 n_rows_grid, n_cols_grid = grid.shape 65 n_cells = n_rows_grid * n_cols_grid 66 67 grid = np.where(np.isfinite(grid) & (grid > 0.0), grid, 0.0) 68 69 # --- Distance kernel over the offset disk ------------------------------ 70 radius_cells = int(max_distance_km // cell_size_km) 71 ax = np.arange(-radius_cells, radius_cells + 1) 72 dr_2d, dc_2d = np.meshgrid(ax, ax, indexing="ij") 73 dist = np.hypot(dr_2d, dc_2d) * cell_size_km 74 in_disk = dist <= max_distance_km 75 kernel = np.exp(-beta * dist) 76 kernel[~in_disk] = 0.0 77 78 offsets = np.argwhere(in_disk) - radius_cells # (K, 2) rows of (dr, dc) 79 kern_vals = kernel[in_disk] 80 81 # --- Row sums over all pairs within the disk (symmetric kernel) -------- 82 row_sums = fftconvolve(grid, kernel, mode="same") 83 84 # --- Pass 1: per-row kept-entry counts + kept probability mass --------- 85 counts = np.zeros((n_rows_grid, n_cols_grid), dtype=np.int64) 86 kept_mass = np.zeros((n_rows_grid, n_cols_grid), dtype=np.float64) 87 88 for (a, b), k in zip(offsets, kern_vals): 89 r0, r1 = max(0, -a), n_rows_grid - max(0, a) 90 c0, c1 = max(0, -b), n_cols_grid - max(0, b) 91 if r0 >= r1 or c0 >= c1: 92 continue # offset larger than the grid itself 93 dest = grid[r0 + a:r1 + a, c0 + b:c1 + b] 94 rs = row_sums[r0:r1, c0:c1] 95 p = (k * dest) / np.where(rs > 0.0, rs, 1.0) 96 m = p > 0.0 if sparsity_threshold <= 0.0 else p >= sparsity_threshold 97 counts[r0:r1, c0:c1] += m 98 kept_mass[r0:r1, c0:c1] += np.where(m, p, 0.0) 99 100 # --- Row pointers; empty rows get an identity (stay-home) entry -------- 101 counts_flat = counts.ravel().copy() 102 empty = counts_flat == 0 103 counts_flat[empty] = 1 104 105 nnz = int(counts_flat.sum()) 106 row_ptr = np.empty(n_cells + 1, dtype=np.int32) 107 row_ptr[0] = 0 108 np.cumsum(counts_flat, dtype=np.int32, out=row_ptr[1:]) 109 110 # --- Pass 2: fill col_idx / values (recompute masks, no big temporaries) 111 col_idx = np.empty(nnz, dtype=np.int32) 112 values = np.empty(nnz, dtype=np.float32) 113 cursor = row_ptr[:-1].astype(np.int64) 114 kept_flat = kept_mass.ravel() 115 116 if empty.any(): 117 eidx = np.flatnonzero(empty) 118 pos = cursor[eidx] 119 col_idx[pos] = eidx.astype(np.int32) 120 values[pos] = 1.0 121 cursor[eidx] += 1 122 123 for (a, b), k in zip(offsets, kern_vals): 124 r0, r1 = max(0, -a), n_rows_grid - max(0, a) 125 c0, c1 = max(0, -b), n_cols_grid - max(0, b) 126 if r0 >= r1 or c0 >= c1: 127 continue # offset larger than the grid itself 128 width = c1 - c0 129 dest = grid[r0 + a:r1 + a, c0 + b:c1 + b] 130 rs = row_sums[r0:r1, c0:c1] 131 p = (k * dest) / np.where(rs > 0.0, rs, 1.0) 132 m = p > 0.0 if sparsity_threshold <= 0.0 else p >= sparsity_threshold 133 loc = np.flatnonzero(m.ravel()) 134 if loc.size == 0: 135 continue 136 lr, lc = np.divmod(loc, width) 137 origin = (r0 + lr) * n_cols_grid + (c0 + lc) 138 pos = cursor[origin] 139 col_idx[pos] = ((r0 + a + lr) * n_cols_grid + (c0 + b + lc)).astype(np.int32) 140 values[pos] = (p.ravel()[loc] / kept_flat[origin]).astype(np.float32) 141 cursor[origin] += 1 142 143 if not np.array_equal(cursor, row_ptr[1:].astype(np.int64)): 144 raise RuntimeError("build_gravity_od: CSR fill cursor mismatch") 145 146 return row_ptr, col_idx, values, n_cells, n_cells 147 148 149def build_identity_od(n_cells: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, int, int]: 150 """Build an identity OD matrix (everyone stays home).""" 151 row_ptr = np.arange(n_cells + 1, dtype=np.int32) 152 col_idx = np.arange(n_cells, dtype=np.int32) 153 values = np.ones(n_cells, dtype=np.float32) 154 return row_ptr, col_idx, values, n_cells, n_cells 155 156 157# --------------------------------------------------------------------------- 158# CSR binary writer 159# --------------------------------------------------------------------------- 160 161def write_csr( 162 row_ptr: np.ndarray, 163 col_idx: np.ndarray, 164 values: np.ndarray, 165 n_rows: int, 166 n_cols: int, 167 path: pathlib.Path, 168) -> pathlib.Path: 169 """Write a sparse OD matrix in CSR binary format. 170 171 Format (all little-endian, matching ``SparseOD::load_from_csr``):: 172 173 [int32] n_rows 174 [int32] n_cols 175 [int32] nnz 176 [int32 × (n_rows+1)] row_ptr 177 [int32 × nnz] col_idx 178 [float32 × nnz] values 179 180 Returns: 181 The path that was written. 182 """ 183 path.parent.mkdir(parents=True, exist_ok=True) 184 nnz = col_idx.shape[0] 185 186 with open(path, "wb") as f: 187 f.write(np.int32(n_rows).tobytes()) 188 f.write(np.int32(n_cols).tobytes()) 189 f.write(np.int32(nnz).tobytes()) 190 f.write(row_ptr.astype(np.int32).tobytes()) 191 f.write(col_idx.astype(np.int32).tobytes()) 192 f.write(values.astype(np.float32).tobytes()) 193 194 return path
22def build_gravity_od( 23 attractiveness: np.ndarray, 24 cell_size_km: float, 25 beta: float, 26 max_distance_km: float = 50.0, 27 sparsity_threshold: float = 5e-4, 28) -> tuple[np.ndarray, np.ndarray, np.ndarray, int, int]: 29 """Build a row-stochastic sparse OD matrix from a gravity model. 30 31 For each origin cell i the probability of moving to destination cell j is:: 32 33 P(i->j) ∝ H(j) × exp(-β × d(i,j)) 34 35 where H(j) is the attractiveness of j and d(i,j) is the Euclidean 36 distance between cell centres in km. 37 38 Rows are normalised so that Σ_j P(i->j) = 1, then entries with 39 P < *sparsity_threshold* are dropped and the kept entries are 40 renormalised so each row sums to 1.0 again (the C++ reader 41 validates row sums within ±0.01). 42 43 Implementation: the grid is regular, so d(i,j) depends only on the 44 offset (Δr, Δc). Row sums are computed with one FFT convolution and 45 entries are enumerated offset-by-offset with vectorised numpy ops — 46 O(K·N) with K = number of offsets inside the distance disk. No dense 47 N×N matrix is ever materialised; peak memory is O(nnz + N). 48 49 Args: 50 attractiveness: (H, W) array — destination attractiveness 51 (e.g. population for humans, livestock count for animals). 52 Negative / non-finite values (nodata) are treated as 0. 53 cell_size_km: side length of each grid cell in km. 54 beta: friction parameter — higher values keep people closer to home. 55 max_distance_km: hard distance cutoff; cells beyond this are excluded. 56 sparsity_threshold: minimum normalised probability to keep an entry. 57 58 Returns: 59 ``(row_ptr, col_idx, values, n_rows, n_cols)`` — CSR arrays where 60 each row sums to ~1.0, compatible with ``SparseOD::load_from_csr()``. 61 """ 62 grid = np.asarray(attractiveness, dtype=np.float64) 63 if grid.ndim != 2: 64 raise ValueError(f"attractiveness must be 2D, got shape {grid.shape}") 65 n_rows_grid, n_cols_grid = grid.shape 66 n_cells = n_rows_grid * n_cols_grid 67 68 grid = np.where(np.isfinite(grid) & (grid > 0.0), grid, 0.0) 69 70 # --- Distance kernel over the offset disk ------------------------------ 71 radius_cells = int(max_distance_km // cell_size_km) 72 ax = np.arange(-radius_cells, radius_cells + 1) 73 dr_2d, dc_2d = np.meshgrid(ax, ax, indexing="ij") 74 dist = np.hypot(dr_2d, dc_2d) * cell_size_km 75 in_disk = dist <= max_distance_km 76 kernel = np.exp(-beta * dist) 77 kernel[~in_disk] = 0.0 78 79 offsets = np.argwhere(in_disk) - radius_cells # (K, 2) rows of (dr, dc) 80 kern_vals = kernel[in_disk] 81 82 # --- Row sums over all pairs within the disk (symmetric kernel) -------- 83 row_sums = fftconvolve(grid, kernel, mode="same") 84 85 # --- Pass 1: per-row kept-entry counts + kept probability mass --------- 86 counts = np.zeros((n_rows_grid, n_cols_grid), dtype=np.int64) 87 kept_mass = np.zeros((n_rows_grid, n_cols_grid), dtype=np.float64) 88 89 for (a, b), k in zip(offsets, kern_vals): 90 r0, r1 = max(0, -a), n_rows_grid - max(0, a) 91 c0, c1 = max(0, -b), n_cols_grid - max(0, b) 92 if r0 >= r1 or c0 >= c1: 93 continue # offset larger than the grid itself 94 dest = grid[r0 + a:r1 + a, c0 + b:c1 + b] 95 rs = row_sums[r0:r1, c0:c1] 96 p = (k * dest) / np.where(rs > 0.0, rs, 1.0) 97 m = p > 0.0 if sparsity_threshold <= 0.0 else p >= sparsity_threshold 98 counts[r0:r1, c0:c1] += m 99 kept_mass[r0:r1, c0:c1] += np.where(m, p, 0.0) 100 101 # --- Row pointers; empty rows get an identity (stay-home) entry -------- 102 counts_flat = counts.ravel().copy() 103 empty = counts_flat == 0 104 counts_flat[empty] = 1 105 106 nnz = int(counts_flat.sum()) 107 row_ptr = np.empty(n_cells + 1, dtype=np.int32) 108 row_ptr[0] = 0 109 np.cumsum(counts_flat, dtype=np.int32, out=row_ptr[1:]) 110 111 # --- Pass 2: fill col_idx / values (recompute masks, no big temporaries) 112 col_idx = np.empty(nnz, dtype=np.int32) 113 values = np.empty(nnz, dtype=np.float32) 114 cursor = row_ptr[:-1].astype(np.int64) 115 kept_flat = kept_mass.ravel() 116 117 if empty.any(): 118 eidx = np.flatnonzero(empty) 119 pos = cursor[eidx] 120 col_idx[pos] = eidx.astype(np.int32) 121 values[pos] = 1.0 122 cursor[eidx] += 1 123 124 for (a, b), k in zip(offsets, kern_vals): 125 r0, r1 = max(0, -a), n_rows_grid - max(0, a) 126 c0, c1 = max(0, -b), n_cols_grid - max(0, b) 127 if r0 >= r1 or c0 >= c1: 128 continue # offset larger than the grid itself 129 width = c1 - c0 130 dest = grid[r0 + a:r1 + a, c0 + b:c1 + b] 131 rs = row_sums[r0:r1, c0:c1] 132 p = (k * dest) / np.where(rs > 0.0, rs, 1.0) 133 m = p > 0.0 if sparsity_threshold <= 0.0 else p >= sparsity_threshold 134 loc = np.flatnonzero(m.ravel()) 135 if loc.size == 0: 136 continue 137 lr, lc = np.divmod(loc, width) 138 origin = (r0 + lr) * n_cols_grid + (c0 + lc) 139 pos = cursor[origin] 140 col_idx[pos] = ((r0 + a + lr) * n_cols_grid + (c0 + b + lc)).astype(np.int32) 141 values[pos] = (p.ravel()[loc] / kept_flat[origin]).astype(np.float32) 142 cursor[origin] += 1 143 144 if not np.array_equal(cursor, row_ptr[1:].astype(np.int64)): 145 raise RuntimeError("build_gravity_od: CSR fill cursor mismatch") 146 147 return row_ptr, col_idx, values, n_cells, n_cells
Build a row-stochastic sparse OD matrix from a gravity model.
For each origin cell i the probability of moving to destination cell j is::
P(i->j) ∝ H(j) × exp(-β × d(i,j))
where H(j) is the attractiveness of j and d(i,j) is the Euclidean distance between cell centres in km.
Rows are normalised so that Σ_j P(i->j) = 1, then entries with P < sparsity_threshold are dropped and the kept entries are renormalised so each row sums to 1.0 again (the C++ reader validates row sums within ±0.01).
Implementation: the grid is regular, so d(i,j) depends only on the offset (Δr, Δc). Row sums are computed with one FFT convolution and entries are enumerated offset-by-offset with vectorised numpy ops — O(K·N) with K = number of offsets inside the distance disk. No dense N×N matrix is ever materialised; peak memory is O(nnz + N).
Args: attractiveness: (H, W) array — destination attractiveness (e.g. population for humans, livestock count for animals). Negative / non-finite values (nodata) are treated as 0. cell_size_km: side length of each grid cell in km. beta: friction parameter — higher values keep people closer to home. max_distance_km: hard distance cutoff; cells beyond this are excluded. sparsity_threshold: minimum normalised probability to keep an entry.
Returns:
(row_ptr, col_idx, values, n_rows, n_cols) — CSR arrays where
each row sums to ~1.0, compatible with SparseOD::load_from_csr().
150def build_identity_od(n_cells: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, int, int]: 151 """Build an identity OD matrix (everyone stays home).""" 152 row_ptr = np.arange(n_cells + 1, dtype=np.int32) 153 col_idx = np.arange(n_cells, dtype=np.int32) 154 values = np.ones(n_cells, dtype=np.float32) 155 return row_ptr, col_idx, values, n_cells, n_cells
Build an identity OD matrix (everyone stays home).
162def write_csr( 163 row_ptr: np.ndarray, 164 col_idx: np.ndarray, 165 values: np.ndarray, 166 n_rows: int, 167 n_cols: int, 168 path: pathlib.Path, 169) -> pathlib.Path: 170 """Write a sparse OD matrix in CSR binary format. 171 172 Format (all little-endian, matching ``SparseOD::load_from_csr``):: 173 174 [int32] n_rows 175 [int32] n_cols 176 [int32] nnz 177 [int32 × (n_rows+1)] row_ptr 178 [int32 × nnz] col_idx 179 [float32 × nnz] values 180 181 Returns: 182 The path that was written. 183 """ 184 path.parent.mkdir(parents=True, exist_ok=True) 185 nnz = col_idx.shape[0] 186 187 with open(path, "wb") as f: 188 f.write(np.int32(n_rows).tobytes()) 189 f.write(np.int32(n_cols).tobytes()) 190 f.write(np.int32(nnz).tobytes()) 191 f.write(row_ptr.astype(np.int32).tobytes()) 192 f.write(col_idx.astype(np.int32).tobytes()) 193 f.write(values.astype(np.float32).tobytes()) 194 195 return path
Write a sparse OD matrix in CSR binary format.
Format (all little-endian, matching SparseOD::load_from_csr)::
[int32] n_rows
[int32] n_cols
[int32] nnz
[int32 × (n_rows+1)] row_ptr
[int32 × nnz] col_idx
[float32 × nnz] values
Returns: The path that was written.