epymorph 1.0.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.
- epymorph/__init__.py +7 -0
- epymorph/__main__.py +16 -0
- epymorph/adrio/__init__.py +0 -0
- epymorph/adrio/acs5.py +1378 -0
- epymorph/adrio/adrio.py +953 -0
- epymorph/adrio/cdc.py +1826 -0
- epymorph/adrio/commuting_flows.py +283 -0
- epymorph/adrio/csv.py +499 -0
- epymorph/adrio/humidity.py +206 -0
- epymorph/adrio/lodes.py +509 -0
- epymorph/adrio/numpy.py +160 -0
- epymorph/adrio/prism.py +345 -0
- epymorph/adrio/processing.py +1221 -0
- epymorph/adrio/soda.py +602 -0
- epymorph/adrio/us_tiger.py +289 -0
- epymorph/adrio/validation.py +382 -0
- epymorph/attribute.py +614 -0
- epymorph/cache.py +680 -0
- epymorph/cli/__init__.py +0 -0
- epymorph/cli/cache.py +78 -0
- epymorph/cli/main.py +29 -0
- epymorph/compartment_model.py +1873 -0
- epymorph/data/__init__.py +1 -0
- epymorph/data/ipm/__init__.py +22 -0
- epymorph/data/ipm/no.py +14 -0
- epymorph/data/ipm/pei.py +40 -0
- epymorph/data/ipm/seirs.py +50 -0
- epymorph/data/ipm/sirh.py +55 -0
- epymorph/data/ipm/sirs.py +48 -0
- epymorph/data/ipm/sparsemod.py +96 -0
- epymorph/data/mm/__init__.py +22 -0
- epymorph/data/mm/centroids.py +76 -0
- epymorph/data/mm/flat.py +61 -0
- epymorph/data/mm/icecube.py +50 -0
- epymorph/data/mm/no.py +29 -0
- epymorph/data/mm/pei.py +105 -0
- epymorph/data/mm/sparsemod.py +73 -0
- epymorph/data/pei.py +424 -0
- epymorph/data_shape.py +593 -0
- epymorph/data_type.py +185 -0
- epymorph/data_usage.py +258 -0
- epymorph/database.py +1301 -0
- epymorph/error.py +195 -0
- epymorph/event.py +196 -0
- epymorph/geography/__init__.py +0 -0
- epymorph/geography/custom.py +93 -0
- epymorph/geography/scope.py +457 -0
- epymorph/geography/us_census.py +1056 -0
- epymorph/geography/us_geography.py +502 -0
- epymorph/geography/us_tiger.py +1083 -0
- epymorph/initializer.py +786 -0
- epymorph/kit.py +107 -0
- epymorph/log/__init__.py +0 -0
- epymorph/log/file.py +128 -0
- epymorph/log/messaging.py +139 -0
- epymorph/log/movement.py +228 -0
- epymorph/movement_model.py +347 -0
- epymorph/parameter_fitting/__init__.py +0 -0
- epymorph/parameter_fitting/distribution.py +68 -0
- epymorph/parameter_fitting/dynamics.py +19 -0
- epymorph/parameter_fitting/filter/__init__.py +0 -0
- epymorph/parameter_fitting/filter/base_filter.py +50 -0
- epymorph/parameter_fitting/filter/particle.py +32 -0
- epymorph/parameter_fitting/filter/particle_filter.py +296 -0
- epymorph/parameter_fitting/likelihood.py +54 -0
- epymorph/parameter_fitting/output.py +73 -0
- epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
- epymorph/parameter_fitting/perturbation.py +19 -0
- epymorph/parameter_fitting/utils/__init__.py +0 -0
- epymorph/parameter_fitting/utils/data_loader.py +97 -0
- epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
- epymorph/parameter_fitting/utils/observations.py +63 -0
- epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
- epymorph/parameter_fitting/utils/params_perturb.py +43 -0
- epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
- epymorph/parameter_fitting/utils/resampler.py +258 -0
- epymorph/parameter_fitting/utils/utils.py +101 -0
- epymorph/params.py +438 -0
- epymorph/py.typed +0 -0
- epymorph/rume.py +871 -0
- epymorph/simulation.py +991 -0
- epymorph/simulator/__init__.py +0 -0
- epymorph/simulator/basic/__init__.py +0 -0
- epymorph/simulator/basic/basic_simulator.py +171 -0
- epymorph/simulator/basic/ipm_exec.py +437 -0
- epymorph/simulator/basic/mm_exec.py +244 -0
- epymorph/simulator/basic/output.py +213 -0
- epymorph/simulator/world.py +149 -0
- epymorph/simulator/world_list.py +274 -0
- epymorph/strata.py +24 -0
- epymorph/sympy_shim.py +57 -0
- epymorph/time.py +1197 -0
- epymorph/tools/__init__.py +0 -0
- epymorph/tools/data.py +297 -0
- epymorph/tools/ipm_diagram.py +208 -0
- epymorph/tools/out_map.py +551 -0
- epymorph/tools/out_plot.py +423 -0
- epymorph/tools/out_table.py +582 -0
- epymorph/util.py +1036 -0
- epymorph-1.0.0.dist-info/METADATA +57 -0
- epymorph-1.0.0.dist-info/RECORD +104 -0
- epymorph-1.0.0.dist-info/WHEEL +5 -0
- epymorph-1.0.0.dist-info/entry_points.txt +2 -0
- epymorph-1.0.0.dist-info/top_level.txt +1 -0
epymorph/error.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Common epymorph exceptions."""
|
|
2
|
+
|
|
3
|
+
from contextlib import contextmanager
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ExternalDependencyError(Exception):
|
|
7
|
+
"""
|
|
8
|
+
Exception when epymorph requires a native program (or programs) to perform an
|
|
9
|
+
application function but the program is not found.
|
|
10
|
+
|
|
11
|
+
Parameters
|
|
12
|
+
----------
|
|
13
|
+
msg :
|
|
14
|
+
The exception message.
|
|
15
|
+
missing :
|
|
16
|
+
The list of external programs which are missing.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
missing: list[str]
|
|
20
|
+
"""The list of external programs which are missing."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, msg: str, missing: list[str]):
|
|
23
|
+
super().__init__(msg)
|
|
24
|
+
self.missing = missing
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class GeographyError(Exception):
|
|
28
|
+
"""Exception working with geographic system representations."""
|
|
29
|
+
|
|
30
|
+
# NOTE: this is *not* for general errors related to the epymorph GEO module,
|
|
31
|
+
# but instead for things like utility functions for working with
|
|
32
|
+
# US Census delineations.
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class DimensionError(Exception):
|
|
36
|
+
"""Raised when epymorph needed dimensional information that was not provided."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ValidationError(Exception):
|
|
40
|
+
"""Superclass for exceptions which happen during simulation validation."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class DataAttributeError(ValidationError):
|
|
44
|
+
"""Exception encountered handling a data attribute."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class DataAttributeErrorGroup(ExceptionGroup, DataAttributeError): # noqa: N818
|
|
48
|
+
"""Multiple exceptions encountered handling data attributes."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class MissingContextError(Exception):
|
|
52
|
+
"""
|
|
53
|
+
Exception during simulation function evaluation, where the function required
|
|
54
|
+
context elements that were not provided.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class IPMValidationError(ValidationError):
|
|
59
|
+
"""Exception for invalid IPM."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class MMValidationError(ValidationError):
|
|
63
|
+
"""Exception for invalid MM."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class InitValidationError(ValidationError):
|
|
67
|
+
"""Exception for invalid Initializer."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class SimValidationError(ValidationError):
|
|
71
|
+
"""
|
|
72
|
+
Exception for cases where a simulation is invalid as configured,
|
|
73
|
+
typically because the MM, IPM, or Initializer require data attributes
|
|
74
|
+
that are not available.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class SimCompilationError(Exception):
|
|
79
|
+
"""Exception during the compilation phase of the simulation."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class SimulationError(Exception):
|
|
83
|
+
"""Superclass for exceptions which happen during simulation runtime."""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class InitError(SimulationError):
|
|
87
|
+
"""Exception for invalid initialization."""
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class IPMSimError(SimulationError):
|
|
91
|
+
"""Exception during IPM processing."""
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class _WithFieldsMixin:
|
|
95
|
+
"""
|
|
96
|
+
A mixin class for exceptions that include diagnostic information about
|
|
97
|
+
the simulation step being processed.
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
display_fields: list[tuple[str, dict]]
|
|
101
|
+
|
|
102
|
+
def __str__(self):
|
|
103
|
+
msg = super().__str__()
|
|
104
|
+
fields = ""
|
|
105
|
+
for name, values in self.display_fields:
|
|
106
|
+
fields += f"Showing current {name}\n"
|
|
107
|
+
for key, value in values.items():
|
|
108
|
+
fields += f"{key}: {value}\n"
|
|
109
|
+
fields += "\n"
|
|
110
|
+
return f"{msg}\n{fields}"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class IPMSimNaNError(_WithFieldsMixin, IPMSimError):
|
|
114
|
+
"""Exception raised when an IPM transition rate is NaN."""
|
|
115
|
+
|
|
116
|
+
def __init__(self, display_fields: list[tuple[str, dict]]):
|
|
117
|
+
msg = [
|
|
118
|
+
"An IPM transition rate was NaN (not a number).",
|
|
119
|
+
"This is often the result of a divide by zero error.",
|
|
120
|
+
"When constructing an IPM, ensure that no edge transitions can result in "
|
|
121
|
+
"division by zero.",
|
|
122
|
+
"This commonly occurs when defining an edge that is divided by "
|
|
123
|
+
"a population total, since populations in nodes can be zero.",
|
|
124
|
+
"Possible fixes include wrapping the divisor with a 'Max' expression so as "
|
|
125
|
+
"to guarantee it is never less than 1. Commonly in this situation, the "
|
|
126
|
+
"numerator must be 0, making the divisor's actual value irrelevant.",
|
|
127
|
+
]
|
|
128
|
+
super().__init__("\n".join(msg))
|
|
129
|
+
self.display_fields = display_fields
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class IPMSimLessThanZeroError(_WithFieldsMixin, IPMSimError):
|
|
133
|
+
"""Exception raised when an IPM transition rate is less than zero."""
|
|
134
|
+
|
|
135
|
+
def __init__(self, display_fields: list[tuple[str, dict]]):
|
|
136
|
+
msg = [
|
|
137
|
+
"An IPM transition rate was less than zero.",
|
|
138
|
+
"When providing IPM parameters ensure that this will not result in a "
|
|
139
|
+
"negative rate.",
|
|
140
|
+
]
|
|
141
|
+
super().__init__("\n".join(msg))
|
|
142
|
+
self.display_fields = display_fields
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class IPMSimInvalidForkError(_WithFieldsMixin, IPMSimError):
|
|
146
|
+
"""Exception raised when an IPM fork transition's probabilities are invalid."""
|
|
147
|
+
|
|
148
|
+
def __init__(self, display_fields: list[tuple[str, dict]]):
|
|
149
|
+
msg = (
|
|
150
|
+
"An IPM fork transition is invalid. The computed probabilities for the "
|
|
151
|
+
"fork must always be non-negative and sum to 1."
|
|
152
|
+
)
|
|
153
|
+
super().__init__(msg)
|
|
154
|
+
self.display_fields = display_fields
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class MMSimError(SimulationError):
|
|
158
|
+
"""Exception during MM processing."""
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@contextmanager
|
|
162
|
+
def error_gate(
|
|
163
|
+
description: str,
|
|
164
|
+
exception_type: type[Exception],
|
|
165
|
+
*reraises: type[Exception],
|
|
166
|
+
):
|
|
167
|
+
"""
|
|
168
|
+
Begin a context that standardizes errors linked to a particular simulation phase.
|
|
169
|
+
Wrap the phase in an error gate and all exceptions raised within will be normalized.
|
|
170
|
+
|
|
171
|
+
If an exception of type `exception_type` is caught, it will be re-raised as-is.
|
|
172
|
+
If an exception is caught from the list of exception types in `reraises`,
|
|
173
|
+
the exception will be stringified and re-raised as `exception_type`.
|
|
174
|
+
All other exceptions will be labeled as "unknown errors".
|
|
175
|
+
|
|
176
|
+
Parameters
|
|
177
|
+
----------
|
|
178
|
+
description :
|
|
179
|
+
Describe the phase in gerund form, e.g., "executing the IPM".
|
|
180
|
+
exception_type :
|
|
181
|
+
The best exception type for this phase.
|
|
182
|
+
reraises :
|
|
183
|
+
Additional exception types which will be stringified and raised as an
|
|
184
|
+
`exception_type`.
|
|
185
|
+
"""
|
|
186
|
+
try:
|
|
187
|
+
yield
|
|
188
|
+
except exception_type as e:
|
|
189
|
+
raise e
|
|
190
|
+
except Exception as e:
|
|
191
|
+
if any(isinstance(e, r) for r in reraises):
|
|
192
|
+
raise exception_type(str(e)) from e
|
|
193
|
+
|
|
194
|
+
msg = f"Unknown error {description}."
|
|
195
|
+
raise exception_type(msg) from e
|
epymorph/event.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""
|
|
2
|
+
epymorph's event framework.
|
|
3
|
+
|
|
4
|
+
epymorph components may define a set of events relevant to their function,
|
|
5
|
+
and during processing can publish to the singleton `EventBus` for subscription
|
|
6
|
+
and processing by other systems.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from typing import NamedTuple
|
|
10
|
+
|
|
11
|
+
from numpy.typing import NDArray
|
|
12
|
+
|
|
13
|
+
from epymorph.attribute import AbsoluteName
|
|
14
|
+
from epymorph.data_type import SimDType
|
|
15
|
+
from epymorph.rume import RUME
|
|
16
|
+
from epymorph.util import Event, Singleton
|
|
17
|
+
|
|
18
|
+
#####################
|
|
19
|
+
# Simulation Events #
|
|
20
|
+
#####################
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class OnStart(NamedTuple):
|
|
24
|
+
"""Event payload for the start of a simulation."""
|
|
25
|
+
|
|
26
|
+
simulator: str
|
|
27
|
+
"""Name of the simulator class."""
|
|
28
|
+
rume: RUME
|
|
29
|
+
"""The RUME for the simulation."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class OnTick(NamedTuple):
|
|
33
|
+
"""Event payload for the completion of a simulation tick."""
|
|
34
|
+
|
|
35
|
+
tick_index: int
|
|
36
|
+
"""The index of the just-completed tick."""
|
|
37
|
+
ticks: int
|
|
38
|
+
"""The total number of ticks for the simulation."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
###################
|
|
42
|
+
# Movement Events #
|
|
43
|
+
###################
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class OnMovementStart(NamedTuple):
|
|
47
|
+
"""Event payload for the start of movement processing during a tick."""
|
|
48
|
+
|
|
49
|
+
tick: int
|
|
50
|
+
"""Which simulation tick."""
|
|
51
|
+
day: int
|
|
52
|
+
"""Which simulation day."""
|
|
53
|
+
step: int
|
|
54
|
+
"""Which tau step (by index)."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class OnMovementClause(NamedTuple):
|
|
58
|
+
"""Event payload for the completion of processing a movement clause."""
|
|
59
|
+
|
|
60
|
+
tick: int
|
|
61
|
+
"""Which simulation tick."""
|
|
62
|
+
day: int
|
|
63
|
+
"""Which simulation day."""
|
|
64
|
+
step: int
|
|
65
|
+
"""Which tau step (by index)."""
|
|
66
|
+
clause_name: str
|
|
67
|
+
"""The clause processed."""
|
|
68
|
+
requested: NDArray[SimDType]
|
|
69
|
+
"""
|
|
70
|
+
The number of individuals this clause 'wants' to move, that is,
|
|
71
|
+
the values returned by its clause function. (An NxN array.)
|
|
72
|
+
"""
|
|
73
|
+
actual: NDArray[SimDType]
|
|
74
|
+
"""
|
|
75
|
+
The actual number of individuals moved, by source, destination, and compartment.
|
|
76
|
+
(An NxNxC array.)
|
|
77
|
+
"""
|
|
78
|
+
total: int
|
|
79
|
+
"""The number of individuals moved by this clause."""
|
|
80
|
+
is_throttled: bool
|
|
81
|
+
"""
|
|
82
|
+
Did the clause request to move more people than were available (at any location)?
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class OnMovementFinish(NamedTuple):
|
|
87
|
+
"""Event payload for the completion of movement processing during a tick."""
|
|
88
|
+
|
|
89
|
+
tick: int
|
|
90
|
+
"""Which simulation tick."""
|
|
91
|
+
day: int
|
|
92
|
+
"""Which simulation day."""
|
|
93
|
+
step: int
|
|
94
|
+
"""Which tau step (by index)."""
|
|
95
|
+
total: int
|
|
96
|
+
"""The total number of individuals moved during this tick."""
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
################
|
|
100
|
+
# ADRIO Events #
|
|
101
|
+
################
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class DownloadActivity(NamedTuple):
|
|
105
|
+
"""
|
|
106
|
+
Part of the `ADRIOProgress` event payload describing ADRIO network activity.
|
|
107
|
+
|
|
108
|
+
All fields are optional, as it may be possible to measure some but not others
|
|
109
|
+
depending on the data source. ADRIOs should avoid reporting empty activity
|
|
110
|
+
events and instead instead just report `None` (see `ADRIO` methods).
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
total: int | None
|
|
114
|
+
"""How many bytes are expected to be downloaded?"""
|
|
115
|
+
downloaded: int | None
|
|
116
|
+
"""How many bytes have been downloaded?"""
|
|
117
|
+
download_speed: int | None
|
|
118
|
+
"""What is the current approximate download speed?"""
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class ADRIOProgress(NamedTuple):
|
|
122
|
+
"""
|
|
123
|
+
Event payload for ADRIO data processing progress.
|
|
124
|
+
|
|
125
|
+
Not all ADRIOs will be able to report progress meaningfully, but those that do
|
|
126
|
+
should emit one event when they start (with `ratio_complete` == 0)
|
|
127
|
+
and one when they finish (with `ratio_complete` == 1). They are free
|
|
128
|
+
to report as many intermediate progress events as they like.
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
adrio_name: str
|
|
132
|
+
"""The full name of the ADRIO class."""
|
|
133
|
+
attribute: AbsoluteName
|
|
134
|
+
"""The name of the attribute being evaluated."""
|
|
135
|
+
final: bool
|
|
136
|
+
"""Is this the last progress update for this ADRIO?"""
|
|
137
|
+
ratio_complete: float
|
|
138
|
+
"""What ratio complete is it? (0: just started; 1: done)"""
|
|
139
|
+
download: DownloadActivity | None
|
|
140
|
+
"""Download activity if any, and if it can be measured."""
|
|
141
|
+
duration: float | None
|
|
142
|
+
"""If complete, how long did the ADRIO take overall (in seconds)?"""
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
############
|
|
146
|
+
# EventBus #
|
|
147
|
+
############
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class EventBus(metaclass=Singleton):
|
|
151
|
+
"""
|
|
152
|
+
A singleton for epymorph event publishing and subscription.
|
|
153
|
+
|
|
154
|
+
Obtain a reference to the global event bus by constructing it as usual --
|
|
155
|
+
`EventBus()` -- but be aware that this will produce the same instance every time.
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
# Simulation Events
|
|
159
|
+
on_start: Event[OnStart]
|
|
160
|
+
"""Event fires at the start of a simulation run."""
|
|
161
|
+
|
|
162
|
+
on_tick: Event[OnTick]
|
|
163
|
+
"""Event fires after each tick has been processed."""
|
|
164
|
+
|
|
165
|
+
on_finish: Event[None]
|
|
166
|
+
"""Event fires after a simulation run is complete."""
|
|
167
|
+
|
|
168
|
+
# Movement Events
|
|
169
|
+
on_movement_start: Event[OnMovementStart]
|
|
170
|
+
"""
|
|
171
|
+
Event fires at the start of the movement processing phase for every simulation tick.
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
on_movement_clause: Event[OnMovementClause]
|
|
175
|
+
"""Event fires after processing each active movement clause."""
|
|
176
|
+
|
|
177
|
+
on_movement_finish: Event[OnMovementFinish]
|
|
178
|
+
"""
|
|
179
|
+
Event fires at the end of the movement processing phase for every simulation tick.
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
# ADRIO Events
|
|
183
|
+
on_adrio_progress: Event[ADRIOProgress]
|
|
184
|
+
"""Event fires when an ADRIO is fetching data."""
|
|
185
|
+
|
|
186
|
+
def __init__(self):
|
|
187
|
+
# SimulationEvents
|
|
188
|
+
self.on_start = Event()
|
|
189
|
+
self.on_tick = Event()
|
|
190
|
+
self.on_finish = Event()
|
|
191
|
+
# MovementEvents
|
|
192
|
+
self.on_movement_start = Event()
|
|
193
|
+
self.on_movement_clause = Event()
|
|
194
|
+
self.on_movement_finish = Event()
|
|
195
|
+
# AdrioEvents
|
|
196
|
+
self.on_adrio_progress = Event()
|
|
File without changes
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Implements a generic geo scope capable of representing arbitrary geographies."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Never
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
from numpy.typing import NDArray
|
|
8
|
+
from typing_extensions import override
|
|
9
|
+
|
|
10
|
+
from epymorph.error import GeographyError
|
|
11
|
+
from epymorph.geography.scope import (
|
|
12
|
+
GeoGroup,
|
|
13
|
+
GeoGrouping,
|
|
14
|
+
GeoScope,
|
|
15
|
+
GeoSelection,
|
|
16
|
+
GeoSelector,
|
|
17
|
+
GeoStrategy,
|
|
18
|
+
strategy_to_scope,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CustomScope(GeoScope):
|
|
23
|
+
"""
|
|
24
|
+
A scope with no logical connection to existing geographic systems.
|
|
25
|
+
|
|
26
|
+
Parameters
|
|
27
|
+
----------
|
|
28
|
+
nodes :
|
|
29
|
+
The identifiers for all nodes in the scope.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
_nodes: NDArray[np.str_]
|
|
33
|
+
|
|
34
|
+
def __init__(self, nodes: NDArray[np.str_] | list[str]):
|
|
35
|
+
if isinstance(nodes, list):
|
|
36
|
+
nodes = np.array(nodes, dtype=np.str_)
|
|
37
|
+
self._nodes = np.sort(np.unique(nodes))
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
@override
|
|
41
|
+
def node_ids(self) -> NDArray[np.str_]:
|
|
42
|
+
return self._nodes
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def select(self) -> "CustomSelector":
|
|
46
|
+
"""Create a selection from this scope."""
|
|
47
|
+
return CustomSelector(self, CustomSelection)
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
@override
|
|
51
|
+
def geography(self) -> Never:
|
|
52
|
+
"""Automatic geography is not supported for custom scopes."""
|
|
53
|
+
raise GeographyError("Geography is not possible for CustomScopes.")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class CustomSelection(GeoSelection[CustomScope]):
|
|
58
|
+
"""
|
|
59
|
+
A `GeoSelection` on a `CustomScope`.
|
|
60
|
+
|
|
61
|
+
Typically you will create one of these by calling methods on a `GeoSelector`
|
|
62
|
+
instance.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def group(self, grouping: GeoGrouping) -> GeoGroup[CustomScope]:
|
|
66
|
+
"""
|
|
67
|
+
Group the geo axis using the specified grouping.
|
|
68
|
+
|
|
69
|
+
Parameters
|
|
70
|
+
----------
|
|
71
|
+
grouping :
|
|
72
|
+
The grouping to use.
|
|
73
|
+
|
|
74
|
+
Returns
|
|
75
|
+
-------
|
|
76
|
+
:
|
|
77
|
+
The grouping strategy.
|
|
78
|
+
"""
|
|
79
|
+
return GeoGroup(self.scope, self.selection, grouping)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True)
|
|
83
|
+
class CustomSelector(GeoSelector[CustomScope, CustomSelection]):
|
|
84
|
+
"""A `GeoSelector` for `CustomScopes`."""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@strategy_to_scope.register
|
|
88
|
+
def _custom_strategy_to_scope(
|
|
89
|
+
scope: CustomScope,
|
|
90
|
+
strategy: GeoStrategy[CustomScope],
|
|
91
|
+
) -> GeoScope:
|
|
92
|
+
selected = scope.node_ids[strategy.selection]
|
|
93
|
+
return CustomScope(selected)
|