Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Changes to the golden LIO trajectory, the check that compares against it and its tolerance
# need approval from one of these owners. See CONTRIBUTING.md.
/tests/golden/ @michalpelka @januszbedkowski
/.github/actions/lio-regression/ @michalpelka @januszbedkowski
/scripts/lio_ate.py @michalpelka @januszbedkowski
/scripts/lio_to_tum.py @michalpelka @januszbedkowski
83 changes: 83 additions & 0 deletions .github/actions/lio-regression/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
name: LIO trajectory regression
description: >
Runs lidar_odometry_step_1 with default parameters on calibration-room/trial-1 of the
HUMANOID-LIO-DATASET (Zenodo 10.5281/zenodo.21318128; 380 s, ~300 m, so it crosses the 200 m
sliding-window reset) and fails when the trajectory's ATE against this platform's golden trajectory,
tests/golden/calibration-room-trial-1-<runner.os>.tum, is above 1 mm. Uploads the trajectory as an
artifact either way.

inputs:
build-dir:
description: CMake build directory containing bin/ (or bin/<config>/ for multi-config generators)
required: true
max-ate-m:
description: Largest accepted position RMSE against the golden trajectory, in metres
default: "0.001"

runs:
using: composite
steps:
- uses: actions/setup-python@v5
with:
python-version: "3.12"

- name: Restore calibration-room dataset
id: dataset-cache
uses: actions/cache@v4
with:
path: ${{ runner.temp }}/lio-dataset/calibration-room.7z
key: humanoid-lio-calibration-room-f965681f362701e48b4631e95e54bd10

- name: Download calibration-room dataset
if: steps.dataset-cache.outputs.cache-hit != 'true'
shell: bash
run: |
mkdir -p "${{ runner.temp }}/lio-dataset"
curl -fsSL --retry 5 --retry-delay 10 -o "${{ runner.temp }}/lio-dataset/calibration-room.7z" \
"https://zenodo.org/api/records/21318128/files/calibration-room.7z/content"

- name: Verify and extract dataset
shell: bash
run: |
archive="${{ runner.temp }}/lio-dataset/calibration-room.7z"
python - "$archive" <<'EOF'
import hashlib, sys
h = hashlib.md5()
with open(sys.argv[1], "rb") as f:
for block in iter(lambda: f.read(1 << 20), b""):
h.update(block)
print(h.hexdigest())
sys.exit(h.hexdigest() != "f965681f362701e48b4631e95e54bd10")
EOF
rm -rf "${{ runner.temp }}/lio-run" && mkdir -p "${{ runner.temp }}/lio-run"
cd "${{ runner.temp }}/lio-run" && cmake -E tar xf "$archive"
rm -rf calibration-room/trial-2 calibration-room/TLS-ground-truth
ls calibration-room/trial-1/hdmapping-raw | head
df -h .

- name: Run lidar_odometry_step_1
shell: bash
run: |
bin=$(find "${{ inputs.build-dir }}/bin" -type f \( -name lidar_odometry_step_1 -o -name lidar_odometry_step_1.exe \) | head -1)
echo "binary: $bin"
start=$(date +%s)
"$bin" "${{ runner.temp }}/lio-run/calibration-room/trial-1/hdmapping-raw"
echo "step 1 took $(( $(date +%s) - start )) s"

- name: Compare with golden trajectory
shell: bash
run: |
result="${{ runner.temp }}/lio-run/calibration-room/trial-1/hdmapping-raw/lio_result_0"
mkdir -p "${{ runner.temp }}/lio-artifact"
cp "$result"/HDMapping_results_*.json "$result"/HDMapping_params_*.toml "$result"/session_ini_poses.mri "${{ runner.temp }}/lio-artifact/"
python "${{ github.workspace }}/scripts/lio_to_tum.py" "$result" "${{ runner.temp }}/lio-artifact/calibration-room-trial-1.tum"
python "${{ github.workspace }}/scripts/lio_ate.py" "${{ github.workspace }}/tests/golden/calibration-room-trial-1-${{ runner.os }}.tum" \
"${{ runner.temp }}/lio-artifact/calibration-room-trial-1.tum" --max-ate-m "${{ inputs.max-ate-m }}"

