blob: b717837b729c880cd8a17b52dda97ab6d46d91d2 [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
7#include "frc971/control_loops/pose.h"
8#include "y2019/control_loops/drivetrain/camera.h"
9#include "frc971/control_loops/drivetrain/hybrid_ekf.h"
10
11namespace y2019 {
12namespace control_loops {
13
14template <int num_cameras, int num_targets, int num_obstacles,
15 int max_targets_per_frame, typename Scalar = double>
16class TypedLocalizer
17 : public ::frc971::control_loops::drivetrain::HybridEkf<Scalar> {
18 public:
19 typedef TypedCamera<num_targets, num_obstacles, Scalar> Camera;
20 typedef typename Camera::TargetView TargetView;
21 typedef typename Camera::Pose Pose;
22 typedef ::frc971::control_loops::drivetrain::HybridEkf<Scalar> HybridEkf;
23 typedef typename HybridEkf::State State;
24 typedef typename HybridEkf::StateSquare StateSquare;
25 typedef typename HybridEkf::Input Input;
26 typedef typename HybridEkf::Output Output;
27 using HybridEkf::kNInputs;
28 using HybridEkf::kNOutputs;
29 using HybridEkf::kNStates;
30
31 // robot_pose should be the object that is used by the cameras, such that when
32 // we update robot_pose, the cameras will change what they report the relative
33 // position of the targets as.
34 // Note that the parameters for the cameras should be set to allow slightly
35 // larger fields of view and slightly longer range than the true cameras so
36 // that we can identify potential matches for targets even when we have slight
37 // modelling errors.
38 TypedLocalizer(
39 const ::frc971::control_loops::drivetrain::DrivetrainConfig<Scalar>
40 &dt_config,
41 Pose *robot_pose)
42 : ::frc971::control_loops::drivetrain::HybridEkf<Scalar>(dt_config),
43 robot_pose_(robot_pose) {}
44
45 // Performs a kalman filter correction with a single camera frame, consisting
46 // of up to max_targets_per_frame targets and taken at time t.
47 // camera is the Camera used to take the images.
48 void UpdateTargets(
49 const Camera &camera,
50 const ::aos::SizedArray<TargetView, max_targets_per_frame> &targets,
51 ::aos::monotonic_clock::time_point t) {
52 if (targets.empty()) {
53 return;
54 }
55
James Kuszmaul6f941b72019-03-08 18:12:25 -080056 if (!SanitizeTargets(targets)) {
57 LOG(ERROR, "Throwing out targets due to in insane values.\n");
58 return;
59 }
60
James Kuszmaul1057ce82019-02-09 17:58:24 -080061 if (t > HybridEkf::latest_t()) {
62 LOG(ERROR,
63 "target observations must be older than most recent encoder/gyro "
James Kuszmaul85ffeb82019-03-03 19:41:44 -080064 "update.\n");
James Kuszmaul1057ce82019-02-09 17:58:24 -080065 return;
66 }
67
68 Output z;
69 Eigen::Matrix<Scalar, kNOutputs, kNOutputs> R;
70 TargetViewToMatrices(targets[0], &z, &R);
71
72 // In order to perform the correction steps for the targets, we will
73 // separately perform a Correct step for each following target.
74 // This way, we can have the first correction figure out the mappings
75 // between targets in the image and targets on the field, and then re-use
76 // those mappings for all the remaining corrections.
77 // As such, we need to store the EKF functions that the remaining targets
78 // will need in arrays:
79 ::aos::SizedArray<::std::function<Output(const State &, const Input &)>,
80 max_targets_per_frame> h_functions;
81 ::aos::SizedArray<::std::function<Eigen::Matrix<Scalar, kNOutputs,
82 kNStates>(const State &)>,
83 max_targets_per_frame> dhdx_functions;
84 HybridEkf::Correct(
85 z, nullptr,
86 ::std::bind(&TypedLocalizer::MakeH, this, camera, targets, &h_functions,
87 &dhdx_functions, ::std::placeholders::_1,
88 ::std::placeholders::_2, ::std::placeholders::_3,
89 ::std::placeholders::_4),
90 {}, {}, R, t);
91 // Fetch cache:
92 for (size_t ii = 1; ii < targets.size(); ++ii) {
93 TargetViewToMatrices(targets[ii], &z, &R);
94 HybridEkf::Correct(z, nullptr, {}, h_functions[ii], dhdx_functions[ii], R,
95 t);
96 }
97 }
98
99 private:
100 // The threshold to use for completely rejecting potentially bad target
101 // matches.
102 // TODO(james): Tune
103 static constexpr Scalar kRejectionScore = 1.0;
104
James Kuszmaul6f941b72019-03-08 18:12:25 -0800105 // Checks that the targets coming in make some sense--mostly to prevent NaNs
106 // or the such from propagating.
107 bool SanitizeTargets(
108 const ::aos::SizedArray<TargetView, max_targets_per_frame> &targets) {
109 for (const TargetView &view : targets) {
110 const typename TargetView::Reading reading = view.reading;
111 if (!(::std::isfinite(reading.heading) &&
112 ::std::isfinite(reading.distance) &&
113 ::std::isfinite(reading.skew) && ::std::isfinite(reading.height))) {
114 LOG(ERROR, "Got non-finite values in target.\n");
115 return false;
116 }
117 if (reading.distance < 0) {
118 LOG(ERROR, "Got negative distance.\n");
119 return false;
120 }
121 if (::std::abs(::aos::math::NormalizeAngle(reading.skew)) > M_PI_2) {
122 LOG(ERROR, "Got skew > pi / 2.\n");
123 return false;
124 }
125 }
126 return true;
127 }
128
James Kuszmaul1057ce82019-02-09 17:58:24 -0800129 // Computes the measurement (z) and noise covariance (R) matrices for a given
130 // TargetView.
131 void TargetViewToMatrices(const TargetView &view, Output *z,
132 Eigen::Matrix<Scalar, kNOutputs, kNOutputs> *R) {
James Kuszmaul6f941b72019-03-08 18:12:25 -0800133 *z << view.reading.heading, view.reading.distance,
134 ::aos::math::NormalizeAngle(view.reading.skew);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800135 // TODO(james): R should account as well for our confidence in the target
136 // matching. However, handling that properly requires thing a lot more about
137 // the probabilities.
138 R->setZero();
139 R->diagonal() << ::std::pow(view.noise.heading, 2),
140 ::std::pow(view.noise.distance, 2), ::std::pow(view.noise.skew, 2);
141 }
142
143 // This is the function that will be called once the Ekf has inserted the
144 // measurement into the right spot in the measurement queue and needs the
145 // output functions to actually perform the corrections.
146 // Specifically, this will take the estimate of the state at that time and
147 // figure out how the targets seen by the camera best map onto the actual
148 // targets on the field.
149 // It then fills in the h and dhdx functions that are called by the Ekf.
150 void MakeH(
151 const Camera &camera,
152 const ::aos::SizedArray<TargetView, max_targets_per_frame> &target_views,
153 ::aos::SizedArray<::std::function<Output(const State &, const Input &)>,
154 max_targets_per_frame> *h_functions,
155 ::aos::SizedArray<::std::function<Eigen::Matrix<Scalar, kNOutputs,
156 kNStates>(const State &)>,
157 max_targets_per_frame> *dhdx_functions,
158 const State &X_hat, const StateSquare &P,
159 ::std::function<Output(const State &, const Input &)> *h,
160 ::std::function<
161 Eigen::Matrix<Scalar, kNOutputs, kNStates>(const State &)> *dhdx) {
162 // Because we need to match camera targets ("views") to actual field
163 // targets, and because we want to take advantage of the correlations
164 // between the targets (i.e., if we see two targets in the image, they
165 // probably correspond to different on-field targets), the matching problem
166 // here is somewhat non-trivial. Some of the methods we use only work
167 // because we are dealing with very small N (e.g., handling the correlations
168 // between multiple views has combinatoric complexity, but since N = 3,
169 // it's not an issue).
170 //
171 // High-level steps:
172 // 1) Set the base robot pose for the cameras to the Pose implied by X_hat.
173 // 2) Fetch all the expected target views from the camera.
174 // 3) Determine the "magnitude" of the Kalman correction from each potential
175 // view/target pair.
176 // 4) Match based on the combination of targets with the smallest
177 // corrections.
178 // 5) Calculate h and dhdx for each pair of targets.
179 //
180 // For the "magnitude" of the correction, we do not directly use the
181 // standard Kalman correction formula. Instead, we calculate the correction
182 // we would get from each component of the measurement and take the L2 norm
183 // of those. This prevents situations where a target matches very poorly but
184 // produces an overall correction of near-zero.
185 // TODO(james): I do not know if this is strictly the correct method to
186 // minimize likely error, but should be reasonable.
187 //
188 // For the matching, we do the following (see MatchFrames):
189 // 1. Compute the best max_targets_per_frame matches for each view.
190 // 2. Exhaust every possible combination of view/target pairs and
191 // choose the best one.
192 // When we don't think the camera should be able to see as many targets as
193 // we actually got in the frame, then we do permit doubling/tripling/etc.
194 // up on potential targets once we've exhausted all the targets we think
195 // we can see.
196
197 // Set the current robot pose so that the cameras know where they are
198 // (all the cameras have robot_pose_ as their base):
199 *robot_pose_->mutable_pos() << X_hat(0, 0), X_hat(1, 0), 0.0;
200 robot_pose_->set_theta(X_hat(2, 0));
201
202 // Compute the things we *think* the camera should be seeing.
203 // Note: Because we will not try to match to any targets that are not
204 // returned by this function, we generally want the modelled camera to have
205 // a slightly larger field of view than the real camera, and be able to see
206 // slightly smaller targets.
207 const ::aos::SizedArray<TargetView, num_targets> camera_views =
208 camera.target_views();
209
210 // Each row contains the scores for each pair of target view and camera
211 // target view. Values in each row will not be populated past
212 // camera.target_views().size(); of the rows, only the first
213 // target_views.size() shall be populated.
214 // Higher scores imply a worse match. Zero implies a perfect match.
215 Eigen::Matrix<Scalar, max_targets_per_frame, num_targets> scores;
216 scores.setConstant(::std::numeric_limits<Scalar>::infinity());
217 // Each row contains the indices of the best matches per view, where
218 // index 0 is the best, 1 the second best, and 2 the third, etc.
219 // -1 indicates an unfilled field.
220 Eigen::Matrix<int, max_targets_per_frame, max_targets_per_frame>
221 best_matches;
222 best_matches.setConstant(-1);
223 // The H matrices for each potential matching. This has the same structure
224 // as the scores matrix.
225 ::std::array<::std::array<Eigen::Matrix<Scalar, kNOutputs, kNStates>,
226 max_targets_per_frame>,
227 num_targets> all_H_matrices;
228
229 // Iterate through and fill out the scores for each potential pairing:
230 for (size_t ii = 0; ii < target_views.size(); ++ii) {
231 const TargetView &target_view = target_views[ii];
232 Output z;
233 Eigen::Matrix<Scalar, kNOutputs, kNOutputs> R;
234 TargetViewToMatrices(target_view, &z, &R);
235
236 for (size_t jj = 0; jj < camera_views.size(); ++jj) {
237 // Compute the ckalman update for this step:
238 const TargetView &view = camera_views[jj];
239 const Eigen::Matrix<Scalar, kNOutputs, kNStates> H =
James Kuszmaul46f3a212019-03-10 10:14:24 -0700240 HMatrix(*view.target, camera.pose());
James Kuszmaul1057ce82019-02-09 17:58:24 -0800241 const Eigen::Matrix<Scalar, kNStates, kNOutputs> PH = P * H.transpose();
242 const Eigen::Matrix<Scalar, kNOutputs, kNOutputs> S = H * PH + R;
243 // Note: The inverse here should be very cheap so long as kNOutputs = 3.
244 const Eigen::Matrix<Scalar, kNStates, kNOutputs> K = PH * S.inverse();
245 const Output err = z - Output(view.reading.heading,
246 view.reading.distance, view.reading.skew);
247 // In order to compute the actual score, we want to consider each
248 // component of the error separately, as well as considering the impacts
249 // on the each of the states separately. As such, we calculate what
250 // the separate updates from each error component would be, and sum
251 // the impacts on the states.
252 Output scorer;
253 for (size_t kk = 0; kk < kNOutputs; ++kk) {
254 // TODO(james): squaredNorm or norm or L1-norm? Do we care about the
255 // square root? Do we prefer a quadratic or linear response?
256 scorer(kk, 0) = (K.col(kk) * err(kk, 0)).squaredNorm();
257 }
258 // Compute the overall score--note that we add in a term for the height,
259 // scaled by a manual fudge-factor. The height is not accounted for
260 // in the Kalman update because we are not trying to estimate the height
261 // of the robot directly.
262 Scalar score =
263 scorer.squaredNorm() +
264 ::std::pow((view.reading.height - target_view.reading.height) /
265 target_view.noise.height / 20.0,
266 2);
267 scores(ii, jj) = score;
268 all_H_matrices[ii][jj] = H;
269
270 // Update the best_matches matrix:
271 int insert_target = jj;
272 for (size_t kk = 0; kk < max_targets_per_frame; ++kk) {
273 int idx = best_matches(ii, kk);
274 // Note that -1 indicates an unfilled value.
275 if (idx == -1 || scores(ii, idx) > scores(ii, insert_target)) {
276 best_matches(ii, kk) = insert_target;
277 insert_target = idx;
278 if (idx == -1) {
279 break;
280 }
281 }
282 }
283 }
284 }
285
286 if (camera_views.size() == 0) {
James Kuszmaul289756f2019-03-05 21:52:10 -0800287 LOG(DEBUG, "Unable to identify potential target matches.\n");
James Kuszmaul1057ce82019-02-09 17:58:24 -0800288 // If we can't get a match, provide H = zero, which will make this
289 // correction step a nop.
290 *h = [](const State &, const Input &) { return Output::Zero(); };
291 *dhdx = [](const State &) {
292 return Eigen::Matrix<Scalar, kNOutputs, kNStates>::Zero();
293 };
294 for (size_t ii = 0; ii < target_views.size(); ++ii) {
295 h_functions->push_back(*h);
296 dhdx_functions->push_back(*dhdx);
297 }
298 } else {
299 // Go through and brute force the issue of what the best combination of
300 // target matches are. The worst case for this algorithm will be
301 // max_targets_per_frame!, which is awful for any N > ~4, but since
302 // max_targets_per_frame = 3, I'm not really worried.
303 ::std::array<int, max_targets_per_frame> best_frames =
304 MatchFrames(scores, best_matches, target_views.size());
305 for (size_t ii = 0; ii < target_views.size(); ++ii) {
James Kuszmaul6f941b72019-03-08 18:12:25 -0800306 size_t view_idx = best_frames[ii];
307 if (view_idx < 0 || view_idx >= camera_views.size()) {
308 LOG(ERROR, "Somehow, the view scorer failed.\n");
309 continue;
310 }
James Kuszmaul1057ce82019-02-09 17:58:24 -0800311 const Eigen::Matrix<Scalar, kNOutputs, kNStates> best_H =
312 all_H_matrices[ii][view_idx];
313 const TargetView best_view = camera_views[view_idx];
314 const TargetView target_view = target_views[ii];
315 const Scalar match_score = scores(ii, view_idx);
316 if (match_score > kRejectionScore) {
James Kuszmaul289756f2019-03-05 21:52:10 -0800317 LOG(DEBUG,
318 "Rejecting target at (%f, %f, %f, %f) due to high score.\n",
319 target_view.reading.heading, target_view.reading.distance,
320 target_view.reading.skew, target_view.reading.height);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800321 h_functions->push_back(
322 [](const State &, const Input &) { return Output::Zero(); });
323 dhdx_functions->push_back([](const State &) {
324 return Eigen::Matrix<Scalar, kNOutputs, kNStates>::Zero();
325 });
326 } else {
327 h_functions->push_back([this, &camera, best_view, target_view](
328 const State &X, const Input &) {
329 // This function actually handles determining what the Output should
330 // be at a given state, now that we have chosen the target that
331 // we want to match to.
332 *robot_pose_->mutable_pos() << X(0, 0), X(1, 0), 0.0;
333 robot_pose_->set_theta(X(2, 0));
334 const Pose relative_pose =
335 best_view.target->pose().Rebase(&camera.pose());
336 const Scalar heading = relative_pose.heading();
337 const Scalar distance = relative_pose.xy_norm();
James Kuszmaul289756f2019-03-05 21:52:10 -0800338 const Scalar skew = ::aos::math::NormalizeAngle(
339 relative_pose.rel_theta() - heading);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800340 return Output(heading, distance, skew);
341 });
342
343 // TODO(james): Experiment to better understand whether we want to
344 // recalculate H or not.
345 dhdx_functions->push_back(
346 [best_H](const Eigen::Matrix<Scalar, kNStates, 1> &) {
347 return best_H;
348 });
349 }
350 }
351 *h = h_functions->at(0);
352 *dhdx = dhdx_functions->at(0);
353 }
354 }
355
356 Eigen::Matrix<Scalar, kNOutputs, kNStates> HMatrix(
James Kuszmaul46f3a212019-03-10 10:14:24 -0700357 const Target &target, const Pose &camera_pose) {
James Kuszmaul1057ce82019-02-09 17:58:24 -0800358 // To calculate dheading/d{x,y,theta}:
359 // heading = arctan2(target_pos - camera_pos) - camera_theta
360 Eigen::Matrix<Scalar, 3, 1> target_pos = target.pose().abs_pos();
James Kuszmaul46f3a212019-03-10 10:14:24 -0700361 Eigen::Matrix<Scalar, 3, 1> camera_pos = camera_pose.abs_pos();
James Kuszmaul1057ce82019-02-09 17:58:24 -0800362 Scalar diffx = target_pos.x() - camera_pos.x();
363 Scalar diffy = target_pos.y() - camera_pos.y();
364 Scalar norm2 = diffx * diffx + diffy * diffy;
365 Scalar dheadingdx = diffy / norm2;
366 Scalar dheadingdy = -diffx / norm2;
367 Scalar dheadingdtheta = -1.0;
368
369 // To calculate ddistance/d{x,y}:
370 // distance = sqrt(diffx^2 + diffy^2)
371 Scalar distance = ::std::sqrt(norm2);
372 Scalar ddistdx = -diffx / distance;
373 Scalar ddistdy = -diffy / distance;
374
James Kuszmaul289756f2019-03-05 21:52:10 -0800375 // Skew = target.theta - camera.theta - heading
376 // = target.theta - arctan2(target_pos - camera_pos)
377 Scalar dskewdx = -dheadingdx;
378 Scalar dskewdy = -dheadingdy;
James Kuszmaul1057ce82019-02-09 17:58:24 -0800379 Eigen::Matrix<Scalar, kNOutputs, kNStates> H;
380 H.setZero();
381 H(0, 0) = dheadingdx;
382 H(0, 1) = dheadingdy;
383 H(0, 2) = dheadingdtheta;
384 H(1, 0) = ddistdx;
385 H(1, 1) = ddistdy;
James Kuszmaul289756f2019-03-05 21:52:10 -0800386 H(2, 0) = dskewdx;
387 H(2, 1) = dskewdy;
James Kuszmaul1057ce82019-02-09 17:58:24 -0800388 return H;
389 }
390
391 // A helper function for the fuller version of MatchFrames; this just
392 // removes some of the arguments that are only needed during the recursion.
393 // n_views is the number of targets actually seen in the camera image (i.e.,
394 // the number of rows in scores/best_matches that are actually populated).
395 ::std::array<int, max_targets_per_frame> MatchFrames(
396 const Eigen::Matrix<Scalar, max_targets_per_frame, num_targets> &scores,
397 const Eigen::Matrix<int, max_targets_per_frame, max_targets_per_frame> &
398 best_matches,
399 int n_views) {
400 ::std::array<int, max_targets_per_frame> best_set;
James Kuszmaul6f941b72019-03-08 18:12:25 -0800401 best_set.fill(-1);
James Kuszmaul1057ce82019-02-09 17:58:24 -0800402 Scalar best_score;
403 // We start out without having "used" any views/targets:
404 ::aos::SizedArray<bool, max_targets_per_frame> used_views;
405 for (int ii = 0; ii < n_views; ++ii) {
406 used_views.push_back(false);
407 }
408 MatchFrames(scores, best_matches, used_views, {{false}}, &best_set,
409 &best_score);
410 return best_set;
411 }
412
413 // Recursively iterates over every plausible combination of targets/views
414 // that there is and determines the lowest-scoring combination.
415 // used_views and used_targets indicate which rows/columns of the
416 // scores/best_matches matrices should be ignored. When used_views is all
417 // true, that means that we are done recursing.
418 void MatchFrames(
419 const Eigen::Matrix<Scalar, max_targets_per_frame, num_targets> &scores,
420 const Eigen::Matrix<int, max_targets_per_frame, max_targets_per_frame> &
421 best_matches,
422 const ::aos::SizedArray<bool, max_targets_per_frame> &used_views,
423 const ::std::array<bool, num_targets> &used_targets,
424 ::std::array<int, max_targets_per_frame> *best_set, Scalar *best_score) {
425 *best_score = ::std::numeric_limits<Scalar>::infinity();
426 // Iterate by letting each target in the camera frame (that isn't in
427 // used_views) choose it's best match that isn't already taken. We then set
428 // the appropriate flags in used_views and used_targets and call MatchFrames
429 // to let all the other views sort themselves out.
430 for (size_t ii = 0; ii < used_views.size(); ++ii) {
431 if (used_views[ii]) {
432 continue;
433 }
434 int best_match = -1;
435 for (size_t jj = 0; jj < max_targets_per_frame; ++jj) {
436 if (best_matches(ii, jj) == -1) {
437 // If we run out of potential targets from the camera, then there
438 // are more targets in the frame than we think there should be.
439 // In this case, we are going to be doubling/tripling/etc. up
440 // anyhow. So we just give everyone their top choice:
441 // TODO(james): If we ever are dealing with larger numbers of
442 // targets per frame, do something to minimize doubling-up.
443 best_match = best_matches(ii, 0);
444 break;
445 }
446 best_match = best_matches(ii, jj);
447 if (!used_targets[best_match]) {
448 break;
449 }
450 }
451 // If we reach here and best_match = -1, that means that no potential
452 // targets were generated by the camera, and we should never have gotten
453 // here.
454 CHECK(best_match != -1);
455 ::aos::SizedArray<bool, max_targets_per_frame> sub_views = used_views;
456 sub_views[ii] = true;
457 ::std::array<bool, num_targets> sub_targets = used_targets;
458 sub_targets[best_match] = true;
459 ::std::array<int, max_targets_per_frame> sub_best_set;
460 Scalar score;
461 MatchFrames(scores, best_matches, sub_views, sub_targets, &sub_best_set,
462 &score);
463 score += scores(ii, best_match);
464 sub_best_set[ii] = best_match;
465 if (score < *best_score) {
466 *best_score = score;
467 *best_set = sub_best_set;
468 }
469 }
470 // best_score will be infinite if we did not find a result due to there
471 // being no targets that weren't set in used_vies; this is the
472 // base case of the recursion and so we set best_score to zero:
473 if (!::std::isfinite(*best_score)) {
474 *best_score = 0.0;
475 }
476 }
477
478 // The pose that is used by the cameras to determine the location of the robot
479 // and thus the expected view of the targets.
480 Pose *robot_pose_;
481}; // class TypedLocalizer
482
483} // namespace control_loops
484} // namespace y2019
485
486#endif // Y2019_CONTROL_LOOPS_DRIVETRAIN_LOCALIZATER_H_