blob: 278b958a66c104ef50101b53f0fbc30b5871f400 [file] [log] [blame]
James Kuszmaul1057ce82019-02-09 17:58:24 -08001#include "y2019/control_loops/drivetrain/localizer.h"
2
James Kuszmaul1057ce82019-02-09 17:58:24 -08003#include <queue>
James Kuszmaul651fc3f2019-05-15 21:14:25 -07004#include <random>
James Kuszmaul1057ce82019-02-09 17:58:24 -08005
Philipp Schrader790cb542023-07-05 21:06:52 -07006#include "gflags/gflags.h"
7
James Kuszmaul1057ce82019-02-09 17:58:24 -08008#include "aos/testing/random_seed.h"
9#include "aos/testing/test_shm.h"
James Kuszmaul1057ce82019-02-09 17:58:24 -080010#include "frc971/control_loops/drivetrain/splinedrivetrain.h"
James Kuszmaul651fc3f2019-05-15 21:14:25 -070011#include "frc971/control_loops/drivetrain/trajectory.h"
James Kuszmaul1057ce82019-02-09 17:58:24 -080012#if defined(SUPPORT_PLOT)
13#include "third_party/matplotlib-cpp/matplotlibcpp.h"
14#endif
15#include "gtest/gtest.h"
Philipp Schrader790cb542023-07-05 21:06:52 -070016
James Kuszmaul1057ce82019-02-09 17:58:24 -080017#include "y2019/constants.h"
James Kuszmaul651fc3f2019-05-15 21:14:25 -070018#include "y2019/control_loops/drivetrain/drivetrain_base.h"
James Kuszmaul1057ce82019-02-09 17:58:24 -080019
20DEFINE_bool(plot, false, "If true, plot");
21
Stephan Pleinesf63bde82024-01-13 15:59:33 -080022namespace y2019::control_loops::testing {
James Kuszmaul1057ce82019-02-09 17:58:24 -080023
24using ::y2019::constants::Field;
25
26constexpr size_t kNumCameras = 4;
27constexpr size_t kNumTargetsPerFrame = 3;
28
29typedef TypedLocalizer<kNumCameras, Field::kNumTargets, Field::kNumObstacles,
James Kuszmaul651fc3f2019-05-15 21:14:25 -070030 kNumTargetsPerFrame, double>
31 TestLocalizer;
James Kuszmaul1057ce82019-02-09 17:58:24 -080032typedef typename TestLocalizer::Camera TestCamera;
James Kuszmaulf4ede202020-02-14 08:47:40 -080033typedef typename TestLocalizer::Target Target;
James Kuszmaul1057ce82019-02-09 17:58:24 -080034typedef typename TestCamera::Pose Pose;
35typedef typename TestCamera::LineSegment Obstacle;
36
37typedef TestLocalizer::StateIdx StateIdx;
38
39using ::frc971::control_loops::drivetrain::DrivetrainConfig;
40
41// When placing the cameras on the robot, set them all kCameraOffset out from
42// the center, to test that we really can handle cameras that aren't at the
43// center-of-mass.
44constexpr double kCameraOffset = 0.1;
45
46#if defined(SUPPORT_PLOT)
47// Plots a line from a vector of Pose's.
48void PlotPlotPts(const ::std::vector<Pose> &poses,
49 const ::std::map<::std::string, ::std::string> &kwargs) {
50 ::std::vector<double> x;
51 ::std::vector<double> y;
James Kuszmaul651fc3f2019-05-15 21:14:25 -070052 for (const Pose &p : poses) {
James Kuszmaul1057ce82019-02-09 17:58:24 -080053 x.push_back(p.abs_pos().x());
54 y.push_back(p.abs_pos().y());
55 }
56 matplotlibcpp::plot(x, y, kwargs);
57}
58#endif
59
60struct LocalizerTestParams {
61 // Control points for the spline to make the robot follow.
62 ::std::array<float, 6> control_pts_x;
63 ::std::array<float, 6> control_pts_y;
64 // The actual state to start the robot at. By setting voltage errors and the
65 // such you can introduce persistent disturbances.
66 TestLocalizer::State true_start_state;
67 // The initial state of the estimator.
68 TestLocalizer::State known_start_state;
69 // Whether or not to add Gaussian noise to the sensors and cameras.
70 bool noisify;
71 // Whether or not to add unmodelled disturbances.
72 bool disturb;
73 // The tolerances for the estimator and for the trajectory following at
74 // the end of the spline:
75 double estimate_tolerance;
76 double goal_tolerance;
77};
78
79class ParameterizedLocalizerTest
80 : public ::testing::TestWithParam<LocalizerTestParams> {
81 public:
82 ::aos::testing::TestSharedMemory shm_;
83
84 // Set up three targets in a row, at (-1, 0), (0, 0), and (1, 0).
85 // Make the right-most target (1, 0) be facing away from the camera, and give
86 // the middle target some skew.
87 // Place one camera facing forward, the other facing backward, and set the
88 // robot at (0, -5) with the cameras each 0.1m from the center.
89 // Place one obstacle in a place where it can block the left-most target (-1,
90 // 0).
91 ParameterizedLocalizerTest()
92 : field_(),
93 targets_(field_.targets()),
94 modeled_obstacles_(field_.obstacles()),
95 true_obstacles_(field_.obstacles()),
96 dt_config_(drivetrain::GetDrivetrainConfig()),
97 // Pull the noise for the encoders/gyros from the R matrix:
98 encoder_noise_(::std::sqrt(
99 dt_config_.make_kf_drivetrain_loop().observer().coefficients().R(
100 0, 0))),
101 gyro_noise_(::std::sqrt(
102 dt_config_.make_kf_drivetrain_loop().observer().coefficients().R(
103 2, 2))),
104 // As per the comments in localizer.h, we set the field of view and
105 // noise parameters on the robot_cameras_ so that they see a bit more
106 // than the true_cameras_. The robot_cameras_ are what is passed to the
107 // localizer and used to generate "expected" targets. The true_cameras_
108 // are what we actually use to generate targets to pass to the
109 // localizer.
110 robot_cameras_{
111 {TestCamera({&robot_pose_, {0.0, kCameraOffset, 0.0}, M_PI_2},
112 M_PI_2 * 1.1, robot_noise_parameters_, targets_,
113 modeled_obstacles_),
114 TestCamera({&robot_pose_, {kCameraOffset, 0.0, 0.0}, 0.0},
115 M_PI_2 * 1.1, robot_noise_parameters_, targets_,
116 modeled_obstacles_),
117 TestCamera({&robot_pose_, {-kCameraOffset, 0.0, 0.0}, M_PI},
118 M_PI_2 * 1.1, robot_noise_parameters_, targets_,
119 modeled_obstacles_),
120 TestCamera({&robot_pose_, {0.0, -kCameraOffset, 0.0}, -M_PI_2},
121 M_PI_2 * 1.1, robot_noise_parameters_, targets_,
122 modeled_obstacles_)}},
123 true_cameras_{
124 {TestCamera({&true_robot_pose_, {0.0, kCameraOffset, 0.0}, M_PI_2},
125 M_PI_2 * 0.9, true_noise_parameters_, targets_,
126 true_obstacles_),
127 TestCamera({&true_robot_pose_, {kCameraOffset, 0.0, 0.0}, 0.0},
128 M_PI_2 * 0.9, true_noise_parameters_, targets_,
129 true_obstacles_),
130 TestCamera({&true_robot_pose_, {-kCameraOffset, 0.0, 0.0}, M_PI},
131 M_PI_2 * 0.9, true_noise_parameters_, targets_,
132 true_obstacles_),
133 TestCamera(
134 {&true_robot_pose_, {-0.0, -kCameraOffset, 0.0}, -M_PI_2},
135 M_PI_2 * 0.9, true_noise_parameters_, targets_,
136 true_obstacles_)}},
137 localizer_(dt_config_, &robot_pose_),
138 spline_drivetrain_(dt_config_) {
139 // We use the default P() for initialization.
140 localizer_.ResetInitialState(t0_, GetParam().known_start_state,
141 localizer_.P());
142 }
143
144 void SetUp() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700145 {
146 flatbuffers::FlatBufferBuilder fbb;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700147 flatbuffers::Offset<flatbuffers::Vector<float>> spline_x_offset =
148 fbb.CreateVector<float>(GetParam().control_pts_x.begin(),
149 GetParam().control_pts_x.size());
150
151 flatbuffers::Offset<flatbuffers::Vector<float>> spline_y_offset =
152 fbb.CreateVector<float>(GetParam().control_pts_y.begin(),
153 GetParam().control_pts_y.size());
154
155 frc971::MultiSpline::Builder multispline_builder(fbb);
156
157 multispline_builder.add_spline_count(1);
158 multispline_builder.add_spline_x(spline_x_offset);
159 multispline_builder.add_spline_y(spline_y_offset);
160
161 flatbuffers::Offset<frc971::MultiSpline> multispline_offset =
162 multispline_builder.Finish();
163
164 frc971::control_loops::drivetrain::SplineGoal::Builder spline_builder(
165 fbb);
166
167 spline_builder.add_spline_idx(1);
168 spline_builder.add_spline(multispline_offset);
169
James Kuszmaul75a18c52021-03-10 22:02:07 -0800170 fbb.Finish(spline_builder.Finish());
171 aos::FlatbufferDetachedBuffer<
172 frc971::control_loops::drivetrain::SplineGoal>
173 spline_goal_buffer(fbb.Release());
174
175 frc971::control_loops::drivetrain::Trajectory trajectory(
James Kuszmaul5c4ccf62024-03-03 17:29:49 -0800176 spline_goal_buffer.message(), &dt_config_);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800177 trajectory.Plan();
178
179 flatbuffers::FlatBufferBuilder traj_fbb;
180
181 traj_fbb.Finish(trajectory.Serialize(&traj_fbb));
182
183 trajectory_ = std::make_unique<aos::FlatbufferDetachedBuffer<
184 frc971::control_loops::drivetrain::fb::Trajectory>>(
185 traj_fbb.Release());
186 spline_drivetrain_.AddTrajectory(&trajectory_->message());
187 }
188
189 flatbuffers::DetachedBuffer goal_buffer;
190 {
191 flatbuffers::FlatBufferBuilder fbb;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700192
193 frc971::control_loops::drivetrain::Goal::Builder goal_builder(fbb);
194
Alex Perrycb7da4b2019-08-28 19:35:56 -0700195 goal_builder.add_controller_type(
Austin Schuh872723c2019-12-25 14:38:09 -0800196 frc971::control_loops::drivetrain::ControllerType::SPLINE_FOLLOWER);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700197 goal_builder.add_spline_handle(1);
198
199 fbb.Finish(goal_builder.Finish());
200
201 goal_buffer = fbb.Release();
202 }
203 aos::FlatbufferDetachedBuffer<frc971::control_loops::drivetrain::Goal> goal(
204 std::move(goal_buffer));
205
Alex Perrycb7da4b2019-08-28 19:35:56 -0700206 spline_drivetrain_.SetGoal(&goal.message());
James Kuszmaul1057ce82019-02-09 17:58:24 -0800207 }
208
209 void TearDown() {
210 printf("Each iteration of the simulation took on average %f seconds.\n",
211 avg_time_.count());
212#if defined(SUPPORT_PLOT)
213 if (FLAGS_plot) {
214 matplotlibcpp::figure();
215 matplotlibcpp::plot(simulation_t_, simulation_vl_, {{"label", "Vl"}});
216 matplotlibcpp::plot(simulation_t_, simulation_vr_, {{"label", "Vr"}});
217 matplotlibcpp::legend();
218
219 matplotlibcpp::figure();
220 matplotlibcpp::plot(spline_x_, spline_y_, {{"label", "spline"}});
221 matplotlibcpp::plot(simulation_x_, simulation_y_, {{"label", "robot"}});
222 matplotlibcpp::plot(estimated_x_, estimated_y_,
223 {{"label", "estimation"}});
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700224 for (const Target &target : targets_) {
James Kuszmaul1057ce82019-02-09 17:58:24 -0800225 PlotPlotPts(target.PlotPoints(), {{"c", "g"}});
226 }
227 for (const Obstacle &obstacle : true_obstacles_) {
228 PlotPlotPts(obstacle.PlotPoints(), {{"c", "k"}});
229 }
230 // Go through and plot true/expected camera targets for a few select
231 // time-steps.
232 ::std::vector<const char *> colors{"m", "y", "c"};
233 int jj = 0;
234 for (size_t ii = 0; ii < simulation_x_.size(); ii += 400) {
235 *true_robot_pose_.mutable_pos() << simulation_x_[ii], simulation_y_[ii],
236 0.0;
237 true_robot_pose_.set_theta(simulation_theta_[ii]);
238 for (const TestCamera &camera : true_cameras_) {
239 for (const auto &plot_pts : camera.PlotPoints()) {
240 PlotPlotPts(plot_pts, {{"c", colors[jj]}});
241 }
242 }
243 for (const TestCamera &camera : robot_cameras_) {
244 *robot_pose_.mutable_pos() << estimated_x_[ii], estimated_y_[ii], 0.0;
245 robot_pose_.set_theta(estimated_theta_[ii]);
246 const auto &all_plot_pts = camera.PlotPoints();
247 *robot_pose_.mutable_pos() = true_robot_pose_.rel_pos();
248 robot_pose_.set_theta(true_robot_pose_.rel_theta());
249 for (const auto &plot_pts : all_plot_pts) {
250 PlotPlotPts(plot_pts, {{"c", colors[jj]}, {"ls", "--"}});
251 }
252 }
253 jj = (jj + 1) % colors.size();
254 }
255 matplotlibcpp::legend();
256
257 matplotlibcpp::figure();
258 matplotlibcpp::plot(
259 simulation_t_, spline_x_,
260 {{"label", "spline x"}, {"c", "g"}, {"ls", ""}, {"marker", "o"}});
261 matplotlibcpp::plot(simulation_t_, simulation_x_,
262 {{"label", "simulated x"}, {"c", "g"}});
263 matplotlibcpp::plot(simulation_t_, estimated_x_,
264 {{"label", "estimated x"}, {"c", "g"}, {"ls", "--"}});
265
266 matplotlibcpp::plot(
267 simulation_t_, spline_y_,
268 {{"label", "spline y"}, {"c", "b"}, {"ls", ""}, {"marker", "o"}});
269 matplotlibcpp::plot(simulation_t_, simulation_y_,
270 {{"label", "simulated y"}, {"c", "b"}});
271 matplotlibcpp::plot(simulation_t_, estimated_y_,
272 {{"label", "estimated y"}, {"c", "b"}, {"ls", "--"}});
273
274 matplotlibcpp::plot(simulation_t_, simulation_theta_,
275 {{"label", "simulated theta"}, {"c", "r"}});
276 matplotlibcpp::plot(
277 simulation_t_, estimated_theta_,
278 {{"label", "estimated theta"}, {"c", "r"}, {"ls", "--"}});
279 matplotlibcpp::legend();
280
281 matplotlibcpp::show();
282 }
283#endif
284 }
285
286 protected:
287 // Returns a random number with a gaussian distribution with a mean of zero
288 // and a standard deviation of std, if noisify = true.
289 // If noisify is false, then returns 0.0.
290 double Normal(double std) {
291 if (GetParam().noisify) {
292 return normal_(gen_) * std;
293 }
294 return 0.0;
295 }
296 // Adds random noise to the given target view.
297 void Noisify(TestCamera::TargetView *view) {
298 view->reading.heading += Normal(view->noise.heading);
299 view->reading.distance += Normal(view->noise.distance);
300 view->reading.height += Normal(view->noise.height);
301 view->reading.skew += Normal(view->noise.skew);
302 }
303 // The differential equation for the dynamics of the system.
304 TestLocalizer::State DiffEq(const TestLocalizer::State &X,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800305 const Eigen::Vector2d &voltage) {
306 TestLocalizer::Input U;
307 U.setZero();
308 U(0) = voltage(0);
309 U(1) = voltage(1);
310 return localizer_.DiffEq(X, U, true);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800311 }
312
313 Field field_;
314 ::std::array<Target, Field::kNumTargets> targets_;
315 // The obstacles that are passed to the camera objects for the localizer.
316 ::std::array<Obstacle, Field::kNumObstacles> modeled_obstacles_;
317 // The obstacles that are used for actually simulating the cameras.
318 ::std::array<Obstacle, Field::kNumObstacles> true_obstacles_;
319
320 DrivetrainConfig<double> dt_config_;
321
322 // Noise information for the actual simulated cameras (true_*) and the
323 // parameters that the localizer should use for modelling the cameras. Note
324 // how the max_viewable_distance is larger for the localizer, so that if
325 // there is any error in the estimation, it still thinks that it can see
326 // any targets that might actually be in range.
327 TestCamera::NoiseParameters true_noise_parameters_ = {
328 .max_viewable_distance = 10.0,
329 .heading_noise = 0.02,
330 .nominal_distance_noise = 0.06,
331 .nominal_skew_noise = 0.1,
332 .nominal_height_noise = 0.01};
333 TestCamera::NoiseParameters robot_noise_parameters_ = {
334 .max_viewable_distance = 11.0,
335 .heading_noise = 0.02,
336 .nominal_distance_noise = 0.06,
337 .nominal_skew_noise = 0.1,
338 .nominal_height_noise = 0.01};
339
340 // Standard deviations of the noise for the encoders/gyro.
341 double encoder_noise_, gyro_noise_;
342
343 Pose robot_pose_;
344 ::std::array<TestCamera, 4> robot_cameras_;
345 Pose true_robot_pose_;
346 ::std::array<TestCamera, 4> true_cameras_;
347
348 TestLocalizer localizer_;
349
James Kuszmaul75a18c52021-03-10 22:02:07 -0800350 std::unique_ptr<aos::FlatbufferDetachedBuffer<
351 frc971::control_loops::drivetrain::fb::Trajectory>>
352 trajectory_;
James Kuszmaul1057ce82019-02-09 17:58:24 -0800353 ::frc971::control_loops::drivetrain::SplineDrivetrain spline_drivetrain_;
354
355 // All the data we want to end up plotting.
356 ::std::vector<double> simulation_t_;
357
358 ::std::vector<double> spline_x_;
359 ::std::vector<double> spline_y_;
360 ::std::vector<double> estimated_x_;
361 ::std::vector<double> estimated_y_;
362 ::std::vector<double> estimated_theta_;
363 ::std::vector<double> simulation_x_;
364 ::std::vector<double> simulation_y_;
365 ::std::vector<double> simulation_theta_;
366
367 ::std::vector<double> simulation_vl_;
368 ::std::vector<double> simulation_vr_;
369
370 // Simulation start time
371 ::aos::monotonic_clock::time_point t0_;
372
373 // Average duration of each iteration; used for debugging and getting a
374 // sanity-check on what performance looks like--uses a real system clock.
375 ::std::chrono::duration<double> avg_time_;
376
377 ::std::mt19937 gen_{static_cast<uint32_t>(::aos::testing::RandomSeed())};
378 ::std::normal_distribution<> normal_;
379};
380
James Kuszmaul6f941b72019-03-08 18:12:25 -0800381using ::std::chrono::milliseconds;
382
James Kuszmaul1057ce82019-02-09 17:58:24 -0800383// Tests that, when we attempt to follow a spline and use the localizer to
384// perform the state estimation, we end up roughly where we should and that
385// the localizer has a valid position estimate.
386TEST_P(ParameterizedLocalizerTest, SplineTest) {
387 // state stores the true state of the robot throughout the simulation.
388 TestLocalizer::State state = GetParam().true_start_state;
389
390 ::aos::monotonic_clock::time_point t = t0_;
391
392 // The period with which we should take frames from the cameras. Currently,
393 // we just trigger all the cameras at once, rather than offsetting them or
394 // anything.
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700395 const int camera_period = 5; // cycles
James Kuszmaul6f941b72019-03-08 18:12:25 -0800396 // The amount of time to delay the camera images from when they are taken, for
397 // each camera.
398 const ::std::array<milliseconds, 4> camera_latencies{
399 {milliseconds(45), milliseconds(50), milliseconds(55),
400 milliseconds(100)}};
James Kuszmaul1057ce82019-02-09 17:58:24 -0800401
James Kuszmaul6f941b72019-03-08 18:12:25 -0800402 // A queue of camera frames for each camera so that we can add a time delay to
403 // the data coming from the cameras.
404 ::std::array<
405 ::std::queue<::std::tuple<
406 ::aos::monotonic_clock::time_point, const TestCamera *,
407 ::aos::SizedArray<TestCamera::TargetView, kNumTargetsPerFrame>>>,
408 4>
409 camera_queues;
James Kuszmaul1057ce82019-02-09 17:58:24 -0800410
411 // Start time, for debugging.
412 const auto begin = ::std::chrono::steady_clock::now();
413
414 size_t i;
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700415 // Run the feedback-controller slightly past the nominal end-time. This both
416 // exercises the code to see what happens when we are trying to stand still,
417 // and gives the control loops time to stabilize.
418 aos::monotonic_clock::duration extra_time = std::chrono::seconds(2);
419 for (i = 0;
420 !spline_drivetrain_.IsAtEnd() || extra_time > std::chrono::seconds(0);
421 ++i) {
422 if (spline_drivetrain_.IsAtEnd()) {
423 extra_time -= dt_config_.dt;
424 }
James Kuszmaul1057ce82019-02-09 17:58:24 -0800425 // Get the current state estimate into a matrix that works for the
426 // trajectory code.
427 ::Eigen::Matrix<double, 5, 1> known_state;
428 TestLocalizer::State X_hat = localizer_.X_hat();
429 known_state << X_hat(StateIdx::kX, 0), X_hat(StateIdx::kY, 0),
430 X_hat(StateIdx::kTheta, 0), X_hat(StateIdx::kLeftVelocity, 0),
431 X_hat(StateIdx::kRightVelocity, 0);
432
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700433 Eigen::Vector2d voltage_error(X_hat(StateIdx::kLeftVoltageError),
434 X_hat(StateIdx::kRightVoltageError));
435 spline_drivetrain_.Update(true, known_state, voltage_error);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800436
Alex Perrycb7da4b2019-08-28 19:35:56 -0700437 ::frc971::control_loops::drivetrain::OutputT output;
James Kuszmaul1057ce82019-02-09 17:58:24 -0800438 output.left_voltage = 0;
439 output.right_voltage = 0;
440 spline_drivetrain_.SetOutput(&output);
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800441 Eigen::Vector2d U(output.left_voltage, output.right_voltage);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800442
443 const ::Eigen::Matrix<double, 5, 1> goal_state =
444 spline_drivetrain_.CurrentGoalState();
445 simulation_t_.push_back(
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700446 ::aos::time::DurationInSeconds(t.time_since_epoch()));
James Kuszmaul1057ce82019-02-09 17:58:24 -0800447 spline_x_.push_back(goal_state(0, 0));
448 spline_y_.push_back(goal_state(1, 0));
449 simulation_x_.push_back(state(StateIdx::kX, 0));
450 simulation_y_.push_back(state(StateIdx::kY, 0));
451 simulation_theta_.push_back(state(StateIdx::kTheta, 0));
452 estimated_x_.push_back(known_state(0, 0));
453 estimated_y_.push_back(known_state(1, 0));
454 estimated_theta_.push_back(known_state(StateIdx::kTheta, 0));
455
456 simulation_vl_.push_back(U(0));
457 simulation_vr_.push_back(U(1));
458 U(0, 0) = ::std::max(::std::min(U(0, 0), 12.0), -12.0);
459 U(1, 0) = ::std::max(::std::min(U(1, 0), 12.0), -12.0);
460
461 state = ::frc971::control_loops::RungeKuttaU(
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800462 [this](const ::Eigen::Matrix<double, 12, 1> &X,
James Kuszmaul1057ce82019-02-09 17:58:24 -0800463 const ::Eigen::Matrix<double, 2, 1> &U) { return DiffEq(X, U); },
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700464 state, U, ::aos::time::DurationInSeconds(dt_config_.dt));
James Kuszmaul1057ce82019-02-09 17:58:24 -0800465
466 // Add arbitrary disturbances at some arbitrary interval. The main points of
467 // interest here are that we (a) stop adding disturbances at the very end of
468 // the trajectory, to allow us to actually converge to the goal, and (b)
469 // scale disturbances by the corruent velocity.
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800470 // TODO(james): Figure out how to persist good accelerometer values through
471 // the disturbances.
James Kuszmaulc73bb222019-04-07 12:15:35 -0700472 if (GetParam().disturb && i % 75 == 0) {
James Kuszmaul1057ce82019-02-09 17:58:24 -0800473 // Scale the disturbance so that when we have near-zero velocity we don't
474 // have much disturbance.
475 double disturbance_scale = ::std::min(
476 1.0, ::std::sqrt(::std::pow(state(StateIdx::kLeftVelocity, 0), 2) +
477 ::std::pow(state(StateIdx::kRightVelocity, 0), 2)) /
478 3.0);
479 TestLocalizer::State disturbance;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800480 disturbance << 0.02, 0.02, 0.001, 0.03, 0.02, 0.0, 0.0, 0.0, 0.0, 0.0,
481 0.0, 0.0;
James Kuszmaul1057ce82019-02-09 17:58:24 -0800482 disturbance *= disturbance_scale;
483 state += disturbance;
484 }
485
486 t += dt_config_.dt;
487 *true_robot_pose_.mutable_pos() << state(StateIdx::kX, 0),
488 state(StateIdx::kY, 0), 0.0;
489 true_robot_pose_.set_theta(state(StateIdx::kTheta, 0));
490 const double left_enc = state(StateIdx::kLeftEncoder, 0);
491 const double right_enc = state(StateIdx::kRightEncoder, 0);
492
Philipp Schrader790cb542023-07-05 21:06:52 -0700493 const double gyro =
494 (state(StateIdx::kRightVelocity) - state(StateIdx::kLeftVelocity)) /
495 dt_config_.robot_radius / 2.0;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800496 const TestLocalizer::State xdot = DiffEq(state, U);
497 const Eigen::Vector3d accel(
498 localizer_.CalcLongitudinalVelocity(xdot) -
499 gyro * state(StateIdx::kLateralVelocity),
500 gyro * localizer_.CalcLongitudinalVelocity(state), 1.0);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800501
502 localizer_.UpdateEncodersAndGyro(left_enc + Normal(encoder_noise_),
503 right_enc + Normal(encoder_noise_),
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800504 gyro + Normal(gyro_noise_), U, accel, t);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800505
James Kuszmaul6f941b72019-03-08 18:12:25 -0800506 for (size_t cam_idx = 0; cam_idx < camera_queues.size(); ++cam_idx) {
507 auto &camera_queue = camera_queues[cam_idx];
508 // Clear out the camera frames that we are ready to pass to the localizer.
509 while (!camera_queue.empty() && ::std::get<0>(camera_queue.front()) <
510 t - camera_latencies[cam_idx]) {
511 const auto tuple = camera_queue.front();
512 camera_queue.pop();
513 ::aos::monotonic_clock::time_point t_obs = ::std::get<0>(tuple);
514 const TestCamera *camera = ::std::get<1>(tuple);
515 ::aos::SizedArray<TestCamera::TargetView, kNumTargetsPerFrame> views =
516 ::std::get<2>(tuple);
517 localizer_.UpdateTargets(*camera, views, t_obs);
518 }
James Kuszmaul1057ce82019-02-09 17:58:24 -0800519
James Kuszmaul6f941b72019-03-08 18:12:25 -0800520 // Actually take all the images and store them in the queue.
521 if (i % camera_period == 0) {
522 for (size_t jj = 0; jj < true_cameras_.size(); ++jj) {
523 const auto target_views = true_cameras_[jj].target_views();
524 ::aos::SizedArray<TestCamera::TargetView, kNumTargetsPerFrame>
525 pass_views;
526 for (size_t ii = 0;
527 ii < ::std::min(kNumTargetsPerFrame, target_views.size());
528 ++ii) {
529 TestCamera::TargetView view = target_views[ii];
530 Noisify(&view);
531 pass_views.push_back(view);
532 }
533 camera_queue.emplace(t, &robot_cameras_[jj], pass_views);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800534 }
James Kuszmaul1057ce82019-02-09 17:58:24 -0800535 }
536 }
James Kuszmaul1057ce82019-02-09 17:58:24 -0800537 }
538
539 const auto end = ::std::chrono::steady_clock::now();
540 avg_time_ = (end - begin) / i;
541 TestLocalizer::State estimate_err = state - localizer_.X_hat();
542 EXPECT_LT(estimate_err.template topRows<7>().norm(),
543 GetParam().estimate_tolerance);
544 // Check that none of the states that we actually care about (x/y/theta, and
545 // wheel positions/speeds) are too far off, individually:
James Kuszmaul7f1a4082019-04-14 10:50:44 -0700546 EXPECT_LT(estimate_err.template topRows<3>().cwiseAbs().maxCoeff(),
James Kuszmaul1057ce82019-02-09 17:58:24 -0800547 GetParam().estimate_tolerance / 3.0)
548 << "Estimate error: " << estimate_err.transpose();
549 Eigen::Matrix<double, 5, 1> final_trajectory_state;
550 final_trajectory_state << state(StateIdx::kX, 0), state(StateIdx::kY, 0),
551 state(StateIdx::kTheta, 0), state(StateIdx::kLeftVelocity, 0),
552 state(StateIdx::kRightVelocity, 0);
553 const Eigen::Matrix<double, 5, 1> final_trajectory_state_err =
554 final_trajectory_state - spline_drivetrain_.CurrentGoalState();
555 EXPECT_LT(final_trajectory_state_err.norm(), GetParam().goal_tolerance)
556 << "Goal error: " << final_trajectory_state_err.transpose();
557}
558
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700559// NOTE: Following the 2019 season, we stopped maintaining this as rigorously.
560// This means that changes to either the base HybridEKF class or the spline
561// controller can cause us to violate the tolerances specified here. We
562// currently just up the tolerances whenever they cause issues, so long as
563// things don't appear to be unstable (since these tests do do a test of the
564// full localizer + spline system, we should pay attention if there is actual
565// instability rather than just poor tolerances).
James Kuszmaulf4bf9fe2021-05-10 22:58:24 -0700566INSTANTIATE_TEST_SUITE_P(
James Kuszmaul1057ce82019-02-09 17:58:24 -0800567 LocalizerTest, ParameterizedLocalizerTest,
568 ::testing::Values(
569 // Checks a "perfect" scenario, where we should track perfectly.
570 LocalizerTestParams({
571 /*control_pts_x=*/{{0.0, 3.0, 3.0, 0.0, 1.0, 1.0}},
572 /*control_pts_y=*/{{-5.0, -5.0, 2.0, 2.0, 2.0, 3.0}},
James Kuszmaul074429e2019-03-23 16:01:49 -0700573 (TestLocalizer::State() << 0.0, -5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800574 0.0, 0.0, 0.0, 0.0)
James Kuszmaul1057ce82019-02-09 17:58:24 -0800575 .finished(),
James Kuszmaul074429e2019-03-23 16:01:49 -0700576 (TestLocalizer::State() << 0.0, -5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800577 0.0, 0.0, 0.0, 0.0)
James Kuszmaul1057ce82019-02-09 17:58:24 -0800578 .finished(),
579 /*noisify=*/false,
580 /*disturb=*/false,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800581 /*estimate_tolerance=*/1e-2,
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700582 /*goal_tolerance=*/0.2,
James Kuszmaul1057ce82019-02-09 17:58:24 -0800583 }),
584 // Checks "perfect" estimation, but start off the spline and check
585 // that we can still follow it.
586 LocalizerTestParams({
587 /*control_pts_x=*/{{0.0, 3.0, 3.0, 0.0, 1.0, 1.0}},
588 /*control_pts_y=*/{{-5.0, -5.0, 2.0, 2.0, 2.0, 3.0}},
James Kuszmaul074429e2019-03-23 16:01:49 -0700589 (TestLocalizer::State() << 0.0, -4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800590 0.0, 0.0, 0.0, 0.0)
James Kuszmaul1057ce82019-02-09 17:58:24 -0800591 .finished(),
James Kuszmaul074429e2019-03-23 16:01:49 -0700592 (TestLocalizer::State() << 0.0, -4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800593 0.0, 0.0, 0.0, 0.0)
James Kuszmaul1057ce82019-02-09 17:58:24 -0800594 .finished(),
595 /*noisify=*/false,
596 /*disturb=*/false,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800597 /*estimate_tolerance=*/1e-2,
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700598 /*goal_tolerance=*/0.4,
James Kuszmaul1057ce82019-02-09 17:58:24 -0800599 }),
600 // Repeats perfect scenario, but add sensor noise.
601 LocalizerTestParams({
602 /*control_pts_x=*/{{0.0, 3.0, 3.0, 0.0, 1.0, 1.0}},
603 /*control_pts_y=*/{{-5.0, -5.0, 2.0, 2.0, 2.0, 3.0}},
James Kuszmaul074429e2019-03-23 16:01:49 -0700604 (TestLocalizer::State() << 0.0, -5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800605 0.0, 0.0, 0.0, 0.0)
James Kuszmaul1057ce82019-02-09 17:58:24 -0800606 .finished(),
James Kuszmaul074429e2019-03-23 16:01:49 -0700607 (TestLocalizer::State() << 0.0, -5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800608 0.0, 0.0, 0.0, 0.0)
James Kuszmaul1057ce82019-02-09 17:58:24 -0800609 .finished(),
610 /*noisify=*/true,
611 /*disturb=*/false,
James Kuszmaulea314d92019-02-18 19:45:06 -0800612 /*estimate_tolerance=*/0.4,
James Kuszmaul07b40442020-03-08 22:20:21 -0700613 /*goal_tolerance=*/0.8,
James Kuszmaul1057ce82019-02-09 17:58:24 -0800614 }),
615 // Repeats perfect scenario, but add initial estimator error.
616 LocalizerTestParams({
617 /*control_pts_x=*/{{0.0, 3.0, 3.0, 0.0, 1.0, 1.0}},
618 /*control_pts_y=*/{{-5.0, -5.0, 2.0, 2.0, 2.0, 3.0}},
James Kuszmaul074429e2019-03-23 16:01:49 -0700619 (TestLocalizer::State() << 0.0, -5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800620 0.0, 0.0, 0.0, 0.0)
James Kuszmaul1057ce82019-02-09 17:58:24 -0800621 .finished(),
James Kuszmaul074429e2019-03-23 16:01:49 -0700622 (TestLocalizer::State() << 0.1, -5.1, -0.01, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800623 0.0, 0.0, 0.0, 0.0, 0.0)
James Kuszmaul074429e2019-03-23 16:01:49 -0700624 .finished(),
625 /*noisify=*/false,
626 /*disturb=*/false,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800627 /*estimate_tolerance=*/1e-2,
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700628 /*goal_tolerance=*/0.2,
James Kuszmaul074429e2019-03-23 16:01:49 -0700629 }),
630 // Repeats perfect scenario, but add voltage + angular errors:
631 LocalizerTestParams({
632 /*control_pts_x=*/{{0.0, 3.0, 3.0, 0.0, 1.0, 1.0}},
633 /*control_pts_y=*/{{-5.0, -5.0, 2.0, 2.0, 2.0, 3.0}},
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700634 (TestLocalizer::State() << 0.0, -5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5,
635 0.25, 0.02, 0.0, 0.0)
James Kuszmaul074429e2019-03-23 16:01:49 -0700636 .finished(),
637 (TestLocalizer::State() << 0.1, -5.1, -0.01, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800638 0.0, 0.0, 0.0, 0.0, 0.0)
James Kuszmaul1057ce82019-02-09 17:58:24 -0800639 .finished(),
640 /*noisify=*/false,
641 /*disturb=*/false,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800642 /*estimate_tolerance=*/1e-2,
James Kuszmaulad394ac2024-04-05 17:31:44 -0700643 /*goal_tolerance=*/0.6,
James Kuszmaul1057ce82019-02-09 17:58:24 -0800644 }),
645 // Add disturbances while we are driving:
646 LocalizerTestParams({
647 /*control_pts_x=*/{{0.0, 3.0, 3.0, 0.0, 1.0, 1.0}},
648 /*control_pts_y=*/{{-5.0, -5.0, 2.0, 2.0, 2.0, 3.0}},
James Kuszmaul074429e2019-03-23 16:01:49 -0700649 (TestLocalizer::State() << 0.0, -5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800650 0.0, 0.0, 0.0, 0.0)
James Kuszmaul1057ce82019-02-09 17:58:24 -0800651 .finished(),
James Kuszmaul074429e2019-03-23 16:01:49 -0700652 (TestLocalizer::State() << 0.0, -5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800653 0.0, 0.0, 0.0, 0.0)
James Kuszmaul1057ce82019-02-09 17:58:24 -0800654 .finished(),
655 /*noisify=*/false,
656 /*disturb=*/true,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800657 /*estimate_tolerance=*/4e-2,
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700658 /*goal_tolerance=*/0.25,
James Kuszmaul1057ce82019-02-09 17:58:24 -0800659 }),
660 // Add noise and some initial error in addition:
661 LocalizerTestParams({
662 /*control_pts_x=*/{{0.0, 3.0, 3.0, 0.0, 1.0, 1.0}},
663 /*control_pts_y=*/{{-5.0, -5.0, 2.0, 2.0, 2.0, 3.0}},
James Kuszmaul074429e2019-03-23 16:01:49 -0700664 (TestLocalizer::State() << 0.0, -5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800665 0.0, 0.0, 0.0, 0.0)
James Kuszmaul1057ce82019-02-09 17:58:24 -0800666 .finished(),
James Kuszmaul074429e2019-03-23 16:01:49 -0700667 (TestLocalizer::State() << 0.1, -5.1, 0.03, 0.0, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800668 0.0, 0.0, 0.0, 0.0)
James Kuszmaul1057ce82019-02-09 17:58:24 -0800669 .finished(),
670 /*noisify=*/true,
671 /*disturb=*/true,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800672 /*estimate_tolerance=*/0.5,
673 /*goal_tolerance=*/1.0,
James Kuszmaul1057ce82019-02-09 17:58:24 -0800674 }),
675 // Try another spline, just in case the one I was using is special for
676 // some reason; this path will also go straight up to a target, to
677 // better simulate what might happen when trying to score:
678 LocalizerTestParams({
679 /*control_pts_x=*/{{0.5, 3.5, 4.0, 8.0, 11.0, 10.2}},
680 /*control_pts_y=*/{{1.0, 1.0, -3.0, -2.0, -3.5, -3.65}},
James Kuszmaul074429e2019-03-23 16:01:49 -0700681 (TestLocalizer::State() << 0.6, 1.01, 0.01, 0.0, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800682 0.0, 0.0, 0.0, 0.0)
James Kuszmaul1057ce82019-02-09 17:58:24 -0800683 .finished(),
James Kuszmaul074429e2019-03-23 16:01:49 -0700684 (TestLocalizer::State() << 0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800685 0.0, 0.0, 0.0, 0.0)
James Kuszmaul1057ce82019-02-09 17:58:24 -0800686 .finished(),
687 /*noisify=*/true,
688 /*disturb=*/false,
James Kuszmaul7f1a4082019-04-14 10:50:44 -0700689 // TODO(james): Improve tests so that we aren't constantly
690 // readjusting the tolerances up.
James Kuszmaulc40c26e2019-03-24 16:26:43 -0700691 /*estimate_tolerance=*/0.3,
James Kuszmaul074429e2019-03-23 16:01:49 -0700692 /*goal_tolerance=*/0.7,
James Kuszmaul1057ce82019-02-09 17:58:24 -0800693 })));
694
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800695} // namespace y2019::control_loops::testing