blob: 818e1b94d66e24405a7526ea2638615a539c569f [file] [log] [blame]
James Kuszmaul1057ce82019-02-09 17:58:24 -08001#ifndef Y2019_CONTROL_LOOPS_DRIVETRAIN_LOCALIZATER_H_
2#define Y2019_CONTROL_LOOPS_DRIVETRAIN_LOCALIZATER_H_
3
4#include <cmath>
5#include <memory>
6
James Kuszmaulf4ede202020-02-14 08:47:40 -08007#include "frc971/control_loops/drivetrain/camera.h"
James Kuszmaul1057ce82019-02-09 17:58:24 -08008#include "frc971/control_loops/drivetrain/hybrid_ekf.h"
James Kuszmaul2971b5a2023-01-29 15:49:32 -08009#include "frc971/control_loops/pose.h"
James Kuszmaul1057ce82019-02-09 17:58:24 -080010
Austin Schuh9f45d702023-05-06 22:18:10 -070011#if !defined(__clang__) && defined(__GNUC__)
12// GCC miss-detects that when zero is set to true, the member variables could be
13// uninitialized. Rather than spend the CPU to initialize them in addition to
14// the memory for no good reason, tell GCC to stop doing that. Clang appears to
15// get it.
16#pragma GCC diagnostic push
17#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
18#endif
19
James Kuszmaul1057ce82019-02-09 17:58:24 -080020namespace y2019 {
21namespace control_loops {
22
23template <int num_cameras, int num_targets, int num_obstacles,
24 int max_targets_per_frame, typename Scalar = double>
25class TypedLocalizer
26 : public ::frc971::control_loops::drivetrain::HybridEkf<Scalar> {
27 public:
James Kuszmaulf4ede202020-02-14 08:47:40 -080028 typedef frc971::control_loops::TypedCamera<num_targets, num_obstacles, Scalar>
29 Camera;
James Kuszmaul1057ce82019-02-09 17:58:24 -080030 typedef typename Camera::TargetView TargetView;
31 typedef typename Camera::Pose Pose;
James Kuszmaulf4ede202020-02-14 08:47:40 -080032 typedef typename frc971::control_loops::Target Target;
James Kuszmaul1057ce82019-02-09 17:58:24 -080033 typedef ::frc971::control_loops::drivetrain::HybridEkf<Scalar> HybridEkf;
34 typedef typename HybridEkf::State State;
35 typedef typename HybridEkf::StateSquare StateSquare;
36 typedef typename HybridEkf::Input Input;
37 typedef typename HybridEkf::Output Output;
38 using HybridEkf::kNInputs;
39 using HybridEkf::kNOutputs;
40 using HybridEkf::kNStates;
41
42 // robot_pose should be the object that is used by the cameras, such that when
43 // we update robot_pose, the cameras will change what they report the relative
44 // position of the targets as.
45 // Note that the parameters for the cameras should be set to allow slightly
46 // larger fields of view and slightly longer range than the true cameras so
47 // that we can identify potential matches for targets even when we have slight
48 // modelling errors.
49 TypedLocalizer(
50 const ::frc971::control_loops::drivetrain::DrivetrainConfig<Scalar>
51 &dt_config,
52 Pose *robot_pose)
53 : ::frc971::control_loops::drivetrain::HybridEkf<Scalar>(dt_config),
James Kuszmaul2971b5a2023-01-29 15:49:32 -080054 robot_pose_(robot_pose),
55 h_queue_(this),
56 make_h_queue_(this) {}
James Kuszmaul1057ce82019-02-09 17:58:24 -080057
58 // Performs a kalman filter correction with a single camera frame, consisting
59 // of up to max_targets_per_frame targets and taken at time t.
60 // camera is the Camera used to take the images.
61 void UpdateTargets(
62 const Camera &camera,
63 const ::aos::SizedArray<TargetView, max_targets_per_frame> &targets,
64 ::aos::monotonic_clock::time_point t) {
65 if (targets.empty()) {
66 return;
67 }
68
James Kuszmaul6f941b72019-03-08 18:12:25 -080069 if (!SanitizeTargets(targets)) {
Austin Schuhf257f3c2019-10-27 21:00:43 -070070 AOS_LOG(ERROR, "Throwing out targets due to in insane values.\n");
James Kuszmaul6f941b72019-03-08 18:12:25 -080071 return;
72 }
73
James Kuszmaul1057ce82019-02-09 17:58:24 -080074 if (t > HybridEkf::latest_t()) {
Austin Schuhf257f3c2019-10-27 21:00:43 -070075 AOS_LOG(ERROR,
76 "target observations must be older than most recent encoder/gyro "
77 "update.\n");
James Kuszmaul1057ce82019-02-09 17:58:24 -080078 return;
79 }
80
81 Output z;
82 Eigen::Matrix<Scalar, kNOutputs, kNOutputs> R;
83 TargetViewToMatrices(targets[0], &z, &R);
84
85 // In order to perform the correction steps for the targets, we will
86 // separately perform a Correct step for each following target.
87 // This way, we can have the first correction figure out the mappings
88 // between targets in the image and targets on the field, and then re-use
89 // those mappings for all the remaining corrections.
90 // As such, we need to store the EKF functions that the remaining targets
91 // will need in arrays:
Austin Schuh9f45d702023-05-06 22:18:10 -070092 ::aos::SizedArray<HFunction, max_targets_per_frame> h_functions;
93 ::aos::SizedArray<Eigen::Matrix<Scalar, kNOutputs, kNStates>,
James Kuszmaul2971b5a2023-01-29 15:49:32 -080094 max_targets_per_frame>
Austin Schuh9f45d702023-05-06 22:18:10 -070095 dhdx;
James Kuszmaul2971b5a2023-01-29 15:49:32 -080096 make_h_queue_.CorrectKnownHBuilder(
James Kuszmaul1057ce82019-02-09 17:58:24 -080097 z, nullptr,
James Kuszmaul2971b5a2023-01-29 15:49:32 -080098 ExpectedObservationBuilder(this, camera, targets, &h_functions,
Austin Schuh9f45d702023-05-06 22:18:10 -070099 &dhdx),
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800100 R, t);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800101 // Fetch cache:
102 for (size_t ii = 1; ii < targets.size(); ++ii) {
103 TargetViewToMatrices(targets[ii], &z, &R);
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800104 h_queue_.CorrectKnownH(
105 z, nullptr,
Austin Schuh9f45d702023-05-06 22:18:10 -0700106 ExpectedObservationFunctor(h_functions[ii], dhdx[ii]), R,
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800107 t);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800108 }
109 }
110
111 private:
Austin Schuh9f45d702023-05-06 22:18:10 -0700112 class HFunction {
113 public:
114 HFunction() : zero_(true) {}
115 HFunction(const Camera *camera, const TargetView &best_view,
116 const TargetView &target_view, TypedLocalizer *localizer)
117 : zero_(false),
118 camera_(camera),
119 best_view_(best_view),
120 target_view_(target_view),
121 localizer_(localizer) {}
122 Output operator()(const State &X, const Input &) {
123 if (zero_) {
124 return Output::Zero();
125 }
126
127 // This function actually handles determining what the Output should
128 // be at a given state, now that we have chosen the target that
129 // we want to match to.
130 *localizer_->robot_pose_->mutable_pos() << X(0, 0), X(1, 0), 0.0;
131 localizer_->robot_pose_->set_theta(X(2, 0));
132 const Pose relative_pose =
133 best_view_.target->pose().Rebase(&camera_->pose());
134 const Scalar heading = relative_pose.heading();
135 const Scalar distance = relative_pose.xy_norm();
136 const Scalar skew =
137 ::aos::math::NormalizeAngle(relative_pose.rel_theta() - heading);
138 return Output(heading, distance, skew);
139 }
140
141 private:
142 bool zero_ = false;
143
144 const Camera *camera_;
145 TargetView best_view_;
146 TargetView target_view_;
147 TypedLocalizer *localizer_;
148 };
149
150 friend class HFunction;
151
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800152 class ExpectedObservationFunctor
153 : public HybridEkf::ExpectedObservationFunctor {
154 public:
Austin Schuh9f45d702023-05-06 22:18:10 -0700155 ExpectedObservationFunctor(const HFunction &h,
156 Eigen::Matrix<Scalar, kNOutputs, kNStates> dhdx)
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800157 : h_(h), dhdx_(dhdx) {}
158
159 Output H(const State &state, const Input &input) final {
160 return h_(state, input);
161 }
162
163 virtual Eigen::Matrix<Scalar, kNOutputs, kNStates> DHDX(
Austin Schuh9f45d702023-05-06 22:18:10 -0700164 const State &) final {
165 return dhdx_;
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800166 }
167
168 private:
Austin Schuh9f45d702023-05-06 22:18:10 -0700169 HFunction h_;
170 Eigen::Matrix<Scalar, kNOutputs, kNStates> dhdx_;
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800171 };
172 class ExpectedObservationBuilder
173 : public HybridEkf::ExpectedObservationBuilder {
174 public:
175 ExpectedObservationBuilder(
176 TypedLocalizer *localizer, const Camera &camera,
177 const ::aos::SizedArray<TargetView, max_targets_per_frame>
178 &target_views,
Austin Schuh9f45d702023-05-06 22:18:10 -0700179 ::aos::SizedArray<HFunction, max_targets_per_frame> *h_functions,
180 ::aos::SizedArray<Eigen::Matrix<Scalar, kNOutputs, kNStates>,
181 max_targets_per_frame> *dhdx)
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800182 : localizer_(localizer),
183 camera_(camera),
184 target_views_(target_views),
185 h_functions_(h_functions),
Austin Schuh9f45d702023-05-06 22:18:10 -0700186 dhdx_(dhdx) {}
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800187
188 virtual ExpectedObservationFunctor *MakeExpectedObservations(
189 const State &state, const StateSquare &P) {
Austin Schuh9f45d702023-05-06 22:18:10 -0700190 HFunction h;
191 Eigen::Matrix<Scalar, kNOutputs, kNStates> dhdx;
192 localizer_->MakeH(camera_, target_views_, h_functions_, dhdx_,
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800193 state, P, &h, &dhdx);
194 functor_.emplace(h, dhdx);
195 return &functor_.value();
196 }
197
198 private:
199 TypedLocalizer *localizer_;
200 const Camera &camera_;
201 const ::aos::SizedArray<TargetView, max_targets_per_frame> &target_views_;
Austin Schuh9f45d702023-05-06 22:18:10 -0700202 ::aos::SizedArray<HFunction, max_targets_per_frame> *h_functions_;
203 ::aos::SizedArray<Eigen::Matrix<Scalar, kNOutputs, kNStates>,
204 max_targets_per_frame> *dhdx_;
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800205 std::optional<ExpectedObservationFunctor> functor_;
206 };
Austin Schuh9f45d702023-05-06 22:18:10 -0700207
James Kuszmaul1057ce82019-02-09 17:58:24 -0800208 // The threshold to use for completely rejecting potentially bad target
209 // matches.
210 // TODO(james): Tune
Austin Schuh113a85d2019-03-28 17:18:08 -0700211 static constexpr Scalar kRejectionScore = 1.0;
James Kuszmaul1057ce82019-02-09 17:58:24 -0800212
James Kuszmaul6f941b72019-03-08 18:12:25 -0800213 // Checks that the targets coming in make some sense--mostly to prevent NaNs
214 // or the such from propagating.
215 bool SanitizeTargets(
216 const ::aos::SizedArray<TargetView, max_targets_per_frame> &targets) {
217 for (const TargetView &view : targets) {
218 const typename TargetView::Reading reading = view.reading;
219 if (!(::std::isfinite(reading.heading) &&
220 ::std::isfinite(reading.distance) &&
221 ::std::isfinite(reading.skew) && ::std::isfinite(reading.height))) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700222 AOS_LOG(ERROR, "Got non-finite values in target.\n");
James Kuszmaul6f941b72019-03-08 18:12:25 -0800223 return false;
224 }
225 if (reading.distance < 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700226 AOS_LOG(ERROR, "Got negative distance.\n");
James Kuszmaul6f941b72019-03-08 18:12:25 -0800227 return false;
228 }
229 if (::std::abs(::aos::math::NormalizeAngle(reading.skew)) > M_PI_2) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700230 AOS_LOG(ERROR, "Got skew > pi / 2.\n");
James Kuszmaul6f941b72019-03-08 18:12:25 -0800231 return false;
232 }
233 }
234 return true;
235 }
236
James Kuszmaul1057ce82019-02-09 17:58:24 -0800237 // Computes the measurement (z) and noise covariance (R) matrices for a given
238 // TargetView.
239 void TargetViewToMatrices(const TargetView &view, Output *z,
240 Eigen::Matrix<Scalar, kNOutputs, kNOutputs> *R) {
James Kuszmaul6f941b72019-03-08 18:12:25 -0800241 *z << view.reading.heading, view.reading.distance,
242 ::aos::math::NormalizeAngle(view.reading.skew);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800243 // TODO(james): R should account as well for our confidence in the target
244 // matching. However, handling that properly requires thing a lot more about
245 // the probabilities.
246 R->setZero();
247 R->diagonal() << ::std::pow(view.noise.heading, 2),
248 ::std::pow(view.noise.distance, 2), ::std::pow(view.noise.skew, 2);
249 }
250
251 // This is the function that will be called once the Ekf has inserted the
252 // measurement into the right spot in the measurement queue and needs the
253 // output functions to actually perform the corrections.
254 // Specifically, this will take the estimate of the state at that time and
255 // figure out how the targets seen by the camera best map onto the actual
256 // targets on the field.
257 // It then fills in the h and dhdx functions that are called by the Ekf.
258 void MakeH(
259 const Camera &camera,
260 const ::aos::SizedArray<TargetView, max_targets_per_frame> &target_views,
Austin Schuh9f45d702023-05-06 22:18:10 -0700261 ::aos::SizedArray<HFunction, max_targets_per_frame> *h_functions,
262 ::aos::SizedArray<Eigen::Matrix<Scalar, kNOutputs, kNStates>,
263 max_targets_per_frame> *dhdx,
264 const State &X_hat, const StateSquare &P, HFunction *h,
265 Eigen::Matrix<Scalar, kNOutputs, kNStates> *current_dhdx) {
James Kuszmaul1057ce82019-02-09 17:58:24 -0800266 // Because we need to match camera targets ("views") to actual field
267 // targets, and because we want to take advantage of the correlations
268 // between the targets (i.e., if we see two targets in the image, they
269 // probably correspond to different on-field targets), the matching problem
270 // here is somewhat non-trivial. Some of the methods we use only work
271 // because we are dealing with very small N (e.g., handling the correlations
272 // between multiple views has combinatoric complexity, but since N = 3,
273 // it's not an issue).
274 //
275 // High-level steps:
276 // 1) Set the base robot pose for the cameras to the Pose implied by X_hat.
277 // 2) Fetch all the expected target views from the camera.
278 // 3) Determine the "magnitude" of the Kalman correction from each potential
279 // view/target pair.
280 // 4) Match based on the combination of targets with the smallest
281 // corrections.
282 // 5) Calculate h and dhdx for each pair of targets.
283 //
284 // For the "magnitude" of the correction, we do not directly use the
285 // standard Kalman correction formula. Instead, we calculate the correction
286 // we would get from each component of the measurement and take the L2 norm
287 // of those. This prevents situations where a target matches very poorly but
288 // produces an overall correction of near-zero.
289 // TODO(james): I do not know if this is strictly the correct method to
290 // minimize likely error, but should be reasonable.
291 //
292 // For the matching, we do the following (see MatchFrames):
293 // 1. Compute the best max_targets_per_frame matches for each view.
294 // 2. Exhaust every possible combination of view/target pairs and
295 // choose the best one.
296 // When we don't think the camera should be able to see as many targets as
297 // we actually got in the frame, then we do permit doubling/tripling/etc.
298 // up on potential targets once we've exhausted all the targets we think
299 // we can see.
300
301 // Set the current robot pose so that the cameras know where they are
302 // (all the cameras have robot_pose_ as their base):
303 *robot_pose_->mutable_pos() << X_hat(0, 0), X_hat(1, 0), 0.0;
304 robot_pose_->set_theta(X_hat(2, 0));
305
306 // Compute the things we *think* the camera should be seeing.
307 // Note: Because we will not try to match to any targets that are not
308 // returned by this function, we generally want the modelled camera to have
309 // a slightly larger field of view than the real camera, and be able to see
310 // slightly smaller targets.
311 const ::aos::SizedArray<TargetView, num_targets> camera_views =
312 camera.target_views();
313
314 // Each row contains the scores for each pair of target view and camera
315 // target view. Values in each row will not be populated past
316 // camera.target_views().size(); of the rows, only the first
317 // target_views.size() shall be populated.
318 // Higher scores imply a worse match. Zero implies a perfect match.
319 Eigen::Matrix<Scalar, max_targets_per_frame, num_targets> scores;
320 scores.setConstant(::std::numeric_limits<Scalar>::infinity());
321 // Each row contains the indices of the best matches per view, where
322 // index 0 is the best, 1 the second best, and 2 the third, etc.
323 // -1 indicates an unfilled field.
324 Eigen::Matrix<int, max_targets_per_frame, max_targets_per_frame>
325 best_matches;
326 best_matches.setConstant(-1);
327 // The H matrices for each potential matching. This has the same structure
328 // as the scores matrix.
329 ::std::array<::std::array<Eigen::Matrix<Scalar, kNOutputs, kNStates>,
330 max_targets_per_frame>,
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800331 num_targets>
332 all_H_matrices;
James Kuszmaul1057ce82019-02-09 17:58:24 -0800333
334 // Iterate through and fill out the scores for each potential pairing:
335 for (size_t ii = 0; ii < target_views.size(); ++ii) {
336 const TargetView &target_view = target_views[ii];
337 Output z;
338 Eigen::Matrix<Scalar, kNOutputs, kNOutputs> R;
339 TargetViewToMatrices(target_view, &z, &R);
340
341 for (size_t jj = 0; jj < camera_views.size(); ++jj) {
342 // Compute the ckalman update for this step:
343 const TargetView &view = camera_views[jj];
344 const Eigen::Matrix<Scalar, kNOutputs, kNStates> H =
James Kuszmaul46f3a212019-03-10 10:14:24 -0700345 HMatrix(*view.target, camera.pose());
James Kuszmaul1057ce82019-02-09 17:58:24 -0800346 const Eigen::Matrix<Scalar, kNStates, kNOutputs> PH = P * H.transpose();
347 const Eigen::Matrix<Scalar, kNOutputs, kNOutputs> S = H * PH + R;
348 // Note: The inverse here should be very cheap so long as kNOutputs = 3.
349 const Eigen::Matrix<Scalar, kNStates, kNOutputs> K = PH * S.inverse();
350 const Output err = z - Output(view.reading.heading,
351 view.reading.distance, view.reading.skew);
352 // In order to compute the actual score, we want to consider each
353 // component of the error separately, as well as considering the impacts
354 // on the each of the states separately. As such, we calculate what
355 // the separate updates from each error component would be, and sum
356 // the impacts on the states.
357 Output scorer;
358 for (size_t kk = 0; kk < kNOutputs; ++kk) {
359 // TODO(james): squaredNorm or norm or L1-norm? Do we care about the
360 // square root? Do we prefer a quadratic or linear response?
361 scorer(kk, 0) = (K.col(kk) * err(kk, 0)).squaredNorm();
362 }
363 // Compute the overall score--note that we add in a term for the height,
364 // scaled by a manual fudge-factor. The height is not accounted for
365 // in the Kalman update because we are not trying to estimate the height
366 // of the robot directly.
367 Scalar score =
368 scorer.squaredNorm() +
369 ::std::pow((view.reading.height - target_view.reading.height) /
370 target_view.noise.height / 20.0,
371 2);
372 scores(ii, jj) = score;
373 all_H_matrices[ii][jj] = H;
374
375 // Update the best_matches matrix:
376 int insert_target = jj;
377 for (size_t kk = 0; kk < max_targets_per_frame; ++kk) {
378 int idx = best_matches(ii, kk);
379 // Note that -1 indicates an unfilled value.
380 if (idx == -1 || scores(ii, idx) > scores(ii, insert_target)) {
381 best_matches(ii, kk) = insert_target;
382 insert_target = idx;
383 if (idx == -1) {
384 break;
385 }
386 }
387 }
388 }
389 }
390
391 if (camera_views.size() == 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700392 AOS_LOG(DEBUG, "Unable to identify potential target matches.\n");
James Kuszmaul1057ce82019-02-09 17:58:24 -0800393 // If we can't get a match, provide H = zero, which will make this
394 // correction step a nop.
Austin Schuh9f45d702023-05-06 22:18:10 -0700395 *h = HFunction();
396 *current_dhdx = Eigen::Matrix<Scalar, kNOutputs, kNStates>::Zero();
James Kuszmaul1057ce82019-02-09 17:58:24 -0800397 for (size_t ii = 0; ii < target_views.size(); ++ii) {
398 h_functions->push_back(*h);
Austin Schuh9f45d702023-05-06 22:18:10 -0700399 dhdx->push_back(*current_dhdx);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800400 }
401 } else {
402 // Go through and brute force the issue of what the best combination of
403 // target matches are. The worst case for this algorithm will be
404 // max_targets_per_frame!, which is awful for any N > ~4, but since
405 // max_targets_per_frame = 3, I'm not really worried.
406 ::std::array<int, max_targets_per_frame> best_frames =
407 MatchFrames(scores, best_matches, target_views.size());
408 for (size_t ii = 0; ii < target_views.size(); ++ii) {
James Kuszmaul6f941b72019-03-08 18:12:25 -0800409 size_t view_idx = best_frames[ii];
James Kuszmaul9776b392023-01-14 14:08:08 -0800410 if (view_idx >= camera_views.size()) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700411 AOS_LOG(ERROR, "Somehow, the view scorer failed.\n");
Austin Schuh9f45d702023-05-06 22:18:10 -0700412 h_functions->emplace_back();
413 dhdx->push_back(
414 Eigen::Matrix<Scalar, kNOutputs, kNStates>::Zero());
James Kuszmaul6f941b72019-03-08 18:12:25 -0800415 continue;
416 }
James Kuszmaul1057ce82019-02-09 17:58:24 -0800417 const Eigen::Matrix<Scalar, kNOutputs, kNStates> best_H =
418 all_H_matrices[ii][view_idx];
419 const TargetView best_view = camera_views[view_idx];
420 const TargetView target_view = target_views[ii];
421 const Scalar match_score = scores(ii, view_idx);
422 if (match_score > kRejectionScore) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700423 AOS_LOG(DEBUG,
424 "Rejecting target at (%f, %f, %f, %f) due to high score.\n",
425 target_view.reading.heading, target_view.reading.distance,
426 target_view.reading.skew, target_view.reading.height);
Austin Schuh9f45d702023-05-06 22:18:10 -0700427 h_functions->emplace_back();
428 dhdx->push_back(Eigen::Matrix<Scalar, kNOutputs, kNStates>::Zero());
James Kuszmaul1057ce82019-02-09 17:58:24 -0800429 } else {
Austin Schuh9f45d702023-05-06 22:18:10 -0700430 h_functions->emplace_back(&camera, best_view, target_view, this);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800431
432 // TODO(james): Experiment to better understand whether we want to
433 // recalculate H or not.
Austin Schuh9f45d702023-05-06 22:18:10 -0700434 dhdx->push_back(best_H);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800435 }
436 }
437 *h = h_functions->at(0);
Austin Schuh9f45d702023-05-06 22:18:10 -0700438 *current_dhdx = dhdx->at(0);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800439 }
440 }
441
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800442 Eigen::Matrix<Scalar, kNOutputs, kNStates> HMatrix(const Target &target,
443 const Pose &camera_pose) {
James Kuszmaul1057ce82019-02-09 17:58:24 -0800444 // To calculate dheading/d{x,y,theta}:
445 // heading = arctan2(target_pos - camera_pos) - camera_theta
446 Eigen::Matrix<Scalar, 3, 1> target_pos = target.pose().abs_pos();
James Kuszmaul46f3a212019-03-10 10:14:24 -0700447 Eigen::Matrix<Scalar, 3, 1> camera_pos = camera_pose.abs_pos();
James Kuszmaul1057ce82019-02-09 17:58:24 -0800448 Scalar diffx = target_pos.x() - camera_pos.x();
449 Scalar diffy = target_pos.y() - camera_pos.y();
450 Scalar norm2 = diffx * diffx + diffy * diffy;
451 Scalar dheadingdx = diffy / norm2;
452 Scalar dheadingdy = -diffx / norm2;
453 Scalar dheadingdtheta = -1.0;
454
455 // To calculate ddistance/d{x,y}:
456 // distance = sqrt(diffx^2 + diffy^2)
457 Scalar distance = ::std::sqrt(norm2);
458 Scalar ddistdx = -diffx / distance;
459 Scalar ddistdy = -diffy / distance;
460
James Kuszmaul289756f2019-03-05 21:52:10 -0800461 // Skew = target.theta - camera.theta - heading
462 // = target.theta - arctan2(target_pos - camera_pos)
463 Scalar dskewdx = -dheadingdx;
464 Scalar dskewdy = -dheadingdy;
James Kuszmaul1057ce82019-02-09 17:58:24 -0800465 Eigen::Matrix<Scalar, kNOutputs, kNStates> H;
466 H.setZero();
467 H(0, 0) = dheadingdx;
468 H(0, 1) = dheadingdy;
469 H(0, 2) = dheadingdtheta;
470 H(1, 0) = ddistdx;
471 H(1, 1) = ddistdy;
James Kuszmaul289756f2019-03-05 21:52:10 -0800472 H(2, 0) = dskewdx;
473 H(2, 1) = dskewdy;
James Kuszmaul1057ce82019-02-09 17:58:24 -0800474 return H;
475 }
476
477 // A helper function for the fuller version of MatchFrames; this just
478 // removes some of the arguments that are only needed during the recursion.
479 // n_views is the number of targets actually seen in the camera image (i.e.,
480 // the number of rows in scores/best_matches that are actually populated).
481 ::std::array<int, max_targets_per_frame> MatchFrames(
482 const Eigen::Matrix<Scalar, max_targets_per_frame, num_targets> &scores,
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800483 const Eigen::Matrix<int, max_targets_per_frame, max_targets_per_frame>
484 &best_matches,
James Kuszmaul1057ce82019-02-09 17:58:24 -0800485 int n_views) {
486 ::std::array<int, max_targets_per_frame> best_set;
James Kuszmaul6f941b72019-03-08 18:12:25 -0800487 best_set.fill(-1);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800488 Scalar best_score;
489 // We start out without having "used" any views/targets:
490 ::aos::SizedArray<bool, max_targets_per_frame> used_views;
491 for (int ii = 0; ii < n_views; ++ii) {
492 used_views.push_back(false);
493 }
494 MatchFrames(scores, best_matches, used_views, {{false}}, &best_set,
495 &best_score);
496 return best_set;
497 }
498
499 // Recursively iterates over every plausible combination of targets/views
500 // that there is and determines the lowest-scoring combination.
501 // used_views and used_targets indicate which rows/columns of the
502 // scores/best_matches matrices should be ignored. When used_views is all
503 // true, that means that we are done recursing.
504 void MatchFrames(
505 const Eigen::Matrix<Scalar, max_targets_per_frame, num_targets> &scores,
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800506 const Eigen::Matrix<int, max_targets_per_frame, max_targets_per_frame>
507 &best_matches,
James Kuszmaul1057ce82019-02-09 17:58:24 -0800508 const ::aos::SizedArray<bool, max_targets_per_frame> &used_views,
509 const ::std::array<bool, num_targets> &used_targets,
510 ::std::array<int, max_targets_per_frame> *best_set, Scalar *best_score) {
511 *best_score = ::std::numeric_limits<Scalar>::infinity();
512 // Iterate by letting each target in the camera frame (that isn't in
513 // used_views) choose it's best match that isn't already taken. We then set
514 // the appropriate flags in used_views and used_targets and call MatchFrames
515 // to let all the other views sort themselves out.
516 for (size_t ii = 0; ii < used_views.size(); ++ii) {
517 if (used_views[ii]) {
518 continue;
519 }
520 int best_match = -1;
521 for (size_t jj = 0; jj < max_targets_per_frame; ++jj) {
522 if (best_matches(ii, jj) == -1) {
523 // If we run out of potential targets from the camera, then there
524 // are more targets in the frame than we think there should be.
525 // In this case, we are going to be doubling/tripling/etc. up
526 // anyhow. So we just give everyone their top choice:
527 // TODO(james): If we ever are dealing with larger numbers of
528 // targets per frame, do something to minimize doubling-up.
529 best_match = best_matches(ii, 0);
530 break;
531 }
532 best_match = best_matches(ii, jj);
533 if (!used_targets[best_match]) {
534 break;
535 }
536 }
537 // If we reach here and best_match = -1, that means that no potential
538 // targets were generated by the camera, and we should never have gotten
539 // here.
Austin Schuhf257f3c2019-10-27 21:00:43 -0700540 AOS_CHECK(best_match != -1);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800541 ::aos::SizedArray<bool, max_targets_per_frame> sub_views = used_views;
542 sub_views[ii] = true;
543 ::std::array<bool, num_targets> sub_targets = used_targets;
544 sub_targets[best_match] = true;
545 ::std::array<int, max_targets_per_frame> sub_best_set;
546 Scalar score;
547 MatchFrames(scores, best_matches, sub_views, sub_targets, &sub_best_set,
548 &score);
549 score += scores(ii, best_match);
550 sub_best_set[ii] = best_match;
551 if (score < *best_score) {
552 *best_score = score;
553 *best_set = sub_best_set;
554 }
555 }
556 // best_score will be infinite if we did not find a result due to there
557 // being no targets that weren't set in used_vies; this is the
558 // base case of the recursion and so we set best_score to zero:
559 if (!::std::isfinite(*best_score)) {
560 *best_score = 0.0;
561 }
562 }
563
564 // The pose that is used by the cameras to determine the location of the robot
565 // and thus the expected view of the targets.
566 Pose *robot_pose_;
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800567
568 typename HybridEkf::template ExpectedObservationAllocator<
569 ExpectedObservationFunctor>
570 h_queue_;
571 typename HybridEkf::template ExpectedObservationAllocator<
572 ExpectedObservationBuilder>
573 make_h_queue_;
574
575 friend class ExpectedObservationBuilder;
Austin Schuh9f45d702023-05-06 22:18:10 -0700576};
577
578#if !defined(__clang__) && defined(__GNUC__)
579#pragma GCC diagnostic pop
580#endif
James Kuszmaul1057ce82019-02-09 17:58:24 -0800581
582} // namespace control_loops
583} // namespace y2019
584
585#endif // Y2019_CONTROL_LOOPS_DRIVETRAIN_LOCALIZATER_H_