From 66625b0bd8d476469be5507d778535bd0484f34b Mon Sep 17 00:00:00 2001 From: Max-Bin Date: Wed, 2 Dec 2026 16:07:52 +0900 Subject: [PATCH 1/5] feat: public fields for the ego position covariance and a route's start pose A Scene could say that an ego pose is missing but not how well it was localised, and it held a route's goal and lanes but not where the route starts. Producers that needed either had to carry it in model_data. EgoSequence.position_covariances_3d is [T,3,3] in Scene axes and m^2: symmetric positive semidefinite, a row fully known or fully masked, and R C R^T under a change of Scene axes. T4Scene.route_start_poses_3d is [T,4,4] start-to-Scene transforms, with the conventions of goal_poses_3d. Both are optional and use new Protobuf field numbers. Python and C++ records, validation, slicing, frame access and reanchoring handle both, and route_start is a consumer requirement name. The ROS2 generator fills them from nav_msgs/Odometry.pose.covariance and LaneletRoute.start_pose. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 9 ++ ros2/t4scene_generation/configs/README.md | 14 ++- ros2/t4scene_generation/cpp/src/generator.cpp | 62 +++++++++- .../cpp/src/observations.cpp | 26 +++- .../cpp/src/observations.hpp | 3 + .../cpp/tests/generator_test.cpp | 80 +++++++++++++ .../python/tests/test_generation.py | 20 ++++ t4scene/cpp/README.md | 7 +- t4scene/cpp/include/t4_scene/coordinates.hpp | 34 ++++++ .../cpp/include/t4_scene/protobuf/scene.hpp | 13 ++ t4scene/cpp/include/t4_scene/requirements.hpp | 1 + t4scene/cpp/include/t4_scene/scene_ops.hpp | 44 +++++++ t4scene/cpp/include/t4_scene/scene_types.hpp | 8 +- t4scene/cpp/tests/protobuf_test.cpp | 31 +++++ t4scene/cpp/tests/records_test.cpp | 113 ++++++++++++++++++ t4scene/proto/README.md | 8 ++ t4scene/proto/t4_scene.proto | 6 + t4scene/python/README.md | 20 +++- t4scene/python/t4scene/data/_coordinates.py | 10 ++ t4scene/python/t4scene/data/ego.py | 25 ++++ t4scene/python/t4scene/data/frame.py | 2 + t4scene/python/t4scene/data/scene.py | 14 +++ t4scene/python/t4scene/protobuf/arrays.py | 2 + t4scene/python/t4scene/requirements.py | 1 + .../python/tests/test_position_covariance.py | 96 +++++++++++++++ .../python/tests/test_route_start_poses_3d.py | 74 ++++++++++++ t4scene/tests/test_cpp_exchange.py | 25 ++++ 27 files changed, 737 insertions(+), 11 deletions(-) create mode 100644 t4scene/python/tests/test_position_covariance.py create mode 100644 t4scene/python/tests/test_route_start_poses_3d.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 481176f..0a494b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ compatibility. ## Unreleased +- A Scene can carry the covariance of the ego position and the pose a route + starts from. `EgoSequence.position_covariances_3d` is `[T,3,3]` in Scene axes + and m², and `T4Scene.route_start_poses_3d` is `[T,4,4]` like `goal_poses_3d`. + Both are optional, follow `slice_time()`, `frame_at()` and `reanchor()` in + Python and C++, and use new Protobuf field numbers, so existing Scenes read + unchanged. `route_start` is a new consumer requirement name. The ROS2 + generator fills both from `nav_msgs/Odometry.pose.covariance` and + `LaneletRoute.start_pose`; see + [ROS2 inputs](ros2/t4scene_generation/configs/README.md#ros2-inputs). - `T4Scene.from_proto(message, rows=(start, stop))` decodes one window of a stored Scene without decoding or validating its other rows; `slice_model_data` cuts a nonempty `model_data` payload to the window. Decoding also diff --git a/ros2/t4scene_generation/configs/README.md b/ros2/t4scene_generation/configs/README.md index e800bcb..b295c3c 100644 --- a/ros2/t4scene_generation/configs/README.md +++ b/ros2/t4scene_generation/configs/README.md @@ -70,14 +70,24 @@ acceleration in addition to the six inputs in the online preset. | Input key | ROS message | Scene data | | --- | --- | --- | -| `odometry` | `nav_msgs/msg/Odometry` | 3D pose and linear and angular velocities | +| `odometry` | `nav_msgs/msg/Odometry` | 3D pose, linear and angular velocities, and the covariance of the position in `position_covariances_3d` | | `steering` | `autoware_vehicle_msgs/msg/SteeringReport` | Road-wheel angle from `steering_tire_angle` in radians | | `indicator` | `autoware_vehicle_msgs/msg/TurnIndicatorsReport` | Turn-indicator state | | `annotations` | `autoware_perception_msgs/msg/TrackedObjects` | Timestamped box, cylinder, and polygon batches | | `traffic_lights` | `autoware_perception_msgs/msg/TrafficLightGroupArray` | Signal group IDs and element observations | -| `route` | `autoware_planning_msgs/msg/LaneletRoute` | Lane alternatives and preferred lanes in `routes`, and goal-to-Scene transforms in `goal_poses_3d` | +| `route` | `autoware_planning_msgs/msg/LaneletRoute` | Lane alternatives and preferred lanes in `routes`, goal-to-Scene transforms in `goal_poses_3d`, and start-to-Scene transforms in `route_start_poses_3d` | | `acceleration` | `geometry_msgs/msg/AccelWithCovarianceStamped` | Linear acceleration, rotated into Scene axes | +The position covariance is the upper-left 3×3 block of the odometry message's +pose covariance, which is expressed in the Scene frame. A row interpolated +between two messages takes the same weighted mean of their covariances as of +their positions. The covariance of a message is unknown when the block is all +zero, not finite, not symmetric or not positive semidefinite; the pose of that +message is still used. A source that never reports one leaves the column out. + +The start pose of a route is unknown when its orientation is not a unit +quaternion; the route and its goal are still used. + For bag input, the configured odometry topic must exist. An optional topic may be absent. Any bound topic present in the bag must use the listed message type and CDR serialization. diff --git a/ros2/t4scene_generation/cpp/src/generator.cpp b/ros2/t4scene_generation/cpp/src/generator.cpp index 4407d42..298d50d 100644 --- a/ros2/t4scene_generation/cpp/src/generator.cpp +++ b/ros2/t4scene_generation/cpp/src/generator.cpp @@ -1,12 +1,15 @@ #include "config.hpp" #include "observations.hpp" +#include #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -19,6 +22,8 @@ struct Motion { Vec position; Eigen::Quaterniond rotation; Vec velocity, angular; + // Covariance of the position in Scene axes; unset when the source gives none. + std::optional position_covariance{}; }; double blend(double a, double b, double t) { const double delta = b - a; @@ -29,8 +34,14 @@ Vec blend(const Vec &a, const Vec &b, double t) { return a.binaryExpr(b, [t](double x, double y) { return blend(x, y, t); }); } Motion blend(const Motion &a, const Motion &b, double t) { - return {blend(a.position, b.position, t), a.rotation.slerp(t, b.rotation), - blend(a.velocity, b.velocity, t), blend(a.angular, b.angular, t)}; + Motion value{ + blend(a.position, b.position, t), a.rotation.slerp(t, b.rotation), + blend(a.velocity, b.velocity, t), blend(a.angular, b.angular, t)}; + // A convex combination of two covariances is a covariance. + if (a.position_covariance && b.position_covariance) + value.position_covariance = + (1 - t) * *a.position_covariance + t * *b.position_covariance; + return value; } struct Accel { Vec vector; @@ -165,6 +176,28 @@ Grid window_grid(const Config &c, int64_t anchor) { return {grid_time(anchor, -history, step), step, size_t(history + 1 + future), size_t(history)}; } +// The position block of a row-major 6x6 pose covariance, in the parent frame. +// Unknown when it is all zero (the usual way to publish "not estimated"), not +// finite, not symmetric or not positive semidefinite: a pose with an unusable +// covariance is still a pose. +std::optional +read_position_covariance(const std::array &pose_covariance) { + Eigen::Matrix3d c; + for (int i = 0; i < 3; ++i) + for (int j = 0; j < 3; ++j) + c(i, j) = pose_covariance[6 * i + j]; + if (!c.allFinite() || c.isZero(0)) + return std::nullopt; + const double tolerance = 1e-9 * std::max(1., c.cwiseAbs().maxCoeff()); + if ((c - c.transpose()).cwiseAbs().maxCoeff() > tolerance) + return std::nullopt; + c = (0.5 * (c + c.transpose())).eval(); + if (Eigen::SelfAdjointEigenSolver(c, Eigen::EigenvaluesOnly) + .eigenvalues() + .minCoeff() < -tolerance) + return std::nullopt; + return c; +} Motion read_motion(const nav_msgs::msg::Odometry &msg, const Config &config) { if (frame_name(msg.header.frame_id) != config.scene_frame || frame_name(msg.child_frame_id) != config.body_frame) @@ -183,6 +216,7 @@ Motion read_motion(const nav_msgs::msg::Odometry &msg, const Config &config) { if (!value.position.allFinite() || !value.velocity.allFinite() || !value.angular.allFinite()) throw std::invalid_argument("invalid odometry pose or twist"); + value.position_covariance = read_position_covariance(msg.pose.covariance); return value; } void write_motion(Array &poses, Array &vel, Array &ang, @@ -197,6 +231,11 @@ void write_motion(Array &poses, Array &vel, Array &ang, ang.set(i * 3 + j, value.angular[j]); } } +void write_covariance(Array &covariances, size_t i, + const Eigen::Matrix3d &value) { + for (size_t j = 0; j < 9; ++j) + covariances.set(i * 9 + j, value(j / 3, j % 3)); +} T4Scene observation(int64_t measured) { T4Scene result; result.scene_metadata = {"observation"}; @@ -452,6 +491,8 @@ struct SceneBuilder::Impl { auto &odom_time = ego.odometry_timestamps_ns.emplace(std::vector{n}); std::vector missing_motion(n, 1), missing_steer(n, 1); + Array covariance(std::vector{n, 3, 3}); + std::vector missing_covariance(n, 1); if (config.steering) { ego.tire_steering_angles.emplace(std::vector{n}); ego.tire_steering_timestamps_ns.emplace(std::vector{n}); @@ -465,6 +506,10 @@ struct SceneBuilder::Impl { missing_motion[i] = 0; odom_time.set(i, s->measured); write_motion(poses, vel, ang, i, s->value); + if (const auto &c = s->value.position_covariance) { + missing_covariance[i] = 0; + write_covariance(covariance, i, *c); + } } if (config.steering) { if (auto s = select(future ? future_steer : past_steer, time, @@ -482,6 +527,12 @@ struct SceneBuilder::Impl { mask_row(vel, missing_motion, 3); mask_row(ang, missing_motion, 3); mask_row(odom_time, missing_motion, 1); + // A source that never reports a covariance leaves the column out. + if (std::find(missing_covariance.begin(), missing_covariance.end(), 0) != + missing_covariance.end()) { + mask_row(covariance, missing_covariance, 9); + ego.position_covariances_3d = std::move(covariance); + } if (config.steering) { mask_row(*ego.tire_steering_angles, missing_steer, 1); mask_row(*ego.tire_steering_timestamps_ns, missing_steer, 1); @@ -688,7 +739,12 @@ T4Scene SceneBuilder::convert(const nav_msgs::msg::Odometry &msg) const { auto &p = ego.poses_3d.emplace(std::vector{1, 4, 4}); auto &v = ego.velocities_3d.emplace(std::vector{1, 3}); auto &w = ego.angular_velocities_3d.emplace(std::vector{1, 3}); - write_motion(p, v, w, 0, read_motion(msg, impl_->config)); + const auto motion = read_motion(msg, impl_->config); + write_motion(p, v, w, 0, motion); + if (motion.position_covariance) + write_covariance( + ego.position_covariances_3d.emplace(std::vector{1, 3, 3}), 0, + *motion.position_covariance); ego.odometry_timestamps_ns = scene.timestamps_ns; return scene; } diff --git a/ros2/t4scene_generation/cpp/src/observations.cpp b/ros2/t4scene_generation/cpp/src/observations.cpp index fcc6feb..8760564 100644 --- a/ros2/t4scene_generation/cpp/src/observations.cpp +++ b/ros2/t4scene_generation/cpp/src/observations.cpp @@ -632,6 +632,18 @@ read_route(const autoware_planning_msgs::msg::LaneletRoute &msg) { Eigen::Vector3d(position.x, position.y, position.z); for (size_t k = 0; k < 16; ++k) result.goal[k] = goal(k / 4, k % 4); + // A planner can leave the start pose unset; that must not reject the route. + const auto &origin = msg.start_pose.position; + const auto heading = quaternion(msg.start_pose.orientation); + if (finite_xyz(origin) && valid_orientation(heading)) { + auto start = Eigen::Matrix4d::Identity().eval(); + start.topLeftCorner<3, 3>() = heading.normalized().toRotationMatrix(); + start.topRightCorner<3, 1>() = + Eigen::Vector3d(origin.x, origin.y, origin.z); + auto &pose = result.start.emplace(); + for (size_t k = 0; k < 16; ++k) + pose[k] = start(k / 4, k % 4); + } return result; } @@ -640,11 +652,19 @@ void pack(T4Scene &scene, const std::vector &rows) { routes.indices = Array({rows.size()}); auto &goals = scene.goal_poses_3d.emplace(std::vector{rows.size(), 4, 4}); + Array starts(std::vector{rows.size(), 4, 4}); std::map indices; - std::vector missing; + std::vector missing, missing_start; + bool any_start = false; for (size_t i = 0; i < rows.size(); ++i) { const auto *observation = rows[i]; missing.insert(missing.end(), 16, !observation); + const bool has_start = observation && observation->start; + missing_start.insert(missing_start.end(), 16, !has_start); + any_start |= has_start; + if (has_start) + for (size_t k = 0; k < 16; ++k) + starts.set(i * 16 + k, (*observation->start)[k]); if (!observation) { routes.indices.set(i, -1); continue; @@ -657,5 +677,9 @@ void pack(T4Scene &scene, const std::vector &rows) { goals.set(i * 16 + k, observation->goal[k]); } goals.set_mask(std::move(missing)); + if (any_start) { + starts.set_mask(std::move(missing_start)); + scene.route_start_poses_3d = std::move(starts); + } } } // namespace t4scene::ros2::generation diff --git a/ros2/t4scene_generation/cpp/src/observations.hpp b/ros2/t4scene_generation/cpp/src/observations.hpp index bd82ef9..27e34cc 100644 --- a/ros2/t4scene_generation/cpp/src/observations.hpp +++ b/ros2/t4scene_generation/cpp/src/observations.hpp @@ -1,4 +1,5 @@ #pragma once +#include #include namespace t4scene::ros2::generation { int64_t measurement_time(const builtin_interfaces::msg::Time &); @@ -12,6 +13,8 @@ void check_observation( struct RouteObservation { RouteData route; Transform3D goal; + // Unset when the message carries no usable start pose. + std::optional start; autoware_planning_msgs::msg::LaneletRoute::ConstSharedPtr source; }; RouteObservation read_route(const autoware_planning_msgs::msg::LaneletRoute &); diff --git a/ros2/t4scene_generation/cpp/tests/generator_test.cpp b/ros2/t4scene_generation/cpp/tests/generator_test.cpp index 039a70a..affc928 100644 --- a/ros2/t4scene_generation/cpp/tests/generator_test.cpp +++ b/ros2/t4scene_generation/cpp/tests/generator_test.cpp @@ -66,6 +66,85 @@ void check_route(const SceneBuilder &builder, int64_t cutoff, int64_t lane, "source route differs from Scene route"); } +// The position block of the odometry's row-major 6x6 pose covariance. +nav_msgs::msg::Odometry located(int64_t time, double x, double variance_x) { + auto msg = odom(time, x); + msg.pose.covariance[0] = variance_x; + msg.pose.covariance[1] = msg.pose.covariance[6] = 0.02; + msg.pose.covariance[7] = 0.04; + msg.pose.covariance[14] = 0.25; + return msg; +} + +void check_position_covariance_and_route_start(const fs::path &configs) { + auto close = [](double a, double b) { return std::abs(a - b) < 1e-12; }; + SceneBuilder builder(configs / "range.yaml"); + check(!builder.convert(odom(0, 0)).ego->position_covariances_3d, + "an all-zero covariance is not an estimate"); + const auto single = builder.convert(located(0, 0, 0.09)); + check(single.ego->position_covariances_3d && + single.ego->position_covariances_3d->at(0) == 0.09 && + single.ego->position_covariances_3d->at(4) == 0.04, + "a converted odometry keeps its position covariance"); + + // Rows at 0, 100, 200 and 300 ms from samples at 0, 150 and 300 ms. + check(builder.ingest(located(0, 0, 0.09), 0), "odometry rejected"); + check(builder.ingest(located(150000000, 1.5, 0.18), 150000000), + "odometry rejected"); + auto asymmetric = located(300000000, 3, 0.09); + asymmetric.pose.covariance[1] = 0.5; + check(builder.ingest(asymmetric, 300000000), + "a pose with an unusable covariance is still a pose"); + auto with_start = route(0, 7); + with_start.start_pose.orientation.w = 1; + with_start.start_pose.position.x = 4; + with_start.start_pose.position.y = -2; + check(builder.ingest(with_start, 0), "route rejected"); + const auto scene = builder.build_range({"covariance"}); + check(scene.size() == 4, "range grid"); + const auto &covariances = scene.ego->position_covariances_3d.value(); + check(covariances.shape() == std::vector{4, 3, 3}, + "covariance column shape"); + check(covariances.at(0) == 0.09 && covariances.at(1) == 0.02 && + covariances.at(3) == 0.02 && covariances.at(4) == 0.04 && + covariances.at(8) == 0.25, + "a row on a sample keeps that sample's covariance"); + // Two thirds of the way from 0.09 to 0.18; equal entries stay equal. + check(close(*covariances.get(9), 0.15) && close(*covariances.get(13), 0.04), + "an interpolated row blends the covariances of its two samples"); + for (size_t i = 18; i < 36; ++i) + check(covariances.masked(i), + "a row that needs a sample without a covariance has none"); + check(!scene.ego->poses_3d->masked(3 * 16 + 3), "the pose itself is kept"); + + const auto &starts = scene.route_start_poses_3d.value(); + const auto last = (scene.size() - 1) * 16; + check(starts.at(last + 3) == 4 && starts.at(last + 7) == -2 && + starts.at(last) == 1, + "the route's start pose follows the route"); + for (size_t i = 0; i < scene.size() * 16; ++i) + check(starts.masked(i) == scene.goal_poses_3d->masked(i), + "a row has a start pose exactly when it has a route"); + check(scene.frame_at(scene.size() - 1).route_start_pose_3d->at(3) == 4, + "a frame carries its route's start pose"); + + // A start pose without a valid orientation is unknown, not a reason to drop + // the route. + SceneBuilder unset(configs / "range.yaml"); + check(unset.ingest(odom(0, 0), 0) && + unset.ingest(odom(100000000, 1), 100000000), + "odometry rejected"); + auto without_start = route(0, 7); + without_start.start_pose.orientation.w = 0; + check(unset.ingest(without_start, 0), + "a route without a start pose is still a route"); + const auto plain = unset.build_range({"plain"}); + check(plain.routes && plain.goal_poses_3d && !plain.route_start_poses_3d, + "no start column without a start pose"); + check(!plain.ego->position_covariances_3d, + "no covariance column from a source that never reports one"); +} + void check_polygon_footprints(const fs::path &configs) { autoware_perception_msgs::msg::TrackedObjects msg; msg.header.frame_id = "map"; @@ -287,6 +366,7 @@ int main(int argc, char **argv) { throw std::runtime_error("cannot create test directory"); fs::path work = pattern, bag = work / "test_bag"; check_polygon_footprints(configs); + check_position_covariance_and_route_start(configs); check_annotation_reuse(configs); check_window_retention(configs, work); SceneBuilder live(configs / "online.yaml"); diff --git a/ros2/t4scene_generation/python/tests/test_generation.py b/ros2/t4scene_generation/python/tests/test_generation.py index 1e62fcd..75bf654 100644 --- a/ros2/t4scene_generation/python/tests/test_generation.py +++ b/ros2/t4scene_generation/python/tests/test_generation.py @@ -479,6 +479,10 @@ def test_discrete_streams_and_acceleration(self): motion = odometry(0) motion.pose.pose.orientation.z = 2**-0.5 motion.pose.pose.orientation.w = 2**-0.5 + # The position block of the row-major 6x6 pose covariance, in the map frame. + motion.pose.covariance[0], motion.pose.covariance[7] = 0.09, 0.04 + motion.pose.covariance[1] = motion.pose.covariance[6] = 0.02 + motion.pose.covariance[14] = 0.25 accel = AccelWithCovarianceStamped() accel.header.frame_id = "base_link" accel.accel.accel.linear.x = 2.0 @@ -509,6 +513,8 @@ def test_discrete_streams_and_acceleration(self): route.header.frame_id = "map" route.goal_pose.orientation.w = 1.0 route.goal_pose.position.x = 9.0 + route.start_pose.orientation.w = 1.0 + route.start_pose.position.x = 3.0 empty = TrackedObjects() empty.header.frame_id = "map" empty.header.stamp.nanosec = STEP @@ -567,6 +573,20 @@ def test_discrete_streams_and_acceleration(self): self.assertEqual(scene.routes.indices.tolist(), [-1, 0, 0, 0, 0]) self.assertEqual(scene.routes.rows[0].segments[0].preferred_lane_id, 42) self.assertEqual(float(scene.goal_poses_3d[4, 0, 3]), 9.0) + # The route's start pose follows the route: unknown before it is received. + self.assertEqual(float(scene.route_start_poses_3d[4, 0, 3]), 3.0) + self.assertTrue(np.ma.getmaskarray(scene.route_start_poses_3d)[0].all()) + self.assertEqual(scene.frame_at(4).route_start_pose_3d[0, 3], 3.0) + # Only the first odometry message reports a covariance. A row between it and a + # message without one has no covariance, as has the row of that message. + covariances = scene.ego.position_covariances_3d + self.assertEqual( + covariances[0].tolist(), [[0.09, 0.02, 0.0], [0.02, 0.04, 0.0], [0.0, 0.0, 0.25]] + ) + self.assertEqual( + np.ma.getmaskarray(covariances).all(axis=(1, 2)).tolist(), + [False, True, True, True, True], + ) self.assertEqual(int(scene.ego.turn_indicators[0]), 2) self.assertEqual(scene.ego.acceleration_timestamps_ns.tolist(), [0, 0, 0, None, None]) for row in range(3): diff --git a/t4scene/cpp/README.md b/t4scene/cpp/README.md index fd2375f..34e062a 100644 --- a/t4scene/cpp/README.md +++ b/t4scene/cpp/README.md @@ -110,8 +110,11 @@ configuration. After editing public records, call `scene.validate()` once before iterating. `frame_at` and `slice_time` check the ranges they access. Read a known goal -from `frame.goal_pose_3d` as a 4×4 goal-to-Scene transform. A fully masked -goal or ego vector yields `std::nullopt` on the frame. A window carries only +from `frame.goal_pose_3d` as a 4×4 goal-to-Scene transform, and the pose its +route starts from as `frame.route_start_pose_3d`. +`frame.ego_status->position_covariance_3d` is the 3×3 covariance of the ego +position in Scene axes, in m². A fully masked goal, route start, covariance or +ego vector yields `std::nullopt` on the frame. A window carries only its selected routes and omits the route table when every selection is missing. **Ownership.** Frame and slice array handles retain their underlying storage. diff --git a/t4scene/cpp/include/t4_scene/coordinates.hpp b/t4scene/cpp/include/t4_scene/coordinates.hpp index e2a2524..1872119 100644 --- a/t4scene/cpp/include/t4_scene/coordinates.hpp +++ b/t4scene/cpp/include/t4_scene/coordinates.hpp @@ -1,7 +1,9 @@ #pragma once #include +#include #include +#include namespace t4scene { namespace coordinate_detail { @@ -100,6 +102,28 @@ struct PlanarChange { throw std::invalid_argument("origin requires finite x, y and yaw"); } + void rotate_pairs( + std::optional> &field, + std::initializer_list> pairs) const { + if (!field || field->size() == 0) + return; + const auto &in = *field; + auto out = in.clone(); + std::vector mask; + if (in.has_mask()) { + mask.resize(in.size()); + for (std::size_t i = 0; i < in.size(); ++i) + mask[i] = in.masked(i); + } + const auto stride = in.size() / in.shape().front(); + for (std::size_t i = 0; i < in.size(); i += stride) + for (const auto &[a, b] : pairs) + rotation.apply(in, out, mask, i + a, i + b); + if (in.has_mask()) + out.set_mask(std::move(mask)); + field = std::move(out); + } + void transform(std::optional> &field, Geometry kind) const { if (!field || field->size() == 0) return; @@ -155,6 +179,13 @@ struct PlanarChange { field = std::move(out); } + // R C R^T for [T,3,3] covariances: rotate each row's x/y pair, then each + // column's. Masks follow the same dependencies as a rotated vector. + void covariances(std::optional> &field) const { + rotate_pairs(field, {{0, 1}, {3, 4}, {6, 7}}); + rotate_pairs(field, {{0, 3}, {1, 4}, {2, 5}}); + } + template void objects(std::optional &group) const { if (!group) return; @@ -190,6 +221,7 @@ T4Scene::reanchor(std::optional origin, if (ego) scene_detail::check_columns(*ego, size()); scene_detail::check_column(goal_poses_3d, size(), {4, 4}); + scene_detail::check_column(route_start_poses_3d, size(), {4, 4}); if (!origin) { if (!ego || !ego->poses_3d || (ego->available && !ego->available->at(current_index))) @@ -211,6 +243,7 @@ T4Scene::reanchor(std::optional origin, change.transform(out.ego->velocities_3d, Geometry::vector); change.transform(out.ego->accelerations_3d, Geometry::vector); change.transform(out.ego->angular_velocities_3d, Geometry::vector); + change.covariances(out.ego->position_covariances_3d); } if (out.annotations) { auto &groups = out.annotations->values; @@ -219,6 +252,7 @@ T4Scene::reanchor(std::optional origin, change.objects(groups.polygons); } change.transform(out.goal_poses_3d, Geometry::pose); + change.transform(out.route_start_poses_3d, Geometry::pose); if (global_origin_3d) out.global_origin_3d = compose_rigid(*global_origin_3d, change.to_old); return out; diff --git a/t4scene/cpp/include/t4_scene/protobuf/scene.hpp b/t4scene/cpp/include/t4_scene/protobuf/scene.hpp index 9310e6a..890c3d5 100644 --- a/t4scene/cpp/include/t4_scene/protobuf/scene.hpp +++ b/t4scene/cpp/include/t4_scene/protobuf/scene.hpp @@ -274,6 +274,9 @@ inline void write(const ::t4scene::EgoSequence &in, wire::EgoSequence &out) { if (in.angular_velocities_3d) { write(*in.angular_velocities_3d, *out.mutable_angular_velocities_3d()); } + if (in.position_covariances_3d) { + write(*in.position_covariances_3d, *out.mutable_position_covariances_3d()); + } } inline ::t4scene::EgoSequence read(const wire::EgoSequence &in) { ::t4scene::EgoSequence out; @@ -324,6 +327,10 @@ inline ::t4scene::EgoSequence read(const wire::EgoSequence &in) { if (in.has_angular_velocities_3d()) { out.angular_velocities_3d = read_array(in.angular_velocities_3d()); } + if (in.has_position_covariances_3d()) { + out.position_covariances_3d = + read_array(in.position_covariances_3d()); + } return out; } inline void write(const ::t4scene::BoxAnnotations &in, wire::BoxAnnotations &out) { @@ -848,6 +855,9 @@ inline void write(const ::t4scene::T4Scene &in, wire::T4Scene &out, if (in.goal_poses_3d) { write(*in.goal_poses_3d, *out.mutable_goal_poses_3d()); } + if (in.route_start_poses_3d) { + write(*in.route_start_poses_3d, *out.mutable_route_start_poses_3d()); + } if (in.map) { write(*in.map, *out.mutable_map(), resource_key); } @@ -899,6 +909,9 @@ inline ::t4scene::T4Scene read(const wire::T4Scene &in) { if (in.has_goal_poses_3d()) { out.goal_poses_3d = read_array(in.goal_poses_3d()); } + if (in.has_route_start_poses_3d()) { + out.route_start_poses_3d = read_array(in.route_start_poses_3d()); + } if (in.has_map()) { out.map = read(in.map()); } diff --git a/t4scene/cpp/include/t4_scene/requirements.hpp b/t4scene/cpp/include/t4_scene/requirements.hpp index d9340b3..3eb8535 100644 --- a/t4scene/cpp/include/t4_scene/requirements.hpp +++ b/t4scene/cpp/include/t4_scene/requirements.hpp @@ -27,6 +27,7 @@ inline constexpr std::pair field_members[]{ {"cameras", present<&T4Scene::cameras>}, {"lidar", present<&T4Scene::lidar>}, {"goal", present<&T4Scene::goal_poses_3d>}, + {"route_start", present<&T4Scene::route_start_poses_3d>}, {"model_data", present<&T4Scene::model_data>}}; inline PresenceCheck find_field(std::string_view name) { for (const auto &[field, check] : field_members) { diff --git a/t4scene/cpp/include/t4_scene/scene_ops.hpp b/t4scene/cpp/include/t4_scene/scene_ops.hpp index 31fa004..f63815e 100644 --- a/t4scene/cpp/include/t4_scene/scene_ops.hpp +++ b/t4scene/cpp/include/t4_scene/scene_ops.hpp @@ -102,6 +102,7 @@ inline void check_columns(const EgoSequence &value, std::size_t count) { check_column(value.velocities_3d, count, {3}); check_column(value.accelerations_3d, count, {3}); check_column(value.angular_velocities_3d, count, {3}); + check_column(value.position_covariances_3d, count, {3, 3}); } inline EgoSequence cut_columns(const EgoSequence &value, std::size_t first, std::size_t count) { @@ -123,6 +124,8 @@ inline EgoSequence cut_columns(const EgoSequence &value, std::size_t first, out.velocities_3d = cut(value.velocities_3d, first, count); out.accelerations_3d = cut(value.accelerations_3d, first, count); out.angular_velocities_3d = cut(value.angular_velocities_3d, first, count); + out.position_covariances_3d = + cut(value.position_covariances_3d, first, count); return out; } template @@ -356,6 +359,36 @@ inline Annotations cut_annotations(const AnnotationSequence &sequence, count), std::nullopt}; } +// A [3,3] covariance: fully known or fully masked, finite, symmetric and +// positive semidefinite (every principal minor is nonnegative). +inline void check_covariance(const double *c, const Array &column, + std::size_t offset) { + unsigned known = 0; + for (unsigned i = 0; i < 9; ++i) + known += !column.masked(offset + i); + require(known == 0 || known == 9, + "position covariance must be fully known or fully masked"); + if (!known) + return; + double scale = 1; + for (unsigned i = 0; i < 9; ++i) { + require(std::isfinite(c[i]), "position covariance must be finite"); + scale = std::max(scale, std::abs(c[i])); + } + const double tolerance = 1e-9 * scale; + for (unsigned i = 0; i < 3; ++i) + for (unsigned j = i + 1; j < 3; ++j) + require(std::abs(c[3 * i + j] - c[3 * j + i]) <= tolerance, + "position covariance must be symmetric"); + const double xy = c[0] * c[4] - c[1] * c[1], xz = c[0] * c[8] - c[2] * c[2], + yz = c[4] * c[8] - c[5] * c[5]; + const double det = c[0] * yz - c[1] * (c[1] * c[8] - c[5] * c[2]) + + c[2] * (c[1] * c[5] - c[4] * c[2]); + require(c[0] >= -tolerance && c[4] >= -tolerance && c[8] >= -tolerance && + xy >= -tolerance * scale && xz >= -tolerance * scale && + yz >= -tolerance * scale && det >= -tolerance * scale * scale, + "position covariance must be positive semidefinite"); +} inline void check_pose(const double *m, const Array *column = nullptr, std::size_t offset = 0, bool ego = false) { unsigned known = 0, rotation_known = 0; @@ -481,12 +514,17 @@ inline void T4Scene::validate() const { if (frame_indices) known(*frame_indices); check_column(goal_poses_3d, count, {4, 4}); + check_column(route_start_poses_3d, count, {4, 4}); normalized_tags(scene_metadata.tags); if (global_origin_3d) check_pose(global_origin_3d->data()); if (goal_poses_3d) for (std::size_t i = 0; i < count; ++i) check_pose(goal_poses_3d->data() + 16 * i, &*goal_poses_3d, 16 * i); + if (route_start_poses_3d) + for (std::size_t i = 0; i < count; ++i) + check_pose(route_start_poses_3d->data() + 16 * i, &*route_start_poses_3d, + 16 * i); if (ego) { check_columns(*ego, count); if (ego->available) @@ -497,6 +535,9 @@ inline void T4Scene::validate() const { if (ego->poses_3d) check_pose(ego->poses_3d->data() + 16 * i, &*ego->poses_3d, 16 * i, true); + if (ego->position_covariances_3d) + check_covariance(ego->position_covariances_3d->data() + 9 * i, + *ego->position_covariances_3d, 9 * i); auto indicator = scalar(ego->turn_indicators, i); require(!indicator || (*indicator >= 0 && *indicator <= 4), "invalid turn indicator"); @@ -623,6 +664,7 @@ T4Scene::slice_time(std::size_t start, std::size_t stop, out.current_index = current_index - start; out.frame_indices = cut(frame_indices, start, count); out.goal_poses_3d = cut(goal_poses_3d, start, count); + out.route_start_poses_3d = cut(route_start_poses_3d, start, count); if (ego) out.ego = cut_columns(*ego, start, count); if (annotations) { @@ -694,6 +736,7 @@ inline T4Frame T4Scene::frame_at(std::size_t index) const { out.map = map; out.global_origin_3d = global_origin_3d; out.goal_pose_3d = row(goal_poses_3d, index); + out.route_start_pose_3d = row(route_start_poses_3d, index); if (ego && (!ego->available || ego->available->at(index))) { out.ego_status.emplace(); auto &e = *out.ego_status; @@ -702,6 +745,7 @@ inline T4Frame T4Scene::frame_at(std::size_t index) const { e.ego_velocity_3d = row(ego->velocities_3d, index); e.ego_acceleration_3d = row(ego->accelerations_3d, index); e.angular_velocity_3d = row(ego->angular_velocities_3d, index); + e.position_covariance_3d = row(ego->position_covariances_3d, index); e.tire_steering_angle = scalar(ego->tire_steering_angles, index); e.steering_wheel_angle = scalar(ego->steering_wheel_angles, index); e.turn_indicator = scalar(ego->turn_indicators, index); diff --git a/t4scene/cpp/include/t4_scene/scene_types.hpp b/t4scene/cpp/include/t4_scene/scene_types.hpp index 1bb41fc..1d77f2a 100644 --- a/t4scene/cpp/include/t4_scene/scene_types.hpp +++ b/t4scene/cpp/include/t4_scene/scene_types.hpp @@ -75,6 +75,9 @@ struct EgoSequence { std::optional> accelerations_3d{}; // float64 [T,3], Scene axes, rad/s. std::optional> angular_velocities_3d{}; + // float64 [T,3,3], covariance of the ego position in Scene axes, m^2. + // Symmetric positive semidefinite; a row is fully known or fully masked. + std::optional> position_covariances_3d{}; }; struct BoxAnnotations { @@ -269,6 +272,8 @@ struct T4Scene { std::optional global_origin_3d{}; // float64 [T,4,4] goal-to-Scene transforms. std::optional> goal_poses_3d{}; + // float64 [T,4,4] start-to-Scene transforms of the route each row follows. + std::optional> route_start_poses_3d{}; // One static map for the interval; no map bytes in a Scene. std::optional map{}; // Optional timestamped routes; IDs refer to the static Scene map. @@ -299,7 +304,7 @@ struct T4Scene { // originating Scene. Per-frame ego arrays remove the leading time dimension. struct EgoStatus { std::optional> ego_pose_3d, ego_velocity_3d, - ego_acceleration_3d, angular_velocity_3d; + ego_acceleration_3d, angular_velocity_3d, position_covariance_3d; std::optional tire_steering_angle, steering_wheel_angle; std::optional turn_indicator, odometry_timestamp_ns, acceleration_timestamp_ns, tire_steering_timestamp_ns, @@ -318,6 +323,7 @@ struct T4Frame { std::optional lidar; std::optional global_origin_3d; std::optional> goal_pose_3d; + std::optional> route_start_pose_3d; std::optional model_data; }; diff --git a/t4scene/cpp/tests/protobuf_test.cpp b/t4scene/cpp/tests/protobuf_test.cpp index 35e524b..2509b9c 100644 --- a/t4scene/cpp/tests/protobuf_test.cpp +++ b/t4scene/cpp/tests/protobuf_test.cpp @@ -74,6 +74,15 @@ void check_reanchor_roundtrip() { std::vector goal_mask(32, 0); std::fill_n(goal_mask.begin() + 16, 16, 1); scene.goal_poses_3d->set_mask(std::move(goal_mask)); + const Transform3D start{0, -1, 0, x - 5, 1, 0, 0, y, + 0, 0, 1, 0.5, 0, 0, 0, 1}; + std::vector starts(start.begin(), start.end()); + starts.resize(32); + scene.route_start_poses_3d = + Array::from_values(std::move(starts), {2, 4, 4}); + std::vector start_mask(32, 0); + std::fill_n(start_mask.begin() + 16, 16, 1); + scene.route_start_poses_3d->set_mask(std::move(start_mask)); auto &ego = scene.ego.emplace(); const Transform3D ego_pose{1, 0, 0, x, 0, 1, 0, y + 1, @@ -84,6 +93,12 @@ void check_reanchor_roundtrip() { std::vector ego_mask(32, 0); ego_mask[11] = ego_mask[15] = 1; ego.poses_3d->set_mask(std::move(ego_mask)); + ego.position_covariances_3d = Array::from_values( + {0.09, 0.02, 0, 0.02, 0.04, 0, 0, 0, 0.25, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {2, 3, 3}); + std::vector covariance_mask(18, 0); + std::fill_n(covariance_mask.begin() + 9, 9, 1); + ego.position_covariances_3d->set_mask(std::move(covariance_mask)); auto &annotations = scene.annotations.emplace(); annotations.available = Array::from_values({true, false}, {2}); @@ -120,6 +135,22 @@ void check_reanchor_roundtrip() { restored.ego->poses_3d->masked(11) && restored.ego->poses_3d->masked(15), "reanchored rigid transforms and their masks must survive Protobuf"); + const auto wire_start = restored.current_frame().route_start_pose_3d; + const auto local_start = local_frame.route_start_pose_3d; + require(wire_start && wire_start->at(3) == local_start->at(3) && + wire_start->at(7) == local_start->at(7) && + wire_start->at(11) == 0.5 && + !restored.frame_at(1).route_start_pose_3d, + "a route start pose and its missing row must survive Protobuf"); + const auto wire_covariance = + restored.current_frame().ego_status->position_covariance_3d; + const auto &local_covariance = *local.ego->position_covariances_3d; + require(wire_covariance && wire_covariance->at(0) == local_covariance.at(0) && + wire_covariance->at(1) == local_covariance.at(1) && + wire_covariance->at(8) == 0.25 && + restored.ego->position_covariances_3d->masked(9) && + restored.ego->position_covariances_3d->masked(17), + "a position covariance and its missing row must survive Protobuf"); } int main(int argc, char **argv) { diff --git a/t4scene/cpp/tests/records_test.cpp b/t4scene/cpp/tests/records_test.cpp index f7bbfca..7ee9bde 100644 --- a/t4scene/cpp/tests/records_test.cpp +++ b/t4scene/cpp/tests/records_test.cpp @@ -287,6 +287,117 @@ void goals_are_rigid_transforms_or_missing() { scene.goal_poses_3d->set_mask(std::move(mask)); rejects([&] { scene.validate(); }); } +void position_covariances_are_symmetric_and_rotate_with_the_scene() { + auto scene = make_scene(); + // Known to 0.3 m along x and 0.2 m along y, with x and y correlated. + const std::vector covariance{0.09, 0.02, 0, 0.02, 0.04, + 0, 0, 0, 0.25}; + std::vector values; + for (int row = 0; row < 3; ++row) + values.insert(values.end(), covariance.begin(), covariance.end()); + scene.ego->position_covariances_3d = + Array::from_values(values, {3, 3, 3}); + std::vector mask(27, 0); + std::fill_n(mask.begin() + 18, 9, 1); + scene.ego->position_covariances_3d->set_mask(mask); + scene.validate(); + { + const auto current = + scene.current_frame().ego_status->position_covariance_3d; + check(current && current->at(0) == 0.09 && current->at(1) == 0.02, + "frame retains its position covariance"); + } + check(!scene.frame_at(2).ego_status->position_covariance_3d, + "fully masked covariance is unavailable"); + check(scene.slice_time(1, 3).ego->position_covariances_3d->shape() == + std::vector{2, 3, 3}, + "a slice keeps the covariance rows of its interval"); + + // A quarter turn of the Scene swaps the x and y variances and flips the sign + // of their correlation; the vertical variance is unchanged. + const auto turned = scene.reanchor(Pose2D{5, -3, std::acos(-1.) / 2}) + .ego->position_covariances_3d; + auto close = [](double a, double b) { return std::abs(a - b) < 1e-15; }; + check(close(turned->at(0), 0.04) && close(turned->at(4), 0.09) && + close(turned->at(1), -0.02) && close(turned->at(3), -0.02) && + close(turned->at(8), 0.25), + "a covariance rotates as R C R^T"); + check(!turned->masked(0) && turned->masked(18) && turned->masked(26), + "a missing covariance stays missing under a new anchor"); + + auto invalid = [&](std::size_t index, double value) { + auto edited = scene; + edited.ego->position_covariances_3d = + scene.ego->position_covariances_3d->clone(); + edited.ego->position_covariances_3d->set(index, value); + rejects([&] { edited.validate(); }); + }; + invalid(1, 0.5); // not symmetric + invalid(4, -0.04); // negative variance + invalid(0, std::numeric_limits::quiet_NaN()); + { + auto edited = scene; + auto partial = mask; + partial[8] = 1; + edited.ego->position_covariances_3d = + scene.ego->position_covariances_3d->clone(); + edited.ego->position_covariances_3d->set_mask(std::move(partial)); + rejects([&] { edited.validate(); }); + } + // A correlation larger than the variances allow is not a covariance. + scene.ego->position_covariances_3d = + Array::from_values({1, 2, 0, 2, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, + 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1}, + {3, 3, 3}); + rejects([&] { scene.validate(); }); + // No uncertainty across one axis is still one. + scene.ego->position_covariances_3d = + Array::from_values({0.09, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1}, + {3, 3, 3}); + scene.validate(); +} + +void route_starts_are_rigid_transforms_or_missing() { + auto scene = make_scene(); + const Transform3D start{0, -1, 0, 4, 1, 0, 0, 2, 0, 0, 1, 0.5, 0, 0, 0, 1}; + std::vector starts(start.begin(), start.end()); + starts.insert(starts.end(), start.begin(), start.end()); + starts.resize(3 * start.size(), 0); + scene.route_start_poses_3d = + Array::from_values(std::move(starts), {3, 4, 4}); + std::vector mask(scene.route_start_poses_3d->size(), 1); + std::fill_n(mask.begin(), 2 * start.size(), 0); + scene.route_start_poses_3d->set_mask(mask); + scene.validate(); + SceneRequirements{{"route_start"}}.validate(scene); + { + const auto current = scene.current_frame().route_start_pose_3d; + check(current && current->at(3) == 4 && current->at(7) == 2, + "frame retains its route start pose"); + } + check(!scene.frame_at(2).route_start_pose_3d, + "fully masked route start is unavailable"); + check(scene.slice_time(1, 3).route_start_poses_3d->shape() == + std::vector{2, 4, 4}, + "a slice keeps the route start rows of its interval"); + + // Seen from an anchor at the start, facing the same way, it is the origin. + const auto local = + scene.reanchor(Pose2D{4, 2, std::acos(-1.) / 2}).route_start_poses_3d; + auto close = [](double a, double b) { return std::abs(a - b) < 1e-15; }; + check(close(local->at(3), 0) && close(local->at(7), 0) && + close(local->at(0), 1) && close(local->at(1), 0) && + local->at(11) == 0.5, + "a route start moves with the Scene anchor and keeps its height"); + check(local->masked(2 * 16), "a missing route start stays missing"); + + scene.route_start_poses_3d->set(0, 0.7); + rejects([&] { scene.validate(); }); + scene.route_start_poses_3d.reset(); + rejects( + [&] { SceneRequirements{{"route_start"}}.validate(scene); }); +} } // namespace int main() { @@ -299,6 +410,8 @@ int main() { spatial_origin_defaults_to_current_ego(); validation_distinguishes_invalid_missing_and_empty(); goals_are_rigid_transforms_or_missing(); + position_covariances_are_symmetric_and_rotate_with_the_scene(); + route_starts_are_rigid_transforms_or_missing(); std::cout << "Native data ownership, selection and validation scenarios passed\n"; return 0; diff --git a/t4scene/proto/README.md b/t4scene/proto/README.md index 069da6b..d1fdd27 100644 --- a/t4scene/proto/README.md +++ b/t4scene/proto/README.md @@ -67,6 +67,8 @@ Frame access is derived from these columns. The optional Scene-to-world transform `global_origin_3d` stores a 3×3 rotation and a 3D translation. Each row of `goal_poses_3d` stores a 4×4 goal-to-Scene transform or is fully masked if the goal is unavailable. +`route_start_poses_3d` stores, in the same form, the pose the route of each row +starts from. A flat source can encode either transform with translation `(x, y, 0)` and a rotation about the z axis. A planar map origin uses the `Pose2D` fields `x`, `y`, `cos_yaw` and `sin_yaw` on the wire. Both SDKs expose @@ -87,6 +89,12 @@ copies. Translation can be partially masked; rotation is fully known or fully masked. `from_planar` explicitly assumes zero roll/pitch while retaining unknown height and vertical motion. +`position_covariances_3d` stores the covariance of the ego position for each +row as a symmetric positive semidefinite 3×3 matrix in Scene axes, in m². A row +is fully known or fully masked. Under a change of Scene axes by a rotation `R` +it becomes `R C Rᵀ`. It covers the position only: the orientation part of a +source's pose covariance is not stored. + Vehicle-axis angular properties and vehicle-z yaw rate are projections of canonical storage. Tilted poses can require more than one known motion axis; projection masks follow those dependencies. Acceleration projection requires diff --git a/t4scene/proto/t4_scene.proto b/t4scene/proto/t4_scene.proto index 5d91d82..ebb4810 100644 --- a/t4scene/proto/t4_scene.proto +++ b/t4scene/proto/t4_scene.proto @@ -100,6 +100,9 @@ message EgoSequence { NumericArray velocities_3d = 12; // float64 [T,3], Scene axes, m/s. NumericArray accelerations_3d = 13; // float64 [T,3], Scene axes, m/s^2. NumericArray angular_velocities_3d = 14; // float64 [T,3], Scene axes, rad/s. + // float64 [T,3,3], covariance of the ego position in Scene axes, m^2. Symmetric + // positive semidefinite; a row is fully known or fully masked. + NumericArray position_covariances_3d = 15; } message OptionalString { optional string value = 1; } message StringColumn { repeated OptionalString values = 1; } @@ -173,6 +176,9 @@ message T4Scene { CameraSequence cameras = 12; // Already-loaded pixels only; no implicit IO. LidarSequence lidar = 13; // Already-loaded arrays only; no implicit IO. ModelData model_data = 14; // Absent differs from a present empty dictionary. + // float64 [T,4,4] start-to-Scene transforms of the route each row follows; whole + // rows may be masked. + NumericArray route_start_poses_3d = 15; } // Registered separately, once per resource. SHA-256 covers the encoding, diff --git a/t4scene/python/README.md b/t4scene/python/README.md index d6609cd..66530df 100644 --- a/t4scene/python/README.md +++ b/t4scene/python/README.md @@ -80,6 +80,21 @@ transform. A missing goal returns `None`. For planar coordinates, `(x, y, yaw)`. See the [goal exchange example](tests/test_goal_poses_3d.py). +The pose a route starts from is read the same way, from +`scene.route_start_pose_3d` or `scene.frame_at(i).route_start_pose_3d`. It tells a +stop where the mission began from a stop along the route, which the route's lanes +cannot: a mission can begin outside the first lane. See the +[route start example](tests/test_route_start_poses_3d.py). + +## Read how well the ego position is known + +`scene.ego.position_covariances_3d` holds a 3×3 covariance of the ego position +for each row, in Scene axes and m². Its diagonal holds the variances along x, y +and z. A row whose source reported no estimate is masked, and +`ego.at(i).position_covariance_3d` is then `None`. `reanchor()` rotates the +covariance with the Scene, so its eigenvalues do not depend on the anchor. See +the [position covariance example](tests/test_position_covariance.py). + Set `scene.global_origin_3d` to a 4×4 Scene-to-world transform. `scene.global_origin` projects it to the read-only planar pose `(x, y, yaw)`, with metres and radians. Map origins and ego poses use the same component @@ -106,8 +121,9 @@ inputs.validate(scene) ``` Both sets accept `ego`, `annotations`, `map`, `route`, `traffic_lights`, `cameras`, -`lidar`, `goal` and `model_data`. Required fields take precedence on overlap. -`route` checks `scene.routes`. `goal` checks `scene.goal_poses_3d`. +`lidar`, `goal`, `route_start` and `model_data`. Required fields take precedence on +overlap. `route` checks `scene.routes`. `goal` checks `scene.goal_poses_3d` and +`route_start` checks `scene.route_start_poses_3d`. The frame minima default to zero and exclude the current row. Missing required blocks or insufficient rows raise `ValueError`. A present block can contain masked values or empty observations. Consumers diff --git a/t4scene/python/t4scene/data/_coordinates.py b/t4scene/python/t4scene/data/_coordinates.py index 7d57829..bd17945 100644 --- a/t4scene/python/t4scene/data/_coordinates.py +++ b/t4scene/python/t4scene/data/_coordinates.py @@ -197,6 +197,14 @@ def poses(self, values): ) return _homogeneous(axes, offset, bottom_mask=bottom_mask) + def covariances(self, values): + """``R C R^T`` for [..., 3, 3] covariances: rotate the columns, then the rows.""" + if values is None: + return None + values, rotation = self.local_pair(values, self.to_old[:3, :3].T) + columns = rotate_components(values.swapaxes(-1, -2), rotation).swapaxes(-1, -2) + return rotate_components(columns, rotation) + def registration(self, values): if values is None: return None @@ -250,6 +258,7 @@ def reanchor(scene, origin, reanchor_model_data): velocities_3d=change.xy(ego.velocities_3d), accelerations_3d=change.xy(ego.accelerations_3d), angular_velocities_3d=change.xy(ego.angular_velocities_3d), + position_covariances_3d=change.covariances(ego.position_covariances_3d), ) annotations = scene.annotations if annotations is not None: @@ -263,6 +272,7 @@ def reanchor(scene, origin, reanchor_model_data): ego=ego, annotations=annotations, goal_poses_3d=change.poses(scene.goal_poses_3d), + route_start_poses_3d=change.poses(scene.route_start_poses_3d), global_origin_3d=registration, model_data=model_data, ) diff --git a/t4scene/python/t4scene/data/ego.py b/t4scene/python/t4scene/data/ego.py index 8a33a6e..5b631b9 100644 --- a/t4scene/python/t4scene/data/ego.py +++ b/t4scene/python/t4scene/data/ego.py @@ -86,6 +86,9 @@ class EgoStatus: ego_velocity_3d: Array | None = None # [3], Scene vx/vy/vz, m/s. ego_acceleration_3d: Array | None = None # [3], Scene ax/ay/az, m/s². angular_velocity_3d: Array | None = None # [3], Scene angular velocity, rad/s. + position_covariance_3d: Array | None = ( + None # [3,3], covariance of the ego position in Scene axes, m². + ) tire_steering_angle: float | None = None # road-wheel angle, rad. steering_wheel_angle: float | None = None # steering-wheel angle, rad. turn_indicator: TurnIndicator | None = None # public indicator value. @@ -168,6 +171,9 @@ class EgoSequence: velocities_3d: Array | None = None # [T,3], Scene vx/vy/vz, m/s. accelerations_3d: Array | None = None # [T,3], Scene ax/ay/az, m/s². angular_velocities_3d: Array | None = None # [T,3], Scene angular velocity, rad/s. + position_covariances_3d: Array | None = ( + None # [T,3,3], covariance of the ego position in Scene axes, m². + ) tire_steering_angles: Array | None = None # [T], road-wheel angle, rad. steering_wheel_angles: Array | None = None # [T], steering-wheel angle, rad. turn_indicators: Array | None = None # [T], public indicator value. @@ -292,6 +298,8 @@ def validate(self, count: int) -> None: selected = slice(None) if self.available is None else self.available if self.poses_3d is not None: _validate_poses(self.poses_3d[selected]) + if self.position_covariances_3d is not None: + _validate_covariances(self.position_covariances_3d[selected]) if self.turn_indicators is not None: turns = np.ma.asarray(self.turn_indicators[selected]).compressed() if not np.isin(turns, list(TurnIndicator)).all(): @@ -303,6 +311,7 @@ def validate(self, count: int) -> None: ("ego_velocity_3d", "velocities_3d", (3,)), ("ego_acceleration_3d", "accelerations_3d", (3,)), ("angular_velocity_3d", "angular_velocities_3d", (3,)), + ("position_covariance_3d", "position_covariances_3d", (3, 3)), ("tire_steering_angle", "tire_steering_angles", ()), ("steering_wheel_angle", "steering_wheel_angles", ()), ("turn_indicator", "turn_indicators", ()), @@ -412,6 +421,22 @@ def _validate_poses(value): raise ValueError("ego_pose_3d must have rigid homogeneous bottom row") +def _validate_covariances(value): + values = np.ma.asarray(value) + masks = np.ma.getmaskarray(values).reshape(len(values), -1) + if (masks.any(axis=1) & ~masks.all(axis=1)).any(): + raise ValueError("position_covariance_3d must be fully known or fully masked") + known = np.asarray(values.data[~masks.any(axis=1)], dtype=np.float64) + if not np.isfinite(known).all(): + raise ValueError("position_covariance_3d must be finite") + scale = np.abs(known).max(axis=(-2, -1), keepdims=True, initial=0.0) + tolerance = 1e-9 * np.maximum(scale, 1.0) + if (np.abs(known - known.swapaxes(-1, -2)) > tolerance).any(): + raise ValueError("position_covariance_3d must be symmetric") + if len(known) and (np.linalg.eigvalsh(known) < -tolerance[..., 0]).any(): + raise ValueError("position_covariance_3d must be positive semidefinite") + + def _planar_vector(value): if value is None: return None diff --git a/t4scene/python/t4scene/data/frame.py b/t4scene/python/t4scene/data/frame.py index f938917..c6b8b13 100644 --- a/t4scene/python/t4scene/data/frame.py +++ b/t4scene/python/t4scene/data/frame.py @@ -36,6 +36,7 @@ class T4Frame: ) global_origin_3d: Array | None = None # [4,4]: Frame coordinates -> world goal_pose_3d: Array | None = None # [4,4]: goal coordinates -> Frame + route_start_pose_3d: Array | None = None # [4,4]: the route's start coordinates -> Frame @validate_snapshot def validate(self) -> None: @@ -45,6 +46,7 @@ def validate(self) -> None: as_int64(self.timestamp_ns, "timestamp_ns") validate_transform(self.global_origin_3d, "global_origin_3d") validate_transform(self.goal_pose_3d, "goal_pose_3d") + validate_transform(self.route_start_pose_3d, "route_start_pose_3d") for value in ( self.ego_status, self.annotations, diff --git a/t4scene/python/t4scene/data/scene.py b/t4scene/python/t4scene/data/scene.py index 11366cf..05fb6a9 100644 --- a/t4scene/python/t4scene/data/scene.py +++ b/t4scene/python/t4scene/data/scene.py @@ -84,6 +84,9 @@ class T4Scene: lidar: Sequence[Lidar | None] | None = None # [T] point clouds with their own reference times. global_origin_3d: Array | None = None # [4,4] Scene-to-world rigid transform, translation in m. goal_poses_3d: Array | None = None # [T,4,4]: goal-to-Scene transforms. + route_start_poses_3d: Array | None = ( + None # [T,4,4]: start-to-Scene transforms of the route each row follows. + ) model_data: ModelData | None = ( None # Optional current-window source payload; not generic evaluator input. ) @@ -271,6 +274,7 @@ def cut(value): cameras=cut(self.cameras), lidar=cut(self.lidar), goal_poses_3d=cut(self.goal_poses_3d), + route_start_poses_3d=cut(self.route_start_poses_3d), ) def frame_at(self, index: int) -> T4Frame: @@ -289,6 +293,7 @@ def frame_at(self, index: int) -> T4Frame: lidar=None if self.lidar is None else self.lidar[index], global_origin_3d=self.global_origin_3d, goal_pose_3d=optional_row(self.goal_poses_3d, index), + route_start_pose_3d=optional_row(self.route_start_poses_3d, index), model_data=self.model_data if index == self.current_index else None, ) @@ -296,6 +301,10 @@ def frame_at(self, index: int) -> T4Frame: def goal_pose_3d(self) -> Array | None: return optional_row(self.goal_poses_3d, self.current_index) + @property + def route_start_pose_3d(self) -> Array | None: + return optional_row(self.route_start_poses_3d, self.current_index) + @property def route(self) -> RouteData | None: return None if self.routes is None else self.routes[self.current_index] @@ -386,6 +395,9 @@ def sequence(name): lidar=sequence("lidar"), global_origin_3d=current.global_origin_3d, goal_poses_3d=stack_optional([frame.goal_pose_3d for frame in frames], (4, 4)), + route_start_poses_3d=stack_optional( + [frame.route_start_pose_3d for frame in frames], (4, 4) + ), model_data=model_data if model_data is not None else current.model_data, ) @@ -407,6 +419,8 @@ def validate(self) -> None: validate_transform(self.global_origin_3d, "global_origin_3d") validate_shape(self.goal_poses_3d, (count, 4, 4), "goal_poses_3d") validate_transforms(self.goal_poses_3d, "goal_poses_3d") + validate_shape(self.route_start_poses_3d, (count, 4, 4), "route_start_poses_3d") + validate_transforms(self.route_start_poses_3d, "route_start_poses_3d") if self.ego is not None: self.ego.validate(count) if self.annotations is not None: diff --git a/t4scene/python/t4scene/protobuf/arrays.py b/t4scene/python/t4scene/protobuf/arrays.py index 9aba8c0..d801e78 100644 --- a/t4scene/python/t4scene/protobuf/arrays.py +++ b/t4scene/python/t4scene/protobuf/arrays.py @@ -74,11 +74,13 @@ def _spec(dtype, *shapes, allow_mask=True): "timestamps_ns": _spec(_I64, (None,), allow_mask=False), "frame_indices": _spec(_I64, (None,), allow_mask=False), "goal_poses_3d": _spec(_F64, (None, 4, 4)), + "route_start_poses_3d": _spec(_F64, (None, 4, 4)), }, "EgoSequence": { "velocities_3d": _spec(_F64, (None, 3)), "accelerations_3d": _spec(_F64, (None, 3)), "angular_velocities_3d": _spec(_F64, (None, 3)), + "position_covariances_3d": _spec(_F64, (None, 3, 3)), "available": _spec("?", (None,), allow_mask=False), "tire_steering_angles": _spec(_F64, (None,)), "steering_wheel_angles": _spec(_F64, (None,)), diff --git a/t4scene/python/t4scene/requirements.py b/t4scene/python/t4scene/requirements.py index 4dcba38..a1e3dac 100644 --- a/t4scene/python/t4scene/requirements.py +++ b/t4scene/python/t4scene/requirements.py @@ -17,6 +17,7 @@ "cameras": "cameras", "lidar": "lidar", "goal": "goal_poses_3d", + "route_start": "route_start_poses_3d", "model_data": "model_data", } diff --git a/t4scene/python/tests/test_position_covariance.py b/t4scene/python/tests/test_position_covariance.py new file mode 100644 index 0000000..a86602a --- /dev/null +++ b/t4scene/python/tests/test_position_covariance.py @@ -0,0 +1,96 @@ +import numpy as np +import pytest + +from t4scene import SceneMetadata, T4Scene +from t4scene.data.ego import EgoSequence, EgoStatus + +# Position known to 0.3 m along x and 0.2 m along y, with x and y correlated. +COVARIANCE = np.array([[0.09, 0.02, 0.0], [0.02, 0.04, 0.0], [0.0, 0.0, 0.25]]) + + +def _scene(covariances): + ego = EgoSequence(position_covariances_3d=covariances, available=np.ones(2, bool)) + return T4Scene(SceneMetadata("covariance"), np.array([0, 10]), 0, ego=ego) + + +def test_position_covariance_keeps_missing_rows(): + covariances = np.ma.array(np.stack((COVARIANCE, np.eye(3))), mask=False) + covariances[1] = np.ma.masked + restored = T4Scene.from_proto(_scene(covariances).to_proto()) + np.testing.assert_array_equal( + np.ma.getmaskarray(restored.ego.position_covariances_3d), covariances.mask + ) + np.testing.assert_array_equal(restored.ego.at(0).position_covariance_3d, COVARIANCE) + assert restored.ego.at(1).position_covariance_3d is None + assert restored.slice_time(0, 1).ego.position_covariances_3d.shape == (1, 3, 3) + + +def test_position_covariance_survives_a_status_round_trip(): + statuses = [EgoStatus(position_covariance_3d=COVARIANCE), None, EgoStatus()] + sequence = EgoSequence.from_statuses(statuses) + assert sequence.position_covariances_3d.shape == (3, 3, 3) + np.testing.assert_array_equal(sequence.at(0).position_covariance_3d, COVARIANCE) + assert sequence.at(2).position_covariance_3d is None + + +def test_position_covariance_rotates_with_the_frame(): + scene = _scene(np.stack((COVARIANCE, COVARIANCE))) + yaw = 0.7 + moved = scene.reanchor((3.0, -4.0, yaw)).ego.position_covariances_3d + c, s = np.cos(yaw), np.sin(yaw) + to_new = np.array([[c, s, 0.0], [-s, c, 0.0], [0.0, 0.0, 1.0]]) + np.testing.assert_allclose(moved[0], to_new @ COVARIANCE @ to_new.T, atol=1e-15) + # A quarter turn swaps the x and y variances and flips the sign of their correlation. + quarter = scene.reanchor((0.0, 0.0, np.pi / 2)).ego.position_covariances_3d[0] + np.testing.assert_allclose( + quarter, [[0.04, -0.02, 0.0], [-0.02, 0.09, 0.0], [0.0, 0.0, 0.25]], atol=1e-15 + ) + # The uncertainty itself does not depend on the frame. + np.testing.assert_allclose(np.linalg.eigvalsh(moved[0]), np.linalg.eigvalsh(COVARIANCE)) + + +def test_a_missing_covariance_stays_missing_under_a_new_anchor(): + covariances = np.ma.array(np.stack((COVARIANCE, COVARIANCE)), mask=False) + covariances[1] = np.ma.masked + moved = _scene(covariances).reanchor((1.0, 2.0, 0.3)).ego.position_covariances_3d + mask = np.ma.getmaskarray(moved) + assert not mask[0].any() and mask[1].all() + T4Scene.from_proto(_scene(moved).to_proto()) # still a valid column + + +@pytest.mark.parametrize( + ("covariance", "message"), + [ + (np.diag([np.nan, 1.0, 1.0]), "finite"), + (np.array([[1.0, 0.5, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]), "symmetric"), + (np.diag([1.0, -0.1, 1.0]), "positive semidefinite"), + (np.array([[1.0, 2.0, 0.0], [2.0, 1.0, 0.0], [0.0, 0.0, 1.0]]), "positive semidefinite"), + (np.ma.array(np.eye(3), mask=np.eye(3, dtype=bool)), "fully known or fully masked"), + ], +) +def test_invalid_position_covariances_are_rejected_by_checked_codecs(covariance, message): + scene = _scene(np.ma.stack((covariance, np.ma.array(np.eye(3))))) + with pytest.raises(ValueError, match=message): + scene.validate() + with pytest.raises(ValueError, match=message): + scene.to_proto() + with pytest.raises(ValueError, match=message): + T4Scene.from_proto(scene.to_proto(validate=False)) + + +def test_a_rank_deficient_covariance_is_valid(): + # No uncertainty across the direction of travel, as a planar source reports it. + _scene(np.stack((np.diag([0.09, 0.0, 0.0]), np.zeros((3, 3))))).validate() + + +def test_tensor_covariances_rotate_and_keep_their_gradient(): + torch = pytest.importorskip("torch") + covariances = torch.tensor(np.stack((COVARIANCE, COVARIANCE)), requires_grad=True) + yaw = 0.7 + moved = _scene(covariances).reanchor((3.0, -4.0, yaw)).ego.position_covariances_3d + c, s = np.cos(yaw), np.sin(yaw) + to_new = np.array([[c, s, 0.0], [-s, c, 0.0], [0.0, 0.0, 1.0]]) + assert torch.is_tensor(moved) and moved.requires_grad + np.testing.assert_allclose( + moved[0].detach().numpy(), to_new @ COVARIANCE @ to_new.T, atol=1e-15 + ) diff --git a/t4scene/python/tests/test_route_start_poses_3d.py b/t4scene/python/tests/test_route_start_poses_3d.py new file mode 100644 index 0000000..5fc4d4d --- /dev/null +++ b/t4scene/python/tests/test_route_start_poses_3d.py @@ -0,0 +1,74 @@ +import numpy as np +import pytest + +from t4scene import SceneMetadata, T4Frame, T4Scene +from t4scene.data.ego import planar_pose +from t4scene.requirements import SceneRequirements + + +def _start(): + start = np.eye(4) + start[:3, :3] = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] + start[:3, 3] = [1.0, 2.0, 0.5] + return start + + +def test_route_start_transforms_keep_missing_rows(): + poses = np.ma.array(np.stack((_start(), np.eye(4))), mask=False) + poses[1] = np.ma.masked + scene = T4Scene(SceneMetadata("starts"), np.array([0, 10]), 0, route_start_poses_3d=poses) + restored = T4Scene.from_proto(scene.to_proto()) + np.testing.assert_array_equal(restored.route_start_poses_3d.mask, poses.mask) + np.testing.assert_array_equal(restored.route_start_pose_3d, _start()) + np.testing.assert_allclose(planar_pose(restored.route_start_pose_3d), [1.0, 2.0, np.pi / 2]) + assert restored.frame_at(1).route_start_pose_3d is None + + +def test_route_start_follows_frames_slices_and_a_new_anchor(): + later = _start() + later[:3, 3] = [7.0, 8.0, 0.0] + scene = T4Scene.from_frames( + SceneMetadata("starts"), + [T4Frame(0, 10, route_start_pose_3d=_start())], + [T4Frame(1, 20), T4Frame(2, 30, route_start_pose_3d=later)], + ) + assert scene.frame_at(1).route_start_pose_3d is None + np.testing.assert_array_equal(scene.frame_at(2).route_start_pose_3d, later) + + cut = scene.slice_time(0, 2) + assert cut.route_start_poses_3d.shape == (2, 4, 4) + np.testing.assert_array_equal(cut.route_start_pose_3d, _start()) + + # A new anchor at (1, 2) turned a quarter left: the start is at its origin, facing ahead. + moved = scene.reanchor((1.0, 2.0, np.pi / 2)) + np.testing.assert_allclose(planar_pose(moved.route_start_pose_3d), [0.0, 0.0, 0.0], atol=1e-12) + assert moved.route_start_pose_3d[2, 3] == 0.5 # height is kept + assert np.ma.getmaskarray(moved.route_start_poses_3d)[1].all() + + +@pytest.mark.parametrize( + "pose", + [ + np.diag([np.nan, 1.0, 1.0, 1.0]), + np.diag([0.5, 1.0, 1.0, 1.0]), + np.diag([1.0, 1.0, 1.0, 0.0]), + np.ma.array(np.eye(4), mask=np.eye(4, dtype=bool)), + ], +) +def test_invalid_route_start_transforms_are_rejected_by_checked_codecs(pose): + scene = T4Scene(SceneMetadata("invalid"), np.array([0]), 0, route_start_poses_3d=pose[None]) + with pytest.raises(ValueError, match="route_start_poses_3d"): + scene.validate() + with pytest.raises(ValueError, match="route_start_poses_3d"): + scene.to_proto() + with pytest.raises(ValueError, match="route_start_poses_3d"): + T4Scene.from_proto(scene.to_proto(validate=False)) + + +def test_route_start_is_a_scene_requirement(): + scene = T4Scene(SceneMetadata("start"), np.array([10]), current_index=0) + req = SceneRequirements(fields={"route_start"}) + with pytest.raises(ValueError, match="missing Scene field: route_start"): + req.validate(scene) + scene.route_start_poses_3d = np.ma.masked_all((1, 4, 4)) + req.validate(scene) diff --git a/t4scene/tests/test_cpp_exchange.py b/t4scene/tests/test_cpp_exchange.py index 3b0fec9..29b66ba 100644 --- a/t4scene/tests/test_cpp_exchange.py +++ b/t4scene/tests/test_cpp_exchange.py @@ -54,6 +54,17 @@ def rich_scene(packed_scene): goal[:2, 3] = (1.0, 2.0) scene.goal_poses_3d = np.ma.array(np.repeat(goal[None], 5, axis=0), mask=False) scene.goal_poses_3d.mask[1] = True + start = np.eye(4) + start[:3, :3] = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] + start[:3, 3] = (-5.0, 4.0, 0.5) + scene.route_start_poses_3d = np.ma.array(np.repeat(start[None], 5, axis=0), mask=False) + scene.route_start_poses_3d.mask[3] = True + # Elongated along x and correlated with y: changes under a rotation of the frame. + covariance = np.array([[0.09, 0.02, 0.0], [0.02, 0.04, 0.0], [0.0, 0.0, 0.25]]) + scene.ego.position_covariances_3d = np.ma.array( + np.repeat(covariance[None], 5, axis=0), mask=False + ) + scene.ego.position_covariances_3d.mask[2] = True scene.map = MapReference( sha256="a" * 64, map_id="", @@ -241,6 +252,8 @@ def test_reanchor_matches_python(cpp_exchange, rich_scene, tmp_path): (actual.ego.poses_3d, expected.ego.poses_3d), (actual.ego.velocities_3d, expected.ego.velocities_3d), (actual.goal_poses_3d, expected.goal_poses_3d), + (actual.route_start_poses_3d, expected.route_start_poses_3d), + (actual.ego.position_covariances_3d, expected.ego.position_covariances_3d), ( actual.annotations.values.polygons.vertices, expected.annotations.values.polygons.vertices, @@ -272,7 +285,11 @@ def test_single_row_route_table(cpp_exchange, rich_scene, tmp_path, row): "scale", "map-planar", "goal", + "route-start", "ego", + "covariance-asymmetric", + "covariance-negative", + "covariance-partial", "indicator", "color", "shape", @@ -295,8 +312,16 @@ def test_both_decoders_reject_invalid_values(cpp_exchange, rich_scene, tmp_path, scene.global_origin_3d[0, 0] = 2 elif case == "goal": scene.goal_poses_3d = np.tile(np.diag([-1.0, 1.0, 1.0, 1.0]), (5, 1, 1)) + elif case == "route-start": + scene.route_start_poses_3d = np.tile(np.diag([-1.0, 1.0, 1.0, 1.0]), (5, 1, 1)) elif case == "ego": scene.ego.poses_3d[0, 0, 0] = 2 + elif case == "covariance-asymmetric": + scene.ego.position_covariances_3d[0, 0, 1] = 0.5 + elif case == "covariance-negative": + scene.ego.position_covariances_3d[0] = np.diag([0.1, -0.1, 0.1]) + elif case == "covariance-partial": + scene.ego.position_covariances_3d[0, 2, 2] = np.ma.masked elif case == "indicator": scene.ego.turn_indicators[0] = -1 elif case in ("color", "shape", "status", "confidence"): From 712b5cc2063e6faaf8aacae3431037a102abea6d Mon Sep 17 00:00:00 2001 From: Max-Bin Date: Wed, 2 Dec 2026 17:50:03 +0900 Subject: [PATCH 2/5] refactor: name the route start column start_poses_3d, beside goal_poses_3d The column, its frame and Scene accessors and the consumer requirement take the names of their goal counterparts: start_poses_3d, start_pose_3d and "start". Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 4 +- ros2/t4scene_generation/configs/README.md | 2 +- .../cpp/src/observations.cpp | 2 +- .../cpp/tests/generator_test.cpp | 10 +-- .../python/tests/test_generation.py | 6 +- t4scene/cpp/README.md | 2 +- t4scene/cpp/include/t4_scene/coordinates.hpp | 4 +- .../cpp/include/t4_scene/protobuf/scene.hpp | 8 +- t4scene/cpp/include/t4_scene/requirements.hpp | 2 +- t4scene/cpp/include/t4_scene/scene_ops.hpp | 11 ++- t4scene/cpp/include/t4_scene/scene_types.hpp | 4 +- t4scene/cpp/tests/protobuf_test.cpp | 11 ++- t4scene/cpp/tests/records_test.cpp | 26 +++---- t4scene/proto/README.md | 2 +- t4scene/proto/t4_scene.proto | 4 +- t4scene/python/README.md | 8 +- t4scene/python/t4scene/data/_coordinates.py | 2 +- t4scene/python/t4scene/data/frame.py | 4 +- t4scene/python/t4scene/data/scene.py | 18 ++--- t4scene/python/t4scene/protobuf/arrays.py | 2 +- t4scene/python/t4scene/requirements.py | 2 +- .../python/tests/test_route_start_poses_3d.py | 74 ------------------- t4scene/python/tests/test_start_poses_3d.py | 74 +++++++++++++++++++ t4scene/tests/test_cpp_exchange.py | 8 +- 24 files changed, 142 insertions(+), 148 deletions(-) delete mode 100644 t4scene/python/tests/test_route_start_poses_3d.py create mode 100644 t4scene/python/tests/test_start_poses_3d.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a494b3..8ee803e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,10 +7,10 @@ compatibility. - A Scene can carry the covariance of the ego position and the pose a route starts from. `EgoSequence.position_covariances_3d` is `[T,3,3]` in Scene axes - and m², and `T4Scene.route_start_poses_3d` is `[T,4,4]` like `goal_poses_3d`. + and m², and `T4Scene.start_poses_3d` is `[T,4,4]` like `goal_poses_3d`. Both are optional, follow `slice_time()`, `frame_at()` and `reanchor()` in Python and C++, and use new Protobuf field numbers, so existing Scenes read - unchanged. `route_start` is a new consumer requirement name. The ROS2 + unchanged. `start` is a new consumer requirement name. The ROS2 generator fills both from `nav_msgs/Odometry.pose.covariance` and `LaneletRoute.start_pose`; see [ROS2 inputs](ros2/t4scene_generation/configs/README.md#ros2-inputs). diff --git a/ros2/t4scene_generation/configs/README.md b/ros2/t4scene_generation/configs/README.md index b295c3c..24e29bf 100644 --- a/ros2/t4scene_generation/configs/README.md +++ b/ros2/t4scene_generation/configs/README.md @@ -75,7 +75,7 @@ acceleration in addition to the six inputs in the online preset. | `indicator` | `autoware_vehicle_msgs/msg/TurnIndicatorsReport` | Turn-indicator state | | `annotations` | `autoware_perception_msgs/msg/TrackedObjects` | Timestamped box, cylinder, and polygon batches | | `traffic_lights` | `autoware_perception_msgs/msg/TrafficLightGroupArray` | Signal group IDs and element observations | -| `route` | `autoware_planning_msgs/msg/LaneletRoute` | Lane alternatives and preferred lanes in `routes`, goal-to-Scene transforms in `goal_poses_3d`, and start-to-Scene transforms in `route_start_poses_3d` | +| `route` | `autoware_planning_msgs/msg/LaneletRoute` | Lane alternatives and preferred lanes in `routes`, goal-to-Scene transforms in `goal_poses_3d`, and start-to-Scene transforms in `start_poses_3d` | | `acceleration` | `geometry_msgs/msg/AccelWithCovarianceStamped` | Linear acceleration, rotated into Scene axes | The position covariance is the upper-left 3×3 block of the odometry message's diff --git a/ros2/t4scene_generation/cpp/src/observations.cpp b/ros2/t4scene_generation/cpp/src/observations.cpp index 8760564..f50c94c 100644 --- a/ros2/t4scene_generation/cpp/src/observations.cpp +++ b/ros2/t4scene_generation/cpp/src/observations.cpp @@ -679,7 +679,7 @@ void pack(T4Scene &scene, const std::vector &rows) { goals.set_mask(std::move(missing)); if (any_start) { starts.set_mask(std::move(missing_start)); - scene.route_start_poses_3d = std::move(starts); + scene.start_poses_3d = std::move(starts); } } } // namespace t4scene::ros2::generation diff --git a/ros2/t4scene_generation/cpp/tests/generator_test.cpp b/ros2/t4scene_generation/cpp/tests/generator_test.cpp index affc928..b5476c1 100644 --- a/ros2/t4scene_generation/cpp/tests/generator_test.cpp +++ b/ros2/t4scene_generation/cpp/tests/generator_test.cpp @@ -76,7 +76,7 @@ nav_msgs::msg::Odometry located(int64_t time, double x, double variance_x) { return msg; } -void check_position_covariance_and_route_start(const fs::path &configs) { +void check_position_covariance_and_start_pose(const fs::path &configs) { auto close = [](double a, double b) { return std::abs(a - b) < 1e-12; }; SceneBuilder builder(configs / "range.yaml"); check(!builder.convert(odom(0, 0)).ego->position_covariances_3d, @@ -117,7 +117,7 @@ void check_position_covariance_and_route_start(const fs::path &configs) { "a row that needs a sample without a covariance has none"); check(!scene.ego->poses_3d->masked(3 * 16 + 3), "the pose itself is kept"); - const auto &starts = scene.route_start_poses_3d.value(); + const auto &starts = scene.start_poses_3d.value(); const auto last = (scene.size() - 1) * 16; check(starts.at(last + 3) == 4 && starts.at(last + 7) == -2 && starts.at(last) == 1, @@ -125,7 +125,7 @@ void check_position_covariance_and_route_start(const fs::path &configs) { for (size_t i = 0; i < scene.size() * 16; ++i) check(starts.masked(i) == scene.goal_poses_3d->masked(i), "a row has a start pose exactly when it has a route"); - check(scene.frame_at(scene.size() - 1).route_start_pose_3d->at(3) == 4, + check(scene.frame_at(scene.size() - 1).start_pose_3d->at(3) == 4, "a frame carries its route's start pose"); // A start pose without a valid orientation is unknown, not a reason to drop @@ -139,7 +139,7 @@ void check_position_covariance_and_route_start(const fs::path &configs) { check(unset.ingest(without_start, 0), "a route without a start pose is still a route"); const auto plain = unset.build_range({"plain"}); - check(plain.routes && plain.goal_poses_3d && !plain.route_start_poses_3d, + check(plain.routes && plain.goal_poses_3d && !plain.start_poses_3d, "no start column without a start pose"); check(!plain.ego->position_covariances_3d, "no covariance column from a source that never reports one"); @@ -366,7 +366,7 @@ int main(int argc, char **argv) { throw std::runtime_error("cannot create test directory"); fs::path work = pattern, bag = work / "test_bag"; check_polygon_footprints(configs); - check_position_covariance_and_route_start(configs); + check_position_covariance_and_start_pose(configs); check_annotation_reuse(configs); check_window_retention(configs, work); SceneBuilder live(configs / "online.yaml"); diff --git a/ros2/t4scene_generation/python/tests/test_generation.py b/ros2/t4scene_generation/python/tests/test_generation.py index 75bf654..e15fa70 100644 --- a/ros2/t4scene_generation/python/tests/test_generation.py +++ b/ros2/t4scene_generation/python/tests/test_generation.py @@ -574,9 +574,9 @@ def test_discrete_streams_and_acceleration(self): self.assertEqual(scene.routes.rows[0].segments[0].preferred_lane_id, 42) self.assertEqual(float(scene.goal_poses_3d[4, 0, 3]), 9.0) # The route's start pose follows the route: unknown before it is received. - self.assertEqual(float(scene.route_start_poses_3d[4, 0, 3]), 3.0) - self.assertTrue(np.ma.getmaskarray(scene.route_start_poses_3d)[0].all()) - self.assertEqual(scene.frame_at(4).route_start_pose_3d[0, 3], 3.0) + self.assertEqual(float(scene.start_poses_3d[4, 0, 3]), 3.0) + self.assertTrue(np.ma.getmaskarray(scene.start_poses_3d)[0].all()) + self.assertEqual(scene.frame_at(4).start_pose_3d[0, 3], 3.0) # Only the first odometry message reports a covariance. A row between it and a # message without one has no covariance, as has the row of that message. covariances = scene.ego.position_covariances_3d diff --git a/t4scene/cpp/README.md b/t4scene/cpp/README.md index 34e062a..d81104e 100644 --- a/t4scene/cpp/README.md +++ b/t4scene/cpp/README.md @@ -111,7 +111,7 @@ configuration. After editing public records, call `scene.validate()` once before iterating. `frame_at` and `slice_time` check the ranges they access. Read a known goal from `frame.goal_pose_3d` as a 4×4 goal-to-Scene transform, and the pose its -route starts from as `frame.route_start_pose_3d`. +route starts from as `frame.start_pose_3d`. `frame.ego_status->position_covariance_3d` is the 3×3 covariance of the ego position in Scene axes, in m². A fully masked goal, route start, covariance or ego vector yields `std::nullopt` on the frame. A window carries only diff --git a/t4scene/cpp/include/t4_scene/coordinates.hpp b/t4scene/cpp/include/t4_scene/coordinates.hpp index 1872119..a015d6f 100644 --- a/t4scene/cpp/include/t4_scene/coordinates.hpp +++ b/t4scene/cpp/include/t4_scene/coordinates.hpp @@ -221,7 +221,7 @@ T4Scene::reanchor(std::optional origin, if (ego) scene_detail::check_columns(*ego, size()); scene_detail::check_column(goal_poses_3d, size(), {4, 4}); - scene_detail::check_column(route_start_poses_3d, size(), {4, 4}); + scene_detail::check_column(start_poses_3d, size(), {4, 4}); if (!origin) { if (!ego || !ego->poses_3d || (ego->available && !ego->available->at(current_index))) @@ -252,7 +252,7 @@ T4Scene::reanchor(std::optional origin, change.objects(groups.polygons); } change.transform(out.goal_poses_3d, Geometry::pose); - change.transform(out.route_start_poses_3d, Geometry::pose); + change.transform(out.start_poses_3d, Geometry::pose); if (global_origin_3d) out.global_origin_3d = compose_rigid(*global_origin_3d, change.to_old); return out; diff --git a/t4scene/cpp/include/t4_scene/protobuf/scene.hpp b/t4scene/cpp/include/t4_scene/protobuf/scene.hpp index 890c3d5..b7458c4 100644 --- a/t4scene/cpp/include/t4_scene/protobuf/scene.hpp +++ b/t4scene/cpp/include/t4_scene/protobuf/scene.hpp @@ -855,8 +855,8 @@ inline void write(const ::t4scene::T4Scene &in, wire::T4Scene &out, if (in.goal_poses_3d) { write(*in.goal_poses_3d, *out.mutable_goal_poses_3d()); } - if (in.route_start_poses_3d) { - write(*in.route_start_poses_3d, *out.mutable_route_start_poses_3d()); + if (in.start_poses_3d) { + write(*in.start_poses_3d, *out.mutable_start_poses_3d()); } if (in.map) { write(*in.map, *out.mutable_map(), resource_key); @@ -909,8 +909,8 @@ inline ::t4scene::T4Scene read(const wire::T4Scene &in) { if (in.has_goal_poses_3d()) { out.goal_poses_3d = read_array(in.goal_poses_3d()); } - if (in.has_route_start_poses_3d()) { - out.route_start_poses_3d = read_array(in.route_start_poses_3d()); + if (in.has_start_poses_3d()) { + out.start_poses_3d = read_array(in.start_poses_3d()); } if (in.has_map()) { out.map = read(in.map()); diff --git a/t4scene/cpp/include/t4_scene/requirements.hpp b/t4scene/cpp/include/t4_scene/requirements.hpp index 3eb8535..71de808 100644 --- a/t4scene/cpp/include/t4_scene/requirements.hpp +++ b/t4scene/cpp/include/t4_scene/requirements.hpp @@ -27,7 +27,7 @@ inline constexpr std::pair field_members[]{ {"cameras", present<&T4Scene::cameras>}, {"lidar", present<&T4Scene::lidar>}, {"goal", present<&T4Scene::goal_poses_3d>}, - {"route_start", present<&T4Scene::route_start_poses_3d>}, + {"start", present<&T4Scene::start_poses_3d>}, {"model_data", present<&T4Scene::model_data>}}; inline PresenceCheck find_field(std::string_view name) { for (const auto &[field, check] : field_members) { diff --git a/t4scene/cpp/include/t4_scene/scene_ops.hpp b/t4scene/cpp/include/t4_scene/scene_ops.hpp index f63815e..e1ebc9f 100644 --- a/t4scene/cpp/include/t4_scene/scene_ops.hpp +++ b/t4scene/cpp/include/t4_scene/scene_ops.hpp @@ -514,17 +514,16 @@ inline void T4Scene::validate() const { if (frame_indices) known(*frame_indices); check_column(goal_poses_3d, count, {4, 4}); - check_column(route_start_poses_3d, count, {4, 4}); + check_column(start_poses_3d, count, {4, 4}); normalized_tags(scene_metadata.tags); if (global_origin_3d) check_pose(global_origin_3d->data()); if (goal_poses_3d) for (std::size_t i = 0; i < count; ++i) check_pose(goal_poses_3d->data() + 16 * i, &*goal_poses_3d, 16 * i); - if (route_start_poses_3d) + if (start_poses_3d) for (std::size_t i = 0; i < count; ++i) - check_pose(route_start_poses_3d->data() + 16 * i, &*route_start_poses_3d, - 16 * i); + check_pose(start_poses_3d->data() + 16 * i, &*start_poses_3d, 16 * i); if (ego) { check_columns(*ego, count); if (ego->available) @@ -664,7 +663,7 @@ T4Scene::slice_time(std::size_t start, std::size_t stop, out.current_index = current_index - start; out.frame_indices = cut(frame_indices, start, count); out.goal_poses_3d = cut(goal_poses_3d, start, count); - out.route_start_poses_3d = cut(route_start_poses_3d, start, count); + out.start_poses_3d = cut(start_poses_3d, start, count); if (ego) out.ego = cut_columns(*ego, start, count); if (annotations) { @@ -736,7 +735,7 @@ inline T4Frame T4Scene::frame_at(std::size_t index) const { out.map = map; out.global_origin_3d = global_origin_3d; out.goal_pose_3d = row(goal_poses_3d, index); - out.route_start_pose_3d = row(route_start_poses_3d, index); + out.start_pose_3d = row(start_poses_3d, index); if (ego && (!ego->available || ego->available->at(index))) { out.ego_status.emplace(); auto &e = *out.ego_status; diff --git a/t4scene/cpp/include/t4_scene/scene_types.hpp b/t4scene/cpp/include/t4_scene/scene_types.hpp index 1d77f2a..e93a300 100644 --- a/t4scene/cpp/include/t4_scene/scene_types.hpp +++ b/t4scene/cpp/include/t4_scene/scene_types.hpp @@ -273,7 +273,7 @@ struct T4Scene { // float64 [T,4,4] goal-to-Scene transforms. std::optional> goal_poses_3d{}; // float64 [T,4,4] start-to-Scene transforms of the route each row follows. - std::optional> route_start_poses_3d{}; + std::optional> start_poses_3d{}; // One static map for the interval; no map bytes in a Scene. std::optional map{}; // Optional timestamped routes; IDs refer to the static Scene map. @@ -323,7 +323,7 @@ struct T4Frame { std::optional lidar; std::optional global_origin_3d; std::optional> goal_pose_3d; - std::optional> route_start_pose_3d; + std::optional> start_pose_3d; std::optional model_data; }; diff --git a/t4scene/cpp/tests/protobuf_test.cpp b/t4scene/cpp/tests/protobuf_test.cpp index 2509b9c..b83c248 100644 --- a/t4scene/cpp/tests/protobuf_test.cpp +++ b/t4scene/cpp/tests/protobuf_test.cpp @@ -78,11 +78,11 @@ void check_reanchor_roundtrip() { 0, 0, 1, 0.5, 0, 0, 0, 1}; std::vector starts(start.begin(), start.end()); starts.resize(32); - scene.route_start_poses_3d = + scene.start_poses_3d = Array::from_values(std::move(starts), {2, 4, 4}); std::vector start_mask(32, 0); std::fill_n(start_mask.begin() + 16, 16, 1); - scene.route_start_poses_3d->set_mask(std::move(start_mask)); + scene.start_poses_3d->set_mask(std::move(start_mask)); auto &ego = scene.ego.emplace(); const Transform3D ego_pose{1, 0, 0, x, 0, 1, 0, y + 1, @@ -135,12 +135,11 @@ void check_reanchor_roundtrip() { restored.ego->poses_3d->masked(11) && restored.ego->poses_3d->masked(15), "reanchored rigid transforms and their masks must survive Protobuf"); - const auto wire_start = restored.current_frame().route_start_pose_3d; - const auto local_start = local_frame.route_start_pose_3d; + const auto wire_start = restored.current_frame().start_pose_3d; + const auto local_start = local_frame.start_pose_3d; require(wire_start && wire_start->at(3) == local_start->at(3) && wire_start->at(7) == local_start->at(7) && - wire_start->at(11) == 0.5 && - !restored.frame_at(1).route_start_pose_3d, + wire_start->at(11) == 0.5 && !restored.frame_at(1).start_pose_3d, "a route start pose and its missing row must survive Protobuf"); const auto wire_covariance = restored.current_frame().ego_status->position_covariance_3d; diff --git a/t4scene/cpp/tests/records_test.cpp b/t4scene/cpp/tests/records_test.cpp index 7ee9bde..338d6d2 100644 --- a/t4scene/cpp/tests/records_test.cpp +++ b/t4scene/cpp/tests/records_test.cpp @@ -358,33 +358,33 @@ void position_covariances_are_symmetric_and_rotate_with_the_scene() { scene.validate(); } -void route_starts_are_rigid_transforms_or_missing() { +void start_poses_are_rigid_transforms_or_missing() { auto scene = make_scene(); const Transform3D start{0, -1, 0, 4, 1, 0, 0, 2, 0, 0, 1, 0.5, 0, 0, 0, 1}; std::vector starts(start.begin(), start.end()); starts.insert(starts.end(), start.begin(), start.end()); starts.resize(3 * start.size(), 0); - scene.route_start_poses_3d = + scene.start_poses_3d = Array::from_values(std::move(starts), {3, 4, 4}); - std::vector mask(scene.route_start_poses_3d->size(), 1); + std::vector mask(scene.start_poses_3d->size(), 1); std::fill_n(mask.begin(), 2 * start.size(), 0); - scene.route_start_poses_3d->set_mask(mask); + scene.start_poses_3d->set_mask(mask); scene.validate(); - SceneRequirements{{"route_start"}}.validate(scene); + SceneRequirements{{"start"}}.validate(scene); { - const auto current = scene.current_frame().route_start_pose_3d; + const auto current = scene.current_frame().start_pose_3d; check(current && current->at(3) == 4 && current->at(7) == 2, "frame retains its route start pose"); } - check(!scene.frame_at(2).route_start_pose_3d, + check(!scene.frame_at(2).start_pose_3d, "fully masked route start is unavailable"); - check(scene.slice_time(1, 3).route_start_poses_3d->shape() == + check(scene.slice_time(1, 3).start_poses_3d->shape() == std::vector{2, 4, 4}, "a slice keeps the route start rows of its interval"); // Seen from an anchor at the start, facing the same way, it is the origin. const auto local = - scene.reanchor(Pose2D{4, 2, std::acos(-1.) / 2}).route_start_poses_3d; + scene.reanchor(Pose2D{4, 2, std::acos(-1.) / 2}).start_poses_3d; auto close = [](double a, double b) { return std::abs(a - b) < 1e-15; }; check(close(local->at(3), 0) && close(local->at(7), 0) && close(local->at(0), 1) && close(local->at(1), 0) && @@ -392,11 +392,11 @@ void route_starts_are_rigid_transforms_or_missing() { "a route start moves with the Scene anchor and keeps its height"); check(local->masked(2 * 16), "a missing route start stays missing"); - scene.route_start_poses_3d->set(0, 0.7); + scene.start_poses_3d->set(0, 0.7); rejects([&] { scene.validate(); }); - scene.route_start_poses_3d.reset(); + scene.start_poses_3d.reset(); rejects( - [&] { SceneRequirements{{"route_start"}}.validate(scene); }); + [&] { SceneRequirements{{"start"}}.validate(scene); }); } } // namespace @@ -411,7 +411,7 @@ int main() { validation_distinguishes_invalid_missing_and_empty(); goals_are_rigid_transforms_or_missing(); position_covariances_are_symmetric_and_rotate_with_the_scene(); - route_starts_are_rigid_transforms_or_missing(); + start_poses_are_rigid_transforms_or_missing(); std::cout << "Native data ownership, selection and validation scenarios passed\n"; return 0; diff --git a/t4scene/proto/README.md b/t4scene/proto/README.md index d1fdd27..094b9d6 100644 --- a/t4scene/proto/README.md +++ b/t4scene/proto/README.md @@ -67,7 +67,7 @@ Frame access is derived from these columns. The optional Scene-to-world transform `global_origin_3d` stores a 3×3 rotation and a 3D translation. Each row of `goal_poses_3d` stores a 4×4 goal-to-Scene transform or is fully masked if the goal is unavailable. -`route_start_poses_3d` stores, in the same form, the pose the route of each row +`start_poses_3d` stores, in the same form, the pose the route of each row starts from. A flat source can encode either transform with translation `(x, y, 0)` and a rotation about the z axis. A planar map origin uses the `Pose2D` diff --git a/t4scene/proto/t4_scene.proto b/t4scene/proto/t4_scene.proto index ebb4810..57fb0e8 100644 --- a/t4scene/proto/t4_scene.proto +++ b/t4scene/proto/t4_scene.proto @@ -176,9 +176,7 @@ message T4Scene { CameraSequence cameras = 12; // Already-loaded pixels only; no implicit IO. LidarSequence lidar = 13; // Already-loaded arrays only; no implicit IO. ModelData model_data = 14; // Absent differs from a present empty dictionary. - // float64 [T,4,4] start-to-Scene transforms of the route each row follows; whole - // rows may be masked. - NumericArray route_start_poses_3d = 15; + NumericArray start_poses_3d = 15; // float64 [T,4,4] start-to-Scene transforms; whole rows may be masked. } // Registered separately, once per resource. SHA-256 covers the encoding, diff --git a/t4scene/python/README.md b/t4scene/python/README.md index 66530df..cca238d 100644 --- a/t4scene/python/README.md +++ b/t4scene/python/README.md @@ -81,10 +81,10 @@ transform. A missing goal returns `None`. For planar coordinates, [goal exchange example](tests/test_goal_poses_3d.py). The pose a route starts from is read the same way, from -`scene.route_start_pose_3d` or `scene.frame_at(i).route_start_pose_3d`. It tells a +`scene.start_pose_3d` or `scene.frame_at(i).start_pose_3d`. It tells a stop where the mission began from a stop along the route, which the route's lanes cannot: a mission can begin outside the first lane. See the -[route start example](tests/test_route_start_poses_3d.py). +[route start example](tests/test_start_poses_3d.py). ## Read how well the ego position is known @@ -121,9 +121,9 @@ inputs.validate(scene) ``` Both sets accept `ego`, `annotations`, `map`, `route`, `traffic_lights`, `cameras`, -`lidar`, `goal`, `route_start` and `model_data`. Required fields take precedence on +`lidar`, `goal`, `start` and `model_data`. Required fields take precedence on overlap. `route` checks `scene.routes`. `goal` checks `scene.goal_poses_3d` and -`route_start` checks `scene.route_start_poses_3d`. +`start` checks `scene.start_poses_3d`. The frame minima default to zero and exclude the current row. Missing required blocks or insufficient rows raise `ValueError`. A present block can contain masked values or empty observations. Consumers diff --git a/t4scene/python/t4scene/data/_coordinates.py b/t4scene/python/t4scene/data/_coordinates.py index bd17945..95a3b35 100644 --- a/t4scene/python/t4scene/data/_coordinates.py +++ b/t4scene/python/t4scene/data/_coordinates.py @@ -272,7 +272,7 @@ def reanchor(scene, origin, reanchor_model_data): ego=ego, annotations=annotations, goal_poses_3d=change.poses(scene.goal_poses_3d), - route_start_poses_3d=change.poses(scene.route_start_poses_3d), + start_poses_3d=change.poses(scene.start_poses_3d), global_origin_3d=registration, model_data=model_data, ) diff --git a/t4scene/python/t4scene/data/frame.py b/t4scene/python/t4scene/data/frame.py index c6b8b13..49997cc 100644 --- a/t4scene/python/t4scene/data/frame.py +++ b/t4scene/python/t4scene/data/frame.py @@ -36,7 +36,7 @@ class T4Frame: ) global_origin_3d: Array | None = None # [4,4]: Frame coordinates -> world goal_pose_3d: Array | None = None # [4,4]: goal coordinates -> Frame - route_start_pose_3d: Array | None = None # [4,4]: the route's start coordinates -> Frame + start_pose_3d: Array | None = None # [4,4]: the route's start coordinates -> Frame @validate_snapshot def validate(self) -> None: @@ -46,7 +46,7 @@ def validate(self) -> None: as_int64(self.timestamp_ns, "timestamp_ns") validate_transform(self.global_origin_3d, "global_origin_3d") validate_transform(self.goal_pose_3d, "goal_pose_3d") - validate_transform(self.route_start_pose_3d, "route_start_pose_3d") + validate_transform(self.start_pose_3d, "start_pose_3d") for value in ( self.ego_status, self.annotations, diff --git a/t4scene/python/t4scene/data/scene.py b/t4scene/python/t4scene/data/scene.py index 05fb6a9..8844ce6 100644 --- a/t4scene/python/t4scene/data/scene.py +++ b/t4scene/python/t4scene/data/scene.py @@ -84,7 +84,7 @@ class T4Scene: lidar: Sequence[Lidar | None] | None = None # [T] point clouds with their own reference times. global_origin_3d: Array | None = None # [4,4] Scene-to-world rigid transform, translation in m. goal_poses_3d: Array | None = None # [T,4,4]: goal-to-Scene transforms. - route_start_poses_3d: Array | None = ( + start_poses_3d: Array | None = ( None # [T,4,4]: start-to-Scene transforms of the route each row follows. ) model_data: ModelData | None = ( @@ -274,7 +274,7 @@ def cut(value): cameras=cut(self.cameras), lidar=cut(self.lidar), goal_poses_3d=cut(self.goal_poses_3d), - route_start_poses_3d=cut(self.route_start_poses_3d), + start_poses_3d=cut(self.start_poses_3d), ) def frame_at(self, index: int) -> T4Frame: @@ -293,7 +293,7 @@ def frame_at(self, index: int) -> T4Frame: lidar=None if self.lidar is None else self.lidar[index], global_origin_3d=self.global_origin_3d, goal_pose_3d=optional_row(self.goal_poses_3d, index), - route_start_pose_3d=optional_row(self.route_start_poses_3d, index), + start_pose_3d=optional_row(self.start_poses_3d, index), model_data=self.model_data if index == self.current_index else None, ) @@ -302,8 +302,8 @@ def goal_pose_3d(self) -> Array | None: return optional_row(self.goal_poses_3d, self.current_index) @property - def route_start_pose_3d(self) -> Array | None: - return optional_row(self.route_start_poses_3d, self.current_index) + def start_pose_3d(self) -> Array | None: + return optional_row(self.start_poses_3d, self.current_index) @property def route(self) -> RouteData | None: @@ -395,9 +395,7 @@ def sequence(name): lidar=sequence("lidar"), global_origin_3d=current.global_origin_3d, goal_poses_3d=stack_optional([frame.goal_pose_3d for frame in frames], (4, 4)), - route_start_poses_3d=stack_optional( - [frame.route_start_pose_3d for frame in frames], (4, 4) - ), + start_poses_3d=stack_optional([frame.start_pose_3d for frame in frames], (4, 4)), model_data=model_data if model_data is not None else current.model_data, ) @@ -419,8 +417,8 @@ def validate(self) -> None: validate_transform(self.global_origin_3d, "global_origin_3d") validate_shape(self.goal_poses_3d, (count, 4, 4), "goal_poses_3d") validate_transforms(self.goal_poses_3d, "goal_poses_3d") - validate_shape(self.route_start_poses_3d, (count, 4, 4), "route_start_poses_3d") - validate_transforms(self.route_start_poses_3d, "route_start_poses_3d") + validate_shape(self.start_poses_3d, (count, 4, 4), "start_poses_3d") + validate_transforms(self.start_poses_3d, "start_poses_3d") if self.ego is not None: self.ego.validate(count) if self.annotations is not None: diff --git a/t4scene/python/t4scene/protobuf/arrays.py b/t4scene/python/t4scene/protobuf/arrays.py index d801e78..b663ce1 100644 --- a/t4scene/python/t4scene/protobuf/arrays.py +++ b/t4scene/python/t4scene/protobuf/arrays.py @@ -74,7 +74,7 @@ def _spec(dtype, *shapes, allow_mask=True): "timestamps_ns": _spec(_I64, (None,), allow_mask=False), "frame_indices": _spec(_I64, (None,), allow_mask=False), "goal_poses_3d": _spec(_F64, (None, 4, 4)), - "route_start_poses_3d": _spec(_F64, (None, 4, 4)), + "start_poses_3d": _spec(_F64, (None, 4, 4)), }, "EgoSequence": { "velocities_3d": _spec(_F64, (None, 3)), diff --git a/t4scene/python/t4scene/requirements.py b/t4scene/python/t4scene/requirements.py index a1e3dac..6649de7 100644 --- a/t4scene/python/t4scene/requirements.py +++ b/t4scene/python/t4scene/requirements.py @@ -17,7 +17,7 @@ "cameras": "cameras", "lidar": "lidar", "goal": "goal_poses_3d", - "route_start": "route_start_poses_3d", + "start": "start_poses_3d", "model_data": "model_data", } diff --git a/t4scene/python/tests/test_route_start_poses_3d.py b/t4scene/python/tests/test_route_start_poses_3d.py deleted file mode 100644 index 5fc4d4d..0000000 --- a/t4scene/python/tests/test_route_start_poses_3d.py +++ /dev/null @@ -1,74 +0,0 @@ -import numpy as np -import pytest - -from t4scene import SceneMetadata, T4Frame, T4Scene -from t4scene.data.ego import planar_pose -from t4scene.requirements import SceneRequirements - - -def _start(): - start = np.eye(4) - start[:3, :3] = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] - start[:3, 3] = [1.0, 2.0, 0.5] - return start - - -def test_route_start_transforms_keep_missing_rows(): - poses = np.ma.array(np.stack((_start(), np.eye(4))), mask=False) - poses[1] = np.ma.masked - scene = T4Scene(SceneMetadata("starts"), np.array([0, 10]), 0, route_start_poses_3d=poses) - restored = T4Scene.from_proto(scene.to_proto()) - np.testing.assert_array_equal(restored.route_start_poses_3d.mask, poses.mask) - np.testing.assert_array_equal(restored.route_start_pose_3d, _start()) - np.testing.assert_allclose(planar_pose(restored.route_start_pose_3d), [1.0, 2.0, np.pi / 2]) - assert restored.frame_at(1).route_start_pose_3d is None - - -def test_route_start_follows_frames_slices_and_a_new_anchor(): - later = _start() - later[:3, 3] = [7.0, 8.0, 0.0] - scene = T4Scene.from_frames( - SceneMetadata("starts"), - [T4Frame(0, 10, route_start_pose_3d=_start())], - [T4Frame(1, 20), T4Frame(2, 30, route_start_pose_3d=later)], - ) - assert scene.frame_at(1).route_start_pose_3d is None - np.testing.assert_array_equal(scene.frame_at(2).route_start_pose_3d, later) - - cut = scene.slice_time(0, 2) - assert cut.route_start_poses_3d.shape == (2, 4, 4) - np.testing.assert_array_equal(cut.route_start_pose_3d, _start()) - - # A new anchor at (1, 2) turned a quarter left: the start is at its origin, facing ahead. - moved = scene.reanchor((1.0, 2.0, np.pi / 2)) - np.testing.assert_allclose(planar_pose(moved.route_start_pose_3d), [0.0, 0.0, 0.0], atol=1e-12) - assert moved.route_start_pose_3d[2, 3] == 0.5 # height is kept - assert np.ma.getmaskarray(moved.route_start_poses_3d)[1].all() - - -@pytest.mark.parametrize( - "pose", - [ - np.diag([np.nan, 1.0, 1.0, 1.0]), - np.diag([0.5, 1.0, 1.0, 1.0]), - np.diag([1.0, 1.0, 1.0, 0.0]), - np.ma.array(np.eye(4), mask=np.eye(4, dtype=bool)), - ], -) -def test_invalid_route_start_transforms_are_rejected_by_checked_codecs(pose): - scene = T4Scene(SceneMetadata("invalid"), np.array([0]), 0, route_start_poses_3d=pose[None]) - with pytest.raises(ValueError, match="route_start_poses_3d"): - scene.validate() - with pytest.raises(ValueError, match="route_start_poses_3d"): - scene.to_proto() - with pytest.raises(ValueError, match="route_start_poses_3d"): - T4Scene.from_proto(scene.to_proto(validate=False)) - - -def test_route_start_is_a_scene_requirement(): - scene = T4Scene(SceneMetadata("start"), np.array([10]), current_index=0) - req = SceneRequirements(fields={"route_start"}) - with pytest.raises(ValueError, match="missing Scene field: route_start"): - req.validate(scene) - scene.route_start_poses_3d = np.ma.masked_all((1, 4, 4)) - req.validate(scene) diff --git a/t4scene/python/tests/test_start_poses_3d.py b/t4scene/python/tests/test_start_poses_3d.py new file mode 100644 index 0000000..6e19041 --- /dev/null +++ b/t4scene/python/tests/test_start_poses_3d.py @@ -0,0 +1,74 @@ +import numpy as np +import pytest + +from t4scene import SceneMetadata, T4Frame, T4Scene +from t4scene.data.ego import planar_pose +from t4scene.requirements import SceneRequirements + + +def _start(): + start = np.eye(4) + start[:3, :3] = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] + start[:3, 3] = [1.0, 2.0, 0.5] + return start + + +def test_start_transforms_keep_missing_rows(): + poses = np.ma.array(np.stack((_start(), np.eye(4))), mask=False) + poses[1] = np.ma.masked + scene = T4Scene(SceneMetadata("starts"), np.array([0, 10]), 0, start_poses_3d=poses) + restored = T4Scene.from_proto(scene.to_proto()) + np.testing.assert_array_equal(restored.start_poses_3d.mask, poses.mask) + np.testing.assert_array_equal(restored.start_pose_3d, _start()) + np.testing.assert_allclose(planar_pose(restored.start_pose_3d), [1.0, 2.0, np.pi / 2]) + assert restored.frame_at(1).start_pose_3d is None + + +def test_start_follows_frames_slices_and_a_new_anchor(): + later = _start() + later[:3, 3] = [7.0, 8.0, 0.0] + scene = T4Scene.from_frames( + SceneMetadata("starts"), + [T4Frame(0, 10, start_pose_3d=_start())], + [T4Frame(1, 20), T4Frame(2, 30, start_pose_3d=later)], + ) + assert scene.frame_at(1).start_pose_3d is None + np.testing.assert_array_equal(scene.frame_at(2).start_pose_3d, later) + + cut = scene.slice_time(0, 2) + assert cut.start_poses_3d.shape == (2, 4, 4) + np.testing.assert_array_equal(cut.start_pose_3d, _start()) + + # A new anchor at (1, 2) turned a quarter left: the start is at its origin, facing ahead. + moved = scene.reanchor((1.0, 2.0, np.pi / 2)) + np.testing.assert_allclose(planar_pose(moved.start_pose_3d), [0.0, 0.0, 0.0], atol=1e-12) + assert moved.start_pose_3d[2, 3] == 0.5 # height is kept + assert np.ma.getmaskarray(moved.start_poses_3d)[1].all() + + +@pytest.mark.parametrize( + "pose", + [ + np.diag([np.nan, 1.0, 1.0, 1.0]), + np.diag([0.5, 1.0, 1.0, 1.0]), + np.diag([1.0, 1.0, 1.0, 0.0]), + np.ma.array(np.eye(4), mask=np.eye(4, dtype=bool)), + ], +) +def test_invalid_start_transforms_are_rejected_by_checked_codecs(pose): + scene = T4Scene(SceneMetadata("invalid"), np.array([0]), 0, start_poses_3d=pose[None]) + with pytest.raises(ValueError, match="start_poses_3d"): + scene.validate() + with pytest.raises(ValueError, match="start_poses_3d"): + scene.to_proto() + with pytest.raises(ValueError, match="start_poses_3d"): + T4Scene.from_proto(scene.to_proto(validate=False)) + + +def test_start_is_a_scene_requirement(): + scene = T4Scene(SceneMetadata("start"), np.array([10]), current_index=0) + req = SceneRequirements(fields={"start"}) + with pytest.raises(ValueError, match="missing Scene field: start"): + req.validate(scene) + scene.start_poses_3d = np.ma.masked_all((1, 4, 4)) + req.validate(scene) diff --git a/t4scene/tests/test_cpp_exchange.py b/t4scene/tests/test_cpp_exchange.py index 29b66ba..1998f41 100644 --- a/t4scene/tests/test_cpp_exchange.py +++ b/t4scene/tests/test_cpp_exchange.py @@ -57,8 +57,8 @@ def rich_scene(packed_scene): start = np.eye(4) start[:3, :3] = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] start[:3, 3] = (-5.0, 4.0, 0.5) - scene.route_start_poses_3d = np.ma.array(np.repeat(start[None], 5, axis=0), mask=False) - scene.route_start_poses_3d.mask[3] = True + scene.start_poses_3d = np.ma.array(np.repeat(start[None], 5, axis=0), mask=False) + scene.start_poses_3d.mask[3] = True # Elongated along x and correlated with y: changes under a rotation of the frame. covariance = np.array([[0.09, 0.02, 0.0], [0.02, 0.04, 0.0], [0.0, 0.0, 0.25]]) scene.ego.position_covariances_3d = np.ma.array( @@ -252,7 +252,7 @@ def test_reanchor_matches_python(cpp_exchange, rich_scene, tmp_path): (actual.ego.poses_3d, expected.ego.poses_3d), (actual.ego.velocities_3d, expected.ego.velocities_3d), (actual.goal_poses_3d, expected.goal_poses_3d), - (actual.route_start_poses_3d, expected.route_start_poses_3d), + (actual.start_poses_3d, expected.start_poses_3d), (actual.ego.position_covariances_3d, expected.ego.position_covariances_3d), ( actual.annotations.values.polygons.vertices, @@ -313,7 +313,7 @@ def test_both_decoders_reject_invalid_values(cpp_exchange, rich_scene, tmp_path, elif case == "goal": scene.goal_poses_3d = np.tile(np.diag([-1.0, 1.0, 1.0, 1.0]), (5, 1, 1)) elif case == "route-start": - scene.route_start_poses_3d = np.tile(np.diag([-1.0, 1.0, 1.0, 1.0]), (5, 1, 1)) + scene.start_poses_3d = np.tile(np.diag([-1.0, 1.0, 1.0, 1.0]), (5, 1, 1)) elif case == "ego": scene.ego.poses_3d[0, 0, 0] = 2 elif case == "covariance-asymmetric": From ef85c7c369089e319fa0b0f62420d131f8842cb2 Mon Sep 17 00:00:00 2001 From: Max-Bin Date: Wed, 2 Dec 2026 18:37:56 +0900 Subject: [PATCH 3/5] fix: one covariance rule in both SDKs and the generator; new fields come last - The position covariance is checked by one rule in Python, C++ and the ROS2 generator: finite; the mirrored differences have a norm of at most tau; the symmetric part plus tau*I has a Cholesky factor, tau = 1e-9 * (1 + |trace|). The answer does not depend on the Scene axes and holds for a weighted mean, so every covariance the generator keeps can be exported and reanchored. - A window with no available ego observation validates. - The new optional fields are the last members of EgoStatus, EgoSequence, T4Scene and T4Frame, so positional construction keeps its meaning. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 2 +- ros2/t4scene_generation/configs/README.md | 7 ++- ros2/t4scene_generation/cpp/src/generator.cpp | 22 +++------ .../cpp/tests/generator_test.cpp | 31 ++++++++++++ t4scene/cpp/include/t4_scene/scene_ops.hpp | 47 +++++++++++-------- t4scene/cpp/include/t4_scene/scene_types.hpp | 10 ++-- t4scene/cpp/tests/records_test.cpp | 20 ++++++++ t4scene/proto/README.md | 7 +++ t4scene/python/t4scene/data/ego.py | 46 +++++++++++++----- t4scene/python/t4scene/data/scene.py | 6 +-- .../python/tests/test_position_covariance.py | 18 +++++++ t4scene/tests/test_cpp_exchange.py | 37 +++++++++++++++ 12 files changed, 196 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ee803e..5cf16b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ compatibility. - A Scene can carry the covariance of the ego position and the pose a route starts from. `EgoSequence.position_covariances_3d` is `[T,3,3]` in Scene axes and m², and `T4Scene.start_poses_3d` is `[T,4,4]` like `goal_poses_3d`. - Both are optional, follow `slice_time()`, `frame_at()` and `reanchor()` in + Both are optional, come last in their records, follow `slice_time()`, `frame_at()` and `reanchor()` in Python and C++, and use new Protobuf field numbers, so existing Scenes read unchanged. `start` is a new consumer requirement name. The ROS2 generator fills both from `nav_msgs/Odometry.pose.covariance` and diff --git a/ros2/t4scene_generation/configs/README.md b/ros2/t4scene_generation/configs/README.md index 24e29bf..aa9f4f0 100644 --- a/ros2/t4scene_generation/configs/README.md +++ b/ros2/t4scene_generation/configs/README.md @@ -82,8 +82,11 @@ The position covariance is the upper-left 3×3 block of the odometry message's pose covariance, which is expressed in the Scene frame. A row interpolated between two messages takes the same weighted mean of their covariances as of their positions. The covariance of a message is unknown when the block is all -zero, not finite, not symmetric or not positive semidefinite; the pose of that -message is still used. A source that never reports one leaves the column out. +zero or fails the SDK's rule for a stored covariance (finite, symmetric and +positive semidefinite within its tolerance, see +[the wire format](../../../t4scene/proto/README.md)); the pose of that message +is still used, and every covariance the generator keeps can be exported. The +symmetric part of the block is stored. A source that never reports one leaves the column out. The start pose of a route is unknown when its orientation is not a unit quaternion; the route and its goal are still used. diff --git a/ros2/t4scene_generation/cpp/src/generator.cpp b/ros2/t4scene_generation/cpp/src/generator.cpp index 298d50d..0d71c9e 100644 --- a/ros2/t4scene_generation/cpp/src/generator.cpp +++ b/ros2/t4scene_generation/cpp/src/generator.cpp @@ -1,6 +1,5 @@ #include "config.hpp" #include "observations.hpp" -#include #include #include #include @@ -177,26 +176,19 @@ Grid window_grid(const Config &c, int64_t anchor) { size_t(history)}; } // The position block of a row-major 6x6 pose covariance, in the parent frame. -// Unknown when it is all zero (the usual way to publish "not estimated"), not -// finite, not symmetric or not positive semidefinite: a pose with an unusable -// covariance is still a pose. +// Unknown when it is all zero (the usual way to publish "not estimated") or +// fails the SDK's rule for a stored covariance (scene_detail::covariance_fault), +// so that every covariance taken here can be exported: the pose of a message +// with an unusable covariance is still a pose. std::optional read_position_covariance(const std::array &pose_covariance) { - Eigen::Matrix3d c; + Eigen::Matrix c; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) c(i, j) = pose_covariance[6 * i + j]; - if (!c.allFinite() || c.isZero(0)) + if (c.isZero(0) || scene_detail::covariance_fault(c.data())) return std::nullopt; - const double tolerance = 1e-9 * std::max(1., c.cwiseAbs().maxCoeff()); - if ((c - c.transpose()).cwiseAbs().maxCoeff() > tolerance) - return std::nullopt; - c = (0.5 * (c + c.transpose())).eval(); - if (Eigen::SelfAdjointEigenSolver(c, Eigen::EigenvaluesOnly) - .eigenvalues() - .minCoeff() < -tolerance) - return std::nullopt; - return c; + return Eigen::Matrix3d(0.5 * (c + c.transpose())); // its symmetric part } Motion read_motion(const nav_msgs::msg::Odometry &msg, const Config &config) { if (frame_name(msg.header.frame_id) != config.scene_frame || diff --git a/ros2/t4scene_generation/cpp/tests/generator_test.cpp b/ros2/t4scene_generation/cpp/tests/generator_test.cpp index b5476c1..4f894dd 100644 --- a/ros2/t4scene_generation/cpp/tests/generator_test.cpp +++ b/ros2/t4scene_generation/cpp/tests/generator_test.cpp @@ -87,6 +87,37 @@ void check_position_covariance_and_start_pose(const fs::path &configs) { single.ego->position_covariances_3d->at(4) == 0.04, "a converted odometry keeps its position covariance"); + { + // Close to singular, inside the SDK's tolerance: what the generator takes, + // the default export must accept, also blended between two messages. + SceneBuilder edge(configs / "range.yaml"); + auto nearly_singular = [](int64_t time, double x) { + auto msg = odom(time, x); + for (int i = 0; i < 3; ++i) + for (int j = 0; j < 3; ++j) + msg.pose.covariance[6 * i + j] = i == j ? 1 : -0.5000000004; + return msg; + }; + check(edge.ingest(nearly_singular(0, 0), 0), "odometry rejected"); + check(edge.ingest(located(150000000, 1.5, 0.18), 150000000), + "odometry rejected"); + check(edge.ingest(nearly_singular(300000000, 3), 300000000), + "odometry rejected"); + check(edge.ingest(route(0, 7), 0), "route rejected"); + const auto exported = edge.build_range({"covariance-edge"}); + exported.validate(); + check(!exported.ego->position_covariances_3d->masked(0), + "a covariance within the tolerance is kept"); + // Not positive semidefinite by 1e-5: no covariance, and still a pose. + auto indefinite = odom(0, 0); + indefinite.pose.covariance[1] = indefinite.pose.covariance[6] = 1e-5; + indefinite.pose.covariance[14] = 1; + const auto converted = builder.convert(indefinite); + check(!converted.ego->position_covariances_3d && + !converted.ego->poses_3d->masked(3), + "an indefinite covariance is dropped and its pose kept"); + } + // Rows at 0, 100, 200 and 300 ms from samples at 0, 150 and 300 ms. check(builder.ingest(located(0, 0, 0.09), 0), "odometry rejected"); check(builder.ingest(located(150000000, 1.5, 0.18), 150000000), diff --git a/t4scene/cpp/include/t4_scene/scene_ops.hpp b/t4scene/cpp/include/t4_scene/scene_ops.hpp index e1ebc9f..8bd0998 100644 --- a/t4scene/cpp/include/t4_scene/scene_ops.hpp +++ b/t4scene/cpp/include/t4_scene/scene_ops.hpp @@ -359,8 +359,31 @@ inline Annotations cut_annotations(const AnnotationSequence &sequence, count), std::nullopt}; } -// A [3,3] covariance: fully known or fully masked, finite, symmetric and -// positive semidefinite (every principal minor is nonnegative). +// Why a row-major [3,3] position covariance is unusable, or nullptr. The one +// rule of both SDKs and the ROS2 generator. With tau = 1e-9 * (1 + |trace C|), +// C is symmetric when the differences of its three pairs of mirrored entries +// have a Euclidean norm of at most tau, and positive semidefinite when its +// symmetric part plus tau*I has a Cholesky factor: every eigenvalue is then +// above -tau. Neither answer depends on the Scene axes, and a weighted mean of +// two valid covariances is valid. +inline const char *covariance_fault(const double *c) { + for (unsigned i = 0; i < 9; ++i) + if (!std::isfinite(c[i])) + return "position covariance must be finite"; + const double tau = 1e-9 * (1 + std::abs(c[0] + c[4] + c[8])); + const double a = c[1] - c[3], b = c[2] - c[6], e = c[5] - c[7]; + if (std::sqrt(a * a + b * b + e * e) > tau) + return "position covariance must be symmetric"; + const double xy = 0.5 * (c[1] + c[3]), xz = 0.5 * (c[2] + c[6]), + yz = 0.5 * (c[5] + c[7]); + const double d0 = c[0] + tau, l10 = xy / d0, l20 = xz / d0; + const double d1 = c[4] + tau - l10 * xy, l21 = (yz - l20 * xy) / d1; + const double d2 = c[8] + tau - l20 * xz - l21 * l21 * d1; + if (!(d0 > 0 && d1 > 0 && d2 > 0)) + return "position covariance must be positive semidefinite"; + return nullptr; +} +// A [3,3] covariance row: fully known or fully masked, and usable. inline void check_covariance(const double *c, const Array &column, std::size_t offset) { unsigned known = 0; @@ -370,24 +393,8 @@ inline void check_covariance(const double *c, const Array &column, "position covariance must be fully known or fully masked"); if (!known) return; - double scale = 1; - for (unsigned i = 0; i < 9; ++i) { - require(std::isfinite(c[i]), "position covariance must be finite"); - scale = std::max(scale, std::abs(c[i])); - } - const double tolerance = 1e-9 * scale; - for (unsigned i = 0; i < 3; ++i) - for (unsigned j = i + 1; j < 3; ++j) - require(std::abs(c[3 * i + j] - c[3 * j + i]) <= tolerance, - "position covariance must be symmetric"); - const double xy = c[0] * c[4] - c[1] * c[1], xz = c[0] * c[8] - c[2] * c[2], - yz = c[4] * c[8] - c[5] * c[5]; - const double det = c[0] * yz - c[1] * (c[1] * c[8] - c[5] * c[2]) + - c[2] * (c[1] * c[5] - c[4] * c[2]); - require(c[0] >= -tolerance && c[4] >= -tolerance && c[8] >= -tolerance && - xy >= -tolerance * scale && xz >= -tolerance * scale && - yz >= -tolerance * scale && det >= -tolerance * scale * scale, - "position covariance must be positive semidefinite"); + const char *fault = covariance_fault(c); + require(!fault, fault ? fault : ""); } inline void check_pose(const double *m, const Array *column = nullptr, std::size_t offset = 0, bool ego = false) { diff --git a/t4scene/cpp/include/t4_scene/scene_types.hpp b/t4scene/cpp/include/t4_scene/scene_types.hpp index e93a300..a0b3b0a 100644 --- a/t4scene/cpp/include/t4_scene/scene_types.hpp +++ b/t4scene/cpp/include/t4_scene/scene_types.hpp @@ -272,8 +272,6 @@ struct T4Scene { std::optional global_origin_3d{}; // float64 [T,4,4] goal-to-Scene transforms. std::optional> goal_poses_3d{}; - // float64 [T,4,4] start-to-Scene transforms of the route each row follows. - std::optional> start_poses_3d{}; // One static map for the interval; no map bytes in a Scene. std::optional map{}; // Optional timestamped routes; IDs refer to the static Scene map. @@ -285,6 +283,8 @@ struct T4Scene { std::optional>> lidar{}; // Absent differs from a present empty dictionary. std::optional model_data{}; + // float64 [T,4,4] start-to-Scene transforms of the route each row follows. + std::optional> start_poses_3d{}; std::size_t size() const { return timestamps_ns.size(); } void validate() const; @@ -304,12 +304,14 @@ struct T4Scene { // originating Scene. Per-frame ego arrays remove the leading time dimension. struct EgoStatus { std::optional> ego_pose_3d, ego_velocity_3d, - ego_acceleration_3d, angular_velocity_3d, position_covariance_3d; + ego_acceleration_3d, angular_velocity_3d; std::optional tire_steering_angle, steering_wheel_angle; std::optional turn_indicator, odometry_timestamp_ns, acceleration_timestamp_ns, tire_steering_timestamp_ns, steering_wheel_timestamp_ns, turn_indicator_timestamp_ns; std::optional ego_shape; + // float64 [3,3], covariance of the ego position in Scene axes, m^2. + std::optional> position_covariance_3d; }; struct T4Frame { int64_t timestamp_ns = 0; @@ -323,8 +325,8 @@ struct T4Frame { std::optional lidar; std::optional global_origin_3d; std::optional> goal_pose_3d; - std::optional> start_pose_3d; std::optional model_data; + std::optional> start_pose_3d; }; } // namespace t4scene diff --git a/t4scene/cpp/tests/records_test.cpp b/t4scene/cpp/tests/records_test.cpp index 338d6d2..4f043c1 100644 --- a/t4scene/cpp/tests/records_test.cpp +++ b/t4scene/cpp/tests/records_test.cpp @@ -350,6 +350,26 @@ void position_covariances_are_symmetric_and_rotate_with_the_scene() { 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1}, {3, 3, 3}); rejects([&] { scene.validate(); }); + // The rule's tolerance is on the smallest eigenvalue, 1e-9 * (1 + trace), + // as in the Python SDK: -8e-10 passes, -1e-5 beside a unit variance fails. + auto with_first = [&](std::vector first) { + first.insert(first.end(), {1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1}); + auto edited = scene; + edited.ego->position_covariances_3d = + Array::from_values(std::move(first), {3, 3, 3}); + return edited; + }; + const double off = -0.5000000004; + with_first({1, off, off, off, 1, off, off, off, 1}).validate(); + rejects( + [&] { with_first({0, 1e-5, 0, 1e-5, 0, 0, 0, 0, 1}).validate(); }); + { + // Fields added later come last: aggregates written before still compile. + EgoStatus status{{}, {}, {}, {}, 0.25}; + check(status.tire_steering_angle == 0.25 && + !status.position_covariance_3d, + "positional ego status fields keep their meaning"); + } // No uncertainty across one axis is still one. scene.ego->position_covariances_3d = Array::from_values({0.09, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, diff --git a/t4scene/proto/README.md b/t4scene/proto/README.md index 094b9d6..8c277ea 100644 --- a/t4scene/proto/README.md +++ b/t4scene/proto/README.md @@ -95,6 +95,13 @@ is fully known or fully masked. Under a change of Scene axes by a rotation `R` it becomes `R C Rᵀ`. It covers the position only: the orientation part of a source's pose covariance is not stored. +Both SDKs and the ROS2 generator apply one rule to a known row, with +`τ = 1e-9 · (1 + |trace C|)`. The entries are finite. `C` is symmetric: the +differences of its three pairs of mirrored entries have a Euclidean norm of at +most `τ`. `C` is positive semidefinite: its symmetric part plus `τ I` has a +Cholesky factor, so every eigenvalue is above `-τ`. The answer does not depend +on the Scene axes, and a weighted mean of two valid covariances is valid. + Vehicle-axis angular properties and vehicle-z yaw rate are projections of canonical storage. Tilted poses can require more than one known motion axis; projection masks follow those dependencies. Acceleration projection requires diff --git a/t4scene/python/t4scene/data/ego.py b/t4scene/python/t4scene/data/ego.py index 5b631b9..cc125dc 100644 --- a/t4scene/python/t4scene/data/ego.py +++ b/t4scene/python/t4scene/data/ego.py @@ -86,9 +86,6 @@ class EgoStatus: ego_velocity_3d: Array | None = None # [3], Scene vx/vy/vz, m/s. ego_acceleration_3d: Array | None = None # [3], Scene ax/ay/az, m/s². angular_velocity_3d: Array | None = None # [3], Scene angular velocity, rad/s. - position_covariance_3d: Array | None = ( - None # [3,3], covariance of the ego position in Scene axes, m². - ) tire_steering_angle: float | None = None # road-wheel angle, rad. steering_wheel_angle: float | None = None # steering-wheel angle, rad. turn_indicator: TurnIndicator | None = None # public indicator value. @@ -98,6 +95,9 @@ class EgoStatus: steering_wheel_timestamp_ns: int | None = None # measurement/alignment reference time, ns. turn_indicator_timestamp_ns: int | None = None # measurement/alignment reference time, ns. ego_shape: EgoShape | None = None + position_covariance_3d: Array | None = ( + None # [3,3], covariance of the ego position in Scene axes, m². + ) @classmethod def from_planar( @@ -171,9 +171,6 @@ class EgoSequence: velocities_3d: Array | None = None # [T,3], Scene vx/vy/vz, m/s. accelerations_3d: Array | None = None # [T,3], Scene ax/ay/az, m/s². angular_velocities_3d: Array | None = None # [T,3], Scene angular velocity, rad/s. - position_covariances_3d: Array | None = ( - None # [T,3,3], covariance of the ego position in Scene axes, m². - ) tire_steering_angles: Array | None = None # [T], road-wheel angle, rad. steering_wheel_angles: Array | None = None # [T], steering-wheel angle, rad. turn_indicators: Array | None = None # [T], public indicator value. @@ -192,6 +189,9 @@ class EgoSequence: ) shape: EgoShape | None = None available: Array | None = None # bool [T], whether each observation is present. + position_covariances_3d: Array | None = ( + None # [T,3,3], covariance of the ego position in Scene axes, m². + ) @classmethod def from_planar(cls, poses=None, velocities=None, accelerations=None, shape=None, **kwargs): @@ -421,19 +421,41 @@ def _validate_poses(value): raise ValueError("ego_pose_3d must have rigid homogeneous bottom row") +def covariance_faults(covariances): + """Why each ``[..., 3, 3]`` position covariance is unusable: ``(asymmetric, indefinite)``. + + The one rule of both SDKs and the ROS2 generator, for finite matrices. With + ``tau = 1e-9 * (1 + |trace C|)``, ``C`` is symmetric when the differences of its + three pairs of mirrored entries have a Euclidean norm of at most ``tau``, and + positive semidefinite when its symmetric part plus ``tau I`` has a Cholesky factor: + every eigenvalue is then above ``-tau``. Neither answer depends on the Scene axes, + and a weighted mean of two valid covariances is valid. + """ + c = np.asarray(covariances, dtype=np.float64).reshape(-1, 9).T + tau = 1e-9 * (1.0 + np.abs(c[0] + c[4] + c[8])) + asymmetric = np.sqrt((c[1] - c[3]) ** 2 + (c[2] - c[6]) ** 2 + (c[5] - c[7]) ** 2) > tau + xy, xz, yz = 0.5 * (c[1] + c[3]), 0.5 * (c[2] + c[6]), 0.5 * (c[5] + c[7]) + with np.errstate(divide="ignore", invalid="ignore"): + d0 = c[0] + tau + l10, l20 = xy / d0, xz / d0 + d1 = c[4] + tau - l10 * xy + l21 = (yz - l20 * xy) / d1 + d2 = c[8] + tau - l20 * xz - l21 * l21 * d1 + return asymmetric, ~((d0 > 0) & (d1 > 0) & (d2 > 0)) + + def _validate_covariances(value): values = np.ma.asarray(value) - masks = np.ma.getmaskarray(values).reshape(len(values), -1) + masks = np.ma.getmaskarray(values).reshape(len(values), 9) if (masks.any(axis=1) & ~masks.all(axis=1)).any(): raise ValueError("position_covariance_3d must be fully known or fully masked") - known = np.asarray(values.data[~masks.any(axis=1)], dtype=np.float64) + known = np.asarray(values.data, dtype=np.float64).reshape(len(values), 9)[~masks.any(axis=1)] if not np.isfinite(known).all(): raise ValueError("position_covariance_3d must be finite") - scale = np.abs(known).max(axis=(-2, -1), keepdims=True, initial=0.0) - tolerance = 1e-9 * np.maximum(scale, 1.0) - if (np.abs(known - known.swapaxes(-1, -2)) > tolerance).any(): + asymmetric, indefinite = covariance_faults(known) + if asymmetric.any(): raise ValueError("position_covariance_3d must be symmetric") - if len(known) and (np.linalg.eigvalsh(known) < -tolerance[..., 0]).any(): + if indefinite.any(): raise ValueError("position_covariance_3d must be positive semidefinite") diff --git a/t4scene/python/t4scene/data/scene.py b/t4scene/python/t4scene/data/scene.py index 8844ce6..3ea5b4d 100644 --- a/t4scene/python/t4scene/data/scene.py +++ b/t4scene/python/t4scene/data/scene.py @@ -84,12 +84,12 @@ class T4Scene: lidar: Sequence[Lidar | None] | None = None # [T] point clouds with their own reference times. global_origin_3d: Array | None = None # [4,4] Scene-to-world rigid transform, translation in m. goal_poses_3d: Array | None = None # [T,4,4]: goal-to-Scene transforms. - start_poses_3d: Array | None = ( - None # [T,4,4]: start-to-Scene transforms of the route each row follows. - ) model_data: ModelData | None = ( None # Optional current-window source payload; not generic evaluator input. ) + start_poses_3d: Array | None = ( + None # [T,4,4]: start-to-Scene transforms of the route each row follows. + ) def __post_init__(self) -> None: validate_current_index(self.current_index, len(self.timestamps_ns)) diff --git a/t4scene/python/tests/test_position_covariance.py b/t4scene/python/tests/test_position_covariance.py index a86602a..3e9bc52 100644 --- a/t4scene/python/tests/test_position_covariance.py +++ b/t4scene/python/tests/test_position_covariance.py @@ -94,3 +94,21 @@ def test_tensor_covariances_rotate_and_keep_their_gradient(): np.testing.assert_allclose( moved[0].detach().numpy(), to_new @ COVARIANCE @ to_new.T, atol=1e-15 ) + + +def test_a_window_without_an_ego_observation_stays_readable(): + sequence = EgoSequence.from_statuses([None, EgoStatus(position_covariance_3d=np.eye(3))]) + scene = T4Scene(SceneMetadata("covariance"), np.array([0, 10]), 0, ego=sequence) + scene.validate() + scene.slice_time(0, 1).validate() + window = T4Scene.from_proto(scene.to_proto(), rows=(0, 1)) + assert window.ego.at(0) is None + + +def test_the_covariance_is_the_last_field_of_the_ego_records(): + # Positional arguments of the earlier fields keep their meaning. + assert EgoStatus(None, None, None, None, 0.25).tire_steering_angle == 0.25 + assert EgoSequence(None, None, None, None, np.zeros(2)).tire_steering_angles is not None + for record in (EgoStatus, EgoSequence): + assert list(record.__dataclass_fields__)[-1].startswith("position_covariance") + assert list(T4Scene.__dataclass_fields__)[-1] == "start_poses_3d" diff --git a/t4scene/tests/test_cpp_exchange.py b/t4scene/tests/test_cpp_exchange.py index 1998f41..d7a1f9d 100644 --- a/t4scene/tests/test_cpp_exchange.py +++ b/t4scene/tests/test_cpp_exchange.py @@ -359,6 +359,43 @@ def test_both_decoders_reject_invalid_values(cpp_exchange, rich_scene, tmp_path, assert result.returncode != 0, case +# Each SDK must give the other's answer close to the limit of the covariance rule: its +# tolerance is 1e-9 * (1 + trace), on the smallest eigenvalue. +_NEARLY_SINGULAR = np.full((3, 3), -0.5000000004) + 1.5000000004 * np.eye(3) # -8e-10 +_SLIGHTLY_INDEFINITE = np.array([[0.0, 1e-5, 0.0], [1e-5, 0.0, 0.0], [0.0, 0.0, 1.0]]) # -1e-5 + + +@pytest.mark.parametrize( + ("covariance", "valid"), + [ + (_NEARLY_SINGULAR, True), + (_SLIGHTLY_INDEFINITE, False), + (np.diag([1e-12, 1e-12, 1e6]), True), + (np.diag([1.0, 1.0, -1e-8]), False), + # Mirrored entries 2e-9 and 3e-9 apart: a norm of 3.5e-9 and 5.2e-9, around 4e-9. + (np.eye(3) + 2e-9 * np.triu(np.ones((3, 3)), 1), True), + (np.eye(3) + 3e-9 * np.triu(np.ones((3, 3)), 1), False), + ], +) +def test_both_sdks_apply_one_covariance_rule(cpp_exchange, rich_scene, tmp_path, covariance, valid): + rich_scene.ego.position_covariances_3d[0] = covariance + wire = rich_scene.to_proto(validate=False) + source = tmp_path / "in" + source.write_bytes(wire.SerializeToString()) + result = subprocess.run([cpp_exchange, source, tmp_path / "out"], capture_output=True) + if valid: + T4Scene.from_proto(wire) + # The rule holds in any Scene axes, so a reanchored window stays readable. + turned = T4Scene.from_proto(wire).reanchor( + (1.0, 2.0, 0.6), reanchor_model_data=lambda _, m: {"old_to_new": m} + ) + turned.validate() + else: + with pytest.raises(ValueError): + T4Scene.from_proto(wire) + assert (result.returncode == 0) == valid, result.stderr + + def test_existing_wire_heading_round_trips_through_both_sdks(cpp_exchange, rich_scene, tmp_path): wire = rich_scene.to_proto() pose = wire.map.global_origin From 06893dc6fb631abd182f6f6816ab4e396c970603 Mon Sep 17 00:00:00 2001 From: Max-Bin Date: Wed, 2 Dec 2026 19:00:47 +0900 Subject: [PATCH 4/5] fix: float32 covariances stay valid under reanchor; defaults for appended members - reanchor() returns the symmetric part of R C R^T, and the covariance rule's tolerance is that of the pose checks, 1e-6 * (1 + |trace|), in both SDKs and the generator: a float32 covariance stays serializable through chained reanchors, with its tensor dtype, device and gradient. - The appended members of the C++ EgoStatus and T4Frame have default initializers, so a positional initializer of the earlier members is complete. Co-Authored-By: Claude Fable 5.2 --- .../cpp/tests/generator_test.cpp | 2 +- t4scene/cpp/include/t4_scene/scene_ops.hpp | 7 ++++--- t4scene/cpp/include/t4_scene/scene_types.hpp | 4 ++-- t4scene/cpp/tests/records_test.cpp | 16 ++++++++------ t4scene/proto/README.md | 6 ++++-- t4scene/python/t4scene/data/_coordinates.py | 5 ++++- t4scene/python/t4scene/data/ego.py | 7 ++++--- .../python/tests/test_position_covariance.py | 21 +++++++++++++++++++ t4scene/tests/test_cpp_exchange.py | 13 ++++++------ 9 files changed, 57 insertions(+), 24 deletions(-) diff --git a/ros2/t4scene_generation/cpp/tests/generator_test.cpp b/ros2/t4scene_generation/cpp/tests/generator_test.cpp index 4f894dd..5c243d8 100644 --- a/ros2/t4scene_generation/cpp/tests/generator_test.cpp +++ b/ros2/t4scene_generation/cpp/tests/generator_test.cpp @@ -95,7 +95,7 @@ void check_position_covariance_and_start_pose(const fs::path &configs) { auto msg = odom(time, x); for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) - msg.pose.covariance[6 * i + j] = i == j ? 1 : -0.5000000004; + msg.pose.covariance[6 * i + j] = i == j ? 1 : -0.5000004; return msg; }; check(edge.ingest(nearly_singular(0, 0), 0), "odometry rejected"); diff --git a/t4scene/cpp/include/t4_scene/scene_ops.hpp b/t4scene/cpp/include/t4_scene/scene_ops.hpp index 8bd0998..5bd26f7 100644 --- a/t4scene/cpp/include/t4_scene/scene_ops.hpp +++ b/t4scene/cpp/include/t4_scene/scene_ops.hpp @@ -360,17 +360,18 @@ inline Annotations cut_annotations(const AnnotationSequence &sequence, std::nullopt}; } // Why a row-major [3,3] position covariance is unusable, or nullptr. The one -// rule of both SDKs and the ROS2 generator. With tau = 1e-9 * (1 + |trace C|), +// rule of both SDKs and the ROS2 generator. With tau = 1e-6 * (1 + |trace C|), // C is symmetric when the differences of its three pairs of mirrored entries // have a Euclidean norm of at most tau, and positive semidefinite when its // symmetric part plus tau*I has a Cholesky factor: every eigenvalue is then // above -tau. Neither answer depends on the Scene axes, and a weighted mean of -// two valid covariances is valid. +// two valid covariances is valid. tau is the tolerance of the pose checks: +// wide enough for a covariance kept and rotated in float32. inline const char *covariance_fault(const double *c) { for (unsigned i = 0; i < 9; ++i) if (!std::isfinite(c[i])) return "position covariance must be finite"; - const double tau = 1e-9 * (1 + std::abs(c[0] + c[4] + c[8])); + const double tau = 1e-6 * (1 + std::abs(c[0] + c[4] + c[8])); const double a = c[1] - c[3], b = c[2] - c[6], e = c[5] - c[7]; if (std::sqrt(a * a + b * b + e * e) > tau) return "position covariance must be symmetric"; diff --git a/t4scene/cpp/include/t4_scene/scene_types.hpp b/t4scene/cpp/include/t4_scene/scene_types.hpp index a0b3b0a..47d330d 100644 --- a/t4scene/cpp/include/t4_scene/scene_types.hpp +++ b/t4scene/cpp/include/t4_scene/scene_types.hpp @@ -311,7 +311,7 @@ struct EgoStatus { steering_wheel_timestamp_ns, turn_indicator_timestamp_ns; std::optional ego_shape; // float64 [3,3], covariance of the ego position in Scene axes, m^2. - std::optional> position_covariance_3d; + std::optional> position_covariance_3d{}; }; struct T4Frame { int64_t timestamp_ns = 0; @@ -326,7 +326,7 @@ struct T4Frame { std::optional global_origin_3d; std::optional> goal_pose_3d; std::optional model_data; - std::optional> start_pose_3d; + std::optional> start_pose_3d{}; }; } // namespace t4scene diff --git a/t4scene/cpp/tests/records_test.cpp b/t4scene/cpp/tests/records_test.cpp index 4f043c1..00487f9 100644 --- a/t4scene/cpp/tests/records_test.cpp +++ b/t4scene/cpp/tests/records_test.cpp @@ -350,8 +350,8 @@ void position_covariances_are_symmetric_and_rotate_with_the_scene() { 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1}, {3, 3, 3}); rejects([&] { scene.validate(); }); - // The rule's tolerance is on the smallest eigenvalue, 1e-9 * (1 + trace), - // as in the Python SDK: -8e-10 passes, -1e-5 beside a unit variance fails. + // The rule's tolerance is on the smallest eigenvalue, 1e-6 * (1 + trace), + // as in the Python SDK: -8e-7 passes, -1e-5 beside a unit variance fails. auto with_first = [&](std::vector first) { first.insert(first.end(), {1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1}); auto edited = scene; @@ -359,16 +359,20 @@ void position_covariances_are_symmetric_and_rotate_with_the_scene() { Array::from_values(std::move(first), {3, 3, 3}); return edited; }; - const double off = -0.5000000004; + const double off = -0.5000004; with_first({1, off, off, off, 1, off, off, off, 1}).validate(); rejects( [&] { with_first({0, 1e-5, 0, 1e-5, 0, 0, 0, 0, 1}).validate(); }); { // Fields added later come last: aggregates written before still compile. - EgoStatus status{{}, {}, {}, {}, 0.25}; + // Naming every earlier member is complete under + // -Werror=missing-field-initializers: the new ones have defaults. + EgoStatus status{{}, {}, {}, {}, 0.25, {}, {}, {}, {}, {}, {}, {}, {}}; + T4Frame frame{7, 0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; check(status.tire_steering_angle == 0.25 && - !status.position_covariance_3d, - "positional ego status fields keep their meaning"); + !status.position_covariance_3d && frame.timestamp_ns == 7 && + !frame.start_pose_3d, + "positional fields keep their meaning"); } // No uncertainty across one axis is still one. scene.ego->position_covariances_3d = diff --git a/t4scene/proto/README.md b/t4scene/proto/README.md index 8c277ea..1f5b994 100644 --- a/t4scene/proto/README.md +++ b/t4scene/proto/README.md @@ -96,11 +96,13 @@ it becomes `R C Rᵀ`. It covers the position only: the orientation part of a source's pose covariance is not stored. Both SDKs and the ROS2 generator apply one rule to a known row, with -`τ = 1e-9 · (1 + |trace C|)`. The entries are finite. `C` is symmetric: the +`τ = 1e-6 · (1 + |trace C|)`. The entries are finite. `C` is symmetric: the differences of its three pairs of mirrored entries have a Euclidean norm of at most `τ`. `C` is positive semidefinite: its symmetric part plus `τ I` has a Cholesky factor, so every eigenvalue is above `-τ`. The answer does not depend -on the Scene axes, and a weighted mean of two valid covariances is valid. +on the Scene axes, and a weighted mean of two valid covariances is valid. `τ` +is the tolerance of the pose checks, wide enough for a covariance kept and +rotated in float32; `reanchor()` returns the symmetric part of `R C Rᵀ`. Vehicle-axis angular properties and vehicle-z yaw rate are projections of canonical storage. Tilted poses can require more than one known motion axis; diff --git a/t4scene/python/t4scene/data/_coordinates.py b/t4scene/python/t4scene/data/_coordinates.py index 95a3b35..0cc6a8a 100644 --- a/t4scene/python/t4scene/data/_coordinates.py +++ b/t4scene/python/t4scene/data/_coordinates.py @@ -203,7 +203,10 @@ def covariances(self, values): return None values, rotation = self.local_pair(values, self.to_old[:3, :3].T) columns = rotate_components(values.swapaxes(-1, -2), rotation).swapaxes(-1, -2) - return rotate_components(columns, rotation) + moved = rotate_components(columns, rotation) + # The two rotations round differently, in float32 by more than a checked + # codec allows between mirrored entries: keep the symmetric part. + return 0.5 * (moved + moved.swapaxes(-1, -2)) def registration(self, values): if values is None: diff --git a/t4scene/python/t4scene/data/ego.py b/t4scene/python/t4scene/data/ego.py index cc125dc..f0fc5c4 100644 --- a/t4scene/python/t4scene/data/ego.py +++ b/t4scene/python/t4scene/data/ego.py @@ -425,14 +425,15 @@ def covariance_faults(covariances): """Why each ``[..., 3, 3]`` position covariance is unusable: ``(asymmetric, indefinite)``. The one rule of both SDKs and the ROS2 generator, for finite matrices. With - ``tau = 1e-9 * (1 + |trace C|)``, ``C`` is symmetric when the differences of its + ``tau = 1e-6 * (1 + |trace C|)``, ``C`` is symmetric when the differences of its three pairs of mirrored entries have a Euclidean norm of at most ``tau``, and positive semidefinite when its symmetric part plus ``tau I`` has a Cholesky factor: every eigenvalue is then above ``-tau``. Neither answer depends on the Scene axes, - and a weighted mean of two valid covariances is valid. + and a weighted mean of two valid covariances is valid. ``tau`` is the tolerance of + the pose checks: wide enough for a covariance kept and rotated in float32. """ c = np.asarray(covariances, dtype=np.float64).reshape(-1, 9).T - tau = 1e-9 * (1.0 + np.abs(c[0] + c[4] + c[8])) + tau = 1e-6 * (1.0 + np.abs(c[0] + c[4] + c[8])) asymmetric = np.sqrt((c[1] - c[3]) ** 2 + (c[2] - c[6]) ** 2 + (c[5] - c[7]) ** 2) > tau xy, xz, yz = 0.5 * (c[1] + c[3]), 0.5 * (c[2] + c[6]), 0.5 * (c[5] + c[7]) with np.errstate(divide="ignore", invalid="ignore"): diff --git a/t4scene/python/tests/test_position_covariance.py b/t4scene/python/tests/test_position_covariance.py index 3e9bc52..66f50f4 100644 --- a/t4scene/python/tests/test_position_covariance.py +++ b/t4scene/python/tests/test_position_covariance.py @@ -112,3 +112,24 @@ def test_the_covariance_is_the_last_field_of_the_ego_records(): for record in (EgoStatus, EgoSequence): assert list(record.__dataclass_fields__)[-1].startswith("position_covariance") assert list(T4Scene.__dataclass_fields__)[-1] == "start_poses_3d" + + +@pytest.mark.parametrize( + "covariance", + [ + np.diag([1.0, 0.0, 1.0]), # rank deficient: roundoff reaches the smallest eigenvalue + np.array([[1.0, 0.2, 0.1], [0.2, 1.0, 0.3], [0.1, 0.3, 1.0]]), + ], +) +def test_float32_covariances_stay_serializable_under_new_anchors(covariance): + torch = pytest.importorskip("torch") + covariances = torch.tensor(np.stack((covariance, covariance)), dtype=torch.float32) + scene = _scene(covariances.requires_grad_()) + T4Scene.from_proto(scene.to_proto()) + for step in range(20): + scene = scene.reanchor((0.3 * step, -0.1, 0.1 + 0.5 * step)) + moved = scene.ego.position_covariances_3d + assert torch.is_tensor(moved) and moved.dtype == torch.float32 and moved.requires_grad + assert moved.device == covariances.device + assert torch.equal(moved, moved.swapaxes(-1, -2)) + T4Scene.from_proto(scene.to_proto()) diff --git a/t4scene/tests/test_cpp_exchange.py b/t4scene/tests/test_cpp_exchange.py index d7a1f9d..3f09e23 100644 --- a/t4scene/tests/test_cpp_exchange.py +++ b/t4scene/tests/test_cpp_exchange.py @@ -360,8 +360,8 @@ def test_both_decoders_reject_invalid_values(cpp_exchange, rich_scene, tmp_path, # Each SDK must give the other's answer close to the limit of the covariance rule: its -# tolerance is 1e-9 * (1 + trace), on the smallest eigenvalue. -_NEARLY_SINGULAR = np.full((3, 3), -0.5000000004) + 1.5000000004 * np.eye(3) # -8e-10 +# tolerance is 1e-6 * (1 + trace), on the smallest eigenvalue. +_NEARLY_SINGULAR = np.full((3, 3), -0.5000004) + 1.5000004 * np.eye(3) # -8e-7 of 4e-6 _SLIGHTLY_INDEFINITE = np.array([[0.0, 1e-5, 0.0], [1e-5, 0.0, 0.0], [0.0, 0.0, 1.0]]) # -1e-5 @@ -370,11 +370,12 @@ def test_both_decoders_reject_invalid_values(cpp_exchange, rich_scene, tmp_path, [ (_NEARLY_SINGULAR, True), (_SLIGHTLY_INDEFINITE, False), + (np.full((3, 3), -0.5000000004) + 1.5000000004 * np.eye(3), True), (np.diag([1e-12, 1e-12, 1e6]), True), - (np.diag([1.0, 1.0, -1e-8]), False), - # Mirrored entries 2e-9 and 3e-9 apart: a norm of 3.5e-9 and 5.2e-9, around 4e-9. - (np.eye(3) + 2e-9 * np.triu(np.ones((3, 3)), 1), True), - (np.eye(3) + 3e-9 * np.triu(np.ones((3, 3)), 1), False), + (np.diag([1.0, 1.0, -1e-5]), False), + # Mirrored entries 2e-6 and 3e-6 apart: a norm of 3.5e-6 and 5.2e-6, around 4e-6. + (np.eye(3) + 2e-6 * np.triu(np.ones((3, 3)), 1), True), + (np.eye(3) + 3e-6 * np.triu(np.ones((3, 3)), 1), False), ], ) def test_both_sdks_apply_one_covariance_rule(cpp_exchange, rich_scene, tmp_path, covariance, valid): From 21fc75462f9298662ef4f1634aa06dc5cd41190d Mon Sep 17 00:00:00 2001 From: "temkei.kem" Date: Wed, 2 Dec 2026 20:06:20 +0900 Subject: [PATCH 5/5] fix: preserve covariance validation through reanchor Restore the shared position covariance tolerance and handle float32 rounding in the rotation that introduces it. Return symmetric reanchored covariances in both SDKs and cover the negative-variance ROS2 export and asymmetric input exchange cases. --- .../cpp/tests/generator_test.cpp | 14 ++++- t4scene/cpp/include/t4_scene/coordinates.hpp | 14 +++++ t4scene/cpp/include/t4_scene/scene_ops.hpp | 12 ++--- t4scene/cpp/tests/records_test.cpp | 6 +-- t4scene/proto/README.md | 9 ++-- t4scene/python/README.md | 4 +- t4scene/python/t4scene/data/_coordinates.py | 36 ++++++++++--- t4scene/python/t4scene/data/ego.py | 52 +++++++++---------- .../python/tests/test_position_covariance.py | 13 +++-- t4scene/tests/test_cpp_exchange.py | 19 ++++--- 10 files changed, 119 insertions(+), 60 deletions(-) diff --git a/ros2/t4scene_generation/cpp/tests/generator_test.cpp b/ros2/t4scene_generation/cpp/tests/generator_test.cpp index 5c243d8..942788d 100644 --- a/ros2/t4scene_generation/cpp/tests/generator_test.cpp +++ b/ros2/t4scene_generation/cpp/tests/generator_test.cpp @@ -95,7 +95,7 @@ void check_position_covariance_and_start_pose(const fs::path &configs) { auto msg = odom(time, x); for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) - msg.pose.covariance[6 * i + j] = i == j ? 1 : -0.5000004; + msg.pose.covariance[6 * i + j] = i == j ? 1 : -0.5000000004; return msg; }; check(edge.ingest(nearly_singular(0, 0), 0), "odometry rejected"); @@ -117,6 +117,18 @@ void check_position_covariance_and_start_pose(const fs::path &configs) { !converted.ego->poses_3d->masked(3), "an indefinite covariance is dropped and its pose kept"); } + { + SceneBuilder invalid(configs / "range.yaml"); + auto msg = odom(0, 4); + msg.pose.covariance[0] = -0.5; + msg.pose.covariance[7] = 0.04; + msg.pose.covariance[14] = 1e6; + check(invalid.ingest(msg, 0), "odometry rejected"); + const auto range = invalid.build_range({"negative-variance"}); + check(!range.ego->position_covariances_3d && + range.ego->poses_3d->get(3) == 4, + "a large Z variance cannot make a negative X variance usable"); + } // Rows at 0, 100, 200 and 300 ms from samples at 0, 150 and 300 ms. check(builder.ingest(located(0, 0, 0.09), 0), "odometry rejected"); diff --git a/t4scene/cpp/include/t4_scene/coordinates.hpp b/t4scene/cpp/include/t4_scene/coordinates.hpp index a015d6f..550557b 100644 --- a/t4scene/cpp/include/t4_scene/coordinates.hpp +++ b/t4scene/cpp/include/t4_scene/coordinates.hpp @@ -184,6 +184,20 @@ struct PlanarChange { void covariances(std::optional> &field) const { rotate_pairs(field, {{0, 1}, {3, 4}, {6, 7}}); rotate_pairs(field, {{0, 3}, {1, 4}, {2, 5}}); + if (!field) + return; + auto &out = *field; + constexpr std::pair mirrored[] = {{1, 3}, {2, 6}, {5, 7}}; + for (std::size_t i = 0; i < out.size(); i += 9) { + for (const auto &[a, b] : mirrored) { + const auto ab = out.get(i + a), ba = out.get(i + b); + if (ab && ba) { + const double mean = 0.5 * *ab + 0.5 * *ba; + out.set(i + a, mean); + out.set(i + b, mean); + } + } + } } template void objects(std::optional &group) const { diff --git a/t4scene/cpp/include/t4_scene/scene_ops.hpp b/t4scene/cpp/include/t4_scene/scene_ops.hpp index 5bd26f7..024ac51 100644 --- a/t4scene/cpp/include/t4_scene/scene_ops.hpp +++ b/t4scene/cpp/include/t4_scene/scene_ops.hpp @@ -360,23 +360,21 @@ inline Annotations cut_annotations(const AnnotationSequence &sequence, std::nullopt}; } // Why a row-major [3,3] position covariance is unusable, or nullptr. The one -// rule of both SDKs and the ROS2 generator. With tau = 1e-6 * (1 + |trace C|), +// rule of both SDKs and the ROS2 generator. With tau = 1e-9 * (1 + |trace C|), // C is symmetric when the differences of its three pairs of mirrored entries // have a Euclidean norm of at most tau, and positive semidefinite when its // symmetric part plus tau*I has a Cholesky factor: every eigenvalue is then -// above -tau. Neither answer depends on the Scene axes, and a weighted mean of -// two valid covariances is valid. tau is the tolerance of the pose checks: -// wide enough for a covariance kept and rotated in float32. +// above -tau. The tolerance is independent of the Scene axes. inline const char *covariance_fault(const double *c) { for (unsigned i = 0; i < 9; ++i) if (!std::isfinite(c[i])) return "position covariance must be finite"; - const double tau = 1e-6 * (1 + std::abs(c[0] + c[4] + c[8])); + const double tau = 1e-9 * (1 + std::abs(c[0] + c[4] + c[8])); const double a = c[1] - c[3], b = c[2] - c[6], e = c[5] - c[7]; if (std::sqrt(a * a + b * b + e * e) > tau) return "position covariance must be symmetric"; - const double xy = 0.5 * (c[1] + c[3]), xz = 0.5 * (c[2] + c[6]), - yz = 0.5 * (c[5] + c[7]); + const double xy = 0.5 * c[1] + 0.5 * c[3], xz = 0.5 * c[2] + 0.5 * c[6], + yz = 0.5 * c[5] + 0.5 * c[7]; const double d0 = c[0] + tau, l10 = xy / d0, l20 = xz / d0; const double d1 = c[4] + tau - l10 * xy, l21 = (yz - l20 * xy) / d1; const double d2 = c[8] + tau - l20 * xz - l21 * l21 * d1; diff --git a/t4scene/cpp/tests/records_test.cpp b/t4scene/cpp/tests/records_test.cpp index 00487f9..04770ea 100644 --- a/t4scene/cpp/tests/records_test.cpp +++ b/t4scene/cpp/tests/records_test.cpp @@ -350,8 +350,8 @@ void position_covariances_are_symmetric_and_rotate_with_the_scene() { 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1}, {3, 3, 3}); rejects([&] { scene.validate(); }); - // The rule's tolerance is on the smallest eigenvalue, 1e-6 * (1 + trace), - // as in the Python SDK: -8e-7 passes, -1e-5 beside a unit variance fails. + // The rule's tolerance is on the smallest eigenvalue, 1e-9 * (1 + trace), + // as in the Python SDK: -8e-10 passes, -1e-5 beside a unit variance fails. auto with_first = [&](std::vector first) { first.insert(first.end(), {1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1}); auto edited = scene; @@ -359,7 +359,7 @@ void position_covariances_are_symmetric_and_rotate_with_the_scene() { Array::from_values(std::move(first), {3, 3, 3}); return edited; }; - const double off = -0.5000004; + const double off = -0.5000000004; with_first({1, off, off, off, 1, off, off, off, 1}).validate(); rejects( [&] { with_first({0, 1e-5, 0, 1e-5, 0, 0, 0, 0, 1}).validate(); }); diff --git a/t4scene/proto/README.md b/t4scene/proto/README.md index 1f5b994..21d7f2f 100644 --- a/t4scene/proto/README.md +++ b/t4scene/proto/README.md @@ -96,13 +96,12 @@ it becomes `R C Rᵀ`. It covers the position only: the orientation part of a source's pose covariance is not stored. Both SDKs and the ROS2 generator apply one rule to a known row, with -`τ = 1e-6 · (1 + |trace C|)`. The entries are finite. `C` is symmetric: the +`τ = 1e-9 · (1 + |trace C|)`. The entries are finite. `C` is symmetric: the differences of its three pairs of mirrored entries have a Euclidean norm of at most `τ`. `C` is positive semidefinite: its symmetric part plus `τ I` has a -Cholesky factor, so every eigenvalue is above `-τ`. The answer does not depend -on the Scene axes, and a weighted mean of two valid covariances is valid. `τ` -is the tolerance of the pose checks, wide enough for a covariance kept and -rotated in float32; `reanchor()` returns the symmetric part of `R C Rᵀ`. +Cholesky factor, so every eigenvalue is above `-τ`. The tolerance is +independent of the Scene axes. Both SDKs use the symmetric part of +`R C Rᵀ` when reanchoring. Vehicle-axis angular properties and vehicle-z yaw rate are projections of canonical storage. Tilted poses can require more than one known motion axis; diff --git a/t4scene/python/README.md b/t4scene/python/README.md index cca238d..cb2c855 100644 --- a/t4scene/python/README.md +++ b/t4scene/python/README.md @@ -92,7 +92,9 @@ cannot: a mission can begin outside the first lane. See the for each row, in Scene axes and m². Its diagonal holds the variances along x, y and z. A row whose source reported no estimate is masked, and `ego.at(i).position_covariance_3d` is then `None`. `reanchor()` rotates the -covariance with the Scene, so its eigenvalues do not depend on the anchor. See +covariance with the Scene. For Torch float32 covariances, the SDK rotates in +double precision and keeps the tensor dtype, device and gradient. If rounding +back would fail validation, it lifts the diagonal by the rounding error. See the [position covariance example](tests/test_position_covariance.py). Set `scene.global_origin_3d` to a 4×4 Scene-to-world transform. diff --git a/t4scene/python/t4scene/data/_coordinates.py b/t4scene/python/t4scene/data/_coordinates.py index 0cc6a8a..23e1474 100644 --- a/t4scene/python/t4scene/data/_coordinates.py +++ b/t4scene/python/t4scene/data/_coordinates.py @@ -15,7 +15,7 @@ torch, world_geometry, ) -from .ego import planar_pose +from .ego import _covariance_tolerance, _shifted_covariance_is_positive, planar_pose def _stack(*values): @@ -151,6 +151,28 @@ def _rotate_xy(values, rotation, origin=None): return _join(rotate_components(xy, rotation[:2, :2]), values[..., 2:]) +def _round_covariances_to_float32(covariances): + rounded = covariances.float() + with torch.no_grad(): + wide = covariances.detach() + stored = rounded.double() + needs_correction = _shifted_covariance_is_positive( + wide, _covariance_tolerance(wide) + ) & ~_shifted_covariance_is_positive(stored, _covariance_tolerance(stored)) + # Bound the spectral effect of rounding by making the added diagonal + # dominate the rounding error in each row. + diagonal = rounded.diagonal(dim1=-2, dim2=-1) + bound = diagonal.double() + (stored - wide).abs().sum(dim=-1) + lifted = bound.float() + lifted = torch.where( + lifted.double() < bound, + torch.nextafter(lifted, torch.full_like(lifted, torch.inf)), + lifted, + ) + correction = torch.where(needs_correction[..., None], lifted - diagonal, 0.0) + return rounded + torch.diag_embed(correction) + + class _PlanarChange: def __init__(self, origin, *, from_ego_pose=False): # The public anchor determines local precision. Its float64 working copy @@ -201,12 +223,14 @@ def covariances(self, values): """``R C R^T`` for [..., 3, 3] covariances: rotate the columns, then the rows.""" if values is None: return None - values, rotation = self.local_pair(values, self.to_old[:3, :3].T) - columns = rotate_components(values.swapaxes(-1, -2), rotation).swapaxes(-1, -2) + values = geometry_array(values) + wide, rotation = geometry_pair(world_geometry(values), self.to_old[:3, :3].T) + columns = rotate_components(wide.swapaxes(-1, -2), rotation).swapaxes(-1, -2) moved = rotate_components(columns, rotation) - # The two rotations round differently, in float32 by more than a checked - # codec allows between mirrored entries: keep the symmetric part. - return 0.5 * (moved + moved.swapaxes(-1, -2)) + symmetric = 0.5 * moved + 0.5 * moved.swapaxes(-1, -2) + if is_tensor(values) and values.dtype == torch.float32: + return _round_covariances_to_float32(symmetric).to(device=values.device) + return symmetric def registration(self, values): if values is None: diff --git a/t4scene/python/t4scene/data/ego.py b/t4scene/python/t4scene/data/ego.py index f0fc5c4..76606e9 100644 --- a/t4scene/python/t4scene/data/ego.py +++ b/t4scene/python/t4scene/data/ego.py @@ -421,28 +421,22 @@ def _validate_poses(value): raise ValueError("ego_pose_3d must have rigid homogeneous bottom row") -def covariance_faults(covariances): - """Why each ``[..., 3, 3]`` position covariance is unusable: ``(asymmetric, indefinite)``. - - The one rule of both SDKs and the ROS2 generator, for finite matrices. With - ``tau = 1e-6 * (1 + |trace C|)``, ``C`` is symmetric when the differences of its - three pairs of mirrored entries have a Euclidean norm of at most ``tau``, and - positive semidefinite when its symmetric part plus ``tau I`` has a Cholesky factor: - every eigenvalue is then above ``-tau``. Neither answer depends on the Scene axes, - and a weighted mean of two valid covariances is valid. ``tau`` is the tolerance of - the pose checks: wide enough for a covariance kept and rotated in float32. - """ - c = np.asarray(covariances, dtype=np.float64).reshape(-1, 9).T - tau = 1e-6 * (1.0 + np.abs(c[0] + c[4] + c[8])) - asymmetric = np.sqrt((c[1] - c[3]) ** 2 + (c[2] - c[6]) ** 2 + (c[5] - c[7]) ** 2) > tau - xy, xz, yz = 0.5 * (c[1] + c[3]), 0.5 * (c[2] + c[6]), 0.5 * (c[5] + c[7]) - with np.errstate(divide="ignore", invalid="ignore"): - d0 = c[0] + tau - l10, l20 = xy / d0, xz / d0 - d1 = c[4] + tau - l10 * xy - l21 = (yz - l20 * xy) / d1 - d2 = c[8] + tau - l20 * xz - l21 * l21 * d1 - return asymmetric, ~((d0 > 0) & (d1 > 0) & (d2 > 0)) +def _covariance_tolerance(value): + trace = value[..., 0, 0] + value[..., 1, 1] + value[..., 2, 2] + return 1e-9 * (1 + abs(trace)) + + +def _shifted_covariance_is_positive(value, shift): + # Test the Cholesky pivots of the symmetric part plus shift * I. + xy = 0.5 * value[..., 0, 1] + 0.5 * value[..., 1, 0] + xz = 0.5 * value[..., 0, 2] + 0.5 * value[..., 2, 0] + yz = 0.5 * value[..., 1, 2] + 0.5 * value[..., 2, 1] + d0 = value[..., 0, 0] + shift + l10, l20 = xy / d0, xz / d0 + d1 = value[..., 1, 1] + shift - l10 * xy + l21 = (yz - l20 * xy) / d1 + d2 = value[..., 2, 2] + shift - l20 * xz - l21 * l21 * d1 + return (d0 > 0) & (d1 > 0) & (d2 > 0) def _validate_covariances(value): @@ -450,14 +444,18 @@ def _validate_covariances(value): masks = np.ma.getmaskarray(values).reshape(len(values), 9) if (masks.any(axis=1) & ~masks.all(axis=1)).any(): raise ValueError("position_covariance_3d must be fully known or fully masked") - known = np.asarray(values.data, dtype=np.float64).reshape(len(values), 9)[~masks.any(axis=1)] + known = np.asarray(values.data, dtype=np.float64)[~masks.any(axis=1)] if not np.isfinite(known).all(): raise ValueError("position_covariance_3d must be finite") - asymmetric, indefinite = covariance_faults(known) - if asymmetric.any(): + tolerance = _covariance_tolerance(known) + xy = known[:, 0, 1] - known[:, 1, 0] + xz = known[:, 0, 2] - known[:, 2, 0] + yz = known[:, 1, 2] - known[:, 2, 1] + if (np.sqrt(xy * xy + xz * xz + yz * yz) > tolerance).any(): raise ValueError("position_covariance_3d must be symmetric") - if indefinite.any(): - raise ValueError("position_covariance_3d must be positive semidefinite") + with np.errstate(divide="ignore", invalid="ignore"): + if not _shifted_covariance_is_positive(known, tolerance).all(): + raise ValueError("position_covariance_3d must be positive semidefinite") def _planar_vector(value): diff --git a/t4scene/python/tests/test_position_covariance.py b/t4scene/python/tests/test_position_covariance.py index 66f50f4..e4170d2 100644 --- a/t4scene/python/tests/test_position_covariance.py +++ b/t4scene/python/tests/test_position_covariance.py @@ -114,6 +114,7 @@ def test_the_covariance_is_the_last_field_of_the_ego_records(): assert list(T4Scene.__dataclass_fields__)[-1] == "start_poses_3d" +@pytest.mark.parametrize("device", ["cpu", "mps"]) @pytest.mark.parametrize( "covariance", [ @@ -121,10 +122,14 @@ def test_the_covariance_is_the_last_field_of_the_ego_records(): np.array([[1.0, 0.2, 0.1], [0.2, 1.0, 0.3], [0.1, 0.3, 1.0]]), ], ) -def test_float32_covariances_stay_serializable_under_new_anchors(covariance): +def test_float32_covariances_stay_serializable_under_new_anchors(covariance, device): torch = pytest.importorskip("torch") - covariances = torch.tensor(np.stack((covariance, covariance)), dtype=torch.float32) - scene = _scene(covariances.requires_grad_()) + if device == "mps" and not torch.backends.mps.is_available(): + pytest.skip("MPS is unavailable") + covariances = torch.tensor( + np.stack((covariance, covariance)), dtype=torch.float32, device=device, requires_grad=True + ) + scene = _scene(covariances) T4Scene.from_proto(scene.to_proto()) for step in range(20): scene = scene.reanchor((0.3 * step, -0.1, 0.1 + 0.5 * step)) @@ -133,3 +138,5 @@ def test_float32_covariances_stay_serializable_under_new_anchors(covariance): assert moved.device == covariances.device assert torch.equal(moved, moved.swapaxes(-1, -2)) T4Scene.from_proto(scene.to_proto()) + moved.square().sum().backward() + assert torch.isfinite(covariances.grad).all() diff --git a/t4scene/tests/test_cpp_exchange.py b/t4scene/tests/test_cpp_exchange.py index 3f09e23..0b59bfe 100644 --- a/t4scene/tests/test_cpp_exchange.py +++ b/t4scene/tests/test_cpp_exchange.py @@ -232,6 +232,7 @@ def test_reanchor_matches_python(cpp_exchange, rich_scene, tmp_path): from t4scene.data.map import map_to_scene rich_scene.ego.velocities_3d.mask[0, 1] = True + rich_scene.ego.position_covariances_3d[0, 0, 1] += 5e-10 poses = np.ma.array( rich_scene.ego.poses_3d, mask=np.ma.getmaskarray(rich_scene.ego.poses_3d).copy() ) @@ -245,6 +246,10 @@ def test_reanchor_matches_python(cpp_exchange, rich_scene, tmp_path): actual = T4Scene.from_proto(pb.T4Scene.FromString(output.read_bytes())) expected = rich_scene.reanchor(origin, reanchor_model_data=lambda _, m: {"old_to_new": m}) expected.validate() + covariances = actual.ego.position_covariances_3d + np.testing.assert_array_equal( + covariances.compressed(), covariances.swapaxes(-1, -2).compressed() + ) pose_mask = np.ma.getmaskarray(actual.ego.poses_3d) assert not pose_mask[:2, :3, :].any() np.testing.assert_array_equal(pose_mask[:2, 3, :], poses.mask[:2, 3, :]) @@ -360,8 +365,8 @@ def test_both_decoders_reject_invalid_values(cpp_exchange, rich_scene, tmp_path, # Each SDK must give the other's answer close to the limit of the covariance rule: its -# tolerance is 1e-6 * (1 + trace), on the smallest eigenvalue. -_NEARLY_SINGULAR = np.full((3, 3), -0.5000004) + 1.5000004 * np.eye(3) # -8e-7 of 4e-6 +# tolerance is 1e-9 * (1 + trace), on the smallest eigenvalue. +_NEARLY_SINGULAR = np.full((3, 3), -0.5000000004) + 1.5000000004 * np.eye(3) # -8e-10 _SLIGHTLY_INDEFINITE = np.array([[0.0, 1e-5, 0.0], [1e-5, 0.0, 0.0], [0.0, 0.0, 1.0]]) # -1e-5 @@ -370,12 +375,12 @@ def test_both_decoders_reject_invalid_values(cpp_exchange, rich_scene, tmp_path, [ (_NEARLY_SINGULAR, True), (_SLIGHTLY_INDEFINITE, False), - (np.full((3, 3), -0.5000000004) + 1.5000000004 * np.eye(3), True), (np.diag([1e-12, 1e-12, 1e6]), True), - (np.diag([1.0, 1.0, -1e-5]), False), - # Mirrored entries 2e-6 and 3e-6 apart: a norm of 3.5e-6 and 5.2e-6, around 4e-6. - (np.eye(3) + 2e-6 * np.triu(np.ones((3, 3)), 1), True), - (np.eye(3) + 3e-6 * np.triu(np.ones((3, 3)), 1), False), + (np.diag([-0.5, 0.04, 1e6]), False), + (np.diag([1.0, 1.0, -1e-8]), False), + # Mirrored entries 2e-9 and 3e-9 apart: norms of 3.5e-9 and 5.2e-9 around 4e-9. + (np.eye(3) + 2e-9 * np.triu(np.ones((3, 3)), 1), True), + (np.eye(3) + 3e-9 * np.triu(np.ones((3, 3)), 1), False), ], ) def test_both_sdks_apply_one_covariance_rule(cpp_exchange, rich_scene, tmp_path, covariance, valid):