slam-doctor 0.2.1__tar.gz

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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.4
2
+ Name: slam_doctor
3
+ Version: 0.2.1
4
+ Summary: Runtime health monitor for any ROS 2 SLAM.
5
+ Maintainer: darshmenon
6
+ Maintainer-email: darshmenon02@gmail.com
7
+ License: Apache-2.0
8
+ License-File: LICENSE
9
+ Requires-Dist: setuptools
10
+ Requires-Dist: numpy
11
+ Dynamic: license
12
+ Dynamic: license-file
13
+ Dynamic: maintainer
14
+ Dynamic: maintainer-email
15
+ Dynamic: requires-dist
16
+ Dynamic: summary
@@ -0,0 +1,94 @@
1
+ # slam_doctor
2
+
3
+ **Is my SLAM healthy?** Attach to any running ROS 2 SLAM (slam_toolbox, Cartographer, RTAB-Map, ORB-SLAM3) and get loop-closure and map-correction timestamps, tracking-lost flaps, map stalls, odometry drift and feature-poor camera views.
4
+
5
+ Companion to [nav2_doctor](https://github.com/darshmenon/nav2_doctor) (why isn't my robot moving?). Built from the [rosnav](https://github.com/darshmenon/rosnav) project's mapping bugs.
6
+
7
+ ![slam_doctor on an ORB-SLAM3 run in Gazebo](docs/demo.gif)
8
+
9
+ Part of [ros2-doctor-tools](https://github.com/darshmenon/ros2-doctor-tools), an index of my ROS 2 diagnosis, fault injection and evaluation tools.
10
+
11
+ ## Install
12
+
13
+ Needs a sourced ROS 2 environment (CI builds it on Humble, Jazzy and Lyrical). With pip:
14
+
15
+ ```bash
16
+ # ROS 2 sourced; if you use a venv, create it with --system-site-packages
17
+ pip install git+https://github.com/darshmenon/slam_doctor
18
+ slam_doctor --help
19
+ ```
20
+
21
+ A pip install puts the `slam_doctor` command on your PATH; run it directly. The `ros2 run` form needs the colcon build.
22
+
23
+ Or with colcon:
24
+
25
+ ```bash
26
+ cd ~/ros2_ws/src && git clone https://github.com/darshmenon/slam_doctor.git
27
+ cd .. && colcon build --packages-select slam_doctor && source install/setup.bash
28
+ ```
29
+
30
+ ## Quick start
31
+
32
+ ```bash
33
+ ros2 run slam_doctor slam_doctor # live report every 2 s
34
+ ros2 run slam_doctor slam_doctor --image /camera/image_raw --hints # + camera quality, next steps
35
+ ros2 run slam_doctor slam_doctor --once 30 --json # CI: exit 1 on ERROR
36
+ ros2 run slam_doctor slam_doctor --events loops.jsonl # loop-closure timeline
37
+ ```
38
+
39
+ Real output from a slam_toolbox maze run (a 0.51 m `map->odom` correction) and an ORB-SLAM3 cafe run:
40
+
41
+ ```
42
+ WARN [BIG_JUMP] map jumped 0.51m / 0.0deg 7s ago
43
+ -> large map correction: expect plan and costmap jumps; clear costmaps after it (costmap_ghost_clear)
44
+
45
+ WARN [FEATURE_POOR] 5 consecutive frames: 74 keypoints, sharpness 52, mean 145
46
+ -> few corners in view (blank wall/floor): a feature-based SLAM will lose tracking here
47
+ ```
48
+
49
+ ## Checks
50
+
51
+ | Code | Level | Meaning |
52
+ |---|---|---|
53
+ | `TRACKING_LOST` | ERROR | `map->odom` silent for 5 s |
54
+ | `MAP_RESET` | ERROR | `/map` lost more than half its free cells (at least 500) in one update; shown for 60 s |
55
+ | `ODOM_STALE` / `SCAN_STALE` | ERROR | odometry or laser scans, once seen, silent for 5 s |
56
+ | `IMAGE_NONE` | WARN | `--image` given but no frame in 5 s |
57
+ | `IMAGE_STALE` | ERROR | camera frames stopped for 5 s |
58
+ | `TRACKING_FLAP` | WARN | tracker stopped and resumed 3+ times in 30 s |
59
+ | `MAP_STALL` | ERROR | no new free cells for 20 s while the robot moved 1 m |
60
+ | `JUMP_STORM` / `BIG_JUMP` | WARN | 4+ map corrections in 60 s / a correction of 0.5 m or more |
61
+ | `DRIFT_HIGH` | WARN | more than 0.10 m of map correction per metre travelled |
62
+ | `FEATURE_POOR`, `BLURRED`, `DARK`, `OVEREXPOSED` | WARN | camera frames a feature-based SLAM will struggle with (`--image`) |
63
+ | `NO_MAP_ODOM`, `MAP_NONE` | WARN | no `map->odom` or no `/map` seen |
64
+
65
+ A correction is a `map->odom` step over 0.10 m or 2 degrees, which is what a loop closure or scan-match jump looks like to the rest of the stack. `--events` writes each one with its time, distance and angle. `--diagnostics` also publishes `/diagnostics`, and the report carries a 0-100 health score.
66
+
67
+ ## Per-robot baselines
68
+
69
+ A 20 Hz `map->odom` is normal for one SLAM setup and a struggling tracker on another. Record normal once, then get warned on drift:
70
+
71
+ ```bash
72
+ slam_doctor --learn 60 --baseline-file my_robot.json # on a healthy run: writes the normal map->odom and odom rates
73
+ slam_doctor --baseline --baseline-file my_robot.json # later: RATE_DROP / RATE_SPIKE below half or above double normal
74
+ ```
75
+
76
+ The rate is the median messages per second: plain statistics, no model. A tracker that goes silent is still `TRACKING_LOST`, not a rate finding. Sparse streams such as `/map` (a few updates a minute) are not baselined.
77
+
78
+ ## How it works
79
+
80
+ Only topics: `/tf` (`map->odom`), `/odom`, `/map` and optionally a camera. No SLAM-specific plugin, so it works with any backend. Camera checks use OpenCV ORB when installed and a NumPy corner proxy otherwise, sampled at 1 Hz.
81
+
82
+ ## Limits
83
+
84
+ - Loop closures are inferred from `map->odom` steps, so a SLAM that publishes corrections smoothly will show smaller steps.
85
+ - Camera thresholds were calibrated on 20 Gazebo cafe frames (ORB at `fastThreshold=7`, ORB-SLAM3's own minimum: 681-1000 keypoints everywhere; default FAST gave as few as 8). Real cameras differ, so check your own frames; the first draft used default FAST and flagged a healthy ORB-SLAM3 run in 44 of 47 reports.
86
+ - One robot per run; use `--ns` once per robot.
87
+
88
+ ## Roadmap
89
+
90
+ - per-camera calibration command (`slam_doctor --calibrate DIR`)
91
+ - live terminal view, multi-robot discovery
92
+ - score a rosbag offline
93
+
94
+ Apache-2.0
@@ -0,0 +1,16 @@
1
+ <?xml version="1.0"?>
2
+ <package format="3">
3
+ <name>slam_doctor</name>
4
+ <version>0.2.1</version>
5
+ <description>Runtime health monitor for any ROS 2 SLAM: loop-closure log, tracking-lost flaps, map stalls, drift, feature-poor views.</description>
6
+ <maintainer email="darshmenon02@gmail.com">darshmenon</maintainer>
7
+ <license>Apache-2.0</license>
8
+ <exec_depend>rclpy</exec_depend>
9
+ <exec_depend>tf2_msgs</exec_depend>
10
+ <exec_depend>nav_msgs</exec_depend>
11
+ <exec_depend>sensor_msgs</exec_depend>
12
+ <exec_depend>diagnostic_msgs</exec_depend>
13
+ <exec_depend>python3-numpy</exec_depend>
14
+ <test_depend>python3-pytest</test_depend>
15
+ <export><build_type>ament_python</build_type></export>
16
+ </package>
File without changes
@@ -0,0 +1,10 @@
1
+ [develop]
2
+ script_dir = $base/lib/slam_doctor
3
+
4
+ [install]
5
+ install_scripts = $base/lib/slam_doctor
6
+
7
+ [egg_info]
8
+ tag_build =
9
+ tag_date = 0
10
+
@@ -0,0 +1,21 @@
1
+ from setuptools import setup
2
+
3
+ package_name = 'slam_doctor'
4
+
5
+ setup(
6
+ name=package_name,
7
+ version='0.2.1',
8
+ packages=[package_name],
9
+ data_files=[
10
+ ('share/ament_index/resource_index/packages', ['resource/' + package_name]),
11
+ ('share/' + package_name, ['package.xml']),
12
+ ],
13
+ install_requires=['setuptools', 'numpy'],
14
+ zip_safe=True,
15
+ maintainer='darshmenon',
16
+ maintainer_email='darshmenon02@gmail.com',
17
+ description='Runtime health monitor for any ROS 2 SLAM.',
18
+ license='Apache-2.0',
19
+ tests_require=['pytest'],
20
+ entry_points={'console_scripts': ['slam_doctor = slam_doctor.doctor:main']},
21
+ )
@@ -0,0 +1 @@
1
+ __version__ = '0.2.1'
@@ -0,0 +1,73 @@
1
+ """Per-robot baselines: learn what normal looks like on this robot, then flag deviations. Pure statistics, no ROS, no training data.
2
+
3
+ `learn` turns message arrival times into a rate (median messages per second) and a jitter (median absolute deviation of that count). `check` compares the recent rate with that baseline."""
4
+ import json
5
+ import statistics
6
+
7
+ MIN_SECONDS = 5 # whole seconds of data needed to trust a stream's baseline
8
+ DROP_RATIO = 0.5 # recent rate below this fraction of the baseline is a drop
9
+ SPIKE_RATIO = 2.0 # recent rate above this multiple is a spike
10
+ WINDOW_S = 6.0 # look-back used by `check`
11
+
12
+
13
+ def per_second_counts(times):
14
+ """Messages per whole second, full seconds only (the first and last are partial)."""
15
+ times = sorted(times)
16
+ if len(times) < 2:
17
+ return []
18
+ t0 = times[0]
19
+ counts = {}
20
+ for t in times:
21
+ counts[int(t - t0)] = counts.get(int(t - t0), 0) + 1
22
+ last = int(times[-1] - t0)
23
+ return [counts.get(i, 0) for i in range(1, last)]
24
+
25
+
26
+ def learn(arrivals):
27
+ """{stream: [times]} -> {stream: {'hz', 'jitter', 'n'}}. The rate is the median messages per second, so bursts of
28
+ messages in one instant (TF) and a few stalls do not skew it. Streams seen for too few seconds are left out."""
29
+ out = {}
30
+ for stream, times in arrivals.items():
31
+ c = per_second_counts(list(times))
32
+ if len(c) < MIN_SECONDS:
33
+ continue
34
+ med = statistics.median(c)
35
+ if med <= 0:
36
+ continue
37
+ mad = statistics.median(abs(x - med) for x in c)
38
+ out[stream] = {'hz': round(float(med), 3), 'jitter': round(float(mad), 3), 'n': len(times)}
39
+ return out
40
+
41
+
42
+ def recent_rate(times, now, window=WINDOW_S):
43
+ t = [x for x in times if now - x <= window]
44
+ if len(t) < 3:
45
+ return None
46
+ return (len(t) - 1) / (t[-1] - t[0]) if t[-1] > t[0] else None
47
+
48
+
49
+ def check(baseline, arrivals, now, window=WINDOW_S):
50
+ """Findings as (level, code, msg). A stream with no recent messages is not reported here: the stale checks own that."""
51
+ found = []
52
+ for stream, b in sorted(baseline.items()):
53
+ r = recent_rate(arrivals.get(stream, []), now, window)
54
+ if r is None:
55
+ continue
56
+ if r < b['hz'] * DROP_RATIO:
57
+ found.append(('WARN', 'RATE_DROP', f'{stream} runs at {r:.1f} Hz, this robot normally gives {b["hz"]:.1f} Hz '
58
+ f'({r / b["hz"]:.0%} of normal)'))
59
+ elif r > b['hz'] * SPIKE_RATIO:
60
+ found.append(('WARN', 'RATE_SPIKE', f'{stream} runs at {r:.1f} Hz, this robot normally gives {b["hz"]:.1f} Hz '
61
+ f'({r / b["hz"]:.1f}x normal)'))
62
+ return found
63
+
64
+
65
+ def save(baseline, path):
66
+ with open(path, 'w') as f:
67
+ json.dump({'version': 1, 'streams': baseline}, f, indent=2, sort_keys=True)
68
+
69
+
70
+ def load(path):
71
+ with open(path) as f:
72
+ data = json.load(f)
73
+ return data['streams']
@@ -0,0 +1,190 @@
1
+ """Pure SLAM-health logic (no ROS): feed it samples with a timestamp, ask for findings."""
2
+ import math
3
+ from collections import deque
4
+ from dataclasses import dataclass
5
+
6
+ JUMP_M = 0.10 # a map->odom step bigger than this is a map correction (loop closure / scan-match jump)
7
+ JUMP_DEG = 2.0
8
+ BIG_JUMP_M = 0.50 # corrections this large make Nav2 plans and costmaps visibly jump
9
+ STORM_WINDOW_S = 60.0
10
+ STORM_COUNT = 4 # this many corrections in the window = periodic jumping (e.g. slam_toolbox every ~10 s)
11
+ GAP_S = 1.0 # map->odom silent this long = tracker stopped publishing
12
+ FLAP_WINDOW_S = 30.0
13
+ FLAP_COUNT = 3
14
+ LOST_S = 5.0 # silent this long = tracking lost, not a blip
15
+ STALL_S = 20.0 # no new free cells for this long ...
16
+ STALL_TRAVEL_M = 1.0 # ... while the robot travelled this far = map not growing
17
+ DRIFT_RATIO = 0.10 # metres of map correction per metre travelled
18
+ DRIFT_MIN_TRAVEL_M = 5.0
19
+ FEATURE_FRAMES = 5 # consecutive bad frames before a visual warning
20
+ RESET_RATIO = 0.5 # free cells dropping by more than this fraction between two maps ...
21
+ RESET_CELLS = 500 # ... and by at least this many cells = the map was reset
22
+ RESET_HOLD_S = 60.0 # keep reporting a reset this long
23
+
24
+
25
+ @dataclass
26
+ class Finding:
27
+ level: str # ERROR / WARN / INFO / OK
28
+ code: str
29
+ msg: str
30
+
31
+
32
+ HINTS = {
33
+ 'RATE_DROP': "a stream is much slower than this robot's learned normal: check CPU load, the SLAM node's publish rate or a throttled bridge; re-learn with --learn if the change is intended",
34
+ 'RATE_SPIKE': "a stream is much faster than this robot's learned normal: a duplicate publisher or a changed rate setting; re-learn with --learn if intended",
35
+ 'TRACKING_LOST': 'move back to a textured, well-lit area; check camera topic rate; look for tracker reset in the SLAM log',
36
+ 'TRACKING_FLAP': 'tracker keeps dropping and recovering: slow down, add texture/light, check sync of image and depth',
37
+ 'JUMP_STORM': 'map corrections arrive in bursts: raise loop-closure / scan-match thresholds',
38
+ 'BIG_JUMP': 'large map correction: expect plan and costmap jumps; clear costmaps after it (costmap_ghost_clear)',
39
+ 'MAP_STALL': 'map stopped growing while the robot moves: check /map publisher, SLAM node queue, and tracking state',
40
+ 'MAP_NONE': 'no /map seen: is the SLAM node running and publishing in this namespace?',
41
+ 'NO_MAP_ODOM': 'SLAM publishes no map->odom: check the SLAM node and its frame names / namespace',
42
+ 'MAP_RESET': 'the map lost most of its free space: did the SLAM node crash and respawn? Check its log; reload a saved map or re-explore',
43
+ 'ODOM_STALE': 'odometry stopped: check the base driver or sim bridge',
44
+ 'SCAN_STALE': 'laser scans stopped: check the lidar driver or sim bridge',
45
+ 'IMAGE_NONE': 'no camera frames: check the --image topic name, the camera driver and QoS',
46
+ 'IMAGE_STALE': 'camera frames stopped: check the camera driver',
47
+ 'DRIFT_HIGH': 'odometry is drifting: check wheel radius/track width, IMU fusion, slip on this surface',
48
+ 'DARK': 'turn on lights or raise exposure', 'OVEREXPOSED': 'lower exposure / avoid facing the light',
49
+ 'BLURRED': 'slow down or raise shutter speed; blur kills feature tracking',
50
+ 'FEATURE_POOR': 'few corners in view (blank wall/floor): a feature-based SLAM will lose tracking here',
51
+ }
52
+
53
+
54
+ def _wrap(a):
55
+ return (a + math.pi) % (2 * math.pi) - math.pi
56
+
57
+
58
+ class SlamDoctor:
59
+ def __init__(self, need_images=False):
60
+ self.need_images = need_images
61
+ self.started = None # first time anything was fed in (or set by the node at launch)
62
+ self.last_odom_t = None
63
+ self.last_scan_t = None
64
+ self.last_image_t = None
65
+ self.reset = None # (time, free_before, free_after) of the latest map reset
66
+ self.last_mo = None # (x, y, yaw) of the previous map->odom sample
67
+ self.last_mo_t = None
68
+ self.events = [] # loop-closure / correction timeline: {t, kind, dist, deg}
69
+ self.gaps = deque() # times a map->odom silence ended (tracker resumed)
70
+ self.gap_open = False
71
+ self.odom_xy = None
72
+ self.travel = 0.0 # metres of odometry travelled
73
+ self.corrected = 0.0 # metres of map->odom correction
74
+ self.map_seen = False
75
+ self.free = None
76
+ self.free_changed_t = None
77
+ self.travel_at_change = 0.0
78
+ self.frames = deque(maxlen=FEATURE_FRAMES)
79
+ self.last_frame = None
80
+ self.arrivals = {'map_odom': deque(maxlen=6000), 'odom': deque(maxlen=6000)} # receive times, for baselines
81
+ self.baseline = None # learned per-robot rates (baseline.py), or None
82
+
83
+ # ---- inputs ----
84
+ def map_odom(self, x, y, yaw, now):
85
+ self.arrivals['map_odom'].append(now)
86
+ if self.last_mo is not None:
87
+ if now - self.last_mo_t > GAP_S:
88
+ self.gaps.append(now)
89
+ self.events.append({'t': now, 'kind': 'resumed', 'dist': 0.0, 'deg': 0.0,
90
+ 'silent_s': round(now - self.last_mo_t, 2)})
91
+ d = math.hypot(x - self.last_mo[0], y - self.last_mo[1])
92
+ a = abs(math.degrees(_wrap(yaw - self.last_mo[2])))
93
+ if d > JUMP_M or a > JUMP_DEG:
94
+ self.corrected += d
95
+ self.events.append({'t': now, 'kind': 'correction', 'dist': round(d, 3), 'deg': round(a, 2)})
96
+ self.last_mo, self.last_mo_t = (x, y, yaw), now
97
+
98
+ def scan(self, now):
99
+ self.last_scan_t = now
100
+
101
+ def image(self, now):
102
+ self.last_image_t = now
103
+
104
+ def odom(self, x, y, now):
105
+ self.last_odom_t = now
106
+ self.arrivals['odom'].append(now)
107
+ if self.odom_xy is not None:
108
+ self.travel += math.hypot(x - self.odom_xy[0], y - self.odom_xy[1])
109
+ self.odom_xy = (x, y)
110
+
111
+ def map_stats(self, free, occupied, unknown, now):
112
+ self.map_seen = True
113
+ if self.free is not None and self.free - free >= RESET_CELLS and free < self.free * (1 - RESET_RATIO):
114
+ self.reset = (now, self.free, free)
115
+ if self.free is None or free != self.free:
116
+ self.free_changed_t, self.travel_at_change = now, self.travel
117
+ self.free = free
118
+
119
+ def frame(self, stats, now):
120
+ from .features import frame_problems
121
+ self.last_frame = stats
122
+ self.frames.append(set(frame_problems(stats)))
123
+
124
+ # ---- verdict ----
125
+ def corrections(self, now, window=STORM_WINDOW_S):
126
+ return [e for e in self.events if e['kind'] == 'correction' and now - e['t'] <= window]
127
+
128
+ def diagnose(self, now):
129
+ f = []
130
+ if self.last_mo is None:
131
+ f.append(Finding('WARN', 'NO_MAP_ODOM', 'no map->odom seen yet'))
132
+ elif now - self.last_mo_t > LOST_S:
133
+ f.append(Finding('ERROR', 'TRACKING_LOST', f'map->odom silent for {now - self.last_mo_t:.1f}s'))
134
+ if not self.map_seen:
135
+ f.append(Finding('WARN', 'MAP_NONE', 'no /map received'))
136
+ if self.reset and now - self.reset[0] <= RESET_HOLD_S:
137
+ f.append(Finding('ERROR', 'MAP_RESET', f'map free cells fell {self.reset[1]} -> {self.reset[2]} '
138
+ f'{now - self.reset[0]:.0f}s ago'))
139
+ for code, label, t in (('ODOM_STALE', 'odometry', self.last_odom_t),
140
+ ('SCAN_STALE', 'laser scan', self.last_scan_t),
141
+ ('IMAGE_STALE', 'camera image', self.last_image_t if self.need_images else None)):
142
+ if t is not None and now - t > LOST_S:
143
+ f.append(Finding('ERROR', code, f'{label} silent for {now - t:.1f}s'))
144
+ if (self.need_images and self.last_image_t is None and self.started is not None
145
+ and now - self.started >= LOST_S):
146
+ f.append(Finding('WARN', 'IMAGE_NONE', f'no camera frames received in {now - self.started:.0f}s'))
147
+ while self.gaps and now - self.gaps[0] > FLAP_WINDOW_S:
148
+ self.gaps.popleft()
149
+ if len(self.gaps) >= FLAP_COUNT:
150
+ f.append(Finding('WARN', 'TRACKING_FLAP',
151
+ f'tracker stopped and resumed {len(self.gaps)}x in {FLAP_WINDOW_S:.0f}s'))
152
+ recent = self.corrections(now)
153
+ if len(recent) >= STORM_COUNT:
154
+ f.append(Finding('WARN', 'JUMP_STORM', f'{len(recent)} map corrections in {STORM_WINDOW_S:.0f}s, '
155
+ f'largest {max(e["dist"] for e in recent):.2f}m'))
156
+ big = [e for e in self.corrections(now, 10.0) if e['dist'] >= BIG_JUMP_M]
157
+ if big:
158
+ f.append(Finding('WARN', 'BIG_JUMP', f'map jumped {big[-1]["dist"]:.2f}m / {big[-1]["deg"]:.1f}deg '
159
+ f'{now - big[-1]["t"]:.0f}s ago'))
160
+ if (self.free_changed_t is not None and now - self.free_changed_t >= STALL_S
161
+ and self.travel - self.travel_at_change >= STALL_TRAVEL_M):
162
+ f.append(Finding('ERROR', 'MAP_STALL', f'no new free cells for {now - self.free_changed_t:.0f}s while the '
163
+ f'robot moved {self.travel - self.travel_at_change:.1f}m'))
164
+ if self.travel >= DRIFT_MIN_TRAVEL_M and self.corrected / self.travel > DRIFT_RATIO:
165
+ f.append(Finding('WARN', 'DRIFT_HIGH', f'{self.corrected:.1f}m of map correction over {self.travel:.1f}m '
166
+ f'travelled ({self.corrected / self.travel:.2f} m/m)'))
167
+ if len(self.frames) == FEATURE_FRAMES:
168
+ for code in sorted(set.intersection(*self.frames)):
169
+ f.append(Finding('WARN', code, f'{FEATURE_FRAMES} consecutive frames: ' +
170
+ (f'{self.last_frame["keypoints"]} keypoints, sharpness {self.last_frame["sharpness"]:.0f}, '
171
+ f'mean {self.last_frame["mean"]:.0f}' if self.last_frame else '')))
172
+ if self.baseline:
173
+ from .baseline import check
174
+ f.extend(Finding(lv, code, msg) for lv, code, msg in check(self.baseline, self.arrivals, now))
175
+ if not any(x.level in ('ERROR', 'WARN') for x in f):
176
+ f.append(Finding('OK', 'HEALTHY', 'SLAM looks healthy'))
177
+ return f
178
+
179
+ def score(self, now):
180
+ """0-100 health score: ERROR -40, WARN -10 each, floor 0."""
181
+ s = 100
182
+ for x in self.diagnose(now):
183
+ s -= 40 if x.level == 'ERROR' else 10 if x.level == 'WARN' else 0
184
+ return max(0, s)
185
+
186
+ def summary(self, now):
187
+ c = [e for e in self.events if e['kind'] == 'correction']
188
+ return {'score': self.score(now), 'travel_m': round(self.travel, 2), 'corrections': len(c),
189
+ 'largest_correction_m': round(max((e['dist'] for e in c), default=0.0), 3),
190
+ 'tracker_resumes': sum(1 for e in self.events if e['kind'] == 'resumed')}