blob: f0c2d114c72e5b6f58e925cfb16f2b7fb8f5650b [file] [log] [blame]
justinT21446e4f62024-06-16 22:36:10 -07001#include <symengine/add.h>
2#include <symengine/matrix.h>
3#include <symengine/number.h>
4#include <symengine/printers.h>
5#include <symengine/real_double.h>
6#include <symengine/simplify.h>
7#include <symengine/solve.h>
8#include <symengine/symbol.h>
9
10#include <array>
11#include <cmath>
12#include <numbers>
13#include <utility>
14
Austin Schuh99f7c6a2024-06-25 22:07:44 -070015#include "absl/flags/flag.h"
16#include "absl/log/check.h"
17#include "absl/log/log.h"
justinT21446e4f62024-06-16 22:36:10 -070018#include "absl/strings/str_format.h"
19#include "absl/strings/str_join.h"
20#include "absl/strings/str_replace.h"
21#include "absl/strings/substitute.h"
justinT21446e4f62024-06-16 22:36:10 -070022
23#include "aos/init.h"
24#include "aos/util/file.h"
25#include "frc971/control_loops/swerve/motors.h"
26
Austin Schuh99f7c6a2024-06-25 22:07:44 -070027ABSL_FLAG(std::string, output_base, "",
28 "Path to strip off the front of the output paths.");
29ABSL_FLAG(std::string, cc_output_path, "",
30 "Path to write generated cc code to");
31ABSL_FLAG(std::string, h_output_path, "",
32 "Path to write generated header code to");
Austin Schuh99f7c6a2024-06-25 22:07:44 -070033ABSL_FLAG(std::string, casadi_py_output_path, "",
34 "Path to write casadi generated py code to");
Austin Schuh27694fa2024-07-20 16:29:49 -070035ABSL_FLAG(double, caster, 0.01, "Caster in meters for the module.");
justinT21446e4f62024-06-16 22:36:10 -070036
Austin Schuh99f7c6a2024-06-25 22:07:44 -070037ABSL_FLAG(bool, symbolic, false, "If true, write everything out symbolically.");
Austin Schuh5371c802024-09-02 13:18:48 -070038ABSL_FLAG(bool, function, true, "If true, make soft_atan2 a function.");
justinT21446e4f62024-06-16 22:36:10 -070039
justinT21942892b2024-07-02 22:33:50 -070040using SymEngine::abs;
justinT21446e4f62024-06-16 22:36:10 -070041using SymEngine::add;
42using SymEngine::atan2;
43using SymEngine::Basic;
44using SymEngine::ccode;
45using SymEngine::cos;
46using SymEngine::DenseMatrix;
47using SymEngine::div;
Austin Schuh78a1b312024-08-18 17:21:34 -070048using SymEngine::exp;
justinT21446e4f62024-06-16 22:36:10 -070049using SymEngine::Inf;
50using SymEngine::integer;
51using SymEngine::map_basic_basic;
52using SymEngine::minus_one;
53using SymEngine::neg;
54using SymEngine::NegInf;
55using SymEngine::pow;
56using SymEngine::RCP;
57using SymEngine::real_double;
58using SymEngine::RealDouble;
59using SymEngine::Set;
60using SymEngine::simplify;
61using SymEngine::sin;
62using SymEngine::solve;
63using SymEngine::symbol;
64using SymEngine::Symbol;
65
66namespace frc971::control_loops::swerve {
67
68// State per module.
69struct Module {
Austin Schuh6ea789e2024-07-27 13:45:53 -070070 DenseMatrix mounting_location;
71
justinT21446e4f62024-06-16 22:36:10 -070072 RCP<const Symbol> Is;
73
74 RCP<const Symbol> Id;
75
76 RCP<const Symbol> thetas;
77 RCP<const Symbol> omegas;
justinT21446e4f62024-06-16 22:36:10 -070078
justinT21446e4f62024-06-16 22:36:10 -070079 RCP<const Symbol> omegad;
justinT21446e4f62024-06-16 22:36:10 -070080
Austin Schuh2a1abec2024-07-10 20:31:16 -070081 DenseMatrix contact_patch_velocity;
Austin Schuhb67a38f2024-07-04 13:48:38 -070082 DenseMatrix wheel_ground_velocity;
Austin Schuhb8b34be2024-07-14 16:06:19 -070083 DenseMatrix wheel_slip_velocity;
Austin Schuhb67a38f2024-07-04 13:48:38 -070084 RCP<const Basic> slip_angle;
85 RCP<const Basic> slip_ratio;
86
Austin Schuhb8b34be2024-07-14 16:06:19 -070087 RCP<const Basic> Ms;
Austin Schuhb67a38f2024-07-04 13:48:38 -070088 RCP<const Basic> Fwy;
89
Austin Schuh6ea789e2024-07-27 13:45:53 -070090 struct Full {
91 RCP<const Basic> Fwx;
92 DenseMatrix F;
93
94 RCP<const Basic> torque;
95
96 RCP<const Basic> alphas_eqn;
97 RCP<const Basic> alphad_eqn;
98 } full;
99
100 struct Direct {
101 RCP<const Basic> Fwx;
102 DenseMatrix F;
103
104 RCP<const Basic> torque;
105
106 RCP<const Basic> alphas_eqn;
107 } direct;
justinT21446e4f62024-06-16 22:36:10 -0700108};
109
Austin Schuh6ea789e2024-07-27 13:45:53 -0700110DenseMatrix SumMatrices(DenseMatrix a) { return a; }
111
112template <typename... Args>
113DenseMatrix SumMatrices(DenseMatrix a, Args... args) {
114 DenseMatrix result = DenseMatrix(2, 1, {integer(0), integer(0)});
115
116 DenseMatrix b = SumMatrices(args...);
117 add_dense_dense(a, b, result);
118 return result;
119}
120
justinT21446e4f62024-06-16 22:36:10 -0700121class SwerveSimulation {
122 public:
123 SwerveSimulation() : drive_motor_(KrakenFOC()), steer_motor_(KrakenFOC()) {
124 auto fx = symbol("fx");
125 auto fy = symbol("fy");
126 auto moment = symbol("moment");
127
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700128 if (absl::GetFlag(FLAGS_symbolic)) {
justinT21446e4f62024-06-16 22:36:10 -0700129 Cx_ = symbol("Cx");
130 Cy_ = symbol("Cy");
131
Austin Schuh2a1abec2024-07-10 20:31:16 -0700132 rw_ = symbol("rw");
justinT21446e4f62024-06-16 22:36:10 -0700133
134 m_ = symbol("m");
135 J_ = symbol("J");
136
137 Gd1_ = symbol("Gd1");
138 rs_ = symbol("rs");
139 rp_ = symbol("rp");
140 Gd2_ = symbol("Gd2");
141
142 rb1_ = symbol("rb1");
143 rb2_ = symbol("rb2");
144
Austin Schuh76534f32024-09-02 13:52:45 -0700145 Gd3_ = symbol("Gd3");
justinT21446e4f62024-06-16 22:36:10 -0700146 Gd_ = symbol("Gd");
147
148 Js_ = symbol("Js");
149
150 Gs_ = symbol("Gs");
151 wb_ = symbol("wb");
152
153 Jdm_ = symbol("Jdm");
154 Jsm_ = symbol("Jsm");
155 Kts_ = symbol("Kts");
156 Ktd_ = symbol("Ktd");
157
158 robot_width_ = symbol("robot_width");
159
160 caster_ = symbol("caster");
161 contact_patch_length_ = symbol("Lcp");
162 } else {
Austin Schuhb8b34be2024-07-14 16:06:19 -0700163 Cx_ = real_double(25.0 * 9.8 / 4.0 / 0.05);
justinT21446e4f62024-06-16 22:36:10 -0700164 Cy_ = real_double(5 * 9.8 / 0.05 / 4.0);
165
Austin Schuh2a1abec2024-07-10 20:31:16 -0700166 rw_ = real_double(2 * 0.0254);
justinT21446e4f62024-06-16 22:36:10 -0700167
168 m_ = real_double(25.0); // base is 20 kg without battery
169 J_ = real_double(6.0);
170
171 Gd1_ = real_double(12.0 / 42.0);
172 rs_ = real_double(28.0 / 20.0 / 2.0);
173 rp_ = real_double(18.0 / 20.0 / 2.0);
174 Gd2_ = div(rs_, rp_);
175
176 // 15 / 45 bevel ratio, calculated using python script ported over to
177 // GetBevelPitchRadius(double
178 // TODO(Justin): Use the function instead of computed constantss
179 rb1_ = real_double(0.3805473);
180 rb2_ = real_double(1.14164);
181
182 Gd3_ = div(rb1_, rb2_);
183 Gd_ = mul(mul(Gd1_, Gd2_), Gd3_);
184
Austin Schuhb8b34be2024-07-14 16:06:19 -0700185 Js_ = real_double(0.001);
justinT21446e4f62024-06-16 22:36:10 -0700186
187 Gs_ = real_double(35.0 / 468.0);
188 wb_ = real_double(0.725);
189
190 Jdm_ = real_double(drive_motor_.motor_inertia);
191 Jsm_ = real_double(steer_motor_.motor_inertia);
192 Kts_ = real_double(steer_motor_.Kt);
193 Ktd_ = real_double(drive_motor_.Kt);
194
195 robot_width_ = real_double(24.75 * 0.0254);
196
Austin Schuh27694fa2024-07-20 16:29:49 -0700197 caster_ = real_double(absl::GetFlag(FLAGS_caster));
justinT21446e4f62024-06-16 22:36:10 -0700198 contact_patch_length_ = real_double(0.02);
199 }
200
201 x_ = symbol("x");
202 y_ = symbol("y");
203 theta_ = symbol("theta");
204
205 vx_ = symbol("vx");
206 vy_ = symbol("vy");
207 omega_ = symbol("omega");
208
209 ax_ = symbol("ax");
210 ay_ = symbol("ay");
211 atheta_ = symbol("atheta");
212
213 // Now, compute the accelerations due to the disturbance forces.
justinT21446e4f62024-06-16 22:36:10 -0700214 DenseMatrix external_accel = DenseMatrix(2, 1, {div(fx, m_), div(fy, m_)});
Austin Schuh6ea789e2024-07-27 13:45:53 -0700215 DenseMatrix external_force = DenseMatrix(2, 1, {fx, fy});
justinT21446e4f62024-06-16 22:36:10 -0700216
217 // And compute the physics contributions from each module.
218 modules_[0] = ModulePhysics(
219 0, DenseMatrix(
220 2, 1,
221 {div(robot_width_, integer(2)), div(robot_width_, integer(2))}));
222 modules_[1] =
223 ModulePhysics(1, DenseMatrix(2, 1,
224 {div(robot_width_, integer(-2)),
225 div(robot_width_, integer(2))}));
226 modules_[2] =
227 ModulePhysics(2, DenseMatrix(2, 1,
228 {div(robot_width_, integer(-2)),
229 div(robot_width_, integer(-2))}));
230 modules_[3] =
231 ModulePhysics(3, DenseMatrix(2, 1,
232 {div(robot_width_, integer(2)),
233 div(robot_width_, integer(-2))}));
234
235 // And convert them into the overall robot contribution.
Austin Schuh6ea789e2024-07-27 13:45:53 -0700236 DenseMatrix net_full_force =
237 SumMatrices(modules_[0].full.F, modules_[1].full.F, modules_[2].full.F,
238 modules_[3].full.F, external_force);
justinT21446e4f62024-06-16 22:36:10 -0700239
Austin Schuh6ea789e2024-07-27 13:45:53 -0700240 DenseMatrix net_direct_force =
241 SumMatrices(modules_[0].direct.F, modules_[1].direct.F,
242 modules_[2].direct.F, modules_[3].direct.F, external_force);
justinT21446e4f62024-06-16 22:36:10 -0700243
Austin Schuh6ea789e2024-07-27 13:45:53 -0700244 full_accel_ = DenseMatrix(2, 1);
245 mul_dense_scalar(net_full_force, pow(m_, minus_one), full_accel_);
justinT21446e4f62024-06-16 22:36:10 -0700246
Austin Schuh6ea789e2024-07-27 13:45:53 -0700247 full_angular_accel_ = div(
248 add(moment, add(add(modules_[0].full.torque, modules_[1].full.torque),
249 add(modules_[2].full.torque, modules_[3].full.torque))),
250 J_);
justinT21446e4f62024-06-16 22:36:10 -0700251
Austin Schuh6ea789e2024-07-27 13:45:53 -0700252 direct_accel_ = DenseMatrix(2, 1);
253 mul_dense_scalar(net_direct_force, pow(m_, minus_one), direct_accel_);
justinT21942892b2024-07-02 22:33:50 -0700254
Austin Schuh6ea789e2024-07-27 13:45:53 -0700255 direct_angular_accel_ =
256 div(add(moment,
257 add(add(modules_[0].direct.torque, modules_[1].direct.torque),
258 add(modules_[2].direct.torque, modules_[3].direct.torque))),
259 J_);
justinT21942892b2024-07-02 22:33:50 -0700260
Austin Schuh6ea789e2024-07-27 13:45:53 -0700261 VLOG(1) << "accel(0, 0) = " << ccode(*full_accel_.get(0, 0));
262 VLOG(1) << "accel(1, 0) = " << ccode(*full_accel_.get(1, 0));
263 VLOG(1) << "angular_accel = " << ccode(*full_angular_accel_);
justinT21942892b2024-07-02 22:33:50 -0700264 }
265
justinT21446e4f62024-06-16 22:36:10 -0700266 // Writes the physics out to the provided .cc and .h path.
267 void Write(std::string_view cc_path, std::string_view h_path) {
268 std::vector<std::string> result_cc;
269 std::vector<std::string> result_h;
270
Austin Schuh0f881092024-06-28 15:36:48 -0700271 std::string_view include_guard_stripped = h_path;
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700272 CHECK(absl::ConsumePrefix(&include_guard_stripped,
273 absl::GetFlag(FLAGS_output_base)));
justinT21446e4f62024-06-16 22:36:10 -0700274 std::string include_guard =
275 absl::StrReplaceAll(absl::AsciiStrToUpper(include_guard_stripped),
276 {{"/", "_"}, {".", "_"}});
277
278 // Write out the header.
279 result_h.emplace_back(absl::Substitute("#ifndef $0_", include_guard));
280 result_h.emplace_back(absl::Substitute("#define $0_", include_guard));
281 result_h.emplace_back("");
282 result_h.emplace_back("#include <Eigen/Dense>");
283 result_h.emplace_back("");
284 result_h.emplace_back("namespace frc971::control_loops::swerve {");
285 result_h.emplace_back("");
James Kuszmaulef14ab42024-09-14 15:05:24 -0700286 result_h.emplace_back("struct FullDynamicsStates {");
287 result_h.emplace_back("enum States {");
288 result_h.emplace_back(" kThetas0 = 0,");
289 result_h.emplace_back(" kThetad0 = 1,");
290 result_h.emplace_back(" kOmegas0 = 2,");
291 result_h.emplace_back(" kOmegad0 = 3,");
292 result_h.emplace_back(" kThetas1 = 4,");
293 result_h.emplace_back(" kThetad1 = 5,");
294 result_h.emplace_back(" kOmegas1 = 6,");
295 result_h.emplace_back(" kOmegad1 = 7,");
296 result_h.emplace_back(" kThetas2 = 8,");
297 result_h.emplace_back(" kThetad2 = 9,");
298 result_h.emplace_back(" kOmegas2 = 10,");
299 result_h.emplace_back(" kOmegad2 = 11,");
300 result_h.emplace_back(" kThetas3 = 12,");
301 result_h.emplace_back(" kThetad3 = 13,");
302 result_h.emplace_back(" kOmegas3 = 14,");
303 result_h.emplace_back(" kOmegad3 = 15,");
304 result_h.emplace_back(" kX = 16,");
305 result_h.emplace_back(" kY = 17,");
306 result_h.emplace_back(" kTheta = 18,");
307 result_h.emplace_back(" kVx = 19,");
308 result_h.emplace_back(" kVy = 20,");
309 result_h.emplace_back(" kOmega = 21,");
310 result_h.emplace_back(" kFx = 22,");
311 result_h.emplace_back(" kFy = 23,");
312 result_h.emplace_back(" kMoment = 24,");
313 result_h.emplace_back(" kNumStates");
314 result_h.emplace_back("};");
315 result_h.emplace_back("};");
316 result_h.emplace_back(
317 "inline constexpr size_t kNumFullDynamicsStates = "
318 "static_cast<size_t>(FullDynamicsStates::kNumStates);");
319 result_h.emplace_back("struct VelocityStates {");
320 result_h.emplace_back("enum States {");
321 result_h.emplace_back(" kThetas0 = 0,");
322 result_h.emplace_back(" kOmegas0 = 1,");
323 result_h.emplace_back(" kThetas1 = 2,");
324 result_h.emplace_back(" kOmegas1 = 3,");
325 result_h.emplace_back(" kThetas2 = 4,");
326 result_h.emplace_back(" kOmegas2 = 5,");
327 result_h.emplace_back(" kThetas3 = 6,");
328 result_h.emplace_back(" kOmegas3 = 7,");
329 result_h.emplace_back(" kTheta = 8,");
330 result_h.emplace_back(" kVx = 9,");
331 result_h.emplace_back(" kVy = 10,");
332 result_h.emplace_back(" kOmega = 11,");
333 result_h.emplace_back(" kNumStates");
334 result_h.emplace_back("};");
335 result_h.emplace_back("};");
336 result_h.emplace_back(
337 "inline constexpr size_t kNumVelocityStates = "
338 "static_cast<size_t>(VelocityStates::kNumStates);");
James Kuszmaulf65b1a52024-10-08 23:37:35 -0700339 result_h.emplace_back("struct InputStates {");
James Kuszmaulef14ab42024-09-14 15:05:24 -0700340 result_h.emplace_back("enum States {");
341 result_h.emplace_back(" kIs0 = 0,");
342 result_h.emplace_back(" kId0 = 1,");
343 result_h.emplace_back(" kIs1 = 2,");
344 result_h.emplace_back(" kId1 = 3,");
345 result_h.emplace_back(" kIs2 = 4,");
346 result_h.emplace_back(" kId2 = 5,");
347 result_h.emplace_back(" kIs3 = 6,");
348 result_h.emplace_back(" kId3 = 7,");
349 result_h.emplace_back(" kNumInputs = 8");
350 result_h.emplace_back("};");
351 result_h.emplace_back("};");
352 result_h.emplace_back(
353 "inline constexpr size_t kNumInputs = "
James Kuszmaulf65b1a52024-10-08 23:37:35 -0700354 "static_cast<size_t>(InputStates::kNumInputs);");
James Kuszmaulef14ab42024-09-14 15:05:24 -0700355 result_h.emplace_back("");
justinT21446e4f62024-06-16 22:36:10 -0700356 result_h.emplace_back("// Returns the derivative of our state vector");
justinT21446e4f62024-06-16 22:36:10 -0700357 result_h.emplace_back(
James Kuszmaulef14ab42024-09-14 15:05:24 -0700358 "Eigen::Matrix<double, kNumFullDynamicsStates, 1> SwervePhysics(");
justinT21446e4f62024-06-16 22:36:10 -0700359 result_h.emplace_back(
James Kuszmaulef14ab42024-09-14 15:05:24 -0700360 " Eigen::Ref<const Eigen::Matrix<double, kNumFullDynamicsStates, "
361 "1>> X,");
362 result_h.emplace_back(
363 " Eigen::Ref<const Eigen::Matrix<double, kNumInputs, 1>> U);");
364 result_h.emplace_back("");
justinT21446e4f62024-06-16 22:36:10 -0700365 result_h.emplace_back("} // namespace frc971::control_loops::swerve");
366 result_h.emplace_back("");
367 result_h.emplace_back(absl::Substitute("#endif // $0_", include_guard));
368
369 // Write out the .cc
370 result_cc.emplace_back(
371 absl::Substitute("#include \"$0\"", include_guard_stripped));
372 result_cc.emplace_back("");
373 result_cc.emplace_back("#include <cmath>");
374 result_cc.emplace_back("");
375 result_cc.emplace_back("namespace frc971::control_loops::swerve {");
376 result_cc.emplace_back("");
justinT21446e4f62024-06-16 22:36:10 -0700377 result_cc.emplace_back(
James Kuszmaulef14ab42024-09-14 15:05:24 -0700378 "Eigen::Matrix<double, kNumFullDynamicsStates, 1> SwervePhysics(");
379 result_cc.emplace_back(
380 " Eigen::Ref<const Eigen::Matrix<double, kNumFullDynamicsStates, "
381 "1>> X,");
382 result_cc.emplace_back(
383 " Eigen::Ref<const Eigen::Matrix<double, kNumInputs, 1>> U) {");
384 result_cc.emplace_back(
385 " Eigen::Matrix<double, kNumFullDynamicsStates, 1> result;");
justinT21446e4f62024-06-16 22:36:10 -0700386
387 // Start by writing out variables matching each of the symbol names we use
388 // so we don't have to modify the computed equations too much.
389 for (size_t m = 0; m < kNumModules; ++m) {
390 result_cc.emplace_back(
391 absl::Substitute(" const double thetas$0 = X($1, 0);", m, m * 4));
392 result_cc.emplace_back(absl::Substitute(
393 " const double omegas$0 = X($1, 0);", m, m * 4 + 2));
394 result_cc.emplace_back(absl::Substitute(
395 " const double omegad$0 = X($1, 0);", m, m * 4 + 3));
396 }
397
398 result_cc.emplace_back(absl::Substitute(" const double theta = X($0, 0);",
399 kNumModules * 4 + 2));
400 result_cc.emplace_back(
401 absl::Substitute(" const double vx = X($0, 0);", kNumModules * 4 + 3));
402 result_cc.emplace_back(
403 absl::Substitute(" const double vy = X($0, 0);", kNumModules * 4 + 4));
404 result_cc.emplace_back(absl::Substitute(" const double omega = X($0, 0);",
405 kNumModules * 4 + 5));
406
407 result_cc.emplace_back(
408 absl::Substitute(" const double fx = X($0, 0);", kNumModules * 4 + 6));
409 result_cc.emplace_back(
410 absl::Substitute(" const double fy = X($0, 0);", kNumModules * 4 + 7));
411 result_cc.emplace_back(absl::Substitute(" const double moment = X($0, 0);",
412 kNumModules * 4 + 8));
413
414 // Now do the same for the inputs.
415 for (size_t m = 0; m < kNumModules; ++m) {
416 result_cc.emplace_back(
417 absl::Substitute(" const double Is$0 = U($1, 0);", m, m * 2));
418 result_cc.emplace_back(
419 absl::Substitute(" const double Id$0 = U($1, 0);", m, m * 2 + 1));
420 }
421
422 result_cc.emplace_back("");
423
424 // And then write out the derivative of each state.
425 for (size_t m = 0; m < kNumModules; ++m) {
426 result_cc.emplace_back(
427 absl::Substitute(" result($0, 0) = omegas$1;", m * 4, m));
428 result_cc.emplace_back(
429 absl::Substitute(" result($0, 0) = omegad$1;", m * 4 + 1, m));
430
Austin Schuh6ea789e2024-07-27 13:45:53 -0700431 result_cc.emplace_back(
432 absl::Substitute(" result($0, 0) = $1;", m * 4 + 2,
433 ccode(*modules_[m].full.alphas_eqn)));
434 result_cc.emplace_back(
435 absl::Substitute(" result($0, 0) = $1;", m * 4 + 3,
436 ccode(*modules_[m].full.alphad_eqn)));
justinT21446e4f62024-06-16 22:36:10 -0700437 }
438
439 result_cc.emplace_back(
Austin Schuh5ddcb472024-07-21 17:55:34 -0700440 absl::Substitute(" result($0, 0) = vx;", kNumModules * 4 + 0));
justinT21446e4f62024-06-16 22:36:10 -0700441 result_cc.emplace_back(
Austin Schuh5ddcb472024-07-21 17:55:34 -0700442 absl::Substitute(" result($0, 0) = vy;", kNumModules * 4 + 1));
justinT21446e4f62024-06-16 22:36:10 -0700443 result_cc.emplace_back(
Austin Schuh5ddcb472024-07-21 17:55:34 -0700444 absl::Substitute(" result($0, 0) = omega;", kNumModules * 4 + 2));
justinT21446e4f62024-06-16 22:36:10 -0700445
justinT21446e4f62024-06-16 22:36:10 -0700446 result_cc.emplace_back(absl::Substitute(" result($0, 0) = $1;",
Austin Schuh5ddcb472024-07-21 17:55:34 -0700447 kNumModules * 4 + 3,
Austin Schuh6ea789e2024-07-27 13:45:53 -0700448 ccode(*full_accel_.get(0, 0))));
justinT21446e4f62024-06-16 22:36:10 -0700449 result_cc.emplace_back(absl::Substitute(" result($0, 0) = $1;",
Austin Schuh5ddcb472024-07-21 17:55:34 -0700450 kNumModules * 4 + 4,
Austin Schuh6ea789e2024-07-27 13:45:53 -0700451 ccode(*full_accel_.get(1, 0))));
452 result_cc.emplace_back(absl::Substitute(" result($0, 0) = $1;",
453 kNumModules * 4 + 5,
454 ccode(*full_angular_accel_)));
justinT21446e4f62024-06-16 22:36:10 -0700455
456 result_cc.emplace_back(
457 absl::Substitute(" result($0, 0) = 0.0;", kNumModules * 4 + 6));
458 result_cc.emplace_back(
459 absl::Substitute(" result($0, 0) = 0.0;", kNumModules * 4 + 7));
460 result_cc.emplace_back(
461 absl::Substitute(" result($0, 0) = 0.0;", kNumModules * 4 + 8));
462
463 result_cc.emplace_back("");
464 result_cc.emplace_back(" return result;");
465 result_cc.emplace_back("}");
466 result_cc.emplace_back("");
467 result_cc.emplace_back("} // namespace frc971::control_loops::swerve");
468
469 aos::util::WriteStringToFileOrDie(cc_path, absl::StrJoin(result_cc, "\n"));
470 aos::util::WriteStringToFileOrDie(h_path, absl::StrJoin(result_h, "\n"));
471 }
472
Austin Schuhb67a38f2024-07-04 13:48:38 -0700473 void WriteCasadiVariables(std::vector<std::string> *result_py) {
474 result_py->emplace_back(" sin = casadi.sin");
475 result_py->emplace_back(" cos = casadi.cos");
Austin Schuh78a1b312024-08-18 17:21:34 -0700476 result_py->emplace_back(" exp = casadi.exp");
Austin Schuh5371c802024-09-02 13:18:48 -0700477 if (absl::GetFlag(FLAGS_function)) {
478 result_py->emplace_back(" atan2 = soft_atan2()");
479 } else {
480 result_py->emplace_back(" atan2 = soft_atan2");
481 }
Austin Schuh2a1abec2024-07-10 20:31:16 -0700482 result_py->emplace_back(" fmax = casadi.fmax");
Austin Schuhb67a38f2024-07-04 13:48:38 -0700483 result_py->emplace_back(" fabs = casadi.fabs");
484
485 // Start by writing out variables matching each of the symbol names we use
486 // so we don't have to modify the computed equations too much.
487 for (size_t m = 0; m < kNumModules; ++m) {
488 result_py->emplace_back(
489 absl::Substitute(" thetas$0 = X[$1, 0]", m, m * 4));
490 result_py->emplace_back(
491 absl::Substitute(" omegas$0 = X[$1, 0]", m, m * 4 + 2));
492 result_py->emplace_back(
493 absl::Substitute(" omegad$0 = X[$1, 0]", m, m * 4 + 3));
494 }
495
496 result_py->emplace_back(
497 absl::Substitute(" theta = X[$0, 0]", kNumModules * 4 + 2));
498 result_py->emplace_back(
499 absl::Substitute(" vx = X[$0, 0]", kNumModules * 4 + 3));
500 result_py->emplace_back(
501 absl::Substitute(" vy = X[$0, 0]", kNumModules * 4 + 4));
502 result_py->emplace_back(
503 absl::Substitute(" omega = X[$0, 0]", kNumModules * 4 + 5));
504
505 result_py->emplace_back(
506 absl::Substitute(" fx = X[$0, 0]", kNumModules * 4 + 6));
507 result_py->emplace_back(
508 absl::Substitute(" fy = X[$0, 0]", kNumModules * 4 + 7));
509 result_py->emplace_back(
510 absl::Substitute(" moment = X[$0, 0]", kNumModules * 4 + 8));
511
512 // Now do the same for the inputs.
513 for (size_t m = 0; m < kNumModules; ++m) {
514 result_py->emplace_back(
515 absl::Substitute(" Is$0 = U[$1, 0]", m, m * 2));
516 result_py->emplace_back(
517 absl::Substitute(" Id$0 = U[$1, 0]", m, m * 2 + 1));
518 }
519 }
520
Austin Schuh6ea789e2024-07-27 13:45:53 -0700521 void WriteCasadiVelocityVariables(std::vector<std::string> *result_py) {
522 result_py->emplace_back(" sin = casadi.sin");
Austin Schuh78a1b312024-08-18 17:21:34 -0700523 result_py->emplace_back(" exp = casadi.exp");
Austin Schuh6ea789e2024-07-27 13:45:53 -0700524 result_py->emplace_back(" cos = casadi.cos");
Austin Schuh5371c802024-09-02 13:18:48 -0700525 if (absl::GetFlag(FLAGS_function)) {
526 result_py->emplace_back(" atan2 = soft_atan2()");
527 } else {
528 result_py->emplace_back(" atan2 = soft_atan2");
529 }
Austin Schuh6ea789e2024-07-27 13:45:53 -0700530 result_py->emplace_back(" fmax = casadi.fmax");
531 result_py->emplace_back(" fabs = casadi.fabs");
532
533 // Start by writing out variables matching each of the symbol names we use
534 // so we don't have to modify the computed equations too much.
535 for (size_t m = 0; m < kNumModules; ++m) {
536 result_py->emplace_back(
537 absl::Substitute(" thetas$0 = X[$1, 0]", m, m * 2 + 0));
538 result_py->emplace_back(
539 absl::Substitute(" omegas$0 = X[$1, 0]", m, m * 2 + 1));
540 }
541
542 result_py->emplace_back(
543 absl::Substitute(" theta = X[$0, 0]", kNumModules * 2 + 0));
544 result_py->emplace_back(
545 absl::Substitute(" vx = X[$0, 0]", kNumModules * 2 + 1));
546 result_py->emplace_back(
547 absl::Substitute(" vy = X[$0, 0]", kNumModules * 2 + 2));
548 result_py->emplace_back(
549 absl::Substitute(" omega = X[$0, 0]", kNumModules * 2 + 3));
550
551 // result_py->emplace_back(
552 // absl::Substitute(" fx = X[$0, 0]", kNumModules * 3 + 4));
553 // result_py->emplace_back(
554 // absl::Substitute(" fy = X[$0, 0]", kNumModules * 3 + 5));
555 // result_py->emplace_back(
556 // absl::Substitute(" moment = X[$0, 0]", kNumModules * 3 + 6));
557 //
558 result_py->emplace_back(" fx = 0");
559 result_py->emplace_back(" fy = 0");
560 result_py->emplace_back(" moment = 0");
561
562 // Now do the same for the inputs.
563 for (size_t m = 0; m < kNumModules; ++m) {
564 result_py->emplace_back(
565 absl::Substitute(" Is$0 = U[$1, 0]", m, m * 2));
566 result_py->emplace_back(
567 absl::Substitute(" Id$0 = U[$1, 0]", m, m * 2 + 1));
568 }
569 }
570
Austin Schuh0f881092024-06-28 15:36:48 -0700571 // Writes the physics out to the provided .cc and .h path.
572 void WriteCasadi(std::string_view py_path) {
573 std::vector<std::string> result_py;
574
575 // Write out the header.
Austin Schuh5371c802024-09-02 13:18:48 -0700576 result_py.emplace_back("#!/usr/bin/env python3");
Austin Schuh0f881092024-06-28 15:36:48 -0700577 result_py.emplace_back("");
Austin Schuh6ea789e2024-07-27 13:45:53 -0700578 result_py.emplace_back("import casadi, numpy");
Austin Schuh0f881092024-06-28 15:36:48 -0700579 result_py.emplace_back("");
Austin Schuh2a1abec2024-07-10 20:31:16 -0700580 result_py.emplace_back(absl::Substitute("WHEEL_RADIUS = $0", ccode(*rw_)));
581 result_py.emplace_back(
582 absl::Substitute("ROBOT_WIDTH = $0", ccode(*robot_width_)));
583 result_py.emplace_back(absl::Substitute("CASTER = $0", ccode(*caster_)));
Austin Schuh6ea789e2024-07-27 13:45:53 -0700584 result_py.emplace_back("STATE_THETAS0 = 0");
585 result_py.emplace_back("STATE_THETAD0 = 1");
586 result_py.emplace_back("STATE_OMEGAS0 = 2");
587 result_py.emplace_back("STATE_OMEGAD0 = 3");
588 result_py.emplace_back("STATE_THETAS1 = 4");
589 result_py.emplace_back("STATE_THETAD1 = 5");
590 result_py.emplace_back("STATE_OMEGAS1 = 6");
591 result_py.emplace_back("STATE_OMEGAD1 = 7");
592 result_py.emplace_back("STATE_THETAS2 = 8");
593 result_py.emplace_back("STATE_THETAD2 = 9");
594 result_py.emplace_back("STATE_OMEGAS2 = 10");
595 result_py.emplace_back("STATE_OMEGAD2 = 11");
596 result_py.emplace_back("STATE_THETAS3 = 12");
597 result_py.emplace_back("STATE_THETAD3 = 13");
598 result_py.emplace_back("STATE_OMEGAS3 = 14");
599 result_py.emplace_back("STATE_OMEGAD3 = 15");
600 result_py.emplace_back("STATE_X = 16");
601 result_py.emplace_back("STATE_Y = 17");
602 result_py.emplace_back("STATE_THETA = 18");
603 result_py.emplace_back("STATE_VX = 19");
604 result_py.emplace_back("STATE_VY = 20");
605 result_py.emplace_back("STATE_OMEGA = 21");
606 result_py.emplace_back("STATE_FX = 22");
607 result_py.emplace_back("STATE_FY = 23");
608 result_py.emplace_back("STATE_MOMENT = 24");
609 result_py.emplace_back("NUM_STATES = 25");
610 result_py.emplace_back("");
611 result_py.emplace_back("VELOCITY_STATE_THETAS0 = 0");
612 result_py.emplace_back("VELOCITY_STATE_OMEGAS0 = 1");
613 result_py.emplace_back("VELOCITY_STATE_THETAS1 = 2");
614 result_py.emplace_back("VELOCITY_STATE_OMEGAS1 = 3");
615 result_py.emplace_back("VELOCITY_STATE_THETAS2 = 4");
616 result_py.emplace_back("VELOCITY_STATE_OMEGAS2 = 5");
617 result_py.emplace_back("VELOCITY_STATE_THETAS3 = 6");
618 result_py.emplace_back("VELOCITY_STATE_OMEGAS3 = 7");
619 result_py.emplace_back("VELOCITY_STATE_THETA = 8");
620 result_py.emplace_back("VELOCITY_STATE_VX = 9");
621 result_py.emplace_back("VELOCITY_STATE_VY = 10");
622 result_py.emplace_back("VELOCITY_STATE_OMEGA = 11");
623 // result_py.emplace_back("VELOCITY_STATE_FX = 16");
624 // result_py.emplace_back("VELOCITY_STATE_FY = 17");
625 // result_py.emplace_back("VELOCITY_STATE_MOMENT = 18");
626 result_py.emplace_back("NUM_VELOCITY_STATES = 12");
627 result_py.emplace_back("");
628 result_py.emplace_back("def to_velocity_state(X):");
629 result_py.emplace_back(" return numpy.array([");
630 result_py.emplace_back(" [X[STATE_THETAS0, 0]],");
631 result_py.emplace_back(" [X[STATE_OMEGAS0, 0]],");
632 result_py.emplace_back(" [X[STATE_THETAS1, 0]],");
633 result_py.emplace_back(" [X[STATE_OMEGAS1, 0]],");
634 result_py.emplace_back(" [X[STATE_THETAS2, 0]],");
635 result_py.emplace_back(" [X[STATE_OMEGAS2, 0]],");
636 result_py.emplace_back(" [X[STATE_THETAS3, 0]],");
637 result_py.emplace_back(" [X[STATE_OMEGAS3, 0]],");
638 result_py.emplace_back(" [X[STATE_THETA, 0]],");
639 result_py.emplace_back(" [X[STATE_VX, 0]],");
640 result_py.emplace_back(" [X[STATE_VY, 0]],");
641 result_py.emplace_back(" [X[STATE_OMEGA, 0]],");
642 // result_py.emplace_back(" [X[STATE_FX, 0]],");
643 // result_py.emplace_back(" [X[STATE_FY, 0]],");
644 // result_py.emplace_back(" [X[STATE_MOMENT, 0]],");
645 result_py.emplace_back(" ])");
Austin Schuh2a1abec2024-07-10 20:31:16 -0700646 result_py.emplace_back("");
Austin Schuhbd75c482024-08-18 00:03:51 -0700647 constexpr double kLogGain = 1.0 / 0.05;
Austin Schuh5371c802024-09-02 13:18:48 -0700648 constexpr double kAbsGain = 1.0 / 0.01;
649 if (absl::GetFlag(FLAGS_function)) {
650 result_py.emplace_back("def soft_atan2():");
651 result_py.emplace_back(" y = casadi.SX.sym('y')");
652 result_py.emplace_back(" x = casadi.SX.sym('x')");
653 result_py.emplace_back(
654 " return casadi.Function('soft_atan2', [y, x], [");
655 result_py.emplace_back(" casadi.arctan2(");
656 result_py.emplace_back(" y,");
657 result_py.emplace_back(" casadi.logsumexp(");
658 result_py.emplace_back(" casadi.SX(");
659 result_py.emplace_back(" numpy.array([");
660 result_py.emplace_back(" 1.0, x * (1.0 - 2.0 /");
661 result_py.emplace_back(
662 absl::Substitute(" (1 + "
663 "casadi.exp($1.0 * x))) * $0.0",
664 kLogGain, kAbsGain));
665 result_py.emplace_back(
666 absl::Substitute(" ]))) / $0.0)", kLogGain));
667 result_py.emplace_back(" ])");
668 } else {
669 result_py.emplace_back("def soft_atan2(y, x):");
670 result_py.emplace_back(" return casadi.arctan2(");
671 result_py.emplace_back(" y,");
672 result_py.emplace_back(" casadi.logsumexp(casadi.SX(numpy.array(");
673 result_py.emplace_back(
674 absl::Substitute(" [1.0, x * (1.0 - 2.0 / (1 + "
675 "casadi.exp($1.0 * x))) * $0.0]))) / $0.0)",
676 kLogGain, kAbsGain));
677 }
678 result_py.emplace_back("");
679 result_py.emplace_back("# Is = STEER_CURRENT_COUPLING_FACTOR * Id");
680 result_py.emplace_back(absl::Substitute(
681 "STEER_CURRENT_COUPLING_FACTOR = $0",
682 ccode(*(neg(
683 mul(div(Gs_, Kts_),
684 mul(div(Ktd_, mul(Gd_, rw_)),
685 neg(mul(add(neg(wb_), mul(add(rs_, rp_),
686 sub(integer(1), div(rb1_, rp_)))),
687 div(rw_, rb2_))))))))));
Austin Schuhbd75c482024-08-18 00:03:51 -0700688 result_py.emplace_back("");
Austin Schuh98fbbe82024-08-18 23:07:26 -0700689 result_py.emplace_back("# Is = STEER_CURRENT_COUPLING_FACTOR * Id");
690 result_py.emplace_back(absl::Substitute(
691 "STEER_CURRENT_COUPLING_FACTOR = $0",
692 ccode(*(neg(
693 mul(div(Gs_, Kts_),
694 mul(div(Ktd_, mul(Gd_, rw_)),
695 neg(mul(add(neg(wb_), mul(add(rs_, rp_),
696 sub(integer(1), div(rb1_, rp_)))),
697 div(rw_, rb2_))))))))));
698 result_py.emplace_back("");
Austin Schuh2a1abec2024-07-10 20:31:16 -0700699
Austin Schuh0f881092024-06-28 15:36:48 -0700700 result_py.emplace_back("# Returns the derivative of our state vector");
701 result_py.emplace_back("# [thetas0, thetad0, omegas0, omegad0,");
702 result_py.emplace_back("# thetas1, thetad1, omegas1, omegad1,");
703 result_py.emplace_back("# thetas2, thetad2, omegas2, omegad2,");
704 result_py.emplace_back("# thetas3, thetad3, omegas3, omegad3,");
705 result_py.emplace_back("# x, y, theta, vx, vy, omega,");
706 result_py.emplace_back("# Fx, Fy, Moment]");
Austin Schuh6ea789e2024-07-27 13:45:53 -0700707 result_py.emplace_back("def swerve_full_dynamics(X, U):");
Austin Schuhb67a38f2024-07-04 13:48:38 -0700708 WriteCasadiVariables(&result_py);
Austin Schuh0f881092024-06-28 15:36:48 -0700709
710 result_py.emplace_back("");
711 result_py.emplace_back(" result = casadi.SX.sym('result', 25, 1)");
712 result_py.emplace_back("");
713
714 // And then write out the derivative of each state.
715 for (size_t m = 0; m < kNumModules; ++m) {
716 result_py.emplace_back(
717 absl::Substitute(" result[$0, 0] = omegas$1", m * 4, m));
718 result_py.emplace_back(
719 absl::Substitute(" result[$0, 0] = omegad$1", m * 4 + 1, m));
720
Austin Schuh6ea789e2024-07-27 13:45:53 -0700721 result_py.emplace_back(
722 absl::Substitute(" result[$0, 0] = $1", m * 4 + 2,
723 ccode(*modules_[m].full.alphas_eqn)));
724 result_py.emplace_back(
725 absl::Substitute(" result[$0, 0] = $1", m * 4 + 3,
726 ccode(*modules_[m].full.alphad_eqn)));
Austin Schuh0f881092024-06-28 15:36:48 -0700727 }
728
729 result_py.emplace_back(
Austin Schuhb8b34be2024-07-14 16:06:19 -0700730 absl::Substitute(" result[$0, 0] = vx", kNumModules * 4 + 0));
Austin Schuh0f881092024-06-28 15:36:48 -0700731 result_py.emplace_back(
Austin Schuhb8b34be2024-07-14 16:06:19 -0700732 absl::Substitute(" result[$0, 0] = vy", kNumModules * 4 + 1));
Austin Schuh0f881092024-06-28 15:36:48 -0700733 result_py.emplace_back(
Austin Schuhb8b34be2024-07-14 16:06:19 -0700734 absl::Substitute(" result[$0, 0] = omega", kNumModules * 4 + 2));
Austin Schuh0f881092024-06-28 15:36:48 -0700735
Austin Schuh0f881092024-06-28 15:36:48 -0700736 result_py.emplace_back(absl::Substitute(" result[$0, 0] = $1",
Austin Schuhb8b34be2024-07-14 16:06:19 -0700737 kNumModules * 4 + 3,
Austin Schuh6ea789e2024-07-27 13:45:53 -0700738 ccode(*full_accel_.get(0, 0))));
Austin Schuh0f881092024-06-28 15:36:48 -0700739 result_py.emplace_back(absl::Substitute(" result[$0, 0] = $1",
Austin Schuhb8b34be2024-07-14 16:06:19 -0700740 kNumModules * 4 + 4,
Austin Schuh6ea789e2024-07-27 13:45:53 -0700741 ccode(*full_accel_.get(1, 0))));
742 result_py.emplace_back(absl::Substitute(" result[$0, 0] = $1",
743 kNumModules * 4 + 5,
744 ccode(*full_angular_accel_)));
Austin Schuh0f881092024-06-28 15:36:48 -0700745
746 result_py.emplace_back(
747 absl::Substitute(" result[$0, 0] = 0.0", kNumModules * 4 + 6));
748 result_py.emplace_back(
749 absl::Substitute(" result[$0, 0] = 0.0", kNumModules * 4 + 7));
750 result_py.emplace_back(
751 absl::Substitute(" result[$0, 0] = 0.0", kNumModules * 4 + 8));
752
753 result_py.emplace_back("");
754 result_py.emplace_back(
755 " return casadi.Function('xdot', [X, U], [result])");
Austin Schuh2a1abec2024-07-10 20:31:16 -0700756
Austin Schuh6ea789e2024-07-27 13:45:53 -0700757 result_py.emplace_back("");
758
759 result_py.emplace_back("# Returns the derivative of our state vector");
760 result_py.emplace_back("# [thetas0, omegas0,");
761 result_py.emplace_back("# thetas1, omegas1,");
762 result_py.emplace_back("# thetas2, omegas2,");
763 result_py.emplace_back("# thetas3, omegas3,");
764 result_py.emplace_back("# theta, vx, vy, omega]");
765 result_py.emplace_back("def velocity_swerve_physics(X, U):");
766 WriteCasadiVelocityVariables(&result_py);
767
768 result_py.emplace_back("");
769 result_py.emplace_back(
770 " result = casadi.SX.sym('result', NUM_VELOCITY_STATES, 1)");
771 result_py.emplace_back("");
772
773 // And then write out the derivative of each state.
774 for (size_t m = 0; m < kNumModules; ++m) {
775 result_py.emplace_back(
776 absl::Substitute(" result[$0, 0] = omegas$1", m * 2 + 0, m));
777 result_py.emplace_back(
778 absl::Substitute(" result[$0, 0] = $1", m * 2 + 1,
779 ccode(*modules_[m].direct.alphas_eqn)));
780 }
781 result_py.emplace_back(
782 absl::Substitute(" result[$0, 0] = omega", kNumModules * 2 + 0));
783
784 result_py.emplace_back(absl::Substitute(" result[$0, 0] = $1",
785 kNumModules * 2 + 1,
786 ccode(*direct_accel_.get(0, 0))));
787 result_py.emplace_back(absl::Substitute(" result[$0, 0] = $1",
788 kNumModules * 2 + 2,
789 ccode(*direct_accel_.get(1, 0))));
790 result_py.emplace_back(absl::Substitute(" result[$0, 0] = $1",
791 kNumModules * 2 + 3,
792 ccode(*direct_angular_accel_)));
793
794 // result_py.emplace_back(
795 // absl::Substitute(" result[$0, 0] = 0.0", kNumModules * 3 + 4));
796 // result_py.emplace_back(
797 // absl::Substitute(" result[$0, 0] = 0.0", kNumModules * 3 + 5));
798 // result_py.emplace_back(
799 // absl::Substitute(" result[$0, 0] = 0.0", kNumModules * 3 + 6));
800
801 result_py.emplace_back("");
802 result_py.emplace_back(
803 " return casadi.Function('xdot', [X, U], [result])");
804
Austin Schuhb8b34be2024-07-14 16:06:19 -0700805 DefineVector2dFunction(
806 "contact_patch_velocity",
807 "# Returns the velocity of the wheel in global coordinates.",
808 [](const Module &m, int dimension) {
809 return ccode(*m.contact_patch_velocity.get(dimension, 0));
810 },
811 &result_py);
812 DefineVector2dFunction(
813 "wheel_ground_velocity",
814 "# Returns the velocity of the wheel in steer module coordinates.",
815 [](const Module &m, int dimension) {
816 return ccode(*m.wheel_ground_velocity.get(dimension, 0));
817 },
818 &result_py);
Austin Schuhb67a38f2024-07-04 13:48:38 -0700819
Austin Schuhb8b34be2024-07-14 16:06:19 -0700820 DefineVector2dFunction(
821 "wheel_slip_velocity",
822 "# Returns the difference in velocities of the wheel surface and the "
823 "ground.",
824 [](const Module &m, int dimension) {
825 return ccode(*m.wheel_slip_velocity.get(dimension, 0));
826 },
827 &result_py);
Austin Schuhb67a38f2024-07-04 13:48:38 -0700828
Austin Schuhb8b34be2024-07-14 16:06:19 -0700829 DefineScalarFunction(
830 "slip_angle", "Returns the slip angle of the ith wheel",
831 [](const Module &m) { return ccode(*m.slip_angle); }, &result_py);
832 DefineScalarFunction(
833 "slip_ratio", "Returns the slip ratio of the ith wheel",
834 [](const Module &m) { return ccode(*m.slip_ratio); }, &result_py);
835 DefineScalarFunction(
836 "module_angular_accel",
837 "Returns the angular acceleration of the robot due to the ith wheel",
Austin Schuh6ea789e2024-07-27 13:45:53 -0700838 [this](const Module &m) { return ccode(*div(m.full.torque, Js_)); },
839 &result_py);
Austin Schuhb67a38f2024-07-04 13:48:38 -0700840
Austin Schuhb8b34be2024-07-14 16:06:19 -0700841 DefineVector2dFunction(
842 "wheel_force",
843 "Returns the force on the wheel in steer module coordinates",
844 [](const Module &m, int dimension) {
Austin Schuh6ea789e2024-07-27 13:45:53 -0700845 return ccode(
846 *std::vector<RCP<const Basic>>{m.full.Fwx, m.Fwy}[dimension]);
Austin Schuhb8b34be2024-07-14 16:06:19 -0700847 },
848 &result_py);
Austin Schuhb67a38f2024-07-04 13:48:38 -0700849
Austin Schuhb8b34be2024-07-14 16:06:19 -0700850 DefineVector2dFunction(
851 "F", "Returns the force on the wheel in absolute coordinates",
852 [](const Module &m, int dimension) {
Austin Schuh6ea789e2024-07-27 13:45:53 -0700853 return ccode(*m.full.F.get(dimension, 0));
Austin Schuhb8b34be2024-07-14 16:06:19 -0700854 },
855 &result_py);
856
justinT21820767f2024-09-11 19:57:55 -0700857 DefineVector2dVelocityFunction(
858 "F_vel",
859 "Returns the force on the wheel in absolute coordinates based on the "
860 "velocity controller",
861 [](const Module &m, int dimension) {
862 return ccode(*m.direct.F.get(dimension, 0));
863 },
864 &result_py);
865
866 DefineVector2dVelocityFunction(
Austin Schuhb8b34be2024-07-14 16:06:19 -0700867 "mounting_location",
868 "Returns the mounting location of wheel in robot coordinates",
869 [](const Module &m, int dimension) {
870 return ccode(*m.mounting_location.get(dimension, 0));
871 },
872 &result_py);
873
874 DefineScalarFunction(
875 "Ms", "Returns the self aligning moment of the ith wheel",
876 [this](const Module &m) {
877 return ccode(*(div(m.Ms, add(Jsm_, div(div(Js_, Gs_), Gs_)))));
878 },
879 &result_py);
Austin Schuh0f881092024-06-28 15:36:48 -0700880
881 aos::util::WriteStringToFileOrDie(py_path, absl::StrJoin(result_py, "\n"));
882 }
883
Austin Schuhb8b34be2024-07-14 16:06:19 -0700884 void DefineScalarFunction(
885 std::string_view name, std::string_view documentation,
886 std::function<std::string(const Module &)> scalar_fn,
887 std::vector<std::string> *result_py) {
888 result_py->emplace_back("");
889 result_py->emplace_back(absl::Substitute("# $0.", documentation));
890 result_py->emplace_back(absl::Substitute("def $0(i, X, U):", name));
891 WriteCasadiVariables(result_py);
892 for (size_t m = 0; m < kNumModules; ++m) {
893 if (m == 0) {
894 result_py->emplace_back(" if i == 0:");
895 } else {
896 result_py->emplace_back(absl::Substitute(" elif i == $0:", m));
897 }
898 result_py->emplace_back(
899 absl::Substitute(" return casadi.Function('$0', [X, U], [$1])",
900 name, scalar_fn(modules_[m])));
901 }
902 result_py->emplace_back(" raise ValueError(\"Invalid module number\")");
903 }
904
905 void DefineVector2dFunction(
906 std::string_view name, std::string_view documentation,
907 std::function<std::string(const Module &, int)> scalar_fn,
908 std::vector<std::string> *result_py) {
909 result_py->emplace_back("");
910 result_py->emplace_back(absl::Substitute("# $0.", documentation));
911 result_py->emplace_back(absl::Substitute("def $0(i, X, U):", name));
912 WriteCasadiVariables(result_py);
913 result_py->emplace_back(
914 absl::Substitute(" result = casadi.SX.sym('$0', 2, 1)", name));
915 for (size_t m = 0; m < kNumModules; ++m) {
916 if (m == 0) {
917 result_py->emplace_back(" if i == 0:");
918 } else {
919 result_py->emplace_back(absl::Substitute(" elif i == $0:", m));
920 }
921 for (int j = 0; j < 2; ++j) {
922 result_py->emplace_back(absl::Substitute(" result[$0, 0] = $1",
923 j, scalar_fn(modules_[m], j)));
924 }
925 }
926 result_py->emplace_back(" else:");
927 result_py->emplace_back(
928 " raise ValueError(\"Invalid module number\")");
929 result_py->emplace_back(absl::Substitute(
930 " return casadi.Function('$0', [X, U], [result])", name));
931 }
932
justinT21820767f2024-09-11 19:57:55 -0700933 void DefineVector2dVelocityFunction(
934 std::string_view name, std::string_view documentation,
935 std::function<std::string(const Module &, int)> scalar_fn,
936 std::vector<std::string> *result_py) {
937 result_py->emplace_back("");
938 result_py->emplace_back(absl::Substitute("# $0.", documentation));
939 result_py->emplace_back(absl::Substitute("def $0(i, X, U):", name));
940 WriteCasadiVelocityVariables(result_py);
941 result_py->emplace_back(
942 absl::Substitute(" result = casadi.SX.sym('$0', 2, 1)", name));
943 for (size_t m = 0; m < kNumModules; ++m) {
944 if (m == 0) {
945 result_py->emplace_back(" if i == 0:");
946 } else {
947 result_py->emplace_back(absl::Substitute(" elif i == $0:", m));
948 }
949 for (int j = 0; j < 2; ++j) {
950 result_py->emplace_back(absl::Substitute(" result[$0, 0] = $1",
951 j, scalar_fn(modules_[m], j)));
952 }
953 }
954 result_py->emplace_back(" else:");
955 result_py->emplace_back(
956 " raise ValueError(\"Invalid module number\")");
957 result_py->emplace_back(absl::Substitute(
958 " return casadi.Function('$0', [X, U], [result])", name));
959 }
960
justinT21446e4f62024-06-16 22:36:10 -0700961 private:
962 static constexpr uint8_t kNumModules = 4;
963
Austin Schuh6ea789e2024-07-27 13:45:53 -0700964 RCP<const Basic> SteerAccel(RCP<const Basic> Fwx, RCP<const Basic> Ms,
965 RCP<const Basic> Is) {
966 RCP<const Basic> lhms =
967 mul(add(neg(wb_), mul(add(rs_, rp_), sub(integer(1), div(rb1_, rp_)))),
968 mul(div(rw_, rb2_), neg(Fwx)));
969 RCP<const Basic> lhs = add(add(Ms, div(mul(Kts_, Is), Gs_)), lhms);
970 RCP<const Basic> rhs = add(Jsm_, div(div(Js_, Gs_), Gs_));
971 return simplify(div(lhs, rhs));
972 }
973
justinT21446e4f62024-06-16 22:36:10 -0700974 Module ModulePhysics(const int m, DenseMatrix mounting_location) {
975 VLOG(1) << "Solving module " << m;
976
977 Module result;
Austin Schuhb8b34be2024-07-14 16:06:19 -0700978 result.mounting_location = mounting_location;
justinT21446e4f62024-06-16 22:36:10 -0700979
980 result.Is = symbol(absl::StrFormat("Is%u", m));
981 result.Id = symbol(absl::StrFormat("Id%u", m));
982
983 RCP<const Symbol> thetamd = symbol(absl::StrFormat("theta_md%u", m));
984 RCP<const Symbol> omegamd = symbol(absl::StrFormat("omega_md%u", m));
985 RCP<const Symbol> alphamd = symbol(absl::StrFormat("alpha_md%u", m));
986
987 result.thetas = symbol(absl::StrFormat("thetas%u", m));
988 result.omegas = symbol(absl::StrFormat("omegas%u", m));
Austin Schuh6ea789e2024-07-27 13:45:53 -0700989 RCP<const Symbol> alphas = symbol(absl::StrFormat("alphas%u", m));
justinT21446e4f62024-06-16 22:36:10 -0700990
justinT21446e4f62024-06-16 22:36:10 -0700991 result.omegad = symbol(absl::StrFormat("omegad%u", m));
Austin Schuh6ea789e2024-07-27 13:45:53 -0700992 RCP<const Symbol> alphad = symbol(absl::StrFormat("alphad%u", m));
justinT21446e4f62024-06-16 22:36:10 -0700993
994 // Velocity of the module in field coordinates
Austin Schuh2a1abec2024-07-10 20:31:16 -0700995 DenseMatrix robot_velocity = DenseMatrix(2, 1, {vx_, vy_});
justinT21446e4f62024-06-16 22:36:10 -0700996 VLOG(1) << "robot velocity: " << robot_velocity.__str__();
997
998 // Velocity of the contact patch in field coordinates
999 DenseMatrix temp_matrix = DenseMatrix(2, 1);
1000 DenseMatrix temp_matrix2 = DenseMatrix(2, 1);
Austin Schuhbd75c482024-08-18 00:03:51 -07001001 DenseMatrix temp_matrix3 = DenseMatrix(2, 1);
Austin Schuh2a1abec2024-07-10 20:31:16 -07001002 result.contact_patch_velocity = DenseMatrix(2, 1);
justinT21446e4f62024-06-16 22:36:10 -07001003
Austin Schuhb8b34be2024-07-14 16:06:19 -07001004 mul_dense_dense(R(theta_), result.mounting_location, temp_matrix);
justinT21446e4f62024-06-16 22:36:10 -07001005 add_dense_dense(angle_cross(temp_matrix, omega_), robot_velocity,
1006 temp_matrix2);
1007 mul_dense_dense(R(add(theta_, result.thetas)),
Austin Schuhbd75c482024-08-18 00:03:51 -07001008 DenseMatrix(2, 1, {neg(caster_), integer(0)}),
1009 temp_matrix3);
justinT21446e4f62024-06-16 22:36:10 -07001010 add_dense_dense(temp_matrix2,
Austin Schuhbd75c482024-08-18 00:03:51 -07001011 angle_cross(temp_matrix3, add(omega_, result.omegas)),
Austin Schuh2a1abec2024-07-10 20:31:16 -07001012 result.contact_patch_velocity);
justinT21446e4f62024-06-16 22:36:10 -07001013
1014 VLOG(1);
Austin Schuh2a1abec2024-07-10 20:31:16 -07001015 VLOG(1) << "contact patch velocity: "
1016 << result.contact_patch_velocity.__str__();
justinT21446e4f62024-06-16 22:36:10 -07001017
1018 // Relative velocity of the surface of the wheel to the ground.
Austin Schuhb67a38f2024-07-04 13:48:38 -07001019 result.wheel_ground_velocity = DenseMatrix(2, 1);
Austin Schuh2a1abec2024-07-10 20:31:16 -07001020 mul_dense_dense(R(neg(add(result.thetas, theta_))),
1021 result.contact_patch_velocity,
Austin Schuhb67a38f2024-07-04 13:48:38 -07001022 result.wheel_ground_velocity);
justinT21446e4f62024-06-16 22:36:10 -07001023
Austin Schuhb8b34be2024-07-14 16:06:19 -07001024 // Compute the relative velocity between the wheel surface and the ground in
1025 // the wheel coordinate system.
1026 result.wheel_slip_velocity = DenseMatrix(2, 1);
1027 DenseMatrix wheel_velocity =
1028 DenseMatrix(2, 1, {mul(rw_, result.omegad), integer(0)});
1029 DenseMatrix negative_wheel_ground_velocity =
1030 DenseMatrix(2, 1,
1031 {neg(result.wheel_ground_velocity.get(0, 0)),
1032 neg(result.wheel_ground_velocity.get(1, 0))});
1033 add_dense_dense(negative_wheel_ground_velocity, wheel_velocity,
1034 result.wheel_slip_velocity);
1035
justinT21446e4f62024-06-16 22:36:10 -07001036 VLOG(1);
Austin Schuhb67a38f2024-07-04 13:48:38 -07001037 VLOG(1) << "wheel ground velocity: "
1038 << result.wheel_ground_velocity.__str__();
justinT21446e4f62024-06-16 22:36:10 -07001039
Austin Schuh5ddcb472024-07-21 17:55:34 -07001040 result.slip_angle = sin(neg(atan2(result.wheel_ground_velocity.get(1, 0),
1041 result.wheel_ground_velocity.get(0, 0))));
justinT21446e4f62024-06-16 22:36:10 -07001042
1043 VLOG(1);
Austin Schuhb67a38f2024-07-04 13:48:38 -07001044 VLOG(1) << "slip angle: " << result.slip_angle->__str__();
justinT21446e4f62024-06-16 22:36:10 -07001045
Austin Schuh2a1abec2024-07-10 20:31:16 -07001046 // TODO(austin): Does this handle decel properly?
Austin Schuhb67a38f2024-07-04 13:48:38 -07001047 result.slip_ratio = div(
Austin Schuh2a1abec2024-07-10 20:31:16 -07001048 sub(mul(rw_, result.omegad), result.wheel_ground_velocity.get(0, 0)),
1049 SymEngine::max(
1050 {real_double(0.02), abs(result.wheel_ground_velocity.get(0, 0))}));
justinT21446e4f62024-06-16 22:36:10 -07001051 VLOG(1);
Austin Schuhb67a38f2024-07-04 13:48:38 -07001052 VLOG(1) << "Slip ratio " << result.slip_ratio->__str__();
justinT21446e4f62024-06-16 22:36:10 -07001053
Austin Schuh6ea789e2024-07-27 13:45:53 -07001054 result.full.Fwx = simplify(mul(Cx_, result.slip_ratio));
Austin Schuhb67a38f2024-07-04 13:48:38 -07001055 result.Fwy = simplify(mul(Cy_, result.slip_angle));
justinT21446e4f62024-06-16 22:36:10 -07001056
Austin Schuh27694fa2024-07-20 16:29:49 -07001057 // The self-aligning moment needs to flip when the module flips direction.
Austin Schuh78a1b312024-08-18 17:21:34 -07001058 RCP<const Basic> softsign_velocity = add(
1059 div(integer(-2),
1060 add(integer(1), exp(mul(integer(100),
1061 result.wheel_ground_velocity.get(0, 0))))),
1062 integer(1));
1063 result.Ms =
1064 mul(neg(result.Fwy),
1065 add(div(mul(softsign_velocity, contact_patch_length_), integer(3)),
1066 caster_));
justinT21446e4f62024-06-16 22:36:10 -07001067 VLOG(1);
Austin Schuhb8b34be2024-07-14 16:06:19 -07001068 VLOG(1) << "Ms " << result.Ms->__str__();
justinT21446e4f62024-06-16 22:36:10 -07001069 VLOG(1);
Austin Schuh6ea789e2024-07-27 13:45:53 -07001070 VLOG(1) << "full.Fwx " << result.full.Fwx->__str__();
justinT21446e4f62024-06-16 22:36:10 -07001071 VLOG(1);
Austin Schuhb67a38f2024-07-04 13:48:38 -07001072 VLOG(1) << "Fwy " << result.Fwy->__str__();
justinT21446e4f62024-06-16 22:36:10 -07001073
Austin Schuh6ea789e2024-07-27 13:45:53 -07001074 // -K_td * Id / Gd + Fwx * rw = 0
1075 // Fwx = K_td * Id / Gd / rw
1076 result.direct.Fwx = mul(Ktd_, div(result.Id, mul(Gd_, rw_)));
1077
1078 result.direct.alphas_eqn =
1079 SteerAccel(result.direct.Fwx, result.Ms, result.Is);
1080
1081 // d/dt omegas = ...
1082 result.full.alphas_eqn = SteerAccel(result.full.Fwx, result.Ms, result.Is);
justinT21446e4f62024-06-16 22:36:10 -07001083
1084 VLOG(1);
Austin Schuh6ea789e2024-07-27 13:45:53 -07001085 VLOG(1) << alphas->__str__() << " = " << result.full.alphas_eqn->__str__();
justinT21446e4f62024-06-16 22:36:10 -07001086
Austin Schuh6ea789e2024-07-27 13:45:53 -07001087 RCP<const Basic> lhs =
1088 sub(mul(sub(div(add(rp_, rs_), rp_), integer(1)), alphas),
1089 mul(Gd1_, mul(Gd2_, alphamd)));
1090 RCP<const Basic> ddplanitary_eqn = sub(mul(Gd3_, lhs), alphad);
justinT21446e4f62024-06-16 22:36:10 -07001091
Austin Schuh6ea789e2024-07-27 13:45:53 -07001092 RCP<const Basic> full_drive_eqn =
1093 sub(add(mul(neg(Jdm_), div(alphamd, Gd_)),
1094 mul(Ktd_, div(neg(result.Id), Gd_))),
1095 mul(neg(result.full.Fwx), rw_));
justinT21446e4f62024-06-16 22:36:10 -07001096
Austin Schuh6ea789e2024-07-27 13:45:53 -07001097 VLOG(1) << "full_drive_eqn: " << full_drive_eqn->__str__();
justinT21446e4f62024-06-16 22:36:10 -07001098
1099 // Substitute in ddplanitary_eqn so we get rid of alphamd
1100 map_basic_basic map;
1101 RCP<const Set> reals = interval(NegInf, Inf, true, true);
1102 RCP<const Set> solve_solution = solve(ddplanitary_eqn, alphamd, reals);
1103 map[alphamd] = solve_solution->get_args()[1]->get_args()[0];
1104 VLOG(1) << "temp: " << solve_solution->__str__();
Austin Schuh6ea789e2024-07-27 13:45:53 -07001105 RCP<const Basic> drive_eqn_subs = full_drive_eqn->subs(map);
justinT21446e4f62024-06-16 22:36:10 -07001106
1107 map.clear();
Austin Schuh6ea789e2024-07-27 13:45:53 -07001108 map[alphas] = result.full.alphas_eqn;
justinT21446e4f62024-06-16 22:36:10 -07001109 RCP<const Basic> drive_eqn_subs2 = drive_eqn_subs->subs(map);
1110 RCP<const Basic> drive_eqn_subs3 = simplify(drive_eqn_subs2);
Austin Schuh6ea789e2024-07-27 13:45:53 -07001111 VLOG(1) << "full_drive_eqn simplified: " << drive_eqn_subs3->__str__();
justinT21446e4f62024-06-16 22:36:10 -07001112
Austin Schuh6ea789e2024-07-27 13:45:53 -07001113 solve_solution = solve(drive_eqn_subs3, alphad, reals);
justinT21446e4f62024-06-16 22:36:10 -07001114
Austin Schuh6ea789e2024-07-27 13:45:53 -07001115 result.full.alphad_eqn =
justinT21446e4f62024-06-16 22:36:10 -07001116 simplify(solve_solution->get_args()[1]->get_args()[0]);
Austin Schuh6ea789e2024-07-27 13:45:53 -07001117 VLOG(1) << "drive_accel: " << result.full.alphad_eqn->__str__();
justinT21446e4f62024-06-16 22:36:10 -07001118
Austin Schuh2a1abec2024-07-10 20:31:16 -07001119 // Compute the resulting force from the module.
Austin Schuh6ea789e2024-07-27 13:45:53 -07001120 result.full.F = DenseMatrix(2, 1);
Austin Schuhb8b34be2024-07-14 16:06:19 -07001121 mul_dense_dense(R(add(theta_, result.thetas)),
Austin Schuh6ea789e2024-07-27 13:45:53 -07001122 DenseMatrix(2, 1, {result.full.Fwx, result.Fwy}),
1123 result.full.F);
justinT21d18f79f2024-09-22 19:43:05 -07001124
1125 DenseMatrix rotated_mounting_location = DenseMatrix(2, 1);
1126 mul_dense_dense(R(theta_), result.mounting_location,
1127 rotated_mounting_location);
1128 result.full.torque = force_cross(rotated_mounting_location, result.full.F);
justinT21446e4f62024-06-16 22:36:10 -07001129
Austin Schuh6ea789e2024-07-27 13:45:53 -07001130 result.direct.F = DenseMatrix(2, 1);
1131 mul_dense_dense(R(add(theta_, result.thetas)),
1132 DenseMatrix(2, 1, {result.direct.Fwx, result.Fwy}),
1133 result.direct.F);
1134 result.direct.torque =
justinT21d18f79f2024-09-22 19:43:05 -07001135 force_cross(rotated_mounting_location, result.direct.F);
justinT21446e4f62024-06-16 22:36:10 -07001136
1137 VLOG(1);
Austin Schuh6ea789e2024-07-27 13:45:53 -07001138 VLOG(1) << "full torque = " << result.full.torque->__str__();
1139 VLOG(1) << "direct torque = " << result.full.torque->__str__();
justinT21446e4f62024-06-16 22:36:10 -07001140
justinT21446e4f62024-06-16 22:36:10 -07001141 return result;
1142 }
1143
1144 DenseMatrix R(const RCP<const Basic> theta) {
1145 return DenseMatrix(2, 2,
1146 {cos(theta), neg(sin(theta)), sin(theta), cos(theta)});
1147 }
1148
1149 DenseMatrix angle_cross(DenseMatrix a, RCP<const Basic> b) {
Austin Schuh2a1abec2024-07-10 20:31:16 -07001150 return DenseMatrix(2, 1, {mul(neg(a.get(1, 0)), b), mul(a.get(0, 0), b)});
justinT21446e4f62024-06-16 22:36:10 -07001151 }
1152
1153 RCP<const Basic> force_cross(DenseMatrix r, DenseMatrix f) {
1154 return sub(mul(r.get(0, 0), f.get(1, 0)), mul(r.get(1, 0), f.get(0, 0)));
1155 }
1156
1157 // z represents the number of teeth per gear, theta is the angle between
1158 // shafts(in degrees), D_02 is the pitch diameter of gear 2 and b_2 is the
1159 // length of the tooth of gear 2
1160 // returns std::pair(r_01, r_02)
1161 std::pair<double, double> GetBevelPitchRadius(double z1, double z2,
1162 double theta, double D_02,
1163 double b_2) {
1164 double gamma_1 = std::atan2(z1, z2);
1165 double gamma_2 = theta / 180.0 * std::numbers::pi - gamma_1;
1166 double R_m = D_02 / 2 / std::sin(gamma_2) - b_2 / 2;
1167 return std::pair(R_m * std::cos(gamma_2), R_m * std::sin(gamma_2));
1168 }
1169
1170 Motor drive_motor_;
1171 Motor steer_motor_;
1172
1173 RCP<const Basic> Cx_;
1174 RCP<const Basic> Cy_;
Austin Schuh2a1abec2024-07-10 20:31:16 -07001175 RCP<const Basic> rw_;
justinT21446e4f62024-06-16 22:36:10 -07001176 RCP<const Basic> m_;
1177 RCP<const Basic> J_;
1178 RCP<const Basic> Gd1_;
1179 RCP<const Basic> rs_;
1180 RCP<const Basic> rp_;
1181 RCP<const Basic> Gd2_;
1182 RCP<const Basic> rb1_;
1183 RCP<const Basic> rb2_;
1184 RCP<const Basic> Gd3_;
1185 RCP<const Basic> Gd_;
1186 RCP<const Basic> Js_;
1187 RCP<const Basic> Gs_;
1188 RCP<const Basic> wb_;
1189 RCP<const Basic> Jdm_;
1190 RCP<const Basic> Jsm_;
1191 RCP<const Basic> Kts_;
1192 RCP<const Basic> Ktd_;
1193 RCP<const Basic> robot_width_;
1194 RCP<const Basic> caster_;
1195 RCP<const Basic> contact_patch_length_;
1196 RCP<const Basic> x_;
1197 RCP<const Basic> y_;
1198 RCP<const Basic> theta_;
1199 RCP<const Basic> vx_;
1200 RCP<const Basic> vy_;
1201 RCP<const Basic> omega_;
1202 RCP<const Basic> ax_;
1203 RCP<const Basic> ay_;
1204 RCP<const Basic> atheta_;
1205
1206 std::array<Module, kNumModules> modules_;
1207
Austin Schuh6ea789e2024-07-27 13:45:53 -07001208 DenseMatrix full_accel_;
1209 RCP<const Basic> full_angular_accel_;
1210 DenseMatrix direct_accel_;
1211 RCP<const Basic> direct_angular_accel_;
justinT21446e4f62024-06-16 22:36:10 -07001212};
1213
1214} // namespace frc971::control_loops::swerve
1215
1216int main(int argc, char **argv) {
1217 aos::InitGoogle(&argc, &argv);
1218
1219 frc971::control_loops::swerve::SwerveSimulation sim;
1220
Austin Schuh99f7c6a2024-06-25 22:07:44 -07001221 if (!absl::GetFlag(FLAGS_cc_output_path).empty() &&
1222 !absl::GetFlag(FLAGS_h_output_path).empty()) {
1223 sim.Write(absl::GetFlag(FLAGS_cc_output_path),
1224 absl::GetFlag(FLAGS_h_output_path));
Austin Schuh0f881092024-06-28 15:36:48 -07001225 }
Austin Schuh99f7c6a2024-06-25 22:07:44 -07001226 if (!absl::GetFlag(FLAGS_casadi_py_output_path).empty()) {
1227 sim.WriteCasadi(absl::GetFlag(FLAGS_casadi_py_output_path));
Austin Schuh0f881092024-06-28 15:36:48 -07001228 }
justinT21446e4f62024-06-16 22:36:10 -07001229
1230 return 0;
1231}