- name: Upload trajectory
if: always()
uses: actions/upload-artifact@v4
with:
name: lio-calibration-room-trial-1-${{ runner.os }}
path: ${{ runner.temp }}/lio-artifact/
if-no-files-found: warn
6 changes: 5 additions & 1 deletion .github/workflows/cmake-linux.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ jobs:
- name: Configure CMake
# Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make.
# See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type
run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBUILD_WITH_UTILITY_APPLICATION=ON -DBUILD_TESTING=ON
run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBUILD_WITH_UTILITY_APPLICATION=ON -DBUILD_TESTING=ON -DHD_CPU_OPTIMIZATION=GENERIC

- name: Build
# Build your program with the given configuration
Expand All @@ -53,3 +53,7 @@ jobs:
# See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail
run: ctest -C ${{env.BUILD_TYPE}}

- name: LIO trajectory regression
uses: ./.github/actions/lio-regression
with:
build-dir: ${{github.workspace}}/build
5 changes: 5 additions & 0 deletions .github/workflows/macos.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ jobs:
# See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail
run: ctest -C ${{env.BUILD_TYPE}} --output-on-failure

- name: LIO trajectory regression
uses: ./.github/actions/lio-regression
with:
build-dir: ${{github.workspace}}/build

- name: List built binaries
run: |
echo "Built binaries:"
Expand Down
7 changes: 6 additions & 1 deletion .github/workflows/windows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ jobs:
- name: Configure CMake
# Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make.
# See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type
run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBUILD_WITH_UTILITY_APPLICATION=ON -DBUILD_TESTING=ON
run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBUILD_WITH_UTILITY_APPLICATION=ON -DBUILD_TESTING=ON -DHD_CPU_OPTIMIZATION=GENERIC

- name: Build
# Build your program with the given configuration
Expand All @@ -56,6 +56,11 @@ jobs:
# See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail
run: ctest -C ${{env.BUILD_TYPE}} --output-on-failure

- name: LIO trajectory regression
uses: ./.github/actions/lio-regression
with:
build-dir: ${{github.workspace}}/build

- name: Deploy mandeye package
shell: cmd
run: deploy_mandeye.bat "${{github.workspace}}\deploy\mandeye"
Expand Down
4 changes: 4 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ macOS, the Debian package and the Python bindings. It fails on any clang-format
- Keep diffs reviewable. Agent-written code is fine, but a large diff that mixes fixes, refactors, tests and UX will
be sent back to be split.
- Performance work must not change results. Give before/after timings.
- A PR must not change the LIO trajectory. CI compares step 1 on a real recording with `tests/golden/calibration-room-trial-1-<platform>.tum`
(ATE limit 1 mm). This includes bug fixes, default parameters and making dead code take effect. Don't edit the
golden trajectory, the check or its tolerance to make CI pass. An intended improvement follows
[CONTRIBUTING.md](CONTRIBUTING.md).

## Existing workflows

Expand Down
59 changes: 59 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Contributing to HDMapping

Project rules for code, builds and PR scope are in [AGENTS.md](AGENTS.md). They apply to people and coding agents
alike. This file adds the rule that protects the processing results.

## The LIO trajectory must not change

HDMapping's lidar-inertial odometry (`lidar_odometry_step_1`) is state of the art. A PR must not change the trajectory
it computes. CI checks this on every PR, on Linux, Windows and macOS: it runs step 1 with default parameters on
`calibration-room/trial-1` of the [HUMANOID-LIO-DATASET](https://zenodo.org/records/21318128) (380 s, about 300 m, so
it crosses the 200 m sliding-window reset) and fails when the ATE against that platform's golden trajectory,
`tests/golden/calibration-room-trial-1-<Linux|Windows|macOS>.tum`, is above 1 mm.

There is one golden trajectory per platform. Each platform repeats its own result exactly, but the compilers and
standard libraries differ in rounding and in how they order equal elements, so the platforms differ from each other by
about 1-1.5 cm on this recording.

This covers every change, not only changes to the odometry code:

- **Bug fixes.** A fix that changes the trajectory changes behaviour. Making dead code take effect (using a result
that was discarded, enabling a branch that never ran, correcting the units of a weight) is a change to the algorithm,
not a cleanup.
- **Default parameters.** They are part of the algorithm. Changing a default changes the trajectory.
- **Refactors, performance work, dependency updates.** They must keep the trajectory as it is.

When the check fails, find what in your change moved the trajectory and keep it as it was. Don't change the tolerance
or the golden trajectory to make the check pass.

## Improving the odometry

A change that is meant to improve the trajectory is welcome, but it goes in its own PR and it must show:

