wilabv2xsim 7.0.0b1__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.
- wilabv2xsim/__init__.py +9 -0
- wilabv2xsim/channel.py +284 -0
- wilabv2xsim/cli.py +241 -0
- wilabv2xsim/config.py +570 -0
- wilabv2xsim/core/__init__.py +0 -0
- wilabv2xsim/core/kernel.py +193 -0
- wilabv2xsim/core/registry.py +164 -0
- wilabv2xsim/core/rng.py +37 -0
- wilabv2xsim/core/time.py +45 -0
- wilabv2xsim/diagnostics.py +695 -0
- wilabv2xsim/ieee80211p/__init__.py +0 -0
- wilabv2xsim/ieee80211p/mac.py +317 -0
- wilabv2xsim/ieee80211p/phy.py +54 -0
- wilabv2xsim/io.py +142 -0
- wilabv2xsim/metrics.py +138 -0
- wilabv2xsim/mobility.py +305 -0
- wilabv2xsim/nr/__init__.py +0 -0
- wilabv2xsim/nr/mode2.py +389 -0
- wilabv2xsim/nr/phy.py +246 -0
- wilabv2xsim/nr/sidelink.py +550 -0
- wilabv2xsim/presets/ieee80211p_highway.yaml +12 -0
- wilabv2xsim/presets/nr_sbds_highway.yaml +16 -0
- wilabv2xsim/presets/nr_sbsps_highway.yaml +16 -0
- wilabv2xsim/presets/validation_aloha.yaml +15 -0
- wilabv2xsim/presets/wilab_benchmark_ds.yaml +24 -0
- wilabv2xsim/presets/wilab_benchmark_sps.yaml +26 -0
- wilabv2xsim/simulation.py +281 -0
- wilabv2xsim/traces.py +227 -0
- wilabv2xsim/traffic.py +156 -0
- wilabv2xsim/validation/__init__.py +0 -0
- wilabv2xsim/validation/analytic.py +174 -0
- wilabv2xsim/validation/scenarios.py +164 -0
- wilabv2xsim/validation/sps_colocated.py +390 -0
- wilabv2xsim/validation/wilab_parity.py +67 -0
- wilabv2xsim-7.0.0b1.dist-info/METADATA +174 -0
- wilabv2xsim-7.0.0b1.dist-info/RECORD +40 -0
- wilabv2xsim-7.0.0b1.dist-info/WHEEL +5 -0
- wilabv2xsim-7.0.0b1.dist-info/entry_points.txt +2 -0
- wilabv2xsim-7.0.0b1.dist-info/licenses/LICENSE +674 -0
- wilabv2xsim-7.0.0b1.dist-info/top_level.txt +1 -0
wilabv2xsim/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""WiLabV2Xsim: open-source Python simulator of V2X networks."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
__version__ = "7.0.0b1"
|
|
6
|
+
|
|
7
|
+
# The package logs through ``logging.getLogger("wilabv2xsim")`` and leaves the handlers to the
|
|
8
|
+
# application: ``logging.basicConfig(level=logging.INFO)`` shows the start and end of every run.
|
|
9
|
+
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
wilabv2xsim/channel.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""Large-scale channel: path loss, vehicle blockage, shadowing, and fast fading.
|
|
2
|
+
|
|
3
|
+
The channel produces one matrix, ``gain_db[i, j]``: the large-scale gain from
|
|
4
|
+
node i to node j (negative path loss minus blockage plus shadowing). It is
|
|
5
|
+
recomputed at each mobility update and stays constant in between, as in
|
|
6
|
+
the MATLAB version (``computeChannelGain``), and published whole as a read-only
|
|
7
|
+
:class:`LinkGains` (``Channel.state``); :class:`LinkGainProvider` is what another
|
|
8
|
+
channel model implements. Fast fading, when enabled, is drawn independently for
|
|
9
|
+
each transmission and each receiver at reception time.
|
|
10
|
+
|
|
11
|
+
Path-loss models (ported from ``initiateChannelModelParameters`` of the MATLAB version):
|
|
12
|
+
|
|
13
|
+
* ``winner_b1`` WINNER+ B1 LOS (dual slope with breakpoint), WiLab model 0
|
|
14
|
+
* ``single_slope`` L0 + 10 beta log10(d), WiLab model 1
|
|
15
|
+
* ``3gpp_highway`` 32.4 + 20 log10(f_GHz) + 10 beta log10(d) (TR 37.885 highway
|
|
16
|
+
LOS, beta = 2); WiLab model 4, which always adds the blockage below
|
|
17
|
+
* ``constant`` the same loss for every link, for validation scenarios
|
|
18
|
+
|
|
19
|
+
Blockage (NLOSv), off by default, adds a fixed loss for each vehicle that
|
|
20
|
+
obstructs the link (``nlosv_db_per_vehicle``; 6.9 dB in the MATLAB version).
|
|
21
|
+
The value and the sum over vehicles are WiLab choices: ETSI TR 103 257-1
|
|
22
|
+
Sec. 5.4.2.4.1 gives one loss per blocked link, computed by knife-edge
|
|
23
|
+
diffraction or drawn at random.
|
|
24
|
+
|
|
25
|
+
The gain is capped at 0 dB (``min(1, gain)`` in WiLab), so very short
|
|
26
|
+
distances never amplify.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
import math
|
|
33
|
+
|
|
34
|
+
import numpy as np
|
|
35
|
+
|
|
36
|
+
SPEED_OF_LIGHT = 299_792_458.0
|
|
37
|
+
BOLTZMANN_DBM_HZ = -174.0 # thermal noise density at 290 K, dBm/Hz
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def noise_dbm(bandwidth_hz: float, noise_figure_db: float) -> float:
|
|
41
|
+
return BOLTZMANN_DBM_HZ + 10 * math.log10(bandwidth_hz) + noise_figure_db
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# Loss at 1 m and exponent of the models that take them, used when they are not given:
|
|
45
|
+
# 3gpp_highway as TR 37.885 (32.4 dB before the 20 log10 f term), single_slope as WiLab model 1.
|
|
46
|
+
PATH_LOSS_DEFAULTS = {"3gpp_highway": (32.4, 2.0), "single_slope": (47.86, 2.2)}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class PathLoss:
|
|
51
|
+
model: str = "3gpp_highway"
|
|
52
|
+
carrier_ghz: float = 5.9
|
|
53
|
+
l0_db: float | None = None # single_slope / 3gpp_highway: loss at 1 m (3gpp: before the 20 log f term)
|
|
54
|
+
beta: float | None = None # path-loss exponent; None: the model's value (PATH_LOSS_DEFAULTS)
|
|
55
|
+
antenna_height_m: float = 1.5 # winner_b1
|
|
56
|
+
loss_db: float = 80.0 # constant
|
|
57
|
+
|
|
58
|
+
def __post_init__(self) -> None:
|
|
59
|
+
l0, beta = PATH_LOSS_DEFAULTS.get(self.model, (None, None))
|
|
60
|
+
if self.l0_db is None:
|
|
61
|
+
self.l0_db = l0
|
|
62
|
+
if self.beta is None:
|
|
63
|
+
self.beta = beta
|
|
64
|
+
|
|
65
|
+
def __call__(self, d: np.ndarray) -> np.ndarray:
|
|
66
|
+
"""Path loss in dB for distances ``d`` in metres (d >= 1 m enforced)."""
|
|
67
|
+
d = np.maximum(np.asarray(d, dtype=float), 1.0)
|
|
68
|
+
f = self.carrier_ghz
|
|
69
|
+
if self.model == "3gpp_highway":
|
|
70
|
+
return self.l0_db + 20 * math.log10(f) + 10 * self.beta * np.log10(d)
|
|
71
|
+
if self.model == "single_slope":
|
|
72
|
+
return self.l0_db + 10 * self.beta * np.log10(d)
|
|
73
|
+
if self.model == "winner_b1":
|
|
74
|
+
h_eff = self.antenna_height_m - 1.0
|
|
75
|
+
d_bp = 4 * h_eff * h_eff * f * 1e9 / SPEED_OF_LIGHT
|
|
76
|
+
near = 27.0 + 20 * math.log10(f) + 22.7 * np.log10(d)
|
|
77
|
+
far = 7.56 - 34.6 * math.log10(h_eff) + 2.7 * math.log10(f) + 40 * np.log10(d)
|
|
78
|
+
return np.where(d <= d_bp, near, far)
|
|
79
|
+
if self.model == "constant":
|
|
80
|
+
return np.full_like(d, self.loss_db)
|
|
81
|
+
raise ValueError(f"unknown path-loss model {self.model!r}")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def count_blocking_vehicles(positions: np.ndarray, ring_length_m: float | None = None,
|
|
85
|
+
threshold_m: float = 1.5, *, max_lanes: int = 32) -> np.ndarray:
|
|
86
|
+
"""Number of vehicles obstructing each link (WiLab ``calculateNLOSv``).
|
|
87
|
+
|
|
88
|
+
A vehicle obstructs the link i-j when it is within ``threshold_m`` of the
|
|
89
|
+
segment i-j and its projection falls inside the segment. On a ring road
|
|
90
|
+
the segment is taken along the shorter way round.
|
|
91
|
+
|
|
92
|
+
Vehicles on a highway sit on a few lanes. For a link and a lane, both
|
|
93
|
+
conditions are affine in the abscissa of the candidate blocker, so each
|
|
94
|
+
one is an open interval of abscissae, and the count is the number of lane
|
|
95
|
+
vehicles inside the intersection, found by bisection on the sorted lane:
|
|
96
|
+
O(N^2 lanes log N) instead of O(N^3) (20 times faster at 1000 vehicles,
|
|
97
|
+
50 at 2000). With more than ``max_lanes`` distinct ordinates (free
|
|
98
|
+
positions) it falls back to the direct count, which it reproduces.
|
|
99
|
+
"""
|
|
100
|
+
x, y = positions[:, 0], positions[:, 1]
|
|
101
|
+
lanes = np.unique(y)
|
|
102
|
+
if len(lanes) > max_lanes:
|
|
103
|
+
return _count_blocking_direct(positions, ring_length_m, threshold_m)
|
|
104
|
+
ring = ring_length_m or None
|
|
105
|
+
n = len(x)
|
|
106
|
+
dx = x[None, :] - x[:, None] # from i to j
|
|
107
|
+
if ring:
|
|
108
|
+
dx = (dx + ring / 2) % ring - ring / 2
|
|
109
|
+
dy = y[None, :] - y[:, None]
|
|
110
|
+
seg2 = dx * dx + dy * dy
|
|
111
|
+
seg = np.sqrt(seg2)
|
|
112
|
+
blocked = np.zeros((n, n), dtype=np.int32)
|
|
113
|
+
eps = 1e-6 # the end points (projection 0 or 1: the link's own nodes) never block
|
|
114
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
115
|
+
for lane in lanes:
|
|
116
|
+
xs = np.sort(x[y == lane])
|
|
117
|
+
if ring:
|
|
118
|
+
xs = np.concatenate([xs - ring, xs, xs + ring])
|
|
119
|
+
py = lane - y[:, None] + np.zeros_like(dx)
|
|
120
|
+
# distance from the line below the threshold: |px dy - py dx| < thr |ij|
|
|
121
|
+
a = (py * dx - threshold_m * seg) / dy
|
|
122
|
+
b = (py * dx + threshold_m * seg) / dy
|
|
123
|
+
lo1, hi1 = np.minimum(a, b), np.maximum(a, b)
|
|
124
|
+
flat = dy == 0 # link along the lane: the condition is |py| < thr
|
|
125
|
+
near = np.abs(py) < threshold_m
|
|
126
|
+
lo1 = np.where(flat, np.where(near, -np.inf, np.inf), lo1)
|
|
127
|
+
hi1 = np.where(flat, np.where(near, np.inf, -np.inf), hi1)
|
|
128
|
+
# projection inside the segment: 0 < px dx + py dy < |ij|^2
|
|
129
|
+
c = -py * dy / dx
|
|
130
|
+
e = (seg2 - py * dy) / dx
|
|
131
|
+
lo = np.maximum(lo1, np.minimum(c, e) + eps)
|
|
132
|
+
hi = np.minimum(hi1, np.maximum(c, e) - eps)
|
|
133
|
+
if ring:
|
|
134
|
+
lo, hi = np.maximum(lo, -ring / 2), np.minimum(hi, ring / 2)
|
|
135
|
+
valid = (hi > lo) & (seg2 > 0)
|
|
136
|
+
xi = np.broadcast_to(x[:, None], dx.shape)[valid]
|
|
137
|
+
count = np.searchsorted(xs, xi + hi[valid], "left") - np.searchsorted(xs, xi + lo[valid], "right")
|
|
138
|
+
blocked[valid] += np.maximum(count, 0).astype(np.int32)
|
|
139
|
+
return blocked
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _count_blocking_direct(positions: np.ndarray, ring_length_m: float | None = None,
|
|
143
|
+
threshold_m: float = 1.5) -> np.ndarray:
|
|
144
|
+
"""The same count, vehicle by vehicle: O(N^3), WiLab ``calculateNLOSv`` as written."""
|
|
145
|
+
x, y = positions[:, 0], positions[:, 1]
|
|
146
|
+
n = len(x)
|
|
147
|
+
dx = x[None, :] - x[:, None] # from i to j
|
|
148
|
+
if ring_length_m:
|
|
149
|
+
dx = (dx + ring_length_m / 2) % ring_length_m - ring_length_m / 2
|
|
150
|
+
dy = y[None, :] - y[:, None]
|
|
151
|
+
seg2 = dx * dx + dy * dy
|
|
152
|
+
seg2[seg2 == 0] = np.inf
|
|
153
|
+
blocked = np.zeros((n, n), dtype=np.int32)
|
|
154
|
+
for k in range(n):
|
|
155
|
+
px = x[k] - x[:, None]
|
|
156
|
+
if ring_length_m:
|
|
157
|
+
px = (px + ring_length_m / 2) % ring_length_m - ring_length_m / 2
|
|
158
|
+
py = y[k] - y[:, None]
|
|
159
|
+
t = (px * dx + py * dy) / seg2 # projection parameter along i -> j
|
|
160
|
+
cross = np.abs(px * dy - py * dx) / np.sqrt(seg2)
|
|
161
|
+
hit = (t > 0) & (t < 1) & (cross < threshold_m)
|
|
162
|
+
hit[k, :] = False
|
|
163
|
+
hit[:, k] = False
|
|
164
|
+
blocked += hit
|
|
165
|
+
return blocked
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _frozen(a) -> np.ndarray:
|
|
169
|
+
a = np.array(a, dtype=float)
|
|
170
|
+
a.setflags(write=False)
|
|
171
|
+
return a
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@dataclass(frozen=True)
|
|
175
|
+
class LinkGains:
|
|
176
|
+
"""The large-scale state of every link after one update. Arrays are read-only, (N, N), indexed
|
|
177
|
+
by the nodes of the active state the update was computed for."""
|
|
178
|
+
|
|
179
|
+
gain_db: np.ndarray # gain from node i to node j, dB, capped at 0
|
|
180
|
+
distance_m: np.ndarray # distance of the link, m
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class LinkGainProvider:
|
|
184
|
+
"""What a channel model gives the rest of the simulation.
|
|
185
|
+
|
|
186
|
+
:meth:`update` computes the large-scale gains of every link for the geometry of a mobility
|
|
187
|
+
update and publishes them whole, as :attr:`state`: the MAC models read only the current state,
|
|
188
|
+
never a mix of two updates, and cannot change it. :meth:`fading_db` draws the fast fading of
|
|
189
|
+
the transmissions of one instant. The model never sees node identities: it gets positions,
|
|
190
|
+
distances and, per link, how far its ends have moved since the last update (infinity after a
|
|
191
|
+
jump, so that what depends on the past of the link starts again). When nodes have entered or
|
|
192
|
+
left since the last update, ``previous_index`` gives, for each node, its index in the last
|
|
193
|
+
update, or -1 for a node that was not there: a model that keeps a history of the links (the
|
|
194
|
+
shadowing) carries it over by it.
|
|
195
|
+
"""
|
|
196
|
+
|
|
197
|
+
state: LinkGains | None = None
|
|
198
|
+
|
|
199
|
+
def update(self, positions: np.ndarray, distances: np.ndarray, moved_m: np.ndarray | float,
|
|
200
|
+
ring_length_m: float | None = None, previous_index: np.ndarray | None = None) -> LinkGains:
|
|
201
|
+
raise NotImplementedError
|
|
202
|
+
|
|
203
|
+
def fading_db(self, shape) -> np.ndarray:
|
|
204
|
+
raise NotImplementedError
|
|
205
|
+
|
|
206
|
+
@property
|
|
207
|
+
def gain_db(self) -> np.ndarray:
|
|
208
|
+
"""``state.gain_db``."""
|
|
209
|
+
return self.state.gain_db
|
|
210
|
+
|
|
211
|
+
@property
|
|
212
|
+
def distance_m(self) -> np.ndarray:
|
|
213
|
+
"""``state.distance_m``."""
|
|
214
|
+
return self.state.distance_m
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class Channel(LinkGainProvider):
|
|
218
|
+
"""Large-scale gains between all nodes, refreshed at each mobility update."""
|
|
219
|
+
|
|
220
|
+
def __init__(self, rng: np.random.Generator, path_loss: PathLoss, *,
|
|
221
|
+
shadowing_std_db: float = 3.0, decorrelation_m: float = 25.0,
|
|
222
|
+
nlosv_db_per_vehicle: float | None = None, rayleigh_fading: bool = False,
|
|
223
|
+
fading_rng: np.random.Generator | None = None):
|
|
224
|
+
self.rng = rng
|
|
225
|
+
self.path_loss = path_loss
|
|
226
|
+
self.shadowing_std_db = shadowing_std_db
|
|
227
|
+
self.decorrelation_m = decorrelation_m
|
|
228
|
+
self.nlosv_db = nlosv_db_per_vehicle
|
|
229
|
+
self.rayleigh_fading = rayleigh_fading
|
|
230
|
+
self.fading_rng = fading_rng if fading_rng is not None else rng
|
|
231
|
+
self.shadowing_db: np.ndarray | None = None # the history of the links, internal to the model
|
|
232
|
+
|
|
233
|
+
def update(self, positions: np.ndarray, distances: np.ndarray, moved_m: np.ndarray | float,
|
|
234
|
+
ring_length_m: float | None = None, previous_index: np.ndarray | None = None) -> LinkGains:
|
|
235
|
+
"""Compute and publish the gains of the new geometry.
|
|
236
|
+
|
|
237
|
+
Shadowing follows the Gudmundson model: with ``dm`` the entry of
|
|
238
|
+
``moved_m`` for the link,
|
|
239
|
+
S_new = exp(-dm/D) S_old + sqrt(1 - exp(-2 dm/D)) N(0, sigma^2),
|
|
240
|
+
and the matrix is kept symmetric (reciprocal links). The simulation
|
|
241
|
+
passes as ``dm`` the larger of the distances travelled by the two nodes
|
|
242
|
+
since the last update, and infinity for a vehicle that re-entered an
|
|
243
|
+
open road. The MATLAB version 7.0 takes instead the change in the
|
|
244
|
+
length of the link, |d(t) - d(t - dt)| (``updateDistanceChangeForShadowing``):
|
|
245
|
+
there, two vehicles driving in the same direction at similar speeds keep
|
|
246
|
+
almost the same shadowing. When the nodes changed (``previous_index``), the shadowing of
|
|
247
|
+
the links between nodes present before and after is carried over, and a link with a new
|
|
248
|
+
node gets a new, independent value.
|
|
249
|
+
"""
|
|
250
|
+
n = len(positions)
|
|
251
|
+
loss = self.path_loss(distances)
|
|
252
|
+
if self.nlosv_db:
|
|
253
|
+
loss = loss + self.nlosv_db * count_blocking_vehicles(positions, ring_length_m)
|
|
254
|
+
if self.shadowing_std_db > 0:
|
|
255
|
+
fresh = self.rng.standard_normal((n, n)) * self.shadowing_std_db
|
|
256
|
+
old = self.shadowing_db
|
|
257
|
+
if old is not None and previous_index is not None:
|
|
258
|
+
prev = np.asarray(previous_index, dtype=np.int64)
|
|
259
|
+
kept = np.flatnonzero(prev >= 0)
|
|
260
|
+
old = np.zeros((n, n))
|
|
261
|
+
old[np.ix_(kept, kept)] = self.shadowing_db[np.ix_(prev[kept], prev[kept])]
|
|
262
|
+
new = prev < 0
|
|
263
|
+
moved_m = np.array(np.broadcast_to(moved_m, (n, n)), dtype=float)
|
|
264
|
+
moved_m[new, :] = np.inf
|
|
265
|
+
moved_m[:, new] = np.inf
|
|
266
|
+
if old is None:
|
|
267
|
+
s = fresh
|
|
268
|
+
else:
|
|
269
|
+
a = np.exp(-np.asarray(moved_m) / self.decorrelation_m)
|
|
270
|
+
s = a * old + np.sqrt(1 - a * a) * fresh
|
|
271
|
+
s = np.triu(s, 1)
|
|
272
|
+
self.shadowing_db = s + s.T
|
|
273
|
+
else:
|
|
274
|
+
self.shadowing_db = np.zeros((n, n))
|
|
275
|
+
gain = -loss + self.shadowing_db
|
|
276
|
+
np.fill_diagonal(gain, 0.0)
|
|
277
|
+
self.state = LinkGains(gain_db=_frozen(np.minimum(gain, 0.0)), distance_m=_frozen(distances))
|
|
278
|
+
return self.state
|
|
279
|
+
|
|
280
|
+
def fading_db(self, shape) -> np.ndarray:
|
|
281
|
+
"""Rayleigh fading power gains in dB (exponential with unit mean), or zeros."""
|
|
282
|
+
if not self.rayleigh_fading:
|
|
283
|
+
return np.zeros(shape)
|
|
284
|
+
return 10 * np.log10(self.fading_rng.exponential(1.0, size=shape))
|
wilabv2xsim/cli.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""Command line: ``wilabv2xsim run|config|check|presets|validate|schema``.
|
|
2
|
+
|
|
3
|
+
wilabv2xsim run nr_sbsps_highway --set technology.mcs=12 --set simulation.seed=3
|
|
4
|
+
wilabv2xsim config my_experiment.yaml # print the effective configuration
|
|
5
|
+
wilabv2xsim check my_experiment.yaml # errors, warnings and info as JSON, without running
|
|
6
|
+
wilabv2xsim presets # list the ready-made configurations
|
|
7
|
+
wilabv2xsim validate aloha # SB-DS vs slotted ALOHA table
|
|
8
|
+
wilabv2xsim validate sps # SB-SPS, co-located nodes, vs exact results
|
|
9
|
+
wilabv2xsim schema # JSON Schema of a configuration
|
|
10
|
+
|
|
11
|
+
Exit codes: 0 done (possibly with warnings), 2 configuration errors (or
|
|
12
|
+
warnings with ``--strict``, or a ``run_id`` whose folder exists: nothing
|
|
13
|
+
runs), 4 the run finished but failed a consistency
|
|
14
|
+
check (``RUN_CONSERVATION``) or raised a simulation error. A command line
|
|
15
|
+
that cannot be parsed (an unknown command or option) also exits with 2,
|
|
16
|
+
with the usage on stderr and no JSON, even with ``--json``.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import argparse
|
|
22
|
+
from dataclasses import replace
|
|
23
|
+
import json
|
|
24
|
+
import math
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
import sys
|
|
27
|
+
import warnings
|
|
28
|
+
|
|
29
|
+
import yaml
|
|
30
|
+
|
|
31
|
+
PRESETS = Path(__file__).parent / "presets"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _print_diagnostics(found) -> None:
|
|
35
|
+
"""Diagnostics on stderr, one line each, with the hint below."""
|
|
36
|
+
for d in found:
|
|
37
|
+
d = d if isinstance(d, dict) else d.as_dict()
|
|
38
|
+
if d["accepted"]:
|
|
39
|
+
continue
|
|
40
|
+
where = f" ({', '.join(d['paths'])})" if d["paths"] else ""
|
|
41
|
+
print(f"{d['severity']} {d['code']}{where}: {d['message']} {d['consequence']}".rstrip(), file=sys.stderr)
|
|
42
|
+
if d["hint"]:
|
|
43
|
+
print(f" hint: {d['hint']}", file=sys.stderr)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _load(args):
|
|
47
|
+
"""Configuration and diagnostics (accepted warnings marked); on a load or schema error, the diagnostics only."""
|
|
48
|
+
from pydantic import ValidationError
|
|
49
|
+
|
|
50
|
+
from .config import load_config
|
|
51
|
+
from .diagnostics import check_config, from_load_error, from_validation_error
|
|
52
|
+
try:
|
|
53
|
+
cfg = load_config(args.config, args.set)
|
|
54
|
+
except ValidationError as exc:
|
|
55
|
+
return None, from_validation_error(exc)
|
|
56
|
+
except (ValueError, OSError, yaml.YAMLError) as exc:
|
|
57
|
+
return None, from_load_error(exc)
|
|
58
|
+
accept = set(getattr(args, "accept", ()))
|
|
59
|
+
return cfg, [replace(d, accepted=True) if d.severity == "warning" and d.code in accept else d
|
|
60
|
+
for d in check_config(cfg)]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _blocking(args, found) -> bool:
|
|
64
|
+
"""Errors, or with --strict warnings that were not accepted."""
|
|
65
|
+
return any(d.severity == "error" or (getattr(args, "strict", False) and d.severity == "warning"
|
|
66
|
+
and not d.accepted) for d in found)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _cmd_run(args) -> int:
|
|
70
|
+
from .core.kernel import SimulationError
|
|
71
|
+
from .diagnostics import DiagnosticWarning
|
|
72
|
+
from .simulation import run
|
|
73
|
+
cfg, found = _load(args)
|
|
74
|
+
if cfg is None or _blocking(args, found):
|
|
75
|
+
return _fail(args, found)
|
|
76
|
+
try:
|
|
77
|
+
with warnings.catch_warnings():
|
|
78
|
+
warnings.simplefilter("ignore", DiagnosticWarning) # printed below, with the run-time ones
|
|
79
|
+
result = run(cfg, write=not args.no_write, strict=args.strict, accept=args.accept)
|
|
80
|
+
except FileExistsError as exc:
|
|
81
|
+
if args.json:
|
|
82
|
+
print(json.dumps({"ok": False, "error": str(exc), "folder": None}))
|
|
83
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
84
|
+
return 2
|
|
85
|
+
except SimulationError as exc:
|
|
86
|
+
if args.json:
|
|
87
|
+
print(json.dumps({"ok": False, "error": f"the simulation failed: {exc}", "folder": None}))
|
|
88
|
+
print(f"error: the simulation failed: {exc}", file=sys.stderr)
|
|
89
|
+
return 4
|
|
90
|
+
s = result.summary()
|
|
91
|
+
prr = result.metrics.prr_table()
|
|
92
|
+
at = {}
|
|
93
|
+
for d in (50, 100, 200, 300, 500):
|
|
94
|
+
k = int(d / result.metrics.bin_m) - 1
|
|
95
|
+
if 0 <= k < len(prr["prr"]):
|
|
96
|
+
p = float(prr["prr"][k])
|
|
97
|
+
at[d] = p if math.isfinite(p) else None # no sample in the bin
|
|
98
|
+
failed = not result.ok
|
|
99
|
+
if args.json:
|
|
100
|
+
print(json.dumps({"ok": not failed, "folder": str(result.folder) if result.folder else None,
|
|
101
|
+
"summary": s, "prr_at_m": at}, indent=2, allow_nan=False))
|
|
102
|
+
else:
|
|
103
|
+
_print_diagnostics(result.diagnostics)
|
|
104
|
+
print(yaml.safe_dump({k: v for k, v in s.items() if k != "diagnostics"}, sort_keys=False).rstrip())
|
|
105
|
+
for d, p in at.items():
|
|
106
|
+
print(f"PRR at {d:>4} m: {p:.4f}" if p is not None else f"PRR at {d:>4} m: no sample")
|
|
107
|
+
codes = [d["code"] for d in result.diagnostics if d["severity"] != "info"]
|
|
108
|
+
if codes:
|
|
109
|
+
print("diagnostics: " + ", ".join(codes))
|
|
110
|
+
if result.folder:
|
|
111
|
+
print(f"results: {result.folder}")
|
|
112
|
+
return 4 if failed else 0
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _fail(args, found) -> int:
|
|
116
|
+
from .diagnostics import report
|
|
117
|
+
if getattr(args, "json", False):
|
|
118
|
+
print(json.dumps({**report(found), "ok": False}, indent=2))
|
|
119
|
+
else:
|
|
120
|
+
_print_diagnostics(found)
|
|
121
|
+
return 2
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _cmd_config(args) -> int:
|
|
125
|
+
from .config import to_dict
|
|
126
|
+
cfg, found = _load(args)
|
|
127
|
+
if cfg is not None:
|
|
128
|
+
print(yaml.safe_dump(to_dict(cfg), sort_keys=False).rstrip())
|
|
129
|
+
_print_diagnostics(found)
|
|
130
|
+
return 2 if cfg is None or any(d.severity == "error" for d in found) else 0
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _cmd_check(args) -> int:
|
|
134
|
+
"""Errors, warnings and info of a configuration as JSON on stdout (for scripts and agents).
|
|
135
|
+
|
|
136
|
+
``ok`` is false when the run would not start: errors, or with --strict warnings not accepted.
|
|
137
|
+
"""
|
|
138
|
+
from .diagnostics import report
|
|
139
|
+
_, found = _load(args)
|
|
140
|
+
blocking = _blocking(args, found)
|
|
141
|
+
print(json.dumps({**report(found), "ok": not blocking}, indent=2))
|
|
142
|
+
return 2 if blocking else 0
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _cmd_presets(args) -> int:
|
|
146
|
+
for p in sorted(PRESETS.glob("*.yaml")):
|
|
147
|
+
first = p.read_text(encoding="utf-8").splitlines()[0].lstrip("# ").strip()
|
|
148
|
+
print(f"{p.stem:<28} {first}")
|
|
149
|
+
return 0
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _cmd_validate(args) -> int:
|
|
153
|
+
from .validation.scenarios import aloha_sweep, sps_colocated_sweep
|
|
154
|
+
if args.which == "sps":
|
|
155
|
+
t = sps_colocated_sweep(seeds=args.seeds, duration_s=args.duration or 50.0)
|
|
156
|
+
print("SB-SPS, co-located nodes, S = 100 slots, against exact results")
|
|
157
|
+
print(f"{'N':>5} {'F':>3} {'case':<34} {'PRR sim':>9} {'+-95%':>7} {'PRR exact':>10}")
|
|
158
|
+
for i in range(len(t["n_nodes"])):
|
|
159
|
+
case = "sensing, simultaneous, never left" if t["frozen"][i] else "no sensing"
|
|
160
|
+
print(f"{t['n_nodes'][i]:5.0f} {t['subchannels'][i]:3.0f} {case:<34} "
|
|
161
|
+
f"{t['prr_sim'][i]:9.4f} {t['prr_ci95'][i]:7.4f} {t['prr_exact'][i]:10.4f}")
|
|
162
|
+
return 0
|
|
163
|
+
t = aloha_sweep(seed=args.seed, duration_s=args.duration or 20.0)
|
|
164
|
+
print(f"{'N':>5} {'G':>6} {'PRR sim':>9} {'+-95%':>7} {'PRR th':>8} {'S sim':>7} {'S th':>7} {'G e^-G':>7}")
|
|
165
|
+
for i in range(len(t["n_nodes"])):
|
|
166
|
+
print(f"{t['n_nodes'][i]:5.0f} {t['load_G'][i]:6.3f} {t['prr_sim'][i]:9.4f} {t['prr_ci95'][i]:7.4f} "
|
|
167
|
+
f"{t['prr_theory'][i]:8.4f} {t['throughput_sim'][i]:7.4f} {t['throughput_theory'][i]:7.4f} "
|
|
168
|
+
f"{t['throughput_G_exp_minus_G'][i]:7.4f}")
|
|
169
|
+
return 0
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _cmd_schema(args) -> int:
|
|
173
|
+
from .config import json_schema
|
|
174
|
+
print(json.dumps(json_schema(), indent=2))
|
|
175
|
+
return 0
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _strict_options(p) -> None:
|
|
179
|
+
p.add_argument("--strict", action="store_true", help="treat warnings as errors")
|
|
180
|
+
p.add_argument("--accept", action="append", default=[], metavar="CODE",
|
|
181
|
+
help="a warning that is expected: allowed with --strict, recorded as accepted")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
DOCS = "https://github.com/V2Xgithub/WiLabV2Xsim/wiki"
|
|
185
|
+
|
|
186
|
+
EPILOG = f"""\
|
|
187
|
+
a typical session:
|
|
188
|
+
wilabv2xsim presets ready-made configurations
|
|
189
|
+
wilabv2xsim config nr_sbsps_highway every parameter with its value
|
|
190
|
+
wilabv2xsim check nr_sbsps_highway --set technology.mcs=12
|
|
191
|
+
wilabv2xsim run nr_sbsps_highway --set technology.mcs=12 --json
|
|
192
|
+
|
|
193
|
+
parameters: `wilabv2xsim schema` prints each one with its type, default, range
|
|
194
|
+
and description; --set takes the dotted path shown by `config`.
|
|
195
|
+
documentation: {DOCS}
|
|
196
|
+
for AI agents (exit codes, JSON, diagnostics): {DOCS}/AI-agents
|
|
197
|
+
"""
|
|
198
|
+
|
|
199
|
+
SET_HELP = "override a parameter by its dotted path, e.g. technology.mcs=12 (repeatable)"
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def main(argv: list[str] | None = None) -> int:
|
|
203
|
+
parser = argparse.ArgumentParser(prog="wilabv2xsim", description="WiLabV2Xsim V2X network simulator",
|
|
204
|
+
epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
205
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
206
|
+
p = sub.add_parser("run", help="run a simulation", epilog=f"documentation: {DOCS}")
|
|
207
|
+
p.add_argument("config", help="YAML file or preset name")
|
|
208
|
+
p.add_argument("--set", action="append", default=[], metavar="PATH=VALUE", help=SET_HELP)
|
|
209
|
+
p.add_argument("--no-write", action="store_true", help="do not write the run folder")
|
|
210
|
+
p.add_argument("--json", action="store_true",
|
|
211
|
+
help="print one JSON object: the summary with its diagnostics, and the PRR "
|
|
212
|
+
"at 50, 100, 200, 300 and 500 m (the distance bin that ends there)")
|
|
213
|
+
_strict_options(p)
|
|
214
|
+
p.set_defaults(func=_cmd_run)
|
|
215
|
+
p = sub.add_parser("config", help="print the effective configuration")
|
|
216
|
+
p.add_argument("config", nargs="?", default=None)
|
|
217
|
+
p.add_argument("--set", action="append", default=[], metavar="PATH=VALUE", help=SET_HELP)
|
|
218
|
+
p.set_defaults(func=_cmd_config)
|
|
219
|
+
p = sub.add_parser("check", help="check a configuration without running it (JSON)")
|
|
220
|
+
p.add_argument("config", nargs="?", default=None)
|
|
221
|
+
p.add_argument("--set", action="append", default=[], metavar="PATH=VALUE", help=SET_HELP)
|
|
222
|
+
_strict_options(p)
|
|
223
|
+
p.set_defaults(func=_cmd_check)
|
|
224
|
+
p = sub.add_parser("presets", help="list the ready-made configurations")
|
|
225
|
+
p.set_defaults(func=_cmd_presets)
|
|
226
|
+
p = sub.add_parser("validate", help="run a validation campaign")
|
|
227
|
+
p.add_argument("which", choices=["aloha", "sps"],
|
|
228
|
+
help="aloha: SB-DS against slotted ALOHA; sps: SB-SPS with co-located nodes")
|
|
229
|
+
p.add_argument("--seed", type=int, default=1, help="aloha: the seed")
|
|
230
|
+
p.add_argument("--seeds", type=int, default=8, help="sps: independent seeds per point")
|
|
231
|
+
p.add_argument("--duration", type=float, default=None, help="seconds per run (aloha 20, sps 50)")
|
|
232
|
+
p.set_defaults(func=_cmd_validate)
|
|
233
|
+
p = sub.add_parser("schema", help="print the JSON Schema of a configuration: every parameter "
|
|
234
|
+
"with its type, default, range and description")
|
|
235
|
+
p.set_defaults(func=_cmd_schema)
|
|
236
|
+
args = parser.parse_args(argv)
|
|
237
|
+
return args.func(args)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
if __name__ == "__main__":
|
|
241
|
+
sys.exit(main())
|