-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcentroids.py
75 lines (64 loc) · 2.48 KB
/
centroids.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from functools import cached_property
import numpy as np
from numpy.typing import NDArray
from epymorph.data_shape import Shapes
from epymorph.data_type import CentroidType, SimDType
from epymorph.movement_model import EveryDay, MovementClause, MovementModel
from epymorph.simulation import AttributeDef, Tick, TickDelta, TickIndex
from epymorph.util import pairwise_haversine, row_normalize
class CentroidsClause(MovementClause):
"""The clause of the centroids model."""
requirements = (
AttributeDef(
"population", int, Shapes.N, comment="The total population at each node."
),
AttributeDef(
"centroid",
CentroidType,
Shapes.N,
comment="The centroids for each node as (longitude, latitude) tuples.",
),
AttributeDef(
"phi",
float,
Shapes.Scalar,
default_value=40.0,
comment="Influences the distance that movers tend to travel.",
),
AttributeDef(
"commuter_proportion",
float,
Shapes.Scalar,
default_value=0.1,
comment="The proportion of the total population which commutes.",
),
)
predicate = EveryDay()
leaves = TickIndex(step=0)
returns = TickDelta(step=1, days=0)
@cached_property
def dispersal_kernel(self) -> NDArray[np.float64]:
"""
The NxN matrix or dispersal kernel describing the tendency for movers to move
to a particular location. In this model, the kernel is:
1 / e ^ (distance / phi)
which is then row-normalized.
"""
centroid = self.data("centroid")
phi = self.data("phi")
distance = pairwise_haversine(centroid)
return row_normalize(1 / np.exp(distance / phi))
def evaluate(self, tick: Tick) -> NDArray[np.int64]:
pop = self.data("population")
comm_prop = self.data("commuter_proportion")
n_commuters = np.floor(pop * comm_prop).astype(SimDType)
return self.rng.multinomial(n_commuters, self.dispersal_kernel)
class Centroids(MovementModel):
"""
The centroids MM describes a basic commuter movement where a fixed proportion
of the population commutes every day, travels to another location for 1/3 of a day
(with a location likelihood that decreases with distance), and then returns home for
the remaining 2/3 of the day.
"""
steps = (1 / 3, 2 / 3)
clauses = (CentroidsClause(),)