diff --git a/CHANGELOG.md b/CHANGELOG.md index 481176f..5cf16b3 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.start_poses_3d` is `[T,4,4]` like `goal_poses_3d`. + 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 + `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..aa9f4f0 100644 --- a/ros2/t4scene_generation/configs/README.md +++ b/ros2/t4scene_generation/configs/README.md @@ -70,14 +70,27 @@ 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 `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 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. + 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..0d71c9e 100644 --- a/ros2/t4scene_generation/cpp/src/generator.cpp +++ b/ros2/t4scene_generation/cpp/src/generator.cpp @@ -2,11 +2,13 @@ #include "observations.hpp" #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -19,6 +21,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 +33,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 +175,21 @@ 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") 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::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.isZero(0) || scene_detail::covariance_fault(c.data())) + return std::nullopt; + 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 || frame_name(msg.child_frame_id) != config.body_frame) @@ -183,6 +208,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 +223,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 +483,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 +498,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 +519,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 +731,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..f50c94c 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.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..942788d 100644 --- a/ros2/t4scene_generation/cpp/tests/generator_test.cpp +++ b/ros2/t4scene_generation/cpp/tests/generator_test.cpp @@ -66,6 +66,128 @@ 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_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, + "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"); + + { + // 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"); + } + { + 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"); + 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.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).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.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 +409,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_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 1e62fcd..e15fa70 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.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 + 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..d81104e 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.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..550557b 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,27 @@ 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}}); + 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 { if (!group) return; @@ -190,6 +235,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(start_poses_3d, size(), {4, 4}); if (!origin) { if (!ego || !ego->poses_3d || (ego->available && !ego->available->at(current_index))) @@ -211,6 +257,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 +266,7 @@ T4Scene::reanchor(std::optional origin, change.objects(groups.polygons); } change.transform(out.goal_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 9310e6a..b7458c4 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.start_poses_3d) { + write(*in.start_poses_3d, *out.mutable_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_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 d9340b3..71de808 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>}, + {"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 31fa004..024ac51 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,42 @@ inline Annotations cut_annotations(const AnnotationSequence &sequence, count), 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|), +// 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. 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-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] + 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; + 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; + 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; + 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) { unsigned known = 0, rotation_known = 0; @@ -481,12 +520,16 @@ inline void T4Scene::validate() const { if (frame_indices) known(*frame_indices); check_column(goal_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 (start_poses_3d) + for (std::size_t i = 0; i < count; ++i) + check_pose(start_poses_3d->data() + 16 * i, &*start_poses_3d, 16 * i); if (ego) { check_columns(*ego, count); if (ego->available) @@ -497,6 +540,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 +669,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.start_poses_3d = cut(start_poses_3d, start, count); if (ego) out.ego = cut_columns(*ego, start, count); if (annotations) { @@ -694,6 +741,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.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; @@ -702,6 +750,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..47d330d 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 { @@ -280,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; @@ -305,6 +310,8 @@ struct EgoStatus { 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; @@ -319,6 +326,7 @@ struct T4Frame { std::optional global_origin_3d; std::optional> goal_pose_3d; std::optional model_data; + std::optional> start_pose_3d{}; }; } // namespace t4scene diff --git a/t4scene/cpp/tests/protobuf_test.cpp b/t4scene/cpp/tests/protobuf_test.cpp index 35e524b..b83c248 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.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.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,21 @@ 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().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).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..04770ea 100644 --- a/t4scene/cpp/tests/records_test.cpp +++ b/t4scene/cpp/tests/records_test.cpp @@ -287,6 +287,141 @@ 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(); }); + // 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. + // 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 && 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 = + 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 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.start_poses_3d = + Array::from_values(std::move(starts), {3, 4, 4}); + std::vector mask(scene.start_poses_3d->size(), 1); + std::fill_n(mask.begin(), 2 * start.size(), 0); + scene.start_poses_3d->set_mask(mask); + scene.validate(); + SceneRequirements{{"start"}}.validate(scene); + { + 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).start_pose_3d, + "fully masked route start is unavailable"); + 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}).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.start_poses_3d->set(0, 0.7); + rejects([&] { scene.validate(); }); + scene.start_poses_3d.reset(); + rejects( + [&] { SceneRequirements{{"start"}}.validate(scene); }); +} } // namespace int main() { @@ -299,6 +434,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(); + 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 069da6b..21d7f2f 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. +`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,20 @@ 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. + +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 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; projection masks follow those dependencies. Acceleration projection requires diff --git a/t4scene/proto/t4_scene.proto b/t4scene/proto/t4_scene.proto index 5d91d82..57fb0e8 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,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. + 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 d6609cd..cb2c855 100644 --- a/t4scene/python/README.md +++ b/t4scene/python/README.md @@ -80,6 +80,23 @@ 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.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_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. 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. `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 +123,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`, `start` and `model_data`. Required fields take precedence on +overlap. `route` checks `scene.routes`. `goal` checks `scene.goal_poses_3d` and +`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 7d57829..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 @@ -197,6 +219,19 @@ 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 = 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) + 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: return None @@ -250,6 +285,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 +299,7 @@ def reanchor(scene, origin, reanchor_model_data): ego=ego, annotations=annotations, goal_poses_3d=change.poses(scene.goal_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/ego.py b/t4scene/python/t4scene/data/ego.py index 8a33a6e..76606e9 100644 --- a/t4scene/python/t4scene/data/ego.py +++ b/t4scene/python/t4scene/data/ego.py @@ -95,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( @@ -186,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): @@ -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,43 @@ def _validate_poses(value): raise ValueError("ego_pose_3d must have rigid homogeneous bottom row") +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): + values = np.ma.asarray(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)[~masks.any(axis=1)] + if not np.isfinite(known).all(): + raise ValueError("position_covariance_3d must be finite") + 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") + 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): if value is None: return None diff --git a/t4scene/python/t4scene/data/frame.py b/t4scene/python/t4scene/data/frame.py index f938917..49997cc 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 + 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.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 11366cf..3ea5b4d 100644 --- a/t4scene/python/t4scene/data/scene.py +++ b/t4scene/python/t4scene/data/scene.py @@ -87,6 +87,9 @@ class T4Scene: 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)) @@ -271,6 +274,7 @@ def cut(value): cameras=cut(self.cameras), lidar=cut(self.lidar), goal_poses_3d=cut(self.goal_poses_3d), + start_poses_3d=cut(self.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), + start_pose_3d=optional_row(self.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 start_pose_3d(self) -> Array | None: + return optional_row(self.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,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)), + 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, ) @@ -407,6 +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.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 9aba8c0..b663ce1 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)), + "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..6649de7 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", + "start": "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..e4170d2 --- /dev/null +++ b/t4scene/python/tests/test_position_covariance.py @@ -0,0 +1,142 @@ +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 + ) + + +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" + + +@pytest.mark.parametrize("device", ["cpu", "mps"]) +@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, device): + torch = pytest.importorskip("torch") + 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)) + 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()) + moved.square().sum().backward() + assert torch.isfinite(covariances.grad).all() 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 3b0fec9..0b59bfe 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.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( + 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="", @@ -221,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() ) @@ -234,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, :]) @@ -241,6 +257,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.start_poses_3d, expected.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 +290,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 +317,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.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"): @@ -334,6 +364,44 @@ 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([-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): + 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