nav-explore-eval 0.3.3__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.
@@ -0,0 +1 @@
1
+ __version__ = '0.3.3'
@@ -0,0 +1,72 @@
1
+ """Offline scoring of a rosbag2: replay /map and /odom in bag time and score like `record`."""
2
+ from .mapio import from_msg
3
+ from .runreport import Scorer, build_report
4
+
5
+
6
+ def read_bag(path, ns='', gt_topic=''):
7
+ """Yield (t_seconds_from_start, kind, msg) for map/odom messages, ordered by bag time."""
8
+ import rosbag2_py
9
+ from nav_msgs.msg import OccupancyGrid, Odometry
10
+ from rclpy.serialization import deserialize_message
11
+ uri = path.rstrip('/')
12
+ fmt = 'sqlite3'
13
+ if uri.endswith('.mcap'):
14
+ fmt = 'mcap'
15
+ reader = rosbag2_py.SequentialReader()
16
+ reader.open(rosbag2_py.StorageOptions(uri=uri, storage_id=fmt),
17
+ rosbag2_py.ConverterOptions('', ''))
18
+ pre = ('/' + ns.strip('/')) if ns else ''
19
+ topics = {pre + '/map': ('map', OccupancyGrid), pre + '/odom': ('odom', Odometry)}
20
+ if gt_topic:
21
+ topics[gt_topic] = ('gt', Odometry)
22
+ have = {t.name for t in reader.get_all_topics_and_types()}
23
+ if pre + '/map' not in have:
24
+ raise ValueError(f'bag has no {pre}/map topic (topics: {sorted(have)})')
25
+ t0 = None
26
+ while reader.has_next():
27
+ name, data, stamp = reader.read_next()
28
+ if name not in topics:
29
+ continue
30
+ if t0 is None:
31
+ t0 = stamp
32
+ kind, typ = topics[name]
33
+ yield (stamp - t0) / 1e9, kind, deserialize_message(data, typ)
34
+
35
+
36
+ def score_bag(path, truth, label='bag', interval=2.0, scorer_kw=None, ns='', stop_at=100.0, truth_path='', gt_topic=''):
37
+ """Score a bag -> run report dict. Raises ValueError if the bag has no map."""
38
+ scorer = Scorer(truth, **(scorer_kw or {}))
39
+ cur, pts, series, next_t, last_t, done = None, [], [], 0.0, 0.0, False
40
+ est, gt = [], []
41
+ for t, kind, msg in read_bag(path, ns, gt_topic):
42
+ if kind == 'gt':
43
+ gt.append((t, msg.pose.pose.position.x, msg.pose.pose.position.y))
44
+ continue
45
+ if kind == 'odom' or not done:
46
+ last_t = t
47
+ if kind == 'odom':
48
+ p = msg.pose.pose.position
49
+ est.append((t, p.x, p.y))
50
+ if not pts or abs(p.x - pts[-1][0]) + abs(p.y - pts[-1][1]) > 0.02:
51
+ pts.append((p.x, p.y))
52
+ continue
53
+ while cur is not None and next_t <= t and not done: # samples due before this map arrives
54
+ series.append((next_t, scorer(cur)))
55
+ next_t += interval
56
+ done = series[-1][1]['coverage_pct'] >= stop_at
57
+ if done:
58
+ continue # target reached: keep reading odom/gt only
59
+ if cur is None:
60
+ next_t = max(next_t, t) # first sample = first map
61
+ cur = from_msg(msg)
62
+ if cur is not None and (not series or series[-1][0] < last_t) and not done:
63
+ series.append((max(last_t, series[-1][0] if series else 0.0), scorer(cur)))
64
+ if not series:
65
+ raise ValueError('no /map messages in bag - nothing to score')
66
+ extra = {'source': 'rosbag', 'bag': str(path)}
67
+ if gt_topic:
68
+ from .metrics import localisation_error
69
+ loc = localisation_error(est, gt)
70
+ if loc:
71
+ extra['localisation'] = loc
72
+ return build_report(label, truth_path, series, pts, extra)
@@ -0,0 +1,380 @@
1
+ #!/usr/bin/env python3
2
+ """nav_explore_eval - score any exploration run on coverage, map accuracy and time-to-percent."""
3
+ import argparse
4
+ import json
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ import time
9
+
10
+ from . import __version__
11
+ from .mapio import load_yaml_map
12
+ from .metrics import TIME_TO, path_length
13
+ from .runreport import Scorer, build_report, validate
14
+
15
+
16
+ def _scorer(a, truth):
17
+ return Scorer(truth, do_align=a.align or a.rotate, rotate=a.rotate, max_shift=a.max_shift,
18
+ max_yaw=a.max_yaw, tol=a.tol)
19
+
20
+
21
+ def cmd_score(a):
22
+ from .metrics import score
23
+ live, truth = load_yaml_map(a.map), load_yaml_map(a.truth)
24
+ if a.offset:
25
+ res = score(live, truth, a.offset[0], a.offset[1], a.tol)
26
+ else:
27
+ res = _scorer(a, truth)(live)
28
+ print(json.dumps(res, indent=2) if a.json else '\n'.join(f'{k:20s} {v:8.2f}' for k, v in res.items()))
29
+ return 0
30
+
31
+
32
+ def _row(path):
33
+ r = json.load(open(path))
34
+ f, tt = r['final'], r['time_to_pct_s']
35
+ return [r['label'], f"{f['coverage_pct']:.1f}", f"{f['wall_f1_pct']:.1f}", f"{f['false_free_pct']:.1f}",
36
+ f"{r['path_length_m']:.1f}"] + [('-' if tt[str(p)] is None else f'{tt[str(p)]:.0f}') for p in TIME_TO]
37
+
38
+
39
+ def cmd_truth(a):
40
+ from .worldmap import rasterize, shapes, write_map
41
+ g = rasterize(shapes(open(a.world).read(), a.z, a.model_path, os.path.dirname(os.path.abspath(a.world))),
42
+ a.res, a.margin, tuple(a.seed))
43
+ write_map(g, a.out)
44
+ free = (g.data == 0).sum() * g.resolution ** 2
45
+ print(f'wrote {a.out}.yaml / .pgm ({g.shape[1]}x{g.shape[0]} @ {g.resolution} m, explorable area {free:.1f} m2)')
46
+ return 0
47
+
48
+
49
+ def cmd_compare(a):
50
+ head = ['label', 'cov%', 'f1%', 'leak%', 'path_m'] + [f't{p}%(s)' for p in TIME_TO]
51
+ rows = [head] + [_row(p) for p in a.reports]
52
+ w = [max(len(r[i]) for r in rows) for i in range(len(head))]
53
+ for r in rows:
54
+ print(' '.join(c.rjust(w[i]) for i, c in enumerate(r)))
55
+ if a.png:
56
+ import matplotlib
57
+ matplotlib.use('Agg')
58
+ import matplotlib.pyplot as plt
59
+ fig, ax = plt.subplots(figsize=(7, 4))
60
+ for p in a.reports:
61
+ r = json.load(open(p))
62
+ ax.plot([s['t'] for s in r['series']], [s['coverage_pct'] for s in r['series']], label=r['label'])
63
+ ax.set_xlabel('time (s)')
64
+ ax.set_ylabel('coverage (%)')
65
+ ax.legend()
66
+ ax.grid(alpha=.3)
67
+ fig.tight_layout()
68
+ fig.savefig(a.png, dpi=140)
69
+ print(f'wrote {a.png}')
70
+ return 0
71
+
72
+
73
+ def _record_once(a, ros_args):
74
+ import rclpy
75
+ from nav_msgs.msg import OccupancyGrid, Odometry
76
+ from rclpy.node import Node
77
+ from rclpy.qos import DurabilityPolicy, QoSProfile, qos_profile_sensor_data
78
+ from .mapio import from_msg
79
+
80
+ rclpy.init(args=ros_args)
81
+ node = Node('nav_explore_eval')
82
+ truth = load_yaml_map(a.truth)
83
+ scorer = _scorer(a, truth)
84
+ robots = [r.strip() for r in a.robots.split(',')] if a.robots else [a.ns]
85
+ maps, pts = [None] * len(robots), [[] for _ in robots]
86
+ est_t, gt_t = [], [] # (t, x, y) for localisation error
87
+ series, per_robot, t0 = [], [], time.monotonic()
88
+ for k, r in enumerate(robots):
89
+ ns = ('/' + r.strip('/')) if r else ''
90
+
91
+ def on_map(m, k=k):
92
+ maps[k] = from_msg(m)
93
+
94
+ def on_odom(m, k=k):
95
+ p = m.pose.pose.position
96
+ q = pts[k]
97
+ if not q or abs(p.x - q[-1][0]) + abs(p.y - q[-1][1]) > 0.02:
98
+ q.append((p.x, p.y))
99
+ node.create_subscription(OccupancyGrid, f'{ns}/map', on_map,
100
+ QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL))
101
+ node.create_subscription(Odometry, f'{ns}/odom', on_odom, qos_profile_sensor_data)
102
+ if k == 0:
103
+ def on_est(m):
104
+ p = m.pose.pose.position
105
+ est_t.append((time.monotonic() - t0, p.x, p.y))
106
+ node.create_subscription(Odometry, f'{ns}/odom', on_est, qos_profile_sensor_data)
107
+ if a.gt_odom:
108
+ def on_gt(m):
109
+ p = m.pose.pose.position
110
+ gt_t.append((time.monotonic() - t0, p.x, p.y))
111
+ node.create_subscription(Odometry, a.gt_odom, on_gt, qos_profile_sensor_data)
112
+
113
+ def tick():
114
+ t = time.monotonic() - t0
115
+ have = [g for g in maps if g is not None]
116
+ if not have:
117
+ if t >= a.duration:
118
+ raise SystemExit
119
+ return
120
+ if len(robots) > 1:
121
+ m, per = scorer.multi(have)
122
+ per_robot[:] = per
123
+ else:
124
+ m = scorer(have[0])
125
+ series.append((t, m))
126
+ node.get_logger().info(f't={t:5.0f}s coverage={m["coverage_pct"]:.1f}% f1={m["wall_f1_pct"]:.1f}%')
127
+ if t >= a.duration or m['coverage_pct'] >= a.stop_at:
128
+ raise SystemExit
129
+ node.create_timer(a.interval, tick)
130
+ from rclpy.executors import ExternalShutdownException
131
+ try:
132
+ rclpy.spin(node)
133
+ except (KeyboardInterrupt, SystemExit, ExternalShutdownException):
134
+ pass
135
+ node.destroy_node()
136
+ rclpy.try_shutdown()
137
+ if not series:
138
+ print('no /map received - nothing to score', file=sys.stderr)
139
+ return 1
140
+ extra = {}
141
+ if len(robots) > 1:
142
+ extra['robots'] = [dict(ns=robots[p['robot']], path_length_m=path_length(pts[p['robot']]), **p)
143
+ for p in per_robot]
144
+ if a.gt_odom:
145
+ from .metrics import localisation_error
146
+ loc = localisation_error(est_t, gt_t)
147
+ if loc:
148
+ extra['localisation'] = loc
149
+ else:
150
+ print(f'warning: no overlapping poses on {a.gt_odom} - localisation error skipped', file=sys.stderr)
151
+ rep = build_report(a.label, a.truth, series, [x for q in pts for x in q], extra)
152
+ rep['path_length_m'] = sum(path_length(q) for q in pts)
153
+ from .metrics import efficiency
154
+ rep['efficiency'] = efficiency(rep['final'], rep['path_length_m'])
155
+ json.dump(rep, open(a.out, 'w'), indent=2)
156
+ print(f'wrote {a.out}')
157
+ return 0
158
+
159
+
160
+ def cmd_record(a, ros_args):
161
+ if a.repeat <= 1:
162
+ return _record_once(a, ros_args)
163
+ base, ext = os.path.splitext(a.out)
164
+ outs, argv = [], [x for x in sys.argv[1:]]
165
+ for n in range(1, a.repeat + 1):
166
+ if a.between:
167
+ print(f'[trial {n}/{a.repeat}] running: {a.between}')
168
+ if subprocess.run(a.between, shell=True).returncode != 0:
169
+ print('--between command failed; stopping', file=sys.stderr)
170
+ break
171
+ out = f'{base}_{n}{ext}'
172
+ trial = [x for x in argv]
173
+ for flag in ('--repeat', '--between', '--out'):
174
+ while flag in trial:
175
+ k = trial.index(flag)
176
+ del trial[k:k + 2]
177
+ cmd = [sys.executable, '-m', 'nav_explore_eval.cli'] + trial + ['--out', out]
178
+ if subprocess.run(cmd).returncode == 0:
179
+ outs.append(out)
180
+ if not outs:
181
+ return 1
182
+ from .stats import aggregate, load_reports, stats_rows, text_table
183
+ print(text_table(stats_rows(aggregate([r for _, r in load_reports(outs)]))))
184
+ return 0
185
+
186
+
187
+ def cmd_bag(a, ros_args):
188
+ from .bag import score_bag
189
+ truth = load_yaml_map(a.truth)
190
+ try:
191
+ rep = score_bag(a.bag, truth, a.label, a.interval, dict(
192
+ do_align=a.align or a.rotate, rotate=a.rotate, max_shift=a.max_shift, max_yaw=a.max_yaw, tol=a.tol),
193
+ a.ns, a.stop_at, a.truth, a.gt_odom)
194
+ except (ValueError, OSError, RuntimeError) as e:
195
+ print(f'error: {e}', file=sys.stderr)
196
+ return 1
197
+ json.dump(rep, open(a.out, 'w'), indent=2)
198
+ f = rep['final']
199
+ if 'localisation' in rep:
200
+ print(f"localisation: ATE rmse {rep['localisation']['ate_rmse_m']:.3f} m, drift {rep['localisation']['drift_pct'] or 0:.1f}%"
201
+ + (f", RPE {rep['localisation']['rpe_rmse_m']:.3f} m/{rep['localisation']['rpe_delta_m']:g} m"
202
+ if 'rpe_rmse_m' in rep['localisation'] else ''))
203
+ print(f"scored {len(rep['series'])} samples over {rep['duration_s']:.0f}s: coverage {f['coverage_pct']:.1f}% "
204
+ f"f1 {f['wall_f1_pct']:.1f}% -> {a.out}")
205
+ return 0
206
+
207
+
208
+ def cmd_multi(a):
209
+ truth = load_yaml_map(a.truth)
210
+ m, per = _scorer(a, truth).multi([load_yaml_map(p) for p in a.maps])
211
+ if a.json:
212
+ print(json.dumps({'merged': m, 'robots': per}, indent=2))
213
+ return 0
214
+ print('merged:')
215
+ print('\n'.join(f' {k:20s} {v:8.2f}' for k, v in m.items()))
216
+ for p, f in zip(a.maps, per):
217
+ print(f"{p}: coverage {f['coverage_pct']:.1f}% unique {f['unique_pct']:.1f}% overlap {f['overlap_pct']:.1f}%")
218
+ return 0
219
+
220
+
221
+ def cmd_stats(a):
222
+ from .stats import aggregate, load_reports, markdown_table, stats_rows, text_table
223
+ try:
224
+ reps = [r for _, r in load_reports(a.reports)]
225
+ except ValueError as e:
226
+ print(f'error: {e}', file=sys.stderr)
227
+ return 2
228
+ rows = stats_rows(aggregate(reps))
229
+ print(markdown_table(rows) if a.md else text_table(rows))
230
+ return 0
231
+
232
+
233
+ def cmd_report(a):
234
+ from .stats import html_report, load_reports, overlay_png
235
+ try:
236
+ reps = [r for _, r in load_reports(a.reports)]
237
+ except ValueError as e:
238
+ print(f'error: {e}', file=sys.stderr)
239
+ return 2
240
+ ov = None
241
+ if a.map and a.truth:
242
+ truth = load_yaml_map(a.truth)
243
+ ov = overlay_png(load_yaml_map(a.map), truth, _scorer(a, truth))
244
+ open(a.out, 'w').write(html_report(reps, ov, a.title))
245
+ print(f'wrote {a.out}')
246
+ return 0
247
+
248
+
249
+ def cmd_validate(a):
250
+ bad = 0
251
+ for p in a.files:
252
+ try:
253
+ errs = validate(json.load(open(p)))
254
+ except (OSError, json.JSONDecodeError) as e:
255
+ errs = [str(e)]
256
+ print(f'{p}: ' + ('ok' if not errs else '; '.join(errs)))
257
+ bad += bool(errs)
258
+ return 1 if bad else 0
259
+
260
+
261
+ def cmd_leaderboard(a):
262
+ from .stats import leaderboard
263
+ try:
264
+ md, problems = leaderboard(a.dir)
265
+ except ValueError as e:
266
+ print(f'error: {e}', file=sys.stderr)
267
+ return 2
268
+ for p in problems:
269
+ print(f'invalid: {p}', file=sys.stderr)
270
+ if not md:
271
+ return 1
272
+ if a.check:
273
+ cur = open(a.out).read() if os.path.exists(a.out) else ''
274
+ if cur != md:
275
+ print(f'{a.out} is out of date: run `nav_explore_eval leaderboard {a.dir} --out {a.out}`', file=sys.stderr)
276
+ return 1
277
+ else:
278
+ open(a.out, 'w').write(md)
279
+ print(f'wrote {a.out}')
280
+ return 1 if problems else 0
281
+
282
+
283
+ def _align_args(p):
284
+ p.add_argument('--align', action='store_true', help='auto-find the translation between map frames')
285
+ p.add_argument('--rotate', action='store_true', help='also search for a yaw offset (implies --align)')
286
+ p.add_argument('--max-shift', type=float, default=3.0)
287
+ p.add_argument('--max-yaw', type=float, default=15.0, help='yaw search range in degrees (+/-)')
288
+ p.add_argument('--tol', type=float, default=0.10, help='wall match tolerance in metres')
289
+
290
+
291
+ def main(argv=None):
292
+ ap = argparse.ArgumentParser(prog='nav_explore_eval', description=__doc__)
293
+ ap.add_argument('--version', action='version', version=f'nav_explore_eval {__version__}')
294
+ sub = ap.add_subparsers(dest='cmd', required=True)
295
+ s = sub.add_parser('score', help='score a saved map against a ground-truth map (offline)')
296
+ s.add_argument('map')
297
+ s.add_argument('truth')
298
+ s.add_argument('--offset', type=float, nargs=2, metavar=('DX', 'DY'))
299
+ s.add_argument('--json', action='store_true')
300
+ _align_args(s)
301
+ t = sub.add_parser('truth-from-world', help='exact ground-truth map from a Gazebo/SDF world file')
302
+ t.add_argument('world')
303
+ t.add_argument('--out', required=True, help='output prefix (writes .pgm + .yaml)')
304
+ t.add_argument('--res', type=float, default=0.05)
305
+ t.add_argument('--margin', type=float, default=1.0)
306
+ t.add_argument('--z', type=float, default=0.2, help='lidar height: only collisions crossing it are walls')
307
+ t.add_argument('--model-path', action='append', default=[], metavar='DIR',
308
+ help='extra directory to resolve model:// includes in (repeatable; also $GAZEBO_MODEL_PATH)')
309
+ t.add_argument('--seed', type=float, nargs=2, default=(0.0, 0.0), metavar=('X', 'Y'),
310
+ help='a free point (robot spawn); free space = what is reachable from it')
311
+ c = sub.add_parser('compare', help='table (and chart) comparing recorded runs')
312
+ c.add_argument('reports', nargs='+')
313
+ c.add_argument('--png')
314
+ r = sub.add_parser('record', help='watch a live /map and score it over time')
315
+ r.add_argument('--truth', required=True, help='ground-truth map yaml')
316
+ r.add_argument('--label', default='run')
317
+ r.add_argument('--out', default='run.json')
318
+ r.add_argument('--ns', default='')
319
+ r.add_argument('--duration', type=float, default=600)
320
+ r.add_argument('--robots', default='', help='comma-separated namespaces: score their merged maps (multi-robot)')
321
+ r.add_argument('--repeat', type=int, default=1, help='N trials -> out_1.json .. out_N.json + mean/std table')
322
+ r.add_argument('--between', default='', help='shell command run before each trial (restart your explorer)')
323
+ r.add_argument('--stop-at', type=float, default=100.0, help='stop when coverage %% reached')
324
+ r.add_argument('--interval', type=float, default=2.0)
325
+ r.add_argument('--gt-odom', default='', metavar='TOPIC',
326
+ help='ground-truth nav_msgs/Odometry topic: adds localisation error (ATE) of /odom to the report')
327
+ _align_args(r)
328
+ b = sub.add_parser('bag', help='score a recorded rosbag2 offline (needs /map, optional /odom)')
329
+ b.add_argument('bag')
330
+ b.add_argument('--truth', required=True)
331
+ b.add_argument('--label', default='bag')
332
+ b.add_argument('--out', default='run.json')
333
+ b.add_argument('--ns', default='')
334
+ b.add_argument('--interval', type=float, default=2.0)
335
+ b.add_argument('--stop-at', type=float, default=100.0)
336
+ b.add_argument('--gt-odom', default='', metavar='TOPIC', help='ground-truth Odometry topic in the bag (adds ATE)')
337
+ _align_args(b)
338
+ m = sub.add_parser('score-multi', help='merge several robots\' saved maps and score them (offline)')
339
+ m.add_argument('maps', nargs='+')
340
+ m.add_argument('--truth', required=True)
341
+ m.add_argument('--json', action='store_true')
342
+ _align_args(m)
343
+ st = sub.add_parser('stats', help='mean +/- std table, grouped by label (repeat trials)')
344
+ st.add_argument('reports', nargs='+', help='run JSON files, globs or directories')
345
+ st.add_argument('--md', action='store_true')
346
+ rp = sub.add_parser('report', help='one-file HTML report (+ map-vs-truth overlay)')
347
+ rp.add_argument('reports', nargs='+')
348
+ rp.add_argument('--out', default='report.html')
349
+ rp.add_argument('--title', default='Exploration report')
350
+ rp.add_argument('--map', help='saved map yaml to overlay on the truth')
351
+ rp.add_argument('--truth')
352
+ _align_args(rp)
353
+ v = sub.add_parser('validate', help='check run JSON files against the report schema')
354
+ v.add_argument('files', nargs='+')
355
+ lb = sub.add_parser('leaderboard', help='build LEADERBOARD.md from a directory of run JSONs')
356
+ lb.add_argument('dir', nargs='?', default='results')
357
+ lb.add_argument('--out', default='LEADERBOARD.md')
358
+ lb.add_argument('--check', action='store_true', help='fail if --out is stale (for CI)')
359
+ a, ros_args = ap.parse_known_args(argv)
360
+ if a.cmd == 'score':
361
+ return cmd_score(a)
362
+ if a.cmd == 'compare':
363
+ return cmd_compare(a)
364
+ for name, fn in (('score-multi', cmd_multi), ('stats', cmd_stats), ('report', cmd_report),
365
+ ('validate', cmd_validate), ('leaderboard', cmd_leaderboard)):
366
+ if a.cmd == name:
367
+ return fn(a)
368
+ if a.cmd == 'bag':
369
+ return cmd_bag(a, ros_args)
370
+ if a.cmd == 'truth-from-world':
371
+ try:
372
+ return cmd_truth(a)
373
+ except (ValueError, OSError) as e:
374
+ print(f'error: {e}', file=sys.stderr)
375
+ return 2
376
+ return cmd_record(a, ros_args)
377
+
378
+
379
+ if __name__ == '__main__':
380
+ raise SystemExit(main())
@@ -0,0 +1,68 @@
1
+ """Occupancy grids as numpy arrays: -1 unknown, 0 free, 100 occupied (OccupancyGrid semantics)."""
2
+ import os
3
+ from dataclasses import dataclass
4
+
5
+ import numpy as np
6
+
7
+
8
+ @dataclass
9
+ class Grid:
10
+ data: np.ndarray # (h, w) int8, row 0 = lowest y
11
+ resolution: float
12
+ ox: float # world x of cell (0,0) corner
13
+ oy: float
14
+
15
+ @property
16
+ def shape(self):
17
+ return self.data.shape
18
+
19
+
20
+ def from_msg(msg):
21
+ i = msg.info
22
+ d = np.asarray(msg.data, dtype=np.int8).reshape(i.height, i.width)
23
+ return Grid(d, float(i.resolution), float(i.origin.position.x), float(i.origin.position.y))
24
+
25
+
26
+ def _read_pgm(path):
27
+ with open(path, 'rb') as f:
28
+ raw = f.read()
29
+ toks, pos = [], 0
30
+ while len(toks) < 4: # magic, w, h, maxval
31
+ while raw[pos:pos + 1].isspace():
32
+ pos += 1
33
+ if raw[pos:pos + 1] == b'#':
34
+ pos = raw.index(b'\n', pos) + 1
35
+ continue
36
+ end = pos
37
+ while not raw[end:end + 1].isspace():
38
+ end += 1
39
+ toks.append(raw[pos:end])
40
+ pos = end
41
+ magic, w, h, mx = toks[0], int(toks[1]), int(toks[2]), int(toks[3])
42
+ if magic == b'P5':
43
+ pix = np.frombuffer(raw[pos + 1:pos + 1 + w * h], dtype=np.uint8)
44
+ elif magic == b'P2':
45
+ pix = np.array(raw[pos:].split(), dtype=np.uint16)[:w * h]
46
+ else:
47
+ raise ValueError(f'{path}: only PGM (P2/P5) maps supported')
48
+ return pix.reshape(h, w).astype(float) / mx
49
+
50
+
51
+ def load_yaml_map(yaml_path):
52
+ import yaml
53
+ y = yaml.safe_load(open(yaml_path))
54
+ img = y['image']
55
+ if not os.path.isabs(img):
56
+ img = os.path.join(os.path.dirname(os.path.abspath(yaml_path)), img)
57
+ v = _read_pgm(img)
58
+ p = v if y.get('negate', 0) else 1.0 - v # occupancy probability
59
+ occ_t, free_t = y.get('occupied_thresh', 0.65), y.get('free_thresh', 0.196)
60
+ g = np.full(p.shape, -1, dtype=np.int8)
61
+ g[p > occ_t] = 100
62
+ g[p < free_t] = 0
63
+ # Nav2's map_saver writes unknown as grey 205 (p = 0.196), which a free_thresh of 0.25 would read as FREE
64
+ # and inflate coverage. Trinary maps keep unknown as unknown.
65
+ if str(y.get('mode', 'trinary')) == 'trinary':
66
+ g[np.abs(v - 205.0 / 255.0) < 0.005] = -1
67
+ g = g[::-1].copy() # image row 0 is top
68
+ return Grid(g, float(y['resolution']), float(y['origin'][0]), float(y['origin'][1]))