Repository navigation
Expand file tree
/
Copy pathscenario_example.py
More file actions
369 lines (317 loc) · 10.8 KB
/
Copy pathscenario_example.py
File metadata and controls
369 lines (317 loc) · 10.8 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
"""Example mosaik scenario: OMOD EV agents coupled with midas-powergrid.
This script demonstrates how to:
1. Start the OmodSimulator with an OMOD JSON file (or auto-generate
one by running OMOD from Python).
2. Create N EV agents with dynamic bus mapping.
3. Route EV charging power to the correct grid bus via LoadRouter
entities, which handle the dynamic bus-to-load mapping that mosaik's
static topology cannot express natively.
4. Run the simulation for 24 hours with step_size = 60 seconds.
5. Persist results via midas-store.
Prerequisites
-------------
- ``midas-mosaik``, ``midas-powergrid``, and ``midas-omod`` must be
installed.
- Either an OMOD JSON file, or Java + OMOD JAR for auto-generation.
Usage
-----
::
# Use an existing OMOD JSON file:
python scenario_example.py --json-path path/to/omod_output.json
# Auto-run OMOD from Python:
python scenario_example.py \
--omod-jar /path/to/omod.jar \
--osm-file region.osm.pbf \
--area-geojson area.geojson \
--n-agents-omod 100 --n-days-omod 1
::
# Use the test fixture (no OMOD or Java required):
python scenario_example.py \
--json-path midas_omod/tests/data/test_agents.json \
--num-agents 2
"""
from __future__ import annotations
import argparse
import importlib.util
import sys
from pathlib import Path
import mosaik # noqa: I001
# ------------------------------------------------------------------
# Configuration
# ------------------------------------------------------------------
SIM_CONFIG = {
"Omod": {
"python": "midas_omod.simulator:OmodSimulator",
},
"LoadRouter": {
"python": "midas_omod.load_router:LoadRouterSimulator",
},
"Powergrid": {
"python": "midas_powergrid.simulator:PandapowerSimulator",
},
"Store": {
"python": "midas_store.simulator:StoreSimulator",
},
}
# Simulation parameters
# time is in seconds; step_size = 60 s; 24 h = 86400 s -> 1440 steps
END = 24 * 60 * 60
STEP_SIZE = 60 # seconds
# ------------------------------------------------------------------
# Mosaik transform: kW -> MW
# ------------------------------------------------------------------
def kw_to_mw(value: float) -> float:
"""Convert kilowatts to megawatts."""
if value is None:
return 0.0
return value / 1000.0
# ------------------------------------------------------------------
# Main scenario
# ------------------------------------------------------------------
def main() -> int:
parser = argparse.ArgumentParser(
description="Run an OMOD + powergrid co-simulation scenario."
)
parser.add_argument(
"--json-path",
type=str,
default=None,
help="Path to the OMOD JSON output file. "
"Takes priority over --omod-jar auto-run.",
)
parser.add_argument(
"--num-agents",
type=int,
default=2,
help="Number of EV agents to create.",
)
parser.add_argument(
"--step-size",
type=int,
default=STEP_SIZE,
help="Step size in seconds.",
)
parser.add_argument(
"--end",
type=int,
default=END,
help="End time in seconds.",
)
# OMOD auto-run arguments.
parser.add_argument(
"--omod-jar",
type=str,
default=None,
help="Path to OMOD JAR file for auto-generation.",
)
parser.add_argument(
"--osm-file",
type=str,
default=None,
help="Path to OpenStreetMap .osm.pbf file.",
)
parser.add_argument(
"--area-geojson",
type=str,
default=None,
help="Path to focus area GeoJSON file.",
)
parser.add_argument(
"--n-agents-omod",
type=int,
default=100,
help="Number of agents for OMOD auto-run.",
)
parser.add_argument(
"--n-days-omod",
type=int,
default=1,
help="Number of days for OMOD auto-run.",
)
args = parser.parse_args()
# ------------------------------------------------------------------
# Determine JSON path: explicit > auto-run > test fixture
# ------------------------------------------------------------------
json_path = None
if args.json_path:
json_path = Path(args.json_path)
if not json_path.exists():
print(
f"Error: JSON file not found: {json_path}",
file=sys.stderr,
)
return 1
elif args.omod_jar and args.osm_file and args.area_geojson:
# Auto-run OMOD from Python.
from midas_omod.omod_runner import (
cached_omod_path,
run_omod,
)
cache_dir = ".cache/omod"
cached = cached_omod_path(
cache_dir,
args.omod_jar,
args.osm_file,
args.area_geojson,
args.n_agents_omod,
args.n_days_omod,
)
if cached is not None:
json_path = cached
else:
print("Running OMOD to generate mobility data...")
out_path = (
f"{cache_dir}/omod_output_{args.n_agents_omod}.json"
)
Path(cache_dir).mkdir(parents=True, exist_ok=True)
json_path = run_omod(
jar_path=args.omod_jar,
osm_file=args.osm_file,
area_geojson=args.area_geojson,
n_agents=args.n_agents_omod,
n_days=args.n_days_omod,
out_path=out_path,
)
print(f"OMOD output: {json_path}")
else:
# Default: use test fixture.
json_path = Path("midas_omod/tests/data/test_agents.json")
if not json_path.exists():
print(
"Error: No JSON path or OMOD parameters provided.\n"
"Use --json-path, or --omod-jar + --osm-file + "
"--area-geojson.",
file=sys.stderr,
)
return 1
# Check for optional dependencies before starting.
missing = []
if importlib.util.find_spec("midas_powergrid") is None:
missing.append("midas-powergrid")
if importlib.util.find_spec("midas_store") is None:
missing.append("midas-store")
if missing:
print(
"The following optional packages are required for the full "
"scenario but are not installed:",
file=sys.stderr,
)
for pkg in missing:
print(f" pip install {pkg}", file=sys.stderr)
print(
"\nInstall them and re-run, or use the OMOD simulator "
"standalone for mobility-only simulation.",
file=sys.stderr,
)
return 1
world = mosaik.World(SIM_CONFIG)
# ------------------------------------------------------------------
# Start simulators
# ------------------------------------------------------------------
# OMOD mobility simulator with bus mapper support.
# Use location_bus_mapping as fallback for grids without geodata.
location_bus_mapping = {
"HOME": "Bus-1-0",
"WORK": "Bus-1-1",
"OTHER": "Bus-1-2",
}
omod_sim = world.start(
"Omod",
time_resolution=args.step_size,
step_size=args.step_size,
json_path=str(json_path),
battery_capacity_kwh=60.0,
charging_power_kw=11.0,
consumption_kwh_per_km=0.18,
location_bus_mapping=location_bus_mapping,
)
# Power grid simulator (pandapower)
pg_sim = world.start(
"Powergrid",
time_resolution=args.step_size,
step_size=args.step_size,
gridfile="midasmv",
)
# LoadRouter simulator for dynamic bus routing.
router_sim = world.start(
"LoadRouter",
time_resolution=args.step_size,
step_size=args.step_size,
)
# Store (database for persistence)
store_sim = world.start(
"Store",
step_size=args.step_size,
filename="omod_powergrid_results.hdf5",
)
# ------------------------------------------------------------------
# Create models
# ------------------------------------------------------------------
# Create EV agents
ev_agents = omod_sim.EVAgent.create(num=args.num_agents)
# Create the power grid
grid = pg_sim.Grid()
# Get the load nodes from the grid.
loads = [e for e in grid.children if e.type == "Load"]
# Create a database
db = store_sim.Database()
# ------------------------------------------------------------------
# Dynamic bus routing via LoadRouter
# ------------------------------------------------------------------
#
# Mosaik connections are static — an EV agent cannot dynamically
# reconnect to a different Load entity at runtime. The LoadRouter
# solves this by acting as a filter: each LoadRoute entity is
# bound to a fixed target_bus_id, receives grid_power_mw and
# bus_id from all EV agents, and forwards only the power from
# agents currently at that bus.
#
# In a real scenario, we would extract bus coordinates from the
# pandapower grid and use BusMapper.nearest_bus(). Here we use a
# simplified mapping for demonstration.
# Build LoadRouter entities — one per available load.
num_loads = min(len(loads), 3) # HOME, WORK, OTHER
load_routers = []
bus_ids = ["Bus-1-0", "Bus-1-1", "Bus-1-2"]
for i in range(num_loads):
router = router_sim.LoadRoute.create(
num=1, target_bus_id=bus_ids[i]
)[0]
load_routers.append((router, loads[i], bus_ids[i]))
# Connect each EV agent's grid_power_mw and bus_id to each
# LoadRouter, and each LoadRouter's p_mw to the corresponding
# Load's p_mw.
for router, load, _bus_id in load_routers:
for ev in ev_agents:
world.connect(ev, router, "grid_power_mw", "bus_id")
world.connect(router, load, "p_mw")
# ------------------------------------------------------------------
# Connect to database (store)
# ------------------------------------------------------------------
for ev in ev_agents:
world.connect(
ev, db,
"lat", "lon", "soc_kwh",
"charging_power_kw", "status",
"bus_id", "grid_power_mw",
)
# Connect grid entities to database
for child in grid.children:
world.connect(child, db, "p_mw")
# ------------------------------------------------------------------
# Run the simulation
# ------------------------------------------------------------------
print(
f"Starting simulation: end={args.end}s, "
f"step_size={args.step_size}s, "
f"agents={args.num_agents}, "
f"loads_routed={num_loads}"
)
world.run(until=args.end)
print(
"Simulation complete. Results saved to "
"omod_powergrid_results.hdf5"
)
return 0
if __name__ == "__main__":
sys.exit(main())