1. **Results on datasets.** Accuracy against ground truth (for example TLS) before and after the change, on several
recordings from different environments, including recordings longer than
`sliding_window_trajectory_length_threshold` (200 m). Use the datasets listed in AGENTS.md and the
[HDMapping datasets](README.md#our-datasets). Report the numbers in the PR description.
2. **The theory.** Why the change is correct and why it improves the result: the math, the model, or a reference.
A change that only makes the numbers better on one recording is not enough.

Only when both hold up are the golden trajectories updated, in the same PR: each
`tests/golden/calibration-room-trial-1-<platform>.tum` is taken from that PR's CI artifact for the platform
(`lio-calibration-room-trial-1-Linux`, `-Windows`, `-macOS`).

**The decision to update the golden trajectories belongs to Janusz Będkowski and Michał Pełka.** `CODEOWNERS` makes
their approval required for any change under `tests/golden/`, to the CI check and to its tolerance.

## PR checklist

Copy this into the PR description:

```
### Does this PR change the LIO trajectory?
- [ ] No. The LIO trajectory regression check passes on all platforms.
- [ ] Yes, on purpose:
- datasets and accuracy against ground truth, before -> after:
- theory (why it is correct and why it is better):
- golden trajectory updated in this PR: yes / no
- line for the release notes:
```
12 changes: 12 additions & 0 deletions scripts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,15 @@
```
python3 scripts/resample_imu.py /path/to/continousScanning_0013 --rate 200
```

* `lio_to_tum.py` — converts a `lidar_odometry_step_1` result folder (`lio_result_N`) to a TUM trajectory (`timestamp tx ty tz qx qy qz qw`). Uses `session_ini_poses.mri`, the poses step 1 wrote, because steps 2 and 3 overwrite `session_poses.mrp`. Standard library only:

```
python3 scripts/lio_to_tum.py /path/to/lio_result_0 trajectory.tum
```

* `lio_ate.py` — absolute trajectory error of a TUM trajectory against a golden one: poses paired in order with timestamps within `--max-dt-s` (default 10 µs), position RMSE without alignment. Exits 0 when the RMSE is within `--max-ate-m` (default 0.001 m), 1 when it is not, 2 when the poses or timestamps differ. Standard library only:

```
python3 scripts/lio_ate.py golden.tum trajectory.tum --max-ate-m 0.001
```
72 changes: 72 additions & 0 deletions scripts/lio_ate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Absolute trajectory error (ATE) of a TUM trajectory against a golden one.

Poses are paired in order and must have the same timestamps (within
--max-dt-s). They are compared without any alignment: both trajectories come
from lidar_odometry_step_1 on the same data and start in the same frame, so an
alignment would only hide drift.

Exit codes: 0 when the position RMSE is within the limit, 1 when it is not,
2 when the two files do not have the same poses or timestamps.

Usage:
lio_ate.py <golden.tum> <candidate.tum> [--max-ate-m 0.001]
"""

import argparse
import math
import sys


def load(path):
"""Return ([timestamp strings], [(x, y, z)]) from a TUM file."""
times, positions = [], []
with open(path) as f:
for line in f:
v = line.split()
if not v or v[0].startswith("#"):
continue
times.append(v[0])
positions.append((float(v[1]), float(v[2]), float(v[3])))
return times, positions


def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("golden", help="reference TUM trajectory")
parser.add_argument("candidate", help="TUM trajectory to check")
parser.add_argument("--max-ate-m", type=float, default=0.001, help="largest accepted position RMSE in metres (default 0.001)")
parser.add_argument(
"--max-dt-s", type=float, default=1e-5, help="largest accepted timestamp difference between paired poses (default 1e-5)"
)
args = parser.parse_args()

golden_times, golden = load(args.golden)
candidate_times, candidate = load(args.candidate)
if len(golden_times) != len(candidate_times):
print(f"Pose counts differ: golden has {len(golden_times)} poses, candidate {len(candidate_times)}")
return 2
# Timestamps are rounded from doubles, so platforms can differ in the last digits (~0.3 us at 1.8e9 s).
worst = max((abs(float(g) - float(c)) for g, c in zip(golden_times, candidate_times)), default=0.0)
if worst > args.max_dt_s:
print(f"Timestamps differ by up to {worst:.9f} s (limit {args.max_dt_s} s)")
return 2
if not golden:
print("No poses to compare")
return 2

errors = [math.dist(g, c) for g, c in zip(golden, candidate)]
ate = math.sqrt(sum(e * e for e in errors) / len(errors))
print(
f"poses {len(errors)} ATE RMSE {ate * 1000:.2f} mm max {max(errors) * 1000:.2f} mm "
f"final {errors[-1] * 1000:.2f} mm (limit {args.max_ate_m * 1000:.1f} mm)"
)
if ate > args.max_ate_m:
print("FAIL: trajectory differs from the golden one")
return 1
print("PASS")
return 0


if __name__ == "__main__":
sys.exit(main())
98 changes: 98 additions & 0 deletions scripts/lio_to_tum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""Convert a lidar_odometry_step_1 result folder to a TUM trajectory.

Each pose is the chunk pose from 'session_ini_poses.mri' times the local pose
from 'trajectory_lio_<N>.csv'. The .mri is read rather than 'session_poses.mrp'
because steps 2 and 3 overwrite the .mrp; the .mri is what step 1 wrote.

Output lines are 'timestamp tx ty tz qx qy qz qw', sorted by time, with the
timestamp in seconds taken from the CSV's 'timestamp_nanoseconds' column.

Usage:
lio_to_tum.py <lio_result_folder> <output.tum>
"""

import argparse
import math
import re
import sys
from pathlib import Path


def read_poses(path):
"""Return {chunk index: 4x4 pose} from a .mri/.mrp file."""
tokens = Path(path).read_text().split()
count = int(tokens[0])
poses = {}
pos = 1
for _ in range(count):
index = int(re.search(r"(\d+)", Path(tokens[pos]).stem).group(1))
values = [float(v) for v in tokens[pos + 1 : pos + 17]]
poses[index] = [values[r * 4 : r * 4 + 4] for r in range(4)]
pos += 17
return poses


def multiply(a, b):
return [[sum(a[r][k] * b[k][c] for k in range(4)) for c in range(4)] for r in range(4)]


def quaternion(m):
"""Rotation part of a 4x4 matrix as (qx, qy, qz, qw)."""
trace = m[0][0] + m[1][1] + m[2][2]
if trace > 0.0:
s = 2.0 * math.sqrt(trace + 1.0)
return ((m[2][1] - m[1][2]) / s, (m[0][2] - m[2][0]) / s, (m[1][0] - m[0][1]) / s, 0.25 * s)
i = max(range(3), key=lambda d: m[d][d])
j, k = (i + 1) % 3, (i + 2) % 3
s = 2.0 * math.sqrt(1.0 + m[i][i] - m[j][j] - m[k][k])
q = [0.0, 0.0, 0.0, 0.0]
q[i] = 0.25 * s
q[j] = (m[j][i] + m[i][j]) / s
q[k] = (m[k][i] + m[i][k]) / s
q[3] = (m[k][j] - m[j][k]) / s
return tuple(q)


def convert(folder):
"""Return [(timestamp_ns, 4x4 global pose)] sorted by time."""
folder = Path(folder)
chunks = read_poses(folder / "session_ini_poses.mri")
rows = []
for index in sorted(chunks):
csv_path = folder / f"trajectory_lio_{index}.csv"
with open(csv_path) as f:
next(f) # header
for line in f:
v = line.split()
if len(v) < 13:
continue
local = [[float(x) for x in v[1 + r * 4 : 5 + r * 4]] for r in range(3)] + [[0.0, 0.0, 0.0, 1.0]]
rows.append((int(v[0]), multiply(chunks[index], local)))
rows.sort(key=lambda row: row[0])
return rows


def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("folder", help="lio_result_N folder written by lidar_odometry_step_1")
parser.add_argument("output", help="TUM file to write")
args = parser.parse_args()

rows = convert(args.folder)
if not rows:
print(f"No poses found in '{args.folder}'", file=sys.stderr)
return 1
with open(args.output, "w", newline="\n") as out: # same bytes on every platform
for ns, m in rows:
qx, qy, qz, qw = quaternion(m)
out.write(
f"{ns // 10**9}.{ns % 10**9:09d} {m[0][3]:.6f} {m[1][3]:.6f} {m[2][3]:.6f} "
f"{qx:.9f} {qy:.9f} {qz:.9f} {qw:.9f}\n"
)
print(f"{len(rows)} poses written to '{args.output}'")
return 0


if __name__ == "__main__":
sys.exit(main())
Loading
Loading