Simultaneous Localization and Mapping (SLAM)
SLAM is an approach to robotics that allows a robot to build a map of its environment while simultaneously determining its own location within that map. This is often referred to as the 'chicken-and-egg problem': to know where it is, it needs an accurate map; to build an accurate map, it needs to know exactly where it was standing when it took each scan.
A common implementation of SLAM involves using a real particle filter for localization and a Bayesian occupancy grid for mapping. The particle filter estimates the robot's pose (position and orientation) based on sensor data like lidar and wheel odometry, while the occupancy grid represents the environment’s geometry, indicating which areas are occupied and which are free.
Crucially, these two components update each other continuously. As the particle filter refines its estimate of the robot's location, it provides updated information to the occupancy grid, allowing the grid to better represent the surrounding environment. Conversely, the occupancy grid’s representation of the environment informs the particle filter's localization process.
Localization: the particle filter
A particle filter (or Monte Carlo Localization) represents the robot's belief about its own pose — not as one number, but as a cloud of thousands of weighted hypotheses, each a candidate (x, y, theta). Every step runs three phases:
1. predict: move every particle by the odometry reading + noise
2. update: score each particle by how well its predicted lidar scan (cast against the current map estimate) matches the robot's actual lidar reading
3. resample: draw a new particle set, probability proportional to score - high-scoring particles get duplicated, low-scoring ones vanish
Because odometry drifts (wheel slip, integration error compounding over time) the predict step alone would let the cloud spread out and drift away from the truth. The update step is what pulls it back: a particle whose hypothesised position would have produced a very different lidar scan than what the sensor actually saw gets a low weight and is culled at resampling. After enough steps the surviving cloud collapses tightly around the true pose — that collapse, visible in the demo as the particle spread shrinking, is localization converging.
1. predict: move every particle by the odometry reading + noise
2. update: score each particle by how well its predicted lidar
scan (cast against the current map estimate) matches
the robot's actual lidar reading
3. resample: draw a new particle set, probability proportional to
score - high-scoring particles get duplicated,
low-scoring ones vanish
Mapping: the log-odds occupancy grid
In parallel, the environment is represented as a grid of cells, each holding the probability that cell is occupied. A single noisy lidar return is weak evidence — it might be a false positive, a reflection, or sensor noise — so instead of storing raw probabilities (which saturate awkwardly at 0 and 1) the standard trick stores the log-odds of occupancy, which turns Bayesian updates into simple addition:
l(cell) = log( p(occ) / (1 - p(occ))) // each lidar ray: l(cell) += l_hit if the ray terminated in this cell (evidence: occupied) l(cell) += l_miss if the ray passed through this cell (evidence: free, l_miss
Every additional scan through a cell nudges its log-odds further toward certainty in one direction; a handful of consistent detections is enough to be confident a wall exists, while a single stray return barely moves the estimate. This is exactly why the occupancy grid sharpens from grey uncertainty into confident black walls and white free space over the first several dozen scans of the demo.
l(cell) = log( p(occ) / (1 - p(occ)) ) // each lidar ray: l(cell) += l_hit if the ray terminated in this cell (evidence: occupied) l(cell) += l_miss if the ray passed through this cell (evidence: free, l_miss < 0) p(occ) = 1 / (1 + e^(-l(cell))) // convert back to a probability for display
Чому вони потребують один одного
Крок спостереження частинки фільтрації частинок потребує карти для оцінки прогнозів лідара, а оновлення сітки зайнятості потребує пози для того, щоб знати, які клітин пролетіла луч – кожен є вхідними даними для іншого. У FastSLAM, класичному алгоритмі, який слідує цьому стилю моделювання, ця циркулярність вирішується шляхом надання кожній частинці власної сітки зайнятості: гіпотези пози та карти подорожують разом, а відсіювання поганих пар пози-карти виконується як одиниця, а не спроба розрізнити погану пози від поганої карти після того, як це було зроблено. Це також пояснює, чому кількість частинок є реальною обчислювальною вартістю в SLAM, а не просто локалізації – кожна частинка несе повну сітку.
Нерозв’язаний режим відмови будь-якого локального методу - це замикання циклу: після тривалої подорожі накопичена дрейф може зробити карту самосумісною, тому повернення до раніше відвіданої кімнати може показати дві перекриті копії одного й того ж коридору з урахуванням дрейфу. Виявлення того, що робот повернувся кудись, і відновлення карти (за допомогою оптимізації графа пози) є окремою, більш складною проблемою, яку ця демонстрація локального зіставлення позицій не намагається вирішити – це те, що перетворює SLAM на сучасні системи SLAM, такі як графовий та факторний SLAM.
Часті запитання
Чому SLAM потребує ймовірнісний фільтр замість простого довіряння датчикам?
Оскільки кожен датчик іноді помиляється: відлік коліс з часом відхиляється через прослизання, а дані лідара шумні або іноді неточні. Ймовірнісний фільтр підтримує ціле розподілення гіпотез та дозволяє узгодженим доказам, отриманим протягом багатьох кроків, переважити будь-яке окреме погане вимірювання, що значно більш надійний, ніж беззастережне довіряння останньому вимірюванню.
Що приносить log-odds представлення порівняно зі зберіганням необроблених ймовірностей?
Необроблені ймовірності насичуються близько 0 і 1, що робить повторні байєсівські оновлення чисельно складними та незбалансованими. У просторі log-odds оновлення байєса – це просто додавання: накопичуйте l_hit для доказів зайнятості та l_miss для доказів свободи, і значення може рости без обмежень у будь-якому напрямку, що забезпечує просте та стабільне арифметичне обчислення протягом тисяч сканів.
Що таке замикання циклу і чому його не показано тут?
Замикання циклу – це визначення того, що робот повернувся до місця, яке вже було відображено на карті, щоб дві незалежно відхилені оцінки цього місця могли бути об'єднані, а накопичена помилка виправлена. Це потребує порівняння поточного скану з усією історією карти, а не лише локальним кроком фільтра, і зазвичай вирішується окремо за допомогою оптимізації поуз-графа – іншого алгоритму, який застосовується поверх локального SLAM, показаного тут.
Спробуйте наживо
Усе, що вище, працює прямо у вашому браузері — відкрийте SLAM і змінюйте параметри під час роботи. Нічого не встановлюється, нічого не завантажується на сервер, уся модель живе в одній вкладці.
▶ Відкрити симуляцію SLAM