Nothing beyond bitsim itself to run it. To see it, or to make the pictures of the GIF, bitsim built with Chrono and Irrlicht. See Installing bitsim.
The inputs of the LQR are the total thrust and the torques about the three axes, which quadrotor_mixer turns into the four rotor speeds. The example linearises one control period of the model, 10 steps with the inputs held, at hover: level, still, with the thrust carrying the weight. It does it by central differences of the model itself, so the linear model is that of the simulation, \(x_{k+1} = A x_k + B u_k\) for the deviations from hover.
The weights follow Bryson's rule: each is one over the square of how much of it is acceptable, 0.5 m of position, 1 m/s, 2 rad/s, 0.3 rad of tilt, 2 N of thrust and 0.05 N m of torque. dlqr() gives the gain, a 4 x 12 matrix, and the controller is
with \(x_{ref}\) the hover at the point of the path where the drone should be, moving at the path's velocity. The slowest mode of the closed loop halves in 0.29 s.
Both drones start at hover 2 m up and follow a reference that waits 2 s and then moves at 1 m/s along a square of 4 m, climbing to 3 m and coming back down; the cascade's is the same, 2.5 m to the west. At 22 s, hovering at the end, both are pushed: their velocity changes by 2 m/s to the east.
The example exits with an error if the LQR does not follow the path or does not recover from the push, so it runs as a test too.
Along the path, the LQR stays about 0.2 m from its reference, the cascade about 0.55 m. Neither gets to zero while it moves, because of the drag: at 1 m/s the drone has to lean to hold its speed, and its reference is level. The cascade lags more: with the gains chosen here its position loop is slower than the LQR. After the push, the LQR is off by at most 0.63 m and back within 0.1 m of its target in 1.8 s; the cascade by 0.77 m, and in 4.5 s.
That is a comparison of two designs, not of the two kinds of controller. The cascade's gains were chosen by hand, and faster gains would close part of the gap. What the LQR gives is a systematic way to get gains for all twelve states at once from what matters, the weights, and the tilt, the speeds and the position are balanced against one another by the same cost.
#include "bitsim/bitsim_config.h"
#if defined(BITSIM_IRRLICHT) && defined(BITSIM_CHRONO)
#endif
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <optional>
#include <string>
#include <thread>
#include <vector>
{
const std::array<const char *, 12>
NAMES{
"x",
"y",
"z",
"u",
"v",
"w",
"p", "q", "r", "phi", "theta", "psi"};
{
QuadrotorDynamicsConfig config;
config.mass = 0.468;
config.l = 0.225;
config.k_1 = 2.980e-6;
config.k_2 = 1.140e-7;
config.Jx = 4.856e-3;
config.Jy = 4.856e-3;
config.Jz = 8.801e-3;
config.drag = 0.25;
return config;
}
{
std::array<std::pair<std::string, real_t>, 12>
values;
for (
uint_t i = 0; i < 12; ++i)
{
}
}
{
for (
uint_t i = 0; i < 12; ++i)
{
}
return x;
}
{
max_rotor_speed);
}
{
const RealVec rotors =
mix(config, u, max_rotor_speed);
{
dynamics.integrate(rotors);
}
}
{
bitsim::control::DiscreteLinearModel model{
Matrix(12, 12),
Matrix(12, 4)};
{
model.
A.col(j) = (
step(config, plus, u_hover, max_rotor_speed) -
step(config, minus, u_hover, max_rotor_speed)) /
(2.0 * h);
}
{
const real_t hu =
h * std::max(1.0, std::abs(u_hover[j]));
plus[j] += hu;
minus[j] -= hu;
model.
B.col(j) = (
step(config, hover, plus, max_rotor_speed) -
step(config, hover, minus, max_rotor_speed)) /
(2.0 * hu);
}
return model;
}
{
std::vector<RealColVec3d>
corners{{0, 0, -2}, {4, 0, -2}, {4, 4, -3}, {0, 4, -3}, {0, 0, -2}};
{
{
if (s <= leg.norm())
{
return corners[i] + leg * (s / leg.norm());
}
s -= leg.norm();
}
}
{
return (
at(time + h) -
at(std::max(0.0, time - h))) / (time +
h - std::max(0.0, time - h));
}
};
{
const real_t cy = std::cos(yaw), sy = std::sin(yaw);
const real_t cp = std::cos(pitch), sp = std::sin(pitch);
const real_t cr = std::cos(roll), sr = std::sin(roll);
R << cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr,
sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr,
-sp, cp * sr, cp * cr;
}
{
Drone(
const std::string &n,
const RealColVec3d &o,
const QuadrotorDynamicsConfig &config,
{
}
{
}
{
}
{
{
}
else
{
if (e > 0.1)
{
}
{
}
}
}
};
{
const RealColVec3d v = drone.world_velocity() - target_velocity;
const real_t a_north = kp * e[0] - kd * v[0];
const real_t a_east = kp * e[1] - kd * v[1];
const real_t a_up = -kp_z * e[2] + kd_z * v[2];
const auto &d = drone.dynamics;
command.pitch = std::atan(a_north /
G) / max_tilt;
command.roll = std::atan(a_east /
G) / max_tilt;
controller.hover_throttle() * (1.0 + a_up /
G) / (std::cos(d.phi()) * std::cos(d.theta()));
}
{
};
{
const real_t max_rotor_speed = flight_controller.max_rotor_speed();
Vector hover = Vector::Zero(12);
hover.head(3) = path.at(0.0);
Vector u_hover = Vector::Zero(4);
u_hover[0] = config.mass *
G;
const auto model =
linearise(config, hover, u_hover, max_rotor_speed);
q << 4, 4, 4, 1, 1, 1, 0.25, 0.25, 0.25, 11, 11, 11;
r << 0.25, 400, 400, 400;
r.asDiagonal().toDenseMatrix());
std::printf("LQR designed at hover: the slowest closed loop mode decays by %.4f a step, %.2f "
"s to halve\n",
A_closed.eigenvalues().cwiseAbs().maxCoeff(),
std::log(0.5) / std::log(A_closed.eigenvalues().cwiseAbs().maxCoeff()) *
Drone lqr_drone(
"LQR", RealColVec3d::Zero(), config, hover);
#if defined(BITSIM_IRRLICHT) && defined(BITSIM_CHRONO)
using bitsim::utils::render::QuadrotorView;
std::optional<QuadrotorView> view;
if (options.render || !options.record.empty())
{
QuadrotorView::Style lqr_style;
lqr_style.body = chrono::ChColor(0.25f, 0.45f, 0.8f);
lqr_style.trail = chrono::ChColor(0.3f, 0.6f, 1.0f);
QuadrotorView::Style cascade_style;
cascade_style.body = chrono::ChColor(0.85f, 0.45f, 0.1f);
cascade_style.trail = chrono::ChColor(1.0f, 0.8f, 0.2f);
view.emplace("A quadrotor flown by an LQR, and by a cascade of PD loops",
std::vector<QuadrotorView::Style>{lqr_style, cascade_style}, options.record,
}
#else
if (options.render || !options.record.empty())
{
std::cerr << "--render and --record need bitsim built with Chrono and Irrlicht\n";
return 1;
}
#endif
std::printf("\n time [s] reference LQR error [m] cascade error [m]\n");
const auto wall_start = std::chrono::steady_clock::now();
for (
uint_t k = 0; k <= steps; ++k)
{
{
cascade_drone.push(
PUSH);
}
lqr_drone.record_error(reference, time);
cascade_drone.record_error(reference + cascade_drone.offset, time);
if (time >= next_print - 1e-9)
{
std::printf("%9.1f (%4.1f %4.1f %4.1f) %13.3f %17.3f\n", time, reference[0],
reference[1], -reference[2], (lqr_drone.position() - reference).norm(),
(cascade_drone.position() - reference - cascade_drone.offset).norm());
}
#if defined(BITSIM_IRRLICHT) && defined(BITSIM_CHRONO)
if (view && time >= next_render - 1e-9)
{
view->set_targets({reference, reference + cascade_drone.offset});
char status[160];
std::snprintf(status, sizeof(status),
"t %5.1f s blue LQR: off by %.2f m orange cascade: off by %.2f m%s",
time, (lqr_drone.position() - reference).norm(),
(cascade_drone.position() - reference - cascade_drone.offset).norm(),
if (!view->show({&lqr_drone.dynamics, &cascade_drone.dynamics}, time, status))
{
break;
}
if (options.render)
{
const real_t ahead = time - std::chrono::duration<real_t>(
std::chrono::steady_clock::now() - wall_start)
.count();
if (ahead > 0.0)
{
std::this_thread::sleep_for(std::chrono::duration<real_t>(ahead));
}
}
}
#endif
const RealColVec3d reference_velocity = path.velocity(time);
x_ref.head(3) = reference;
x_ref.segment(3, 3) = reference_velocity;
const RealVec lqr_rotors =
mix(config, u, max_rotor_speed);
reference_velocity, flight_controller);
{
lqr_drone.dynamics.integrate(lqr_rotors);
cascade_drone.dynamics.integrate(
flight_controller.rotor_speeds(command, cascade_drone.dynamics));
}
}
std::printf("\n%-8s RMS error along the path [m] largest error after the push [m] back "
"within 0.1 m after [s]\n",
"");
for (
const Drone *d : {&lqr_drone, &cascade_drone})
{
std::printf("%-8s %28.3f %32.3f %26.2f\n", d->name.c_str(),
std::sqrt(d->sum_sq_error / std::max<uint_t>(1, d->n_errors)),
d->max_error_after_push, d->back_within_10cm);
}
const bool ok = lqr_drone.back_within_10cm > 0.0 &&
std::sqrt(lqr_drone.sum_sq_error / lqr_drone.n_errors) < 0.5;
return ok ? 0 : 1;
}
}
int main(
int argc,
char **argv)
{
for (int i = 1; i < argc; ++i)
{
const std::string arg = argv[i];
if (arg == "--render")
{
}
else if (arg == "--record" && i + 1 < argc)
{
}
else
{
std::cerr << "Usage: quadrotor_lqr [--render] [--record DIR]\n";
return 1;
}
}
}
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
The flight controller of a toy quadrotor in angle mode: it turns the sticks of an RCCommand into roto...
Definition quadrotor_flight_controller.h:52
The QuadrotorDynamics class. Implements quadrotor dynamics The implementation of this class follows t...
Definition quadrotor_dynamics.h:134
SysState utility class describing the state of a system.
Definition system_state.h:25
int main()
Definition discounted_returns.cpp:19
RealVec quadrotor_mixer(const dynamics::QuadrotorDynamicsConfig &config, real_t thrust, const RealColVec3d &tau, real_t max_rotor_speed)
The rotor speeds [rad/s] of a plus quadrotor (see dynamics::QuadrotorDynamics) that give the thrust T...
Definition quadrotor_flight_controller.cpp:13
Linear quadratic regulators: the Riccati equations, the discretisation of a linear model,...
const real_t G
Acceleration due to gravity m/secs.
Definition bitsim_consts.h:68
LQRSolution dlqr(const Matrix &A, const Matrix &B, const Matrix &Q, const Matrix &R)
The LQR of : with P from solve_dare().
Definition lqr.cpp:154
RealMat Matrix
The matrices of the linear models and the controllers.
Definition lqr.h:20
LQRSolution lqr(const Matrix &A, const Matrix &B, const Matrix &Q, const Matrix &R)
The LQR of : with P from solve_care().
Definition lqr.cpp:161
RealColVec Vector
The vectors of the linear models and the controllers: states, inputs.
Definition lqr.h:23
@ R
Definition fixed_wing_dynamics.h:39
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
Eigen::Index index_t
The type Eigen indexes and sizes matrices and vectors with.
Definition bitsim_types.h:45
DynVec< real_t > RealVec
double precision floating point vector
Definition bitsim_types.h:111
Eigen::Matrix3< real_t > RealMat3d
3×3 matrix of type double.
Definition bitsim_types.h:86
double real_t
real_t
Definition bitsim_types.h:20
Eigen::Vector3d RealColVec3d
3D column vector
Definition bitsim_types.h:137
std::map< std::string, std::any > command(real_t v, real_t w)
Definition diff_drive_kinematics.cpp:29
Controller controller(const MultiRobotNavigation &env, uint_t robot)
Definition distributed_robot_navigation.cpp:113
real_t h(real_t x)
Definition importance_sampling.cpp:39
state
Definition play.py:39
list values
Definition plot_losses.py:13
Definition quadrotor_lqr.cpp:36
const real_t SEPARATION
Definition quadrotor_lqr.cpp:61
const real_t DURATION
Definition quadrotor_lqr.cpp:60
const real_t PRINT_PERIOD
Definition quadrotor_lqr.cpp:62
const real_t START
Definition quadrotor_lqr.cpp:57
QuadrotorDynamicsConfig quadrotor_config()
Definition quadrotor_lqr.cpp:71
const real_t G
Definition quadrotor_lqr.cpp:52
RCCommand position_loop(const Drone &drone, const RealColVec3d &target, const RealColVec3d &target_velocity, const QuadrotorFlightController &controller)
Definition quadrotor_lqr.cpp:264
SysState< 12 > to_state(const Vector &x)
Definition quadrotor_lqr.cpp:86
int run(const Options &options)
Definition quadrotor_lqr.cpp:298
Vector to_vector(const SysState< 12 > &state)
Definition quadrotor_lqr.cpp:96
const real_t PUSH_AT
Definition quadrotor_lqr.cpp:58
RealMat3d body_to_world(real_t yaw, real_t pitch, real_t roll)
Definition quadrotor_lqr.cpp:189
const real_t SPEED
Definition quadrotor_lqr.cpp:56
const real_t PUSH
Definition quadrotor_lqr.cpp:59
const real_t CONTROL_PERIOD
Definition quadrotor_lqr.cpp:54
RealVec mix(const QuadrotorDynamicsConfig &config, const Vector &u, real_t max_rotor_speed)
Definition quadrotor_lqr.cpp:107
const uint_t SUB_STEPS
Definition quadrotor_lqr.cpp:55
const real_t RENDER_RATE
Definition quadrotor_lqr.cpp:63
const real_t STEP_SIZE
Definition quadrotor_lqr.cpp:53
Vector step(const QuadrotorDynamicsConfig &config, const Vector &x, const Vector &u, real_t max_rotor_speed)
Definition quadrotor_lqr.cpp:114
bitsim::control::DiscreteLinearModel linearise(const QuadrotorDynamicsConfig &config, const Vector &hover, const Vector &u_hover, real_t max_rotor_speed)
Definition quadrotor_lqr.cpp:129
const std::array< const char *, 12 > NAMES
Definition quadrotor_lqr.cpp:67
const real_t RECORD_RATE
Definition quadrotor_lqr.cpp:64
An Irrlicht window that shows quadrotors flying over a tiled floor. Needs bitsim built with Chrono an...
Matrix A
Definition lqr.h:30
Matrix B
Definition lqr.h:31
Matrix K
Definition lqr.h:75
What the sticks of a radio transmitter for a quadrotor say, as a toy drone's transmitter sends them: ...
Definition rc_command.h:20
Definition quadrotor_dynamics.h:13
real_t dt
The time step to use.
Definition quadrotor_dynamics.h:56
Definition quadrotor_lqr.cpp:203
void push(real_t east)
Definition quadrotor_lqr.cpp:229
RealColVec3d position() const
Definition quadrotor_lqr.cpp:219
real_t max_error_after_push
Definition quadrotor_lqr.cpp:210
void record_error(const RealColVec3d &reference, real_t time)
Definition quadrotor_lqr.cpp:238
real_t back_within_10cm
Definition quadrotor_lqr.cpp:211
Drone(const std::string &n, const RealColVec3d &o, const QuadrotorDynamicsConfig &config, const Vector &x0)
Definition quadrotor_lqr.cpp:213
real_t sum_sq_error
Definition quadrotor_lqr.cpp:208
std::string name
Definition quadrotor_lqr.cpp:204
QuadrotorDynamics dynamics
Definition quadrotor_lqr.cpp:207
SysState< 12 > state
Definition quadrotor_lqr.cpp:206
RealColVec3d world_velocity() const
Definition quadrotor_lqr.cpp:222
uint_t n_errors
Definition quadrotor_lqr.cpp:209
RealColVec3d offset
Definition quadrotor_lqr.cpp:205
Definition quadrotor_lqr.cpp:293
std::string record
Definition quadrotor_lqr.cpp:295
bool render
Definition quadrotor_lqr.cpp:294
Definition quadrotor_lqr.cpp:161
RealColVec3d velocity(real_t time) const
Definition quadrotor_lqr.cpp:180
std::vector< RealColVec3d > corners
Definition quadrotor_lqr.cpp:162
RealColVec3d at(real_t time) const
Definition quadrotor_lqr.cpp:164