diff --git a/src/lib/tecs/TECSControlClosedLoopTest.cpp b/src/lib/tecs/TECSControlClosedLoopTest.cpp index de0cd98ef42..b7c05dc10df 100644 --- a/src/lib/tecs/TECSControlClosedLoopTest.cpp +++ b/src/lib/tecs/TECSControlClosedLoopTest.cpp @@ -629,3 +629,36 @@ TEST_F(TECSControlClosedLoopTest, AirspeedlessAltitudeStepHalfFeedforward) EXPECT_LT(_sim_stats.max_airspeed_error, MAX_NUMERICAL_ERR_OPENLOOP) << "peak at t=" << _sim_stats.t_max_airspeed_error << " s"; EXPECT_LT(_sim_stats.max_pitch_integ_norm, MAX_NUMERICAL_ERR_OPENLOOP); } + +// --- Energy error phase portrait ----------------------------------------------- +// Every combination of a {+1, 0, -1} J/kg specific kinetic and potential energy error (setpoint - state), each +// started from level flight at the offset state with the setpoints at trim. The plant flies level at trim throttle at +// any airspeed, so the offset state is a steady state of the plant. All cases go into one CSV, each restarting at t = 0, +// which plot_closed_loop.py draws as a phase portrait in the (SKE error, SPE error) plane. + +TEST_F(TECSControlClosedLoopTest, EnergyErrorPhasePortrait) +{ + static constexpr float ENERGY_ERROR = 1.f; // [J/kg] + + // 1 J/kg is 0.1 m: at ALT_INIT the float altitude resolution stalls the final convergence + setAltitudeSetpoint(0.f); + + for (int ske_sign = -1; ske_sign <= 1; ske_sign++) { + for (int spe_sign = -1; spe_sign <= 1; spe_sign++) { + const float ske_error = ske_sign * ENERGY_ERROR; + const float spe_error = spe_sign * ENERGY_ERROR; + + _state = {sqrtf(_V_sp * _V_sp - 2.f * ske_error), _alt_sp - spe_error / CONSTANTS_ONE_G}; + _pitch = 0.f; + _throttle = _params.throttle_trim; + _step = 0; + _t = 0.f; + initTecs(); + + run(60.f); + + EXPECT_NEAR(_state.V, _V_sp, TRACKING_ERROR_TOL) << "SKE error " << ske_error << " SPE error " << spe_error; + EXPECT_NEAR(_state.h, _alt_sp, TRACKING_ERROR_TOL) << "SKE error " << ske_error << " SPE error " << spe_error; + } + } +} diff --git a/src/lib/tecs/plot_closed_loop.py b/src/lib/tecs/plot_closed_loop.py index 78fc168863a..e62b18624de 100755 --- a/src/lib/tecs/plot_closed_loop.py +++ b/src/lib/tecs/plot_closed_loop.py @@ -16,6 +16,10 @@ Each CSV becomes one figure with eight panels on a shared time axis: altitude, airspeed, pitch, throttle, total energy rate, energy balance rate, altitude rate and airspeed rate. The measured rates are finite differences of the logged states. + +A CSV holding several cases (time restarting at 0) is drawn as a phase portrait of the +energy errors instead: one trajectory per case in the (SKE error, SPE error) +plane, errors being setpoint - state. Only numpy and matplotlib are required. """ @@ -35,6 +39,17 @@ C_INTEG = "#6250d6" # integrator contribution C_GRID = "#d8d7d2" C_TEXT = "#52514e" +G = 9.80665 # [m/s^2] + +# Phase portrait trajectory label and colour by the sign of the initial (SKE error, SPE error). +PHASE_CASES = { + (1, 0): ("SKE", "#1f77b4"), + (0, 1): ("SPE", "#ff7f0e"), + (1, 1): ("STE", "#2ca02c"), + (-1, 1): ("SEB", "#d62728"), +} +PHASE_CASES.update({(-x, -y): ("−" + label, c) for (x, y), (label, c) in list(PHASE_CASES.items())}) + REQUIRED = ["t", "V", "h", "V_sp", "alt_sp", "pitch_cmd", "throttle", "pitch_integ", "throttle_integ", "ste_rate_sp", "ste_rate_est", "seb_rate_sp", "seb_rate_est"] @@ -133,6 +148,47 @@ def plot(d, title): return fig +def split_cases(d): + """Index slices of the cases in a CSV, each starting where the time restarts.""" + starts = np.concatenate(([0], np.flatnonzero(np.diff(d["t"]) < 0) + 1, [len(d["t"])])) + return [slice(a, b) for a, b in zip(starts[:-1], starts[1:])] + + +def plot_phase(d, title): + fig, ax = plt.subplots(figsize=(6, 6)) + ax.set_title(title) + ax.axhline(0, color="k", lw=0.5) + ax.axvline(0, color="k", lw=0.5) + + for m in split_cases(d): + e_ske = 0.5 * (d["V_sp"][m] ** 2 - d["V"][m] ** 2) + e_spe = G * (d["alt_sp"][m] - d["h"][m]) + key = (int(np.sign(np.round(e_ske[0], 3))), int(np.sign(np.round(e_spe[0], 3)))) + + if key not in PHASE_CASES: + continue # zero initial error: nothing to draw + + label, c = PHASE_CASES[key] + ax.plot(e_ske, e_spe, color=c, lw=2) + ax.plot(e_ske[0], e_spe[0], "o", color=c, ms=9) + ax.annotate(label, (e_ske[0], e_spe[0]), xytext=(6, 6), textcoords="offset points", + color=c, fontsize=12, fontweight="bold") + + # Direction arrow halfway along the path + s = np.concatenate(([0.0], np.cumsum(np.hypot(np.diff(e_ske), np.diff(e_spe))))) + i = min(int(np.searchsorted(s, 0.5 * s[-1])), len(s) - 2) + ax.annotate("", xy=(e_ske[i + 1], e_spe[i + 1]), xytext=(e_ske[i], e_spe[i]), + arrowprops=dict(arrowstyle="-|>", color=c, lw=2, mutation_scale=18)) + + ax.set_xlim(-1.5, 1.5) + ax.set_ylim(-1.5, 1.5) + ax.set_aspect("equal") + ax.set_xlabel("SKE error [J/kg]") + ax.set_ylabel("SPE error [J/kg]") + fig.tight_layout() + return fig + + def collect(paths): files = [] @@ -170,7 +226,8 @@ def main(): args.out.mkdir(parents=True, exist_ok=True) for f in files: - fig = plot(load(f), f.stem) + d = load(f) + fig = (plot_phase if len(split_cases(d)) > 1 else plot)(d, f.stem) if args.out: target = args.out / f"{f.stem}.png"