Nothing beyond bitsim itself. To make the pictures of the GIF, bitsim built with OpenCV. See Installing bitsim.
Both the LQR and MPC weigh the deviations from the trim at the reference, a heading and an altitude, by Bryson's rule: one over the square of how much of each is acceptable, 0.25 m of altitude, 1 m/s, 0.2 rad of bank, 0.1 rad of pitch and of heading, 0.5 rad/s, 0.1 rad of each control surface and 0.2 of throttle.
The example exits with an error unless MPC keeps within its bound on the bank and ends on the heading and the altitude it was given, so it runs as a test too.
The LQR does what its cost asks: it turns in 2.2 s, and climbs in 2.2 s, with no overshoot. To do it, it rolls to 75 degrees and pitches to 46, an aircraft standing on its wing and then on its tail, far outside the linear model it was designed on. In the turn it loses 4.6 m of altitude, because at 75 degrees of bank the wing's lift is mostly sideways, and nothing in a linear model about level flight says so.
MPC turns at 25 degrees of bank, the most its bound allows, and takes 6.8 s; it climbs at 15 degrees of pitch above the trim, 18 in all, in 3.5 s. It does not lose altitude in the turn, and overshoots the climb by 0.2 m. The autopilot takes as long, and goes past its own limit of 30 degrees, to 34: its loops limit what they command, not what the aircraft does. It loses 0.6 m in the turn, overshoots the heading by 2 degrees and the climb by 2 m.
The comparison is with the autopilot's default design, which was not tuned for these steps. What MPC adds is the limits, kept by the controller itself, with the same weights as the LQR: an LQR that should not bank beyond 25 degrees would need its weights tuned until it happens not to, for this step and every other.
#include "bitsim/bitsim_config.h"
#ifdef BITSIM_OPENCV
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#endif
#include <array>
#include <cmath>
#include <cstdio>
#include <filesystem>
#include <iostream>
#include <limits>
#include <string>
#include <vector>
{
const real_t PI = 3.14159265358979323846;
const std::array<int, 10>
STATES{fw::PD, fw::U, fw::V, fw::W, fw::PHI,
fw::THETA, fw::PSI, fw::P, fw::Q, fw::R};
struct Track
{
std::vector<std::array<real_t, 2>>
ground;
std::vector<real_t>
bank;
std::vector<real_t>
pitch;
};
{
u << c.elevator, c.aileron, c.rudder, c.throttle;
return u;
}
{
c.aileron = u[1];
c.rudder = u[2];
c.throttle = u[3];
return c;
}
{
{
}
dx[0] = aircraft.state()[
fw::PD] + altitude_ref;
dx[6] = std::remainder(aircraft.state()[
fw::PSI] - heading_ref, 2.0 *
PI);
return dx;
}
{
track.ground.push_back({a.state()[
fw::PN], a.state()[
fw::PE]});
track.bank.push_back(a.state()[
fw::PHI]);
track.heading.push_back(a.state()[
fw::PSI]);
track.altitude.push_back(a.altitude());
}
#ifdef BITSIM_OPENCV
const std::array<cv::Scalar, 3>
COLOURS{cv::Scalar(60, 60, 220), cv::Scalar(200, 120, 30),
cv::Scalar(40, 150, 40)};
{
cv::Mat picture(H, W, CV_8UC3, cv::Scalar(250, 250, 250));
const auto text =
[&](const std::string &s, cv::Point at, const cv::Scalar &colour, double size = 0.5)
{ cv::putText(picture, s, at, cv::FONT_HERSHEY_SIMPLEX, size, colour, 1, cv::LINE_AA); };
const cv::Rect map(20, 40, 920, 160);
cv::rectangle(picture, map, cv::Scalar(200, 200, 200), 1);
{
return cv::Point(map.x + static_cast<int>((east + 50.0) * scale),
map.y + map.height - 8 - static_cast<int>(north * scale));
};
text("from above", {map.x, map.y - 12}, cv::Scalar(60, 60, 60));
for (
uint_t i = 0; i < tracks.size(); ++i)
{
const auto &g = tracks[i].ground;
for (
uint_t j = 1; j <= k && j < g.size(); ++j)
{
cv::line(picture, ground_px(g[j - 1][0], g[j - 1][1]), ground_px(g[j][0], g[j][1]),
}
const auto here = ground_px(g[k][0], g[k][1]);
const real_t psi = tracks[i].heading[k];
const cv::Point nose(here.x + static_cast<int>(12 * std::sin(psi)),
here.y - static_cast<int>(12 * std::cos(psi)));
cv::circle(picture, here, 4,
COLOURS[i], -1, cv::LINE_AA);
cv::line(picture, here, nose,
COLOURS[i], 2, cv::LINE_AA);
}
const auto plot = [&](
const cv::Rect &box,
const std::string &title,
real_t lo,
real_t hi,
const std::vector<real_t> &marks, auto value)
{
cv::rectangle(picture, box, cv::Scalar(200, 200, 200), 1);
text(title, {box.x, box.y - 8}, cv::Scalar(60, 60, 60));
{
return cv::Point(box.x +
static_cast<int>(j * sample_period /
DURATION * box.width),
box.y + box.height -
static_cast<int>((v - lo) / (hi - lo) * box.height));
};
{
for (int x = box.x; x < box.x + box.width; x += 10)
{
const int y = px(0, m).y;
cv::line(picture, {x, y}, {x + 5, y}, cv::Scalar(150, 150, 150), 1);
}
}
for (
uint_t i = 0; i < tracks.size(); ++i)
{
for (
uint_t j = 1; j <= k; ++j)
{
cv::line(picture, px(j - 1, value(tracks[i], j - 1)), px(j, value(tracks[i], j)),
}
}
};
plot(cv::Rect(20, 250, 440, 250), "bank [deg], with MPC's bound", -30.0, 80.0, {-25.0, 25.0},
plot(cv::Rect(500, 250, 440, 250), "altitude [m]", 90.0, 125.0, {100.0, 120.0},
[](
const Track &t,
uint_t j) {
return t.altitude[j]; });
char status[120];
std::snprintf(status, sizeof(status), "t %4.1f s", k * sample_period);
text(status, {20, 530}, cv::Scalar(30, 30, 30));
for (
uint_t i = 0; i < tracks.size(); ++i)
{
text(tracks[i].name, {140 + 110 *
static_cast<int>(i), 530},
COLOURS[i]);
}
return picture;
}
void record(
const std::vector<Track> &tracks,
const std::string &directory,
real_t sample_period)
{
std::filesystem::create_directories(directory);
const auto every =
static_cast<uint_t>(std::lround(1.0 / (
RECORD_RATE * sample_period)));
for (
uint_t k = 0; k < tracks.front().ground.size(); k += every)
{
char name[32];
std::snprintf(name, sizeof(name), "/frame_%04u.png", static_cast<unsigned>(n++));
cv::imwrite(directory + name,
draw(tracks, k, sample_period));
}
std::cout << "Wrote " << n << " pictures to " << directory << std::endl;
}
#endif
}
int main(
int argc,
char **argv)
{
std::string record_dir;
for (int i = 1; i < argc; ++i)
{
const std::string arg = argv[i];
if (arg == "--record" && i + 1 < argc)
{
record_dir = argv[++i];
}
else
{
std::cerr << "Usage: fixed_wing_lqr_mpc [--record DIR]\n";
return 1;
}
}
{
{
}
for (
uint_t j = 0; j < 4; ++j)
{
B(i, j) = linear.B(
STATES[i], j);
}
}
q << 16, 1, 1, 1, 25, 100, 100, 4, 4, 4;
r << 100, 100, 100, 25;
const Matrix Q = q.asDiagonal().toDenseMatrix();
const Matrix R = r.asDiagonal().toDenseMatrix();
const real_t inf = std::numeric_limits<real_t>::infinity();
mpc.set_model(model.A, model.B);
mpc.set_weights(Q, R);
u_lo << -p.max_elevator, -p.max_aileron, -p.max_rudder, 0.0;
u_hi << p.max_elevator, p.max_aileron, p.max_rudder, p.max_throttle;
mpc.set_input_bounds(u_lo - u_trim, u_hi - u_trim);
Vector x_lo = Vector::Constant(10, -inf);
Vector x_hi = Vector::Constant(10, inf);
mpc.set_state_bounds(x_lo, x_hi,
PENALTY);
std::vector<Track> tracks{{"LQR", {}, {}, {}, {}, {}},
{"MPC", {}, {}, {}, {}, {}},
{"autopilot", {}, {}, {}, {}, {}}};
for (
uint_t k = 0; k <= steps; ++k)
{
if (k % every == 0)
{
const Vector lqr_dx =
deviation(aircraft[0], trim, heading_ref, altitude_ref);
const Vector mpc_dx =
deviation(aircraft[1], trim, heading_ref, altitude_ref);
unsolved += mpc.status() == bitsim::control::LinearMPC::QPStatus::SOLVED ? 0 : 1;
++n_solves;
commands.
course = heading_ref;
controls[2] = autopilot.update(aircraft[2], commands,
CONTROL_PERIOD);
for (
uint_t i = 0; i < 3; ++i)
{
}
}
for (
uint_t i = 0; i < 3; ++i)
{
aircraft[i].step(controls[i],
STEP);
}
}
std::printf("%-10s %9s %10s %22s %18s %14s %10s %20s\n", "", "max bank", "max pitch",
"turn: heading overshoot", "within 2 deg after", "lowest", "climb: max",
"within 0.5 m after");
for (const auto &track : tracks)
{
for (
uint_t j = 0; j < track.bank.size(); ++j)
{
bank = std::max(bank, std::abs(track.bank[j]));
pitch = std::max(pitch, std::abs(track.pitch[j]));
{
const real_t off = std::remainder(track.heading[j] - 90.0 *
DEG, 2.0 *
PI);
overshoot = std::max(overshoot, off);
lowest = std::min(lowest, track.altitude[j]);
if (turned < 0.0 && std::abs(off) < 2.0 *
DEG)
{
}
}
{
top = std::max(top, track.altitude[j]);
if (climbed < 0.0 && std::abs(track.altitude[j] -
ALTITUDE - 20.0) < 0.5)
{
}
}
}
std::printf(
"%-10s %5.1f deg %6.1f deg %18.1f deg %16.1f s %12.1f m %8.1f m %18.1f s\n",
track.name.c_str(), bank /
DEG, pitch /
DEG, overshoot /
DEG, turned, lowest, top,
climbed);
}
std::printf("\nMPC solved %u QPs, %u of them not to the tolerance\n",
static_cast<unsigned>(n_solves), static_cast<unsigned>(unsolved));
if (!record_dir.empty())
{
#ifdef BITSIM_OPENCV
#else
std::cerr << "--record needs bitsim built with OpenCV\n";
return 1;
#endif
}
for (
const real_t b : tracks[1].bank)
{
mpc_bank = std::max(mpc_bank, std::abs(b));
}
const real_t final_heading = tracks[1].heading.back();
std::abs(std::remainder(final_heading - 90.0 *
DEG, 2.0 *
PI)) < 1.0 *
DEG &&
std::abs(tracks[1].altitude.back() -
ALTITUDE - 20.0) < 0.5;
return ok ? 0 : 1;
}
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
Holds airspeed, altitude and course with loops closed one inside the other, as in Beard and McLain,...
Definition fixed_wing_autopilot.h:78
Model predictive control with a linear model, a quadratic cost and bounds on the inputs and the state...
Definition linear_mpc.h:46
The 6-DOF flight dynamics of a fixed wing aircraft, with its landing gear on a flat ground at down = ...
Definition fixed_wing_dynamics.h:176
int main()
Definition discounted_returns.cpp:19
The trim of a fixed wing aircraft for level flight, its linear model about a trim,...
Linear quadratic regulators: the Riccati equations, the discretisation of a linear model,...
DiscreteLinearModel discretise(const Matrix &A, const Matrix &B, real_t dt)
Discretise for a step dt, with the input held over the step (zero-order hold): and ,...
Definition lqr.cpp:41
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
Where each value is in a FixedWingState.
Definition fixed_wing_dynamics.h:25
@ THETA
Definition fixed_wing_dynamics.h:35
@ PE
Definition fixed_wing_dynamics.h:29
@ PD
Definition fixed_wing_dynamics.h:30
@ PN
Definition fixed_wing_dynamics.h:28
@ Q
Definition fixed_wing_dynamics.h:38
@ PSI
Definition fixed_wing_dynamics.h:36
@ PHI
Definition fixed_wing_dynamics.h:34
@ R
Definition fixed_wing_dynamics.h:39
@ W
Definition fixed_wing_dynamics.h:33
FixedWingTrim trim_level_flight(const FixedWingParameters ¶meters, real_t airspeed, real_t altitude, real_t heading)
Find the controls for straight and level flight at the given airspeed, with no wind....
Definition fixed_wing_trim.cpp:108
FixedWingLinearModel linearise(const FixedWingParameters ¶meters, const FixedWingTrim &trim)
Linearise the dynamics about a trim, by central differences.
Definition fixed_wing_trim.cpp:194
const GeomPoint< spacedim, T > scale(const GeomPoint< spacedim, T > &t, T factor)
scale the given point by facto and returns a copyr. This function does not change the entries of t.
Definition geom_point.h:421
@ off
Definition logger.h:51
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
double real_t
real_t
Definition bitsim_types.h:20
H
Definition extended_kalman_filter.py:42
Definition fixed_wing_lqr_mpc.cpp:34
void record(const std::vector< Track > &tracks, const std::string &directory, real_t sample_period)
Definition fixed_wing_lqr_mpc.cpp:203
void record_track(Track &track, const FixedWingDynamics &a)
Definition fixed_wing_lqr_mpc.cpp:108
const real_t MAX_PITCH
Definition fixed_wing_lqr_mpc.cpp:57
const std::array< cv::Scalar, 3 > COLOURS
Definition fixed_wing_lqr_mpc.cpp:118
const real_t RECORD_RATE
Definition fixed_wing_lqr_mpc.cpp:59
Vector deviation(const FixedWingDynamics &aircraft, const bitsim::dynamics::FixedWingTrim &trim, real_t heading_ref, real_t altitude_ref)
Definition fixed_wing_lqr_mpc.cpp:95
const real_t AIRSPEED
Definition fixed_wing_lqr_mpc.cpp:50
const real_t PENALTY
Definition fixed_wing_lqr_mpc.cpp:58
Vector controls_vector(const FixedWingControls &c)
Definition fixed_wing_lqr_mpc.cpp:77
const real_t MAX_BANK
Definition fixed_wing_lqr_mpc.cpp:56
const real_t ALTITUDE
Definition fixed_wing_lqr_mpc.cpp:51
const real_t DURATION
Definition fixed_wing_lqr_mpc.cpp:54
const real_t TURN_AT
Definition fixed_wing_lqr_mpc.cpp:52
const real_t STEP
Definition fixed_wing_lqr_mpc.cpp:48
const real_t DEG
Definition fixed_wing_lqr_mpc.cpp:47
FixedWingControls to_controls(const Vector &u)
Definition fixed_wing_lqr_mpc.cpp:84
const real_t CLIMB_AT
Definition fixed_wing_lqr_mpc.cpp:53
const real_t PI
Definition fixed_wing_lqr_mpc.cpp:46
const uint_t HORIZON
Definition fixed_wing_lqr_mpc.cpp:55
const std::array< int, 10 > STATES
Definition fixed_wing_lqr_mpc.cpp:63
cv::Mat draw(const std::vector< Track > &tracks, uint_t k, real_t sample_period)
Definition fixed_wing_lqr_mpc.cpp:123
const real_t CONTROL_PERIOD
Definition fixed_wing_lqr_mpc.cpp:49
What the autopilot holds.
Definition fixed_wing_autopilot.h:15
real_t airspeed
[m/s]
Definition fixed_wing_autopilot.h:16
real_t course
the direction over the ground [rad]
Definition fixed_wing_autopilot.h:18
real_t altitude
[m]
Definition fixed_wing_autopilot.h:17
Matrix K
Definition lqr.h:75
What the pilot or the autopilot sets.
Definition fixed_wing_dynamics.h:47
real_t elevator
[rad]; positive is trailing edge down, which pitches the nose down
Definition fixed_wing_dynamics.h:48
The aircraft: its mass, its geometry, its aerodynamic coefficients, its propeller and motor,...
Definition fixed_wing_dynamics.h:73
FixedWingControls controls
Definition fixed_wing_trim.h:28
FixedWingState state
Definition fixed_wing_trim.h:27
static FixedWingParameters aerosonde()
The Aerosonde of Beard and McLain, Small Unmanned Aircraft, 2nd edition, with a tricycle landing gear...
Definition fixed_wing_dynamics.h:130
Definition fixed_wing_lqr_mpc.cpp:68
std::vector< real_t > pitch
Definition fixed_wing_lqr_mpc.cpp:72
std::vector< real_t > altitude
Definition fixed_wing_lqr_mpc.cpp:74
std::string name
Definition fixed_wing_lqr_mpc.cpp:69
std::vector< real_t > heading
Definition fixed_wing_lqr_mpc.cpp:73
std::vector< real_t > bank
Definition fixed_wing_lqr_mpc.cpp:71
std::vector< std::array< real_t, 2 > > ground
Definition fixed_wing_lqr_mpc.cpp:70