MnMS 1.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.
- mnms/__init__.py +4 -0
- mnms/cli/__init__.py +0 -0
- mnms/cli/run.py +334 -0
- mnms/demand/__init__.py +6 -0
- mnms/demand/horizon.py +41 -0
- mnms/demand/manager.py +260 -0
- mnms/demand/user.py +904 -0
- mnms/flow/MFD.py +399 -0
- mnms/flow/__init__.py +3 -0
- mnms/flow/abstract.py +139 -0
- mnms/flow/congested_MFD.py +225 -0
- mnms/flow/user_flow.py +383 -0
- mnms/generation/__init__.py +0 -0
- mnms/generation/demand.py +92 -0
- mnms/generation/layers.py +140 -0
- mnms/generation/mlgraph.py +31 -0
- mnms/generation/roads.py +401 -0
- mnms/generation/zones.py +78 -0
- mnms/graph/__init__.py +0 -0
- mnms/graph/dynamic_space_sharing.py +291 -0
- mnms/graph/layers.py +1071 -0
- mnms/graph/road.py +125 -0
- mnms/graph/specific_layers.py +35 -0
- mnms/graph/zone.py +86 -0
- mnms/io/__init__.py +0 -0
- mnms/io/graph.py +165 -0
- mnms/io/utils.py +25 -0
- mnms/log.py +58 -0
- mnms/mobility_service/__init__.py +3 -0
- mnms/mobility_service/abstract.py +836 -0
- mnms/mobility_service/filters.py +464 -0
- mnms/mobility_service/interfaces.py +40 -0
- mnms/mobility_service/on_demand.py +715 -0
- mnms/mobility_service/on_demand_shared.py +738 -0
- mnms/mobility_service/personal_vehicle.py +104 -0
- mnms/mobility_service/public_transport.py +703 -0
- mnms/mobility_service/vehicle_sharing.py +339 -0
- mnms/simulation.py +537 -0
- mnms/time.py +312 -0
- mnms/tools/__init__.py +0 -0
- mnms/tools/cost.py +16 -0
- mnms/tools/dict_tools.py +14 -0
- mnms/tools/exceptions.py +28 -0
- mnms/tools/geometry.py +135 -0
- mnms/tools/observer.py +183 -0
- mnms/tools/preprocessing.py +135 -0
- mnms/tools/progress.py +62 -0
- mnms/tools/render.py +357 -0
- mnms/travel_decision/__init__.py +5 -0
- mnms/travel_decision/abstract.py +967 -0
- mnms/travel_decision/dummy.py +66 -0
- mnms/travel_decision/logit.py +168 -0
- mnms/vehicles/__init__.py +0 -0
- mnms/vehicles/fleet.py +38 -0
- mnms/vehicles/manager.py +62 -0
- mnms/vehicles/veh_type.py +569 -0
- mnms-1.1.0.dist-info/METADATA +141 -0
- mnms-1.1.0.dist-info/RECORD +61 -0
- mnms-1.1.0.dist-info/WHEEL +4 -0
- mnms-1.1.0.dist-info/entry_points.txt +2 -0
- mnms-1.1.0.dist-info/licenses/LICENSE +165 -0
mnms/__init__.py
ADDED
mnms/cli/__init__.py
ADDED
|
File without changes
|
mnms/cli/run.py
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import json
|
|
3
|
+
import math
|
|
4
|
+
from functools import partial
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from mnms.demand import CSVDemandManager
|
|
9
|
+
from mnms.flow.MFD import MFDFlowMotor, Reservoir
|
|
10
|
+
from mnms.io.graph import load_graph, load_odlayer
|
|
11
|
+
from mnms.log import LOGLEVEL, attach_log_file, set_mnms_logger_level
|
|
12
|
+
from mnms.mobility_service.personal_vehicle import PersonalMobilityService
|
|
13
|
+
from mnms.mobility_service.public_transport import PublicTransportMobilityService
|
|
14
|
+
from mnms.simulation import Supervisor
|
|
15
|
+
from mnms.time import Dt, Time
|
|
16
|
+
from mnms.tools.observer import CSVUserObserver, CSVVehicleObserver
|
|
17
|
+
from mnms.travel_decision.dummy import DummyDecisionModel
|
|
18
|
+
from mnms.travel_decision.logit import LogitDecisionModel
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class MnMSParameters:
|
|
22
|
+
"""Load and provide access to a MnMS simulation configuration."""
|
|
23
|
+
|
|
24
|
+
_SECTIONS = (
|
|
25
|
+
"GRAPH",
|
|
26
|
+
"DEMAND",
|
|
27
|
+
"FLOW_MOTOR",
|
|
28
|
+
"DECISION_MODEL",
|
|
29
|
+
"SCENARIO"
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
def __init__(self, config_file: str | Path) -> None:
|
|
33
|
+
self.config_file = Path(config_file).expanduser().resolve()
|
|
34
|
+
with self.config_file.open(encoding="utf-8") as parameter_file:
|
|
35
|
+
config = json.load(parameter_file)
|
|
36
|
+
|
|
37
|
+
for section_name in self._SECTIONS:
|
|
38
|
+
section = config.get(section_name)
|
|
39
|
+
if not isinstance(section, (dict, list)):
|
|
40
|
+
raise ValueError( # noqa: TRY004
|
|
41
|
+
f"Missing or invalid '{section_name}' section in {self.config_file}"
|
|
42
|
+
)
|
|
43
|
+
setattr(self, section_name.lower(), section)
|
|
44
|
+
|
|
45
|
+
def _resolve_path(self, base_directory: str, configured_path: str) -> Path:
|
|
46
|
+
path = Path(configured_path.lstrip("/\\"))
|
|
47
|
+
return (self.config_file.parent / base_directory / path).resolve()
|
|
48
|
+
|
|
49
|
+
# GRAPH
|
|
50
|
+
@property
|
|
51
|
+
def network_file(self) -> str:
|
|
52
|
+
return str(self._resolve_path("", self.graph["network_file"]))
|
|
53
|
+
|
|
54
|
+
# OD_LAYER
|
|
55
|
+
@property
|
|
56
|
+
def odlayer_file(self) -> str:
|
|
57
|
+
return str(self._resolve_path("", self.graph["OD_LAYER"]["file"]))
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def odlayer_connection_distance(self) -> float:
|
|
61
|
+
return self.graph["OD_LAYER"]["connection_distance"]
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def mobility_services(self) -> list[dict]:
|
|
65
|
+
return self.graph.get("MOBILITY_SERVICES", [])
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def intra_layer_connections(self) -> list[dict]:
|
|
69
|
+
return self.graph.get("CONNECTION_INTRA_LAYER", [])
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def inter_layers_connections(self) -> list[dict]:
|
|
73
|
+
return self.graph.get("CONNECTION_INTER_LAYERS", [])
|
|
74
|
+
|
|
75
|
+
# DEMAND
|
|
76
|
+
@property
|
|
77
|
+
def demand_file(self) -> str:
|
|
78
|
+
return str(self._resolve_path("", self.demand["file"]))
|
|
79
|
+
|
|
80
|
+
# FLOW_MOTOR
|
|
81
|
+
@property
|
|
82
|
+
def MFD_parameters(self) -> list[dict[str, Any]]:
|
|
83
|
+
return self.flow_motor.get("MFD", [])
|
|
84
|
+
|
|
85
|
+
# DECISION_MODEL
|
|
86
|
+
@property
|
|
87
|
+
def decision_model_type(self) -> str:
|
|
88
|
+
return self.decision_model.get("model", "logit")
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def decision_model_nb_shortest_paths(self) -> int:
|
|
92
|
+
return self.decision_model.get("n_shortest_path", 3)
|
|
93
|
+
|
|
94
|
+
# SCENARIO
|
|
95
|
+
@property
|
|
96
|
+
def start_time(self) -> Time:
|
|
97
|
+
return Time(self.scenario["start"])
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def end_time(self) -> Time:
|
|
101
|
+
return Time(self.scenario["end"])
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def flow_timestep(self) -> Dt:
|
|
105
|
+
return Dt(seconds=self.scenario["flow_timestep"])
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def assignment_factor(self) -> int:
|
|
109
|
+
return self.scenario.get("assignment_factor", 10)
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def output_directory(self) -> Path:
|
|
113
|
+
return self._resolve_path("", self.scenario["output_dir"])
|
|
114
|
+
|
|
115
|
+
def output_path(self, configured_path: str) -> Path:
|
|
116
|
+
return self._resolve_path(self.scenario["output_dir"], configured_path)
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def log_level(self) -> int:
|
|
120
|
+
configured_level = self.scenario["logger_level"].removeprefix("LOGLEVEL.")
|
|
121
|
+
try:
|
|
122
|
+
return getattr(LOGLEVEL, configured_level)
|
|
123
|
+
except AttributeError as error:
|
|
124
|
+
raise ValueError(f"Unknown log level: {self.scenario['logger_level']}") from error
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def calculate_speed_from_MFD(
|
|
128
|
+
accumulations: dict[str, float],
|
|
129
|
+
mfd_by_mode: dict[str, list[dict[str, Any]]],
|
|
130
|
+
) -> dict[str, float]:
|
|
131
|
+
speeds = {}
|
|
132
|
+
for mode, ranges in mfd_by_mode.items():
|
|
133
|
+
accumulation = accumulations.get(mode, 0)
|
|
134
|
+
for accumulation_range in ranges:
|
|
135
|
+
minimum = float(accumulation_range["min"])
|
|
136
|
+
maximum_value = accumulation_range["max"]
|
|
137
|
+
maximum = math.inf if maximum_value == "inf" else float(maximum_value)
|
|
138
|
+
if minimum <= accumulation <= maximum:
|
|
139
|
+
speeds[mode] = (
|
|
140
|
+
float(accumulation_range["slope"]) * accumulation
|
|
141
|
+
+ float(accumulation_range["intercept"])
|
|
142
|
+
)
|
|
143
|
+
break
|
|
144
|
+
else:
|
|
145
|
+
raise ValueError(
|
|
146
|
+
f"No MFD accumulation range configured for mode '{mode}' "
|
|
147
|
+
f"at accumulation {accumulation}"
|
|
148
|
+
)
|
|
149
|
+
return speeds
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _mfd_parameters_by_mode(
|
|
153
|
+
reservoir_id: str,
|
|
154
|
+
mfd_parameters: list[dict[str, Any]],
|
|
155
|
+
layers: dict[str, Any],
|
|
156
|
+
) -> dict[str, list[dict[str, Any]]]:
|
|
157
|
+
mfd_by_mode = {}
|
|
158
|
+
for reservoir_parameters in mfd_parameters:
|
|
159
|
+
if reservoir_parameters.get("reservoir_id") != reservoir_id:
|
|
160
|
+
continue
|
|
161
|
+
|
|
162
|
+
layer_parameters = reservoir_parameters.get(
|
|
163
|
+
"MFD", reservoir_parameters.get("MFD_param", [])
|
|
164
|
+
)
|
|
165
|
+
for layer_parameter in layer_parameters:
|
|
166
|
+
layer_name = layer_parameter["layer"]
|
|
167
|
+
if layer_name not in layers:
|
|
168
|
+
raise ValueError(
|
|
169
|
+
f"MFD configuration for reservoir '{reservoir_id}' "
|
|
170
|
+
f"references unknown layer '{layer_name}'"
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
mode = layers[layer_name]._veh_type.__name__.upper()
|
|
174
|
+
ranges = layer_parameter["acc_ranges"]
|
|
175
|
+
if mode in mfd_by_mode and mfd_by_mode[mode] != ranges:
|
|
176
|
+
raise ValueError(
|
|
177
|
+
f"Conflicting MFD configuration for mode '{mode}' "
|
|
178
|
+
f"in reservoir '{reservoir_id}'"
|
|
179
|
+
)
|
|
180
|
+
mfd_by_mode[mode] = ranges
|
|
181
|
+
|
|
182
|
+
if not mfd_by_mode:
|
|
183
|
+
raise ValueError(f"No MFD configuration found for reservoir '{reservoir_id}'")
|
|
184
|
+
return mfd_by_mode
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def run_simulation(parameters: MnMSParameters) -> None:
|
|
188
|
+
|
|
189
|
+
parameters.output_directory.mkdir(parents=True, exist_ok=True)
|
|
190
|
+
set_mnms_logger_level(parameters.log_level, ["mnms.simulation"])
|
|
191
|
+
attach_log_file(str(parameters.output_path("log.log")))
|
|
192
|
+
|
|
193
|
+
veh_observer = CSVVehicleObserver(str(parameters.output_path("veh.csv")))
|
|
194
|
+
|
|
195
|
+
# Create the graph from the network file
|
|
196
|
+
print(f"Loading graph from {parameters.network_file}...")
|
|
197
|
+
mmgraph = load_graph(parameters.network_file)
|
|
198
|
+
|
|
199
|
+
# Add the origin-destination layer
|
|
200
|
+
print(f"Loading OD layer from {parameters.odlayer_file}...")
|
|
201
|
+
odlayer = load_odlayer(parameters.odlayer_file)
|
|
202
|
+
mmgraph.add_origin_destination_layer(odlayer)
|
|
203
|
+
mmgraph.connect_origindestination_layers(parameters.odlayer_connection_distance)
|
|
204
|
+
|
|
205
|
+
# Create the mobility services
|
|
206
|
+
print("Creating mobility services...")
|
|
207
|
+
for ms in parameters.mobility_services:
|
|
208
|
+
layer_name = ms["layer"]
|
|
209
|
+
if layer_name not in mmgraph.layers:
|
|
210
|
+
raise ValueError(f"Layer '{layer_name}' not found in the graph.")
|
|
211
|
+
else:
|
|
212
|
+
ms_type = ms["mobility_service_type"]
|
|
213
|
+
if ms_type == "PersonalMobilityService":
|
|
214
|
+
mobility_service = PersonalMobilityService()
|
|
215
|
+
elif ms_type == "PublicTransportMobilityService":
|
|
216
|
+
mobility_service = PublicTransportMobilityService(ms["label"])
|
|
217
|
+
else:
|
|
218
|
+
raise ValueError(f"Unknown mobility service type: {ms_type}")
|
|
219
|
+
|
|
220
|
+
# Attach the mobility service to the corresponding layer
|
|
221
|
+
layer_name = ms["layer"]
|
|
222
|
+
mmgraph.layers[layer_name].add_mobility_service(mobility_service)
|
|
223
|
+
|
|
224
|
+
mobility_service.attach_vehicle_observer(veh_observer)
|
|
225
|
+
|
|
226
|
+
# Connect the layers (intra-layer and inter-layer connections)
|
|
227
|
+
print("Connecting layers...")
|
|
228
|
+
for conn in parameters.intra_layer_connections:
|
|
229
|
+
mmgraph.connect_intra_layer(conn["layer"], conn["connection_distance"])
|
|
230
|
+
|
|
231
|
+
for conn in parameters.inter_layers_connections:
|
|
232
|
+
mmgraph.connect_inter_layers(conn["layers"], conn["connection_distance"])
|
|
233
|
+
|
|
234
|
+
# Load demand and create the demand manager
|
|
235
|
+
demand = CSVDemandManager(parameters.demand_file)
|
|
236
|
+
demand.add_user_observer(CSVUserObserver(str(parameters.output_path("user.csv"))), user_ids="all")
|
|
237
|
+
|
|
238
|
+
# Create the flow motor and add reservoirs
|
|
239
|
+
print("Creating flow motor...")
|
|
240
|
+
flow_motor = MFDFlowMotor(outfile=str(parameters.output_path("flow.csv")))
|
|
241
|
+
|
|
242
|
+
for res in mmgraph.roads.zones.values():
|
|
243
|
+
mfd_by_mode = _mfd_parameters_by_mode(
|
|
244
|
+
res.id, parameters.MFD_parameters, mmgraph.layers
|
|
245
|
+
)
|
|
246
|
+
mfd_speed = partial(calculate_speed_from_MFD, mfd_by_mode=mfd_by_mode)
|
|
247
|
+
flow_motor.add_reservoir(Reservoir(res, list(mfd_by_mode), mfd_speed))
|
|
248
|
+
|
|
249
|
+
# Create the travel decision model
|
|
250
|
+
print(f"Creating decision model of type '{parameters.decision_model_type}'...")
|
|
251
|
+
if parameters.decision_model_type == "logit":
|
|
252
|
+
decision_model_class = LogitDecisionModel
|
|
253
|
+
elif parameters.decision_model_type == "dummy":
|
|
254
|
+
decision_model_class = DummyDecisionModel
|
|
255
|
+
else:
|
|
256
|
+
raise ValueError(f"Unknown decision model: {parameters.decision_model_type}")
|
|
257
|
+
|
|
258
|
+
decision_model = decision_model_class(
|
|
259
|
+
mmgraph,
|
|
260
|
+
outfile=str(parameters.output_path("path.csv")),
|
|
261
|
+
n_shortest_path=parameters.decision_model_nb_shortest_paths,
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
# Create the supervisor
|
|
265
|
+
print("Creating supervisor...")
|
|
266
|
+
supervisor = Supervisor(
|
|
267
|
+
graph=mmgraph,
|
|
268
|
+
flow_motor=flow_motor,
|
|
269
|
+
demand=demand,
|
|
270
|
+
decision_model=decision_model,
|
|
271
|
+
outfile=str(parameters.output_path("travel_time.csv")),
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
# Run the simulation
|
|
275
|
+
supervisor.run(
|
|
276
|
+
parameters.start_time,
|
|
277
|
+
parameters.end_time,
|
|
278
|
+
parameters.flow_timestep,
|
|
279
|
+
parameters.assignment_factor,
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
_DESCRIPTION = """\
|
|
284
|
+
Run a MnMS simulation.
|
|
285
|
+
|
|
286
|
+
Read a JSON configuration file, build the multimodal network, the demand,
|
|
287
|
+
the flow model and the travel decision model, then run the MnMS simulation
|
|
288
|
+
over the configured time period. Simulation results and logs are saved
|
|
289
|
+
to the configured output directory."""
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
_EPILOG = """\
|
|
293
|
+
configuration file:
|
|
294
|
+
The JSON configuration contains the following sections:
|
|
295
|
+
|
|
296
|
+
GRAPH Network file, origin-destination layer and connection distance,
|
|
297
|
+
mobility services, and connections between layers.
|
|
298
|
+
DEMAND CSV file containing the demand to load.
|
|
299
|
+
FLOW_MOTOR MFD parameters for each reservoir and layer.
|
|
300
|
+
Each accumulation range specifies min, max (or "inf"),
|
|
301
|
+
slope, and intercept.
|
|
302
|
+
Speed is computed as `slope × accumulation + intercept`.
|
|
303
|
+
DECISION_MODEL Decision model ("logit" or "dummy") and the number of
|
|
304
|
+
shortest paths to consider.
|
|
305
|
+
SCENARIO Start and end times, flow timestep in seconds, assignment factor,
|
|
306
|
+
output directory, and log level ("DEBUG", "INFO", "WARNING",
|
|
307
|
+
"ERROR" or "CRITICAL").
|
|
308
|
+
|
|
309
|
+
Input paths and the output directory are resolved relative to the directory
|
|
310
|
+
containing the configuration file. Configured layers and mobility service types
|
|
311
|
+
must match the network. Each road reservoir must also have MFD parameters
|
|
312
|
+
for its layers.
|
|
313
|
+
|
|
314
|
+
An example configuration file is available at:
|
|
315
|
+
https://github.com/EMob-Lab/MnMS/tree/main/examples/cli"""
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def main() -> None:
|
|
319
|
+
"""CLI application entry point."""
|
|
320
|
+
|
|
321
|
+
parser = argparse.ArgumentParser(
|
|
322
|
+
description=_DESCRIPTION,
|
|
323
|
+
epilog=_EPILOG,
|
|
324
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
325
|
+
)
|
|
326
|
+
parser.add_argument(
|
|
327
|
+
"config_file",
|
|
328
|
+
type=Path,
|
|
329
|
+
help="path to the JSON configuration file",
|
|
330
|
+
)
|
|
331
|
+
arguments = parser.parse_args()
|
|
332
|
+
run_simulation(MnMSParameters(arguments.config_file))
|
|
333
|
+
|
|
334
|
+
print("Simulation completed successfully")
|
mnms/demand/__init__.py
ADDED
mnms/demand/horizon.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
|
|
3
|
+
from mnms.demand import User
|
|
4
|
+
from mnms.demand.manager import AbstractDemandManager
|
|
5
|
+
from mnms.time import Dt, Time
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AbstractDemandHorizon(ABC):
|
|
9
|
+
def __init__(self, manager: AbstractDemandManager, dt: Dt):
|
|
10
|
+
"""
|
|
11
|
+
Abstraction of the demand horizon, it provides the next demand for the current time until current time + dt
|
|
12
|
+
|
|
13
|
+
Args:
|
|
14
|
+
manager: The demand manager
|
|
15
|
+
dt: The time window of the horizon
|
|
16
|
+
|
|
17
|
+
"""
|
|
18
|
+
self.dt: Dt = dt
|
|
19
|
+
self.manager: AbstractDemandManager = manager.copy()
|
|
20
|
+
|
|
21
|
+
@abstractmethod
|
|
22
|
+
def get(self, tstart: Time) -> list[User]:
|
|
23
|
+
"""
|
|
24
|
+
Return a list of User from tsart to start + dt
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
tstart: the start time of the horizon
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
A list of Users
|
|
31
|
+
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class DemandHorizon(AbstractDemandHorizon):
|
|
36
|
+
"""
|
|
37
|
+
A simple implementation of the Demand Horizon that returns the exact demand
|
|
38
|
+
between tstart and tstart + dt
|
|
39
|
+
"""
|
|
40
|
+
def get(self, tstart: Time):
|
|
41
|
+
return self.manager.get_next_departures(tstart, tstart.add_time(self.dt))
|
mnms/demand/manager.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import re
|
|
3
|
+
import sys
|
|
4
|
+
from abc import ABC, abstractmethod
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from pathlib import Path as Pathl
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
from mnms.demand.user import Path, User
|
|
13
|
+
from mnms.log import create_logger
|
|
14
|
+
from mnms.time import Time
|
|
15
|
+
from mnms.tools.exceptions import CSVDemandParseError
|
|
16
|
+
from mnms.tools.observer import Observer
|
|
17
|
+
|
|
18
|
+
log = create_logger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AbstractDemandManager(ABC):
|
|
22
|
+
"""Abstract class for loading a User demand
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(self, user_parameters: Callable[[User], dict] = lambda x: {}):
|
|
26
|
+
self._observers = []
|
|
27
|
+
self._user_to_attach = []
|
|
28
|
+
self._user_parameter = user_parameters
|
|
29
|
+
|
|
30
|
+
@abstractmethod
|
|
31
|
+
def get_next_departures(self, tstart: Time, tend: Time) -> list[User]:
|
|
32
|
+
"""Return the Users with a departure time between tstart and tend
|
|
33
|
+
|
|
34
|
+
Parameters
|
|
35
|
+
----------
|
|
36
|
+
tstart: Time
|
|
37
|
+
Lower bound of departure time
|
|
38
|
+
tend: Time
|
|
39
|
+
Upper bound of departure time
|
|
40
|
+
|
|
41
|
+
Returns
|
|
42
|
+
-------
|
|
43
|
+
List[User]
|
|
44
|
+
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def construct_user_parameters(self, users: list[User]) -> None:
|
|
48
|
+
for u in users:
|
|
49
|
+
u.parameters = self._user_parameter(u)
|
|
50
|
+
|
|
51
|
+
@abstractmethod
|
|
52
|
+
def copy(self):
|
|
53
|
+
pass
|
|
54
|
+
|
|
55
|
+
def add_user_observer(self, obs: Observer, user_ids: Literal['all'] | list[str] = "all"):
|
|
56
|
+
self._observers.append(obs)
|
|
57
|
+
self._user_to_attach.append(user_ids)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class BaseDemandManager(AbstractDemandManager):
|
|
61
|
+
"""Basic demand manager, it takes a list of User as input
|
|
62
|
+
|
|
63
|
+
Parameters
|
|
64
|
+
----------
|
|
65
|
+
users: List[User]
|
|
66
|
+
list of User to manage
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def __init__(self, users, user_parameters: Callable[[User], dict] = lambda x: {}):
|
|
70
|
+
super().__init__(user_parameters)
|
|
71
|
+
self._users = users
|
|
72
|
+
self._iter_demand = iter(self._users)
|
|
73
|
+
self._current_user = next(self._iter_demand)
|
|
74
|
+
|
|
75
|
+
self.nb_users = len(self._users)
|
|
76
|
+
|
|
77
|
+
def get_next_departures(self, tstart: Time, tend: Time) -> list[User]:
|
|
78
|
+
departure = []
|
|
79
|
+
while tstart <= self._current_user.departure_time < tend:
|
|
80
|
+
# Attaching observers to Users
|
|
81
|
+
for iobs, obs in enumerate(self._observers):
|
|
82
|
+
if self._user_to_attach[iobs] == 'all' or self._current_user.id in self._user_to_attach[iobs]:
|
|
83
|
+
self._current_user.attach(obs)
|
|
84
|
+
|
|
85
|
+
departure.append(self._current_user)
|
|
86
|
+
try:
|
|
87
|
+
self._current_user = next(self._iter_demand)
|
|
88
|
+
except StopIteration:
|
|
89
|
+
return departure
|
|
90
|
+
return departure
|
|
91
|
+
|
|
92
|
+
def copy(self):
|
|
93
|
+
cls = self.__class__
|
|
94
|
+
copy = cls(self._users)
|
|
95
|
+
return copy
|
|
96
|
+
|
|
97
|
+
def show_users(self):
|
|
98
|
+
for u in self._users:
|
|
99
|
+
print(u)
|
|
100
|
+
|
|
101
|
+
def to_csv(self, file: Pathl | str, delimiter=";"):
|
|
102
|
+
with open(file, 'w') as f:
|
|
103
|
+
writer = csv.writer(f, delimiter=delimiter)
|
|
104
|
+
writer.writerow(["ID", "DEPARTURE", "ORIGIN", "DESTINATION"])
|
|
105
|
+
|
|
106
|
+
for u in self._users:
|
|
107
|
+
writer.writerow([u.id, u.departure_time, u.origin, u.destination])
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class CSVDemandManager(AbstractDemandManager):
|
|
111
|
+
"""Read a demand from a CSV file
|
|
112
|
+
|
|
113
|
+
Parameters
|
|
114
|
+
----------
|
|
115
|
+
csvfile: str
|
|
116
|
+
Path to the CSV file
|
|
117
|
+
demand_type: Literal[node, coordinate]
|
|
118
|
+
Type of demand, either the origin?destination are node ids or coordinates
|
|
119
|
+
delimiter: str
|
|
120
|
+
Delimiter for the CSV file
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
def init_demand_reader(self, csvfile: Pathl | str):
|
|
124
|
+
|
|
125
|
+
mandatory_columns = ['ID', 'DEPARTURE', 'ORIGIN', 'DESTINATION']
|
|
126
|
+
time_format_1 = "%H:%M:%S"
|
|
127
|
+
time_format_2 = "%H:%M:%S.%f"
|
|
128
|
+
|
|
129
|
+
try:
|
|
130
|
+
headers = next(self._reader)
|
|
131
|
+
if headers[:4] != mandatory_columns:
|
|
132
|
+
raise CSVDemandParseError(csvfile)
|
|
133
|
+
optional_columns = [h for h in headers if h not in mandatory_columns]
|
|
134
|
+
self._optional_columns = {c: headers.index(c) for c in optional_columns}
|
|
135
|
+
# Small checks on consistency of optional columns
|
|
136
|
+
noms = 'MOBILITY SERVICES' not in self._optional_columns
|
|
137
|
+
nomsg = 'MOBILITY SERVICES GRAPH' not in self._optional_columns
|
|
138
|
+
if (noms and nomsg) or (noms and not nomsg) or (not noms and nomsg):
|
|
139
|
+
pass
|
|
140
|
+
else:
|
|
141
|
+
raise CSVDemandParseError(csvfile)
|
|
142
|
+
nop = 'PATH' not in self._optional_columns
|
|
143
|
+
nocms = 'CHOSEN SERVICES' not in self._optional_columns
|
|
144
|
+
if (nop and nocms) or (not nop and not nocms):
|
|
145
|
+
pass
|
|
146
|
+
else:
|
|
147
|
+
raise CSVDemandParseError(csvfile)
|
|
148
|
+
except StopIteration:
|
|
149
|
+
log.error(f'{self._filename} is empty')
|
|
150
|
+
sys.exit(-1)
|
|
151
|
+
|
|
152
|
+
first_line = next(self._reader)
|
|
153
|
+
departure_time = first_line[1]
|
|
154
|
+
try:
|
|
155
|
+
datetime.strptime(departure_time, time_format_1).replace(tzinfo=timezone.utc)
|
|
156
|
+
except ValueError:
|
|
157
|
+
try:
|
|
158
|
+
datetime.strptime(departure_time, time_format_2).replace(tzinfo=timezone.utc)
|
|
159
|
+
except ValueError:
|
|
160
|
+
raise CSVDemandParseError(csvfile)
|
|
161
|
+
match_x = re.match(r'^[-+]?[0-9]*\.*[0-9]*\d\s[-+]?[0-9]*\.*[0-9]*\d$', first_line[2])
|
|
162
|
+
match_y = re.match(r'^[-+]?[0-9]*\.*[0-9]*\d\s[-+]?[0-9]*\.*[0-9]*\d$', first_line[3])
|
|
163
|
+
if match_x is not None and match_y is not None:
|
|
164
|
+
self._demand_type = 'coordinate'
|
|
165
|
+
else:
|
|
166
|
+
match_x = re.match(r'^\w+$', first_line[2].strip())
|
|
167
|
+
match_y = re.match(r'^\w+$', first_line[3].strip())
|
|
168
|
+
if match_x is not None and match_y is not None:
|
|
169
|
+
self._demand_type = 'node'
|
|
170
|
+
else:
|
|
171
|
+
raise CSVDemandParseError(csvfile)
|
|
172
|
+
|
|
173
|
+
self._current_user = self.construct_user(first_line)
|
|
174
|
+
|
|
175
|
+
def __init__(self, csvfile: Pathl | str, delimiter=';', user_parameters: Callable[[User], dict] = lambda x: {}):
|
|
176
|
+
super().__init__(user_parameters)
|
|
177
|
+
self._filename = csvfile
|
|
178
|
+
self._delimiter = delimiter
|
|
179
|
+
self._file = open(self._filename, 'r')
|
|
180
|
+
self._reader = csv.reader(self._file, delimiter=self._delimiter, quotechar='|')
|
|
181
|
+
self._demand_type = None
|
|
182
|
+
self._optional_columns = None
|
|
183
|
+
|
|
184
|
+
self._current_user= None
|
|
185
|
+
|
|
186
|
+
self.init_demand_reader(csvfile)
|
|
187
|
+
|
|
188
|
+
def __getstate__(self):
|
|
189
|
+
|
|
190
|
+
state = self.__dict__.copy()
|
|
191
|
+
|
|
192
|
+
if '_reader' in state:
|
|
193
|
+
del state['_reader']
|
|
194
|
+
|
|
195
|
+
return state
|
|
196
|
+
|
|
197
|
+
def __setstate__(self, state):
|
|
198
|
+
|
|
199
|
+
self.__dict__.update(state)
|
|
200
|
+
self._reader = csv.reader(self._file, delimiter=self._delimiter, quotechar='|')
|
|
201
|
+
self.init_demand_reader(self._filename)
|
|
202
|
+
|
|
203
|
+
def get_next_departures(self, tstart: Time, tend: Time) -> list[User]:
|
|
204
|
+
departure = []
|
|
205
|
+
|
|
206
|
+
# If the lower bound of next departures is after the fist departure in the demand, we skip the first users until
|
|
207
|
+
# reaching the lower bound of next departures
|
|
208
|
+
while self._current_user.departure_time < tstart:
|
|
209
|
+
try:
|
|
210
|
+
self._current_user = self.construct_user(next(self._reader))
|
|
211
|
+
except StopIteration:
|
|
212
|
+
return departure
|
|
213
|
+
|
|
214
|
+
while tstart <= self._current_user.departure_time < tend:
|
|
215
|
+
# Attaching observers to Users
|
|
216
|
+
for iobs, obs in enumerate(self._observers):
|
|
217
|
+
if self._user_to_attach[iobs] == 'all' or self._current_user.id in self._user_to_attach[iobs]:
|
|
218
|
+
self._current_user.attach(obs)
|
|
219
|
+
|
|
220
|
+
departure.append(self._current_user)
|
|
221
|
+
try:
|
|
222
|
+
self._current_user = self.construct_user(next(self._reader))
|
|
223
|
+
except StopIteration:
|
|
224
|
+
return departure
|
|
225
|
+
|
|
226
|
+
return departure
|
|
227
|
+
|
|
228
|
+
def copy(self):
|
|
229
|
+
cls = self.__class__
|
|
230
|
+
copy = cls(self._filename, self._delimiter)
|
|
231
|
+
return copy
|
|
232
|
+
|
|
233
|
+
def construct_user(self, row) -> User:
|
|
234
|
+
if self._demand_type == 'node':
|
|
235
|
+
origin = row[2]
|
|
236
|
+
destination = row[3]
|
|
237
|
+
elif self._demand_type == 'coordinate':
|
|
238
|
+
origin = np.fromstring(row[2], sep=' ')
|
|
239
|
+
destination = np.fromstring(row[3], sep=' ')
|
|
240
|
+
else:
|
|
241
|
+
raise TypeError("demand_type must be either 'node' or 'coordinate'")
|
|
242
|
+
forced_path = None
|
|
243
|
+
chosen_ms = None
|
|
244
|
+
if 'PATH' in self._optional_columns and row[self._optional_columns['PATH']] != '':
|
|
245
|
+
forced_path = Path(None, row[self._optional_columns['PATH']].split(' '))
|
|
246
|
+
chosen_ms = row[self._optional_columns['CHOSEN SERVICES']].split(' ')
|
|
247
|
+
chosen_ms = {cms.split(':')[0]:cms.split(':')[1] for cms in chosen_ms}
|
|
248
|
+
return User(
|
|
249
|
+
row[0],
|
|
250
|
+
origin,
|
|
251
|
+
destination,
|
|
252
|
+
Time(row[1]),
|
|
253
|
+
available_mobility_services=None if 'MOBILITY SERVICES' not in self._optional_columns else row[self._optional_columns['MOBILITY SERVICES']].split(' '),
|
|
254
|
+
mobility_services_graph=None if 'MOBILITY SERVICES GRAPH' not in self._optional_columns else row[self._optional_columns['MOBILITY SERVICES GRAPH']],
|
|
255
|
+
path=forced_path,
|
|
256
|
+
forced_path_chosen_mobility_services=chosen_ms
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
def __del__(self):
|
|
260
|
+
self._file.close()
|