quakecascade 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,55 @@
1
+ """Earthquake scenario cascades for cities.
2
+
3
+ Ground motion -> building damage -> casualties and shelter -> liquefaction ->
4
+ debris reach and street closure -> post-event network access -> allocation and
5
+ ranking, on open or municipal inventories.
6
+ """
7
+
8
+ __version__ = "0.1.0"
9
+
10
+ from . import (
11
+ access,
12
+ allocate,
13
+ cascade,
14
+ contract,
15
+ crs,
16
+ datasets,
17
+ debris,
18
+ fragility,
19
+ groundmotion,
20
+ hydro,
21
+ impact,
22
+ lifelines,
23
+ liquefaction,
24
+ mcda,
25
+ montecarlo,
26
+ network,
27
+ )
28
+ from .groundmotion import FaultGeometry
29
+ from .mcda import topsis
30
+ from .network import RoadNetwork, speed_by_class, tobler_walk_speed
31
+
32
+ __all__ = [
33
+ "FaultGeometry",
34
+ "RoadNetwork",
35
+ "__version__",
36
+ "access",
37
+ "allocate",
38
+ "cascade",
39
+ "contract",
40
+ "crs",
41
+ "datasets",
42
+ "debris",
43
+ "fragility",
44
+ "groundmotion",
45
+ "hydro",
46
+ "impact",
47
+ "lifelines",
48
+ "liquefaction",
49
+ "mcda",
50
+ "montecarlo",
51
+ "network",
52
+ "speed_by_class",
53
+ "tobler_walk_speed",
54
+ "topsis",
55
+ ]
@@ -0,0 +1,32 @@
1
+ """Optional-dependency flags shared by the kernels."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+
6
+ try: # SciPy is a declared dependency, but every kernel keeps a pure-NumPy path.
7
+ from scipy.sparse import csgraph as _csgraph # noqa: F401
8
+ from scipy.sparse import csr_matrix as _csr_matrix # noqa: F401
9
+ HAS_SCIPY = True
10
+ # A broken SciPy build (ABI mismatch, missing DLL) raises more than ImportError;
11
+ # it must not break importing the package, so the catch is deliberately broad.
12
+ except Exception: # noqa: BLE001 # pragma: no cover - depends on host install
13
+ HAS_SCIPY = False
14
+
15
+ # QUAKECASCADE_FORCE_NUMPY=1 runs every kernel on its pure-NumPy path (used in CI
16
+ # to keep the fallback tested).
17
+ if os.environ.get("QUAKECASCADE_FORCE_NUMPY", "").strip() in ("1", "true", "yes"):
18
+ HAS_SCIPY = False
19
+
20
+
21
+ class Cancelled(Exception):
22
+ """Raised by a long kernel when its ``cancel()`` callback returns True.
23
+
24
+ ``partial`` carries whatever had been computed; it is never a finished result.
25
+ """
26
+
27
+ def __init__(self, partial=None, message: str = "cancelled"):
28
+ super().__init__(message)
29
+ self.partial = partial
30
+
31
+
32
+ __all__ = ["HAS_SCIPY", "Cancelled"]
quakecascade/access.py ADDED
@@ -0,0 +1,466 @@
1
+ """Place-based accessibility and post-event isolation.
2
+
3
+ Decay functions, Hansen potential and the two-step floating catchment area
4
+ (2SFCA) are ported from the PlanX engine (``engine/accessibility.py``, same
5
+ author); the cost-matrix layout of the public wrappers follows
6
+ :meth:`quakecascade.network.RoadNetwork.travel_time_matrix`: rows are demand
7
+ units (origins), columns are facilities.
8
+
9
+ * Cumulative opportunities (Wachs & Kumagai 1973).
10
+ * Gravity potential (Hansen 1959): $A_i = \\sum_j S_j f(c_{ij})$.
11
+ * 2SFCA (Radke & Mu 2000; Luo & Wang 2003) with a decayed catchment
12
+ (Luo & Qi 2009): $R_j = S_j / \\sum_k P_k f(c_{kj})$,
13
+ $A_i = \\sum_j R_j f(c_{ij})$.
14
+
15
+ The isolation status compares access before and after an event (closed roads)
16
+ for each unit: newly cut off, worse, same, improved or always cut off.
17
+
18
+ Decay kinds (``c`` cost, ``T`` threshold/cutoff, ``p`` the kind's parameter):
19
+
20
+ ============== ===================================== =============================
21
+ cumulative 1 if c <= T Wachs & Kumagai 1973
22
+ linear max(0, 1 - c/T) cone (Luo & Qi 2009)
23
+ exponential exp(-p c) p = beta per cost unit
24
+ gaussian (exp(-c^2/(2T^2)) - e^-1/2)/(1-e^-1/2) Dai 2010, Eq. 2; no p
25
+ gaussian_sigma exp(-c^2 / (2 p^2)) p = sigma (Kwan 1998)
26
+ power min(1, c^-p) p = beta; c < 1 reads as 1
27
+ logistic 1 / (1 + exp((c - p) 4/p)) p = half-weight cost
28
+ ============== ===================================== =============================
29
+
30
+ Every kind is exactly zero beyond ``T`` and for non-finite costs.
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import numpy as np
35
+ import pandas as pd
36
+
37
+ from . import contract
38
+
39
+ DECAY_KINDS = ("cumulative", "linear", "exponential", "gaussian", "gaussian_sigma", "power",
40
+ "logistic")
41
+ _NEEDS_PARAM = ("exponential", "gaussian_sigma", "power", "logistic")
42
+
43
+ # Isolation categories
44
+ NEWLY_CUT_OFF = "newly_cut_off"
45
+ WORSE = "worse"
46
+ SAME = "same"
47
+ IMPROVED = "improved"
48
+ ALWAYS_CUT_OFF = "always_cut_off"
49
+ ISOLATION_CATEGORIES = (NEWLY_CUT_OFF, WORSE, SAME, IMPROVED, ALWAYS_CUT_OFF)
50
+ NO_TRAVEL_TIME = contract.missing("travel_time")
51
+
52
+
53
+ # --------------------------------------------------------------------------- #
54
+ # Decay
55
+ # --------------------------------------------------------------------------- #
56
+ def gaussian_decay(cost, threshold: float) -> np.ndarray:
57
+ """Threshold-normalised Gaussian weight of Dai (2010).
58
+
59
+ $$G(c, T) = \\frac{e^{-\\frac12 (c/T)^2} - e^{-\\frac12}}{1 - e^{-\\frac12}}, \\quad c \\le T$$
60
+
61
+ and 0 beyond ``T``; 1 at ``c = 0`` and 0 at ``c = T``.
62
+
63
+ Source: Dai, D. (2010). Black residential segregation, disparities in
64
+ spatial access to health care facilities, and late-stage breast cancer
65
+ diagnosis in metropolitan Detroit. Health & Place 16(5), 1038-1052,
66
+ Eq. 2. doi:10.1016/j.healthplace.2010.06.012
67
+ """
68
+ return decay(cost, "gaussian", None, threshold)
69
+
70
+
71
+ def decay(cost, kind: str, param: float | None, cutoff: float) -> np.ndarray:
72
+ """Weight in [0, 1] for travel costs ``cost``.
73
+
74
+ Parameters
75
+ ----------
76
+ cost : array_like
77
+ Travel costs (any unit consistent with ``cutoff`` and ``param``).
78
+ ``inf``/``NaN`` and costs above ``cutoff`` weigh zero.
79
+ kind : str
80
+ One of :data:`DECAY_KINDS` (see the module table for sources).
81
+ param : float or None
82
+ The kind's own parameter; required (positive) for exponential,
83
+ gaussian_sigma, power and logistic, ignored otherwise.
84
+ cutoff : float
85
+ Threshold ``T`` beyond which every weight is zero.
86
+ """
87
+ if kind not in DECAY_KINDS:
88
+ raise ValueError(f"unknown decay kind '{kind}'")
89
+ if kind in _NEEDS_PARAM:
90
+ contract.require(param, "param", f"the {kind} decay parameter")
91
+ param = float(param)
92
+ if not param > 0:
93
+ raise ValueError(f"{kind} decay needs a positive parameter")
94
+ cutoff = float(cutoff)
95
+ c = np.asarray(cost, dtype=np.float64)
96
+ with np.errstate(invalid="ignore"):
97
+ ok = np.isfinite(c) & (c <= cutoff)
98
+ cc = np.where(ok, np.maximum(np.where(ok, c, 0.0), 0.0), 0.0)
99
+ if kind == "cumulative":
100
+ w = np.ones_like(cc)
101
+ elif kind == "linear":
102
+ w = 1.0 - cc / cutoff if cutoff > 0 else np.zeros_like(cc)
103
+ elif kind == "exponential":
104
+ w = np.exp(-param * cc)
105
+ elif kind == "gaussian":
106
+ if cutoff <= 0:
107
+ w = np.zeros_like(cc)
108
+ else:
109
+ e = np.exp(-0.5)
110
+ w = (np.exp(-0.5 * (cc / cutoff) ** 2) - e) / (1.0 - e)
111
+ elif kind == "gaussian_sigma":
112
+ w = np.exp(-(cc * cc) / (2.0 * param ** 2))
113
+ elif kind == "power":
114
+ w = np.power(np.maximum(cc, 1.0), -param)
115
+ else: # logistic
116
+ slope = 4.0 / param
117
+ z = np.clip((cc - param) * slope, -700.0, 700.0)
118
+ w = 1.0 / (1.0 + np.exp(z))
119
+ return np.where(ok, np.clip(w, 0.0, 1.0), 0.0)
120
+
121
+
122
+ def half_weight_time(kind: str, param: float | None, cutoff: float) -> float | None:
123
+ """Cost at which the decay first reaches 0.5 (None if it never does)."""
124
+ if kind not in DECAY_KINDS:
125
+ raise ValueError(f"unknown decay kind '{kind}'")
126
+ if kind == "cumulative":
127
+ return None
128
+ if kind == "linear":
129
+ return 0.5 * cutoff
130
+ if kind == "gaussian":
131
+ # solve G(c, T) = 0.5
132
+ e = np.exp(-0.5)
133
+ t = cutoff * np.sqrt(-2.0 * np.log(0.5 * (1.0 - e) + e))
134
+ elif kind == "exponential":
135
+ t = np.log(2.0) / param if param and param > 0 else None
136
+ elif kind == "gaussian_sigma":
137
+ t = param * np.sqrt(2.0 * np.log(2.0))
138
+ elif kind == "power":
139
+ t = 2.0 ** (1.0 / param)
140
+ else:
141
+ t = float(param)
142
+ if t is None or t > cutoff:
143
+ return None
144
+ return float(t)
145
+
146
+
147
+ _decay = decay
148
+
149
+
150
+ # --------------------------------------------------------------------------- #
151
+ # Chunked accumulator (PlanX layout: destinations x origins)
152
+ # --------------------------------------------------------------------------- #
153
+ class AccessAccumulator:
154
+ """Chunk-wise Hansen and 2SFCA sums over destination-by-origin blocks.
155
+
156
+ The caller feeds blocks of destinations (:meth:`add_block`), each with its
157
+ costs to every origin; the sums are complete when the last block is in.
158
+ 2SFCA can be built this way because each facility's ratio ``R_j`` needs
159
+ only its own column. Costs must be finite or ``inf``; NaN handling is done
160
+ by :func:`two_step_fca`.
161
+ """
162
+
163
+ def __init__(self, n_origins: int, population, kind: str, param, cutoff: float):
164
+ self.population = np.asarray(population, dtype=np.float64)
165
+ if len(self.population) != n_origins:
166
+ raise ValueError("population needs one value per origin")
167
+ decay(np.zeros(1), kind, param, cutoff) # validates kind and parameter
168
+ self.kind, self.param, self.cutoff = kind, param, float(cutoff)
169
+ self.hansen = np.zeros(n_origins)
170
+ self.cumulative = np.zeros(n_origins)
171
+ self.fca = np.zeros(n_origins)
172
+ self.nearest = np.full(n_origins, np.inf)
173
+ self.n_reached = np.zeros(n_origins, dtype=np.int64)
174
+ self.ratios: list[float] = []
175
+ self.catchment_pop: list[float] = []
176
+
177
+ def add_block(self, cost_dest_by_origin, supply) -> None:
178
+ """Costs shaped (block, n_origins) and the block's supply weights."""
179
+ cost = np.asarray(cost_dest_by_origin, dtype=np.float64)
180
+ supply = np.asarray(supply, dtype=np.float64)
181
+ w = decay(cost, self.kind, self.param, self.cutoff)
182
+ inside = np.isfinite(cost) & (cost <= self.cutoff)
183
+ self.hansen += supply @ w
184
+ self.cumulative += supply @ inside.astype(np.float64)
185
+ self.n_reached += inside.sum(axis=0)
186
+ if cost.size:
187
+ finite = np.where(np.isfinite(cost), cost, np.inf)
188
+ self.nearest = np.minimum(self.nearest, finite.min(axis=0))
189
+ demand = w @ self.population
190
+ ratio = np.where(demand > 0, supply / np.where(demand > 0, demand, 1.0), 0.0)
191
+ self.fca += ratio @ w
192
+ self.ratios.extend(ratio.tolist())
193
+ self.catchment_pop.extend(demand.tolist())
194
+
195
+
196
+ # --------------------------------------------------------------------------- #
197
+ # Whole-matrix measures (rows = demand units, columns = facilities)
198
+ # --------------------------------------------------------------------------- #
199
+ def _cost_matrix(cost) -> np.ndarray:
200
+ c = np.asarray(cost, dtype=np.float64)
201
+ if c.ndim != 2:
202
+ raise ValueError("cost must be a 2-D (demand x facilities) matrix")
203
+ return c
204
+
205
+
206
+ def two_step_fca(cost, supply, demand, threshold: float, decay: str = "cumulative",
207
+ param: float | None = None, return_ratio: bool = False):
208
+ """Two-step floating catchment area accessibility.
209
+
210
+ $$R_j = \\frac{S_j}{\\sum_k P_k\\, f(c_{kj})}, \\qquad A_i = \\sum_j R_j\\, f(c_{ij})$$
211
+
212
+ (Radke & Mu 2000; Luo & Wang 2003; decayed catchment: Luo & Qi 2009;
213
+ Gaussian: Dai 2010). Population-weighted access sums to the supply of
214
+ every facility that someone can reach: $\\sum_i P_i A_i = \\sum_{j:\\,D_j>0} S_j$.
215
+
216
+ Parameters
217
+ ----------
218
+ cost : (n_demand, n_facility) array
219
+ Travel cost from each demand unit to each facility; ``inf`` =
220
+ unreachable, ``NaN`` = unknown (for example an unsnapped unit).
221
+ supply : (n_facility,) array
222
+ Facility capacity (beds, places). NaN = unknown; the facility is left
223
+ out and every unit that reaches it is marked ``partial``.
224
+ demand : (n_demand,) array
225
+ Population per unit. NaN = unknown; the unit adds nobody to any
226
+ catchment, so the ratios it touches are upper bounds (``partial``).
227
+ threshold : float
228
+ Catchment size ``T`` in cost units.
229
+ decay : str
230
+ A :data:`DECAY_KINDS` entry; ``"gaussian"`` is Dai (2010).
231
+ param : float, optional
232
+ Parameter of the decay kind when it needs one.
233
+ return_ratio : bool
234
+ Also return the facility table.
235
+
236
+ Returns
237
+ -------
238
+ DataFrame (and facility DataFrame when ``return_ratio``)
239
+ Per demand unit: ``access``, ``n_reachable`` (facilities within
240
+ ``T``), ``access_status`` (``computed``, ``partial``, or
241
+ ``no_travel_time`` when its whole cost row is unknown). Per facility:
242
+ ``ratio``, ``catchment_demand``, ``ratio_status`` (``no_supply``;
243
+ ``no_travel_time`` when every cost to the facility is unknown;
244
+ ``empty`` with NaN ratio when nobody lives within the catchment, so
245
+ the ratio is undefined, and the units that still reach it read
246
+ ``partial``; ``no_demand`` when the only residents within it have
247
+ unknown numbers; ``partial``; ``computed``).
248
+ """
249
+ c = _cost_matrix(cost)
250
+ n_dem, n_fac = c.shape
251
+ supply = np.asarray(supply, dtype=np.float64).reshape(-1)
252
+ pop = np.asarray(demand, dtype=np.float64).reshape(-1)
253
+ if supply.shape != (n_fac,) or pop.shape != (n_dem,):
254
+ raise ValueError("supply needs one value per column and demand one per row of cost")
255
+ unknown = np.isnan(c)
256
+ w = _decay(np.where(unknown, np.inf, c), decay, param, threshold) # (dem, fac)
257
+ pop_ok = np.isfinite(pop)
258
+ pop0 = np.where(pop_ok, pop, 0.0)
259
+ sup_ok = np.isfinite(supply)
260
+ catch = pop0 @ w # (fac,)
261
+ ratio = np.where(sup_ok & (catch > 0), np.where(sup_ok, supply, 0.0)
262
+ / np.where(catch > 0, catch, 1.0), 0.0)
263
+ access = w @ ratio
264
+ reached = w > 0
265
+ fac_incomplete = (unknown.any(axis=0) | (reached & ~pop_ok[:, None]).any(axis=0)
266
+ | ~sup_ok)
267
+ undefined = catch <= 0 # nobody within the catchment: S/0 has no value
268
+ row_partial = (unknown.any(axis=1) | (reached & fac_incomplete[None, :]).any(axis=1)
269
+ | (reached & undefined[None, :]).any(axis=1) | ~pop_ok)
270
+ row_missing = unknown.all(axis=1) if n_fac else np.zeros(n_dem, dtype=bool)
271
+ status = np.where(row_missing, NO_TRAVEL_TIME,
272
+ np.where(row_partial, contract.PARTIAL, contract.COMPUTED)).astype(object)
273
+ out = pd.DataFrame({
274
+ "access": np.where(row_missing, np.nan, access),
275
+ "n_reachable": reached.sum(axis=1).astype(np.int64),
276
+ "access_status": status,
277
+ })
278
+ if not return_ratio:
279
+ return out
280
+ no_catch = undefined
281
+ no_cost = unknown.all(axis=0) if n_dem else np.zeros(n_fac, dtype=bool)
282
+ fac_status = np.where(
283
+ ~sup_ok, contract.missing("supply"),
284
+ np.where(no_cost, NO_TRAVEL_TIME,
285
+ np.where(no_catch & fac_incomplete, contract.missing("demand"),
286
+ np.where(no_catch, contract.EMPTY,
287
+ np.where(fac_incomplete, contract.PARTIAL,
288
+ contract.COMPUTED)))))
289
+ fac = pd.DataFrame({
290
+ "ratio": np.where(sup_ok & ~no_catch, ratio, np.nan),
291
+ "catchment_demand": np.where(no_cost | (no_catch & fac_incomplete), np.nan, catch),
292
+ "ratio_status": fac_status.astype(object),
293
+ })
294
+ return out, fac
295
+
296
+
297
+ def hansen(cost, supply, threshold: float, decay: str = "cumulative",
298
+ param: float | None = None) -> np.ndarray:
299
+ """Hansen (1959) potential $A_i = \\sum_j S_j f(c_{ij})$ per demand unit.
300
+
301
+ ``cost`` is (n_demand, n_facility). A unit whose whole cost row is NaN
302
+ gets NaN; NaN entries elsewhere count as unreachable (the value is then a
303
+ lower bound). Facilities with NaN supply are skipped, which also makes the
304
+ value a lower bound; a unit that reaches only facilities of unknown
305
+ supply gets NaN, not 0.
306
+ """
307
+ c = _cost_matrix(cost)
308
+ supply = np.asarray(supply, dtype=np.float64).reshape(-1)
309
+ if supply.shape != (c.shape[1],):
310
+ raise ValueError("supply needs one value per column of cost")
311
+ w = _decay(np.where(np.isnan(c), np.inf, c), decay, param, threshold)
312
+ sup_ok = np.isfinite(supply)
313
+ out = w @ np.where(sup_ok, supply, 0.0)
314
+ if c.shape[1]:
315
+ reached = w > 0
316
+ only_unknown = reached.any(axis=1) & ~(reached & sup_ok[None, :]).any(axis=1)
317
+ out = np.where(np.isnan(c).all(axis=1) | only_unknown, np.nan, out)
318
+ return out
319
+
320
+
321
+ def nearest_time(matrix) -> pd.DataFrame:
322
+ """Cost to the nearest facility per row of a cost matrix.
323
+
324
+ Returns ``nearest_time`` (``inf`` when no facility is reachable),
325
+ ``nearest_index`` (column, -1 when none) and ``nearest_status``:
326
+ ``computed``; ``partial`` when some entries were unknown (the value is an
327
+ upper bound); ``no_travel_time`` when the known entries reach nothing and
328
+ some are unknown, or the whole row is unknown (value NaN).
329
+ """
330
+ c = _cost_matrix(matrix)
331
+ n = c.shape[0]
332
+ unknown = np.isnan(c)
333
+ filled = np.where(unknown, np.inf, c)
334
+ if c.shape[1]:
335
+ idx = np.argmin(filled, axis=1)
336
+ val = filled[np.arange(n), idx]
337
+ else:
338
+ idx = np.zeros(n, dtype=np.int64)
339
+ val = np.full(n, np.inf)
340
+ any_unknown = unknown.any(axis=1)
341
+ found = np.isfinite(val)
342
+ missing = any_unknown & ~found
343
+ status = np.where(missing, NO_TRAVEL_TIME,
344
+ np.where(any_unknown, contract.PARTIAL, contract.COMPUTED)).astype(object)
345
+ return pd.DataFrame({
346
+ "nearest_time": np.where(missing, np.nan, val),
347
+ "nearest_index": np.where(found, idx, -1).astype(np.int64),
348
+ "nearest_status": status,
349
+ })
350
+
351
+
352
+ def isolation_status(pre, post, limit_s: float | None = None,
353
+ worse_tol_s: float | None = None) -> pd.DataFrame:
354
+ """Compare access before and after an event, unit by unit.
355
+
356
+ A unit is *reachable* when its time is finite (and not above ``limit_s``
357
+ when a limit is given). With ``d = post - pre``:
358
+
359
+ ================ ============================================
360
+ newly_cut_off reachable before, not after
361
+ always_cut_off reachable neither before nor after
362
+ improved not reachable before, reachable after; or d < -tol
363
+ worse d > tol
364
+ same |d| <= tol
365
+ ================ ============================================
366
+
367
+ A NaN (unknown) time gives ``no_pre_time`` / ``no_post_time`` and no
368
+ category. The categories follow the pre/post comparison of network
369
+ accessibility-loss studies (e.g. Sohn 2006, doi:10.1016/j.tra.2005.08.006);
370
+ the tolerance is the caller's.
371
+
372
+ Parameters
373
+ ----------
374
+ pre, post : array_like
375
+ Times per unit (``inf`` = unreachable, ``NaN`` = unknown), e.g. the
376
+ ``nearest_time`` column of :func:`nearest_time`.
377
+ limit_s : float, optional
378
+ Times above it count as unreachable.
379
+ worse_tol_s : float
380
+ Change smaller than or equal to this is ``same``. Required: no
381
+ published default exists (use 0 for an exact comparison).
382
+
383
+ Returns
384
+ -------
385
+ DataFrame
386
+ ``pre_time``, ``post_time``, ``delta_time`` (NaN unless both are
387
+ reachable) and ``isolation_status``.
388
+ """
389
+ tol = float(contract.require(worse_tol_s, "worse_tol_s",
390
+ "largest change in seconds still read as 'same'"))
391
+ if tol < 0:
392
+ raise ValueError("worse_tol_s must be >= 0")
393
+ a = np.asarray(pre, dtype=np.float64).reshape(-1)
394
+ b = np.asarray(post, dtype=np.float64).reshape(-1)
395
+ if a.shape != b.shape:
396
+ raise ValueError("pre and post need the same length")
397
+
398
+ def reachable(x):
399
+ r = np.isfinite(x)
400
+ if limit_s is not None:
401
+ r &= np.where(r, x, np.inf) <= float(limit_s)
402
+ return r
403
+
404
+ ra, rb = reachable(a), reachable(b)
405
+ na, nb = np.isnan(a), np.isnan(b)
406
+ with np.errstate(invalid="ignore"):
407
+ d = np.where(ra & rb, b - a, np.nan)
408
+ status = np.full(a.shape, SAME, dtype=object)
409
+ status[ra & rb & (d > tol)] = WORSE
410
+ status[ra & rb & (d < -tol)] = IMPROVED
411
+ status[~ra & rb] = IMPROVED
412
+ status[ra & ~rb] = NEWLY_CUT_OFF
413
+ status[~ra & ~rb] = ALWAYS_CUT_OFF
414
+ status[nb] = contract.missing("post_time")
415
+ status[na] = contract.missing("pre_time")
416
+ return pd.DataFrame({"pre_time": a, "post_time": b, "delta_time": d,
417
+ "isolation_status": status})
418
+
419
+
420
+ def population_by_status(status, population) -> pd.DataFrame:
421
+ """People and units per isolation category.
422
+
423
+ Returns one row per category (the five of :data:`ISOLATION_CATEGORIES`
424
+ always, plus any missing-data code present) with ``n_units``,
425
+ ``population`` (sum; NaN when every unit in the category lacks a
426
+ population) and ``n_population_missing``.
427
+ """
428
+ if isinstance(status, pd.DataFrame):
429
+ status = status["isolation_status"]
430
+ s = pd.Series(np.asarray(status, dtype=object).reshape(-1), name="isolation_status")
431
+ p = pd.Series(np.asarray(population, dtype=np.float64).reshape(-1))
432
+ if len(s) != len(p):
433
+ raise ValueError("status and population need the same length")
434
+ frame = pd.DataFrame({"isolation_status": s, "population": p})
435
+ extra = sorted(set(s) - set(ISOLATION_CATEGORIES))
436
+ order = list(ISOLATION_CATEGORIES) + extra
437
+ g = frame.groupby("isolation_status", sort=False)
438
+ n_units = g.size().reindex(order, fill_value=0)
439
+ pop_sum = g["population"].sum(min_count=1).reindex(order)
440
+ n_missing = g["population"].apply(lambda x: int(x.isna().sum())).reindex(order, fill_value=0)
441
+ pop_sum = pop_sum.where(n_units > 0, 0.0)
442
+ out = pd.DataFrame({"n_units": n_units.astype(np.int64), "population": pop_sum,
443
+ "n_population_missing": n_missing.astype(np.int64)})
444
+ out.index.name = "isolation_status"
445
+ return out.reset_index()
446
+
447
+
448
+ __all__ = [
449
+ "ALWAYS_CUT_OFF",
450
+ "DECAY_KINDS",
451
+ "IMPROVED",
452
+ "ISOLATION_CATEGORIES",
453
+ "NEWLY_CUT_OFF",
454
+ "NO_TRAVEL_TIME",
455
+ "SAME",
456
+ "WORSE",
457
+ "AccessAccumulator",
458
+ "decay",
459
+ "gaussian_decay",
460
+ "half_weight_time",
461
+ "hansen",
462
+ "isolation_status",
463
+ "nearest_time",
464
+ "population_by_status",
465
+ "two_step_fca",
466
+ ]