From 563de9611b3e618f9061599d505859eee993feef Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Sun, 26 Jul 2026 17:17:37 +0000 Subject: [PATCH 1/4] add bang bang controller --- README.md | 2 +- ROADMAP.md | 7 -- doc/controllers/BangBangHysteresis.md | 103 ++++++++++++++++++ doc/controllers/README.md | 1 + .../implementations/BangBangHysteresis.cpp | 6 + .../implementations/BangBangHysteresis.hpp | 75 +++++++++++++ .../implementations/CMakeLists.txt | 2 + .../implementations/test/CMakeLists.txt | 1 + .../test/TestBangBangHysteresis.cpp | 92 ++++++++++++++++ 9 files changed, 281 insertions(+), 8 deletions(-) create mode 100644 doc/controllers/BangBangHysteresis.md create mode 100644 numerical/controllers/implementations/BangBangHysteresis.cpp create mode 100644 numerical/controllers/implementations/BangBangHysteresis.hpp create mode 100644 numerical/controllers/implementations/test/TestBangBangHysteresis.cpp diff --git a/README.md b/README.md index 5fa99af6..a4fa74ae 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal |--------------------------------------------------------------------|----------------------------------------------------------------------| | [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Window Functions | | [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus | -| [Controllers](doc/controllers/README.md) | PID, LQR, MPC | +| [Controllers](doc/controllers/README.md) | Bang-Bang/Hysteresis, PID, LQR, MPC | | [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA | | [Estimators](doc/estimators/README.md) | Linear Regression, Yule-Walker (offline), Recursive Least Squares (online) | | [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, FIR, IIR, Moving Average | diff --git a/ROADMAP.md b/ROADMAP.md index 500d6847..d84abc48 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -28,7 +28,6 @@ Difficulty legend: |----|------------------------------------------------------|---------------------------|------------| | 1 | Exponential Moving Average (one-pole) | `filters/passive` | ★☆☆☆☆ | | 3 | Saturation / rate-limiter / slew blocks | `controllers` | ★☆☆☆☆ | -| 4 | Bang-bang / hysteresis (relay) controller | `controllers` | ★☆☆☆☆ | | 5 | Peak / zero-crossing / RMS-envelope detectors | `analysis` | ★☆☆☆☆ | | 6 | Median filter | `filters/passive` | ★★☆☆☆ | | 7 | Feedforward / 2-DOF controller | `controllers` | ★★☆☆☆ | @@ -95,12 +94,6 @@ Difficulty legend: - **Algorithm / paper:** K. J. Åström, R. M. Murray, *Feedback Systems* (2008), actuator saturation & windup. - **Reuses:** Scalar/`Vector` templates. -### 4. Bang-bang / hysteresis (relay) controller -- **What:** Two-state relay output with a Schmitt-trigger dead-band to prevent chatter. -- **Embedded value:** The standard control law for thermostats, level control, and power-stage on/off regulation. -- **Algorithm / paper:** Åström & Murray, *Feedback Systems*, relay feedback; Ya. Z. Tsypkin, *Relay Control Systems* (1984). -- **Reuses:** `controllers` interfaces. - ### 5. Peak / zero-crossing / RMS-envelope detectors - **What:** Lightweight feature extractors: rising/falling peak hold, sign-change (zero-crossing) counter, and RMS envelope via one-pole on `x²`. - **Embedded value:** Cheap building blocks for frequency estimation, VU metering, activity detection, and event triggers. diff --git a/doc/controllers/BangBangHysteresis.md b/doc/controllers/BangBangHysteresis.md new file mode 100644 index 00000000..98589392 --- /dev/null +++ b/doc/controllers/BangBangHysteresis.md @@ -0,0 +1,103 @@ +# Bang-Bang / Hysteresis (Relay) Controller + +## Overview & Motivation + +The bang-bang controller is the simplest closed-loop regulator: its output switches between two discrete levels depending on whether the controlled variable is above or below a threshold. Without hysteresis, a plain threshold comparator chatters — switching at high frequency whenever noise nudges the signal across the boundary. + +Adding a **dead-band (Schmitt trigger)** eliminates chatter by giving the relay memory: once the output goes High it stays High until the measurement falls all the way to a *lower* threshold, and vice versa. This makes the relay a practical actuator-safe control primitive for thermostats, fridge compressors, tank level switches, and power-stage on/off regulation. + +## Mathematical Theory + +### State Transition + +The relay holds a binary state $s \in \{\text{Low}, \text{High}\}$ with the following transition rules: + +$$ +s[k] = \begin{cases} +\text{High} & \text{if } s[k-1] = \text{Low} \text{ and } x[k] \geq \theta_H \\ +\text{Low} & \text{if } s[k-1] = \text{High} \text{ and } x[k] \leq \theta_L \\ +s[k-1] & \text{otherwise} +\end{cases} +$$ + +where $\theta_L < \theta_H$ are the lower and upper switching thresholds (the hysteresis band). + +### Output Map + +$$ +u[k] = \begin{cases} +u_H & \text{if } s[k] = \text{High} \\ +u_L & \text{if } s[k] = \text{Low} +\end{cases} +$$ + +The output levels $u_L$ and $u_H$ are arbitrary; common choices are $\{0, 1\}$ or $\{-1, +1\}$. + +### Hysteresis Band Width + +The band width $\Delta = \theta_H - \theta_L$ is the key design parameter. It bounds the switching frequency $f_s$ given a signal slope $\dot{x}$: + +$$ +f_s \leq \frac{|\dot{x}|}{2\Delta} +$$ + +A wider band reduces $f_s$ (protecting relays and power stages) at the cost of a larger steady-state limit cycle amplitude. + +## Complexity Analysis + +| Case | Time | Space | Notes | +|-------|---------|---------|------------------------------------| +| All | $O(1)$ | $O(1)$ | Two comparisons, one state bit, one select | + +No arithmetic on the signal path — only comparisons — so the relay introduces no numerical error and is exactly representable in any floating-point format. + +## Step-by-Step Walkthrough + +**Setup:** band $[\theta_L, \theta_H] = [-0.2, 0.2]$, outputs $u_L = 0$, $u_H = 1$, initial state Low. + +| Step | $x[k]$ | Condition | $s[k]$ | $u[k]$ | +|------|--------|----------------------------|--------|--------| +| 1 | 0.0 | Low, $x < 0.2$ | Low | 0 | +| 2 | 0.3 | Low, $x \geq 0.2$ → switch | High | 1 | +| 3 | 0.1 | High, $x > -0.2$ → hold | High | 1 | +| 4 | −0.3 | High, $x \leq -0.2$ → switch | Low | 0 | +| 5 | 0.0 | Low, $x < 0.2$ → hold | Low | 0 | + +## Pitfalls & Edge Cases + +- **Inverted band.** $\theta_H \leq \theta_L$ latches the output in an undefined state; reject this at construction time via a precondition assertion. +- **Exactly on threshold.** Transitions are inclusive: $x = \theta_H$ triggers Low→High and $x = \theta_L$ triggers High→Low. This avoids a dead-zone at the switching points. +- **Zero-width band.** $\theta_H = \theta_L$ collapses the relay to a pure comparator (no hysteresis). The logic is still correct but offers no chatter suppression. +- **Noise sizing.** The band width must exceed the peak-to-peak noise amplitude; otherwise noise alone drives state transitions at the sampling rate. +- **Actuator minimum on-time.** Size $\Delta$ so that the minimum on-time (derived from $\Delta / |\dot{x}|_\text{max}$) is above the actuator's rated minimum switching period. + +## Variants & Generalizations + +| Variant | Key Difference | +|---------|---------------| +| **Plain comparator** | $\Delta = 0$; no memory, chatters on noise | +| **Asymmetric band** | $\theta_H$ and $\theta_L$ not symmetric around the set-point; biases the duty cycle | +| **Three-state relay** | Adds a dead-band output level $u_0$; used in motor direction control | +| **Adaptive hysteresis** | Band width tracks signal variance online to maintain a target switching rate | +| **Relay feedback test (Åström–Hägglund)** | Deliberate oscillation under relay feedback to identify the ultimate gain/period for automatic PID tuning | + +## Applications + +- **Thermostats and HVAC** — heating/cooling switched on/off around a temperature set-point. +- **Tank and vessel level control** — pump on/off between high- and low-level floats. +- **Power-stage converters** — hysteretic current-mode control in DC-DC converters and class-D amplifiers. +- **Motor drive enable/disable** — protecting power stages with a current-band relay. +- **Åström–Hägglund auto-tuning** — the relay feedback experiment that drives limit-cycle oscillation for PID parameter identification. + +## Connections to Other Algorithms + +| Algorithm | Relationship | +|-----------|-------------| +| [PID Controller](Pid.md) | The relay's limit cycle can be used to identify PID tuning parameters via the Åström–Hägglund relay-feedback test | +| [Saturation / Rate Limiter](SaturationRateLimiter.md) | Continuous-output counterpart for actuator constraint; often combined with a relay in cascaded loops | + +## References & Further Reading + +- K. J. Åström, R. M. Murray, *Feedback Systems: An Introduction for Scientists and Engineers*, Princeton University Press, 2008 — relay feedback, Chapter 10. +- Ya. Z. Tsypkin, *Relay Control Systems*, Cambridge University Press, 1984. +- K. J. Åström, T. Hägglund, "Automatic Tuning of Simple Regulators with Specifications on Phase and Amplitude Margins," *Automatica*, 20(5), 1984. diff --git a/doc/controllers/README.md b/doc/controllers/README.md index c03f6164..06a446b0 100644 --- a/doc/controllers/README.md +++ b/doc/controllers/README.md @@ -6,6 +6,7 @@ Feedback control algorithms for regulating dynamic systems in real time. | Algorithm | Description | |--------------------------|-----------------------------------------------------------------------------------------| +| [Bang-Bang / Hysteresis Controller](BangBangHysteresis.md) | Two-state relay controller with Schmitt-trigger dead-band to prevent chatter | | [PID Controller](Pid.md) | Proportional-Integral-Derivative controller using a discrete recursive formulation | | [LQR Controller](Lqr.md) | Linear Quadratic Regulator — optimal state-feedback control minimizing a quadratic cost | | [LQG Controller](Lqg.md) | Linear Quadratic Gaussian — output-feedback optimal control via LQR + Kalman Filter | diff --git a/numerical/controllers/implementations/BangBangHysteresis.cpp b/numerical/controllers/implementations/BangBangHysteresis.cpp new file mode 100644 index 00000000..62918933 --- /dev/null +++ b/numerical/controllers/implementations/BangBangHysteresis.cpp @@ -0,0 +1,6 @@ +#include "numerical/controllers/implementations/BangBangHysteresis.hpp" + +namespace controllers +{ + template class BangBangHysteresis; +} diff --git a/numerical/controllers/implementations/BangBangHysteresis.hpp b/numerical/controllers/implementations/BangBangHysteresis.hpp new file mode 100644 index 00000000..ac48b109 --- /dev/null +++ b/numerical/controllers/implementations/BangBangHysteresis.hpp @@ -0,0 +1,75 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "infra/util/ReallyAssert.hpp" +#include "numerical/math/CompilerOptimizations.hpp" +#include + +namespace controllers +{ + enum class RelayState + { + Low, + High + }; + + template + class BangBangHysteresis + { + public: + static_assert(std::is_floating_point_v, "BangBangHysteresis supports floating-point types"); + + BangBangHysteresis(T lowThreshold, T highThreshold, T outputLow, T outputHigh); + + OPTIMIZE_FOR_SPEED T Update(T measurement); + void Reset(RelayState initial = RelayState::Low); + RelayState State() const; + + private: + T lowThreshold; + T highThreshold; + T outputLow; + T outputHigh; + RelayState state{ RelayState::Low }; + }; + + template + BangBangHysteresis::BangBangHysteresis(T lowThreshold, T highThreshold, T outputLow, T outputHigh) + : lowThreshold{ lowThreshold } + , highThreshold{ highThreshold } + , outputLow{ outputLow } + , outputHigh{ outputHigh } + { + really_assert(highThreshold > lowThreshold); + } + + template + OPTIMIZE_FOR_SPEED T BangBangHysteresis::Update(T measurement) + { + if (state == RelayState::Low && measurement >= highThreshold) + state = RelayState::High; + else if (state == RelayState::High && measurement <= lowThreshold) + state = RelayState::Low; + + return (state == RelayState::High) ? outputHigh : outputLow; + } + + template + void BangBangHysteresis::Reset(RelayState initial) + { + state = initial; + } + + template + RelayState BangBangHysteresis::State() const + { + return state; + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class BangBangHysteresis; +#endif +} diff --git a/numerical/controllers/implementations/CMakeLists.txt b/numerical/controllers/implementations/CMakeLists.txt index 5d5be31e..d74bdc08 100644 --- a/numerical/controllers/implementations/CMakeLists.txt +++ b/numerical/controllers/implementations/CMakeLists.txt @@ -12,6 +12,7 @@ target_link_libraries(numerical.controllers.implementations ${NUMERICAL_VISIBILI ) target_sources(numerical.controllers.implementations PRIVATE + BangBangHysteresis.hpp Lqg.hpp Lqr.hpp Mpc.hpp @@ -19,6 +20,7 @@ target_sources(numerical.controllers.implementations PRIVATE ) numerical_add_coverage_sources(numerical.controllers.implementations + BangBangHysteresis.cpp Lqg.cpp Lqr.cpp Mpc.cpp diff --git a/numerical/controllers/implementations/test/CMakeLists.txt b/numerical/controllers/implementations/test/CMakeLists.txt index fd1e42e6..d52bab34 100644 --- a/numerical/controllers/implementations/test/CMakeLists.txt +++ b/numerical/controllers/implementations/test/CMakeLists.txt @@ -9,6 +9,7 @@ target_link_libraries(numerical.controllers_test PUBLIC ) target_sources(numerical.controllers_test PRIVATE + TestBangBangHysteresis.cpp TestLqg.cpp TestLqr.cpp TestMpc.cpp diff --git a/numerical/controllers/implementations/test/TestBangBangHysteresis.cpp b/numerical/controllers/implementations/test/TestBangBangHysteresis.cpp new file mode 100644 index 00000000..b2500101 --- /dev/null +++ b/numerical/controllers/implementations/test/TestBangBangHysteresis.cpp @@ -0,0 +1,92 @@ +#include "numerical/controllers/implementations/BangBangHysteresis.hpp" +#include "gtest/gtest.h" + +namespace +{ + class TestBangBangHysteresis + : public ::testing::Test + { + public: + controllers::BangBangHysteresis relay{ -0.2f, 0.2f, 0.0f, 1.0f }; + }; +} + +TEST_F(TestBangBangHysteresis, starts_in_low_state) +{ + EXPECT_EQ(relay.State(), controllers::RelayState::Low); + EXPECT_FLOAT_EQ(relay.Update(0.0f), 0.0f); +} + +TEST_F(TestBangBangHysteresis, switches_high_at_upper_threshold) +{ + float output = relay.Update(0.2f); + + EXPECT_EQ(relay.State(), controllers::RelayState::High); + EXPECT_FLOAT_EQ(output, 1.0f); +} + +TEST_F(TestBangBangHysteresis, stays_high_inside_band) +{ + relay.Update(0.2f); + + float output = relay.Update(0.0f); + + EXPECT_EQ(relay.State(), controllers::RelayState::High); + EXPECT_FLOAT_EQ(output, 1.0f); +} + +TEST_F(TestBangBangHysteresis, switches_low_at_lower_threshold) +{ + relay.Update(0.2f); + + float output = relay.Update(-0.2f); + + EXPECT_EQ(relay.State(), controllers::RelayState::Low); + EXPECT_FLOAT_EQ(output, 0.0f); +} + +TEST_F(TestBangBangHysteresis, hysteresis_prevents_chatter) +{ + std::array inputs{ 0.1f, -0.1f, 0.15f, -0.15f, 0.05f }; + + for (float x : inputs) + relay.Update(x); + + EXPECT_EQ(relay.State(), controllers::RelayState::Low); +} + +TEST_F(TestBangBangHysteresis, full_cycle_sequence) +{ + std::array inputs{ 0.0f, 0.3f, 0.1f, -0.3f, 0.0f }; + std::array expectedStates{ + controllers::RelayState::Low, + controllers::RelayState::High, + controllers::RelayState::High, + controllers::RelayState::Low, + controllers::RelayState::Low + }; + + for (std::size_t i = 0; i < inputs.size(); ++i) + { + relay.Update(inputs[i]); + EXPECT_EQ(relay.State(), expectedStates[i]); + } +} + +TEST_F(TestBangBangHysteresis, reset_restores_initial_state) +{ + relay.Update(0.2f); + EXPECT_EQ(relay.State(), controllers::RelayState::High); + + relay.Reset(controllers::RelayState::Low); + + EXPECT_EQ(relay.State(), controllers::RelayState::Low); +} + +TEST_F(TestBangBangHysteresis, custom_output_levels) +{ + controllers::BangBangHysteresis customRelay{ -0.2f, 0.2f, -1.0f, 1.0f }; + + EXPECT_FLOAT_EQ(customRelay.Update(0.0f), -1.0f); + EXPECT_FLOAT_EQ(customRelay.Update(0.2f), 1.0f); +} From 5c34be4147e6efcbce08e44232a96f54d603ca91 Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Sun, 26 Jul 2026 17:19:40 +0000 Subject: [PATCH 2/4] remove old files from roadmap --- .../BangBangHysteresis/explanation.md | 30 -------- .../BangBangHysteresis/implementation.md | 71 ------------------- .../controllers/BangBangHysteresis/tests.md | 59 --------------- 3 files changed, 160 deletions(-) delete mode 100644 roadmap/controllers/BangBangHysteresis/explanation.md delete mode 100644 roadmap/controllers/BangBangHysteresis/implementation.md delete mode 100644 roadmap/controllers/BangBangHysteresis/tests.md diff --git a/roadmap/controllers/BangBangHysteresis/explanation.md b/roadmap/controllers/BangBangHysteresis/explanation.md deleted file mode 100644 index 6b1ffced..00000000 --- a/roadmap/controllers/BangBangHysteresis/explanation.md +++ /dev/null @@ -1,30 +0,0 @@ -# Bang-Bang / Hysteresis (Relay) Controller — Overview - -## What it is -A two-state on/off (relay) controller. The output snaps between two levels depending on whether -the measurement is above the upper threshold or below the lower threshold. The gap between the -two thresholds is a **Schmitt-trigger dead-band** that gives the relay memory. - -## Why it matters (embedded) -This is the control law running in thermostats, fridge compressors, tank level switches, and -hysteretic power converters. It needs no gain tuning and no floating-point math — just two -comparisons — making it the cheapest closed-loop regulator that still behaves sensibly. - -## How it works (intuition) -Without hysteresis, a plain comparator would chatter — switching rapidly whenever noise nudges -the signal across a single threshold. The dead-band fixes this: once the output goes High it -stays High until the signal falls all the way to the *lower* threshold, and vice-versa. The width -of the band directly sets the trade-off between regulation tightness and switching rate. - -## Key parameters -- **lowThreshold / highThreshold** — the switch-off and switch-on points; their gap is the - hysteresis band. -- **outputLow / outputHigh** — the two actuator levels (e.g. `0`/`1`, or `−1`/`+1`). - -## Reference -K. J. Åström, R. M. Murray, *Feedback Systems* (2008), relay feedback; Ya. Z. Tsypkin, -*Relay Control Systems* (1984). - -## See also -`SaturationRateLimiter` (continuous actuator constraints); relay feedback is also the basis of -Åström–Hägglund automatic PID tuning. diff --git a/roadmap/controllers/BangBangHysteresis/implementation.md b/roadmap/controllers/BangBangHysteresis/implementation.md deleted file mode 100644 index 4b15e40b..00000000 --- a/roadmap/controllers/BangBangHysteresis/implementation.md +++ /dev/null @@ -1,71 +0,0 @@ -# Bang-Bang / Hysteresis (Relay) Controller — Implementation Pseudocode - -> Roadmap ref: #4 (Tier 1) · Target: `numerical/controllers` · Namespace `controllers` · Type: `float` (templated on `T`, instantiated for `float` only) - -## Data structures - -``` -enum RelayState: Low, High - -template # static_assert(std::is_floating_point_v); instantiated for float -class BangBangHysteresis: - T lowThreshold # switch-off point - T highThreshold # switch-on point, high > low - T outputLow # value emitted in Low state - T outputHigh # value emitted in High state - RelayState state = Low -``` - -## Interface - -``` -BangBangHysteresis(T lowThreshold, T highThreshold, - T outputLow, T outputHigh) -T Update(T measurement) # hot path -void Reset(RelayState initial = Low) -RelayState State() const -``` - -## Algorithm (pseudocode) - -``` -function Update(x): # OPTIMIZE_FOR_SPEED - # Schmitt trigger: transitions only at the band edges - if state == Low and x >= highThreshold: - state = High - else if state == High and x <= lowThreshold: - state = Low - return (state == High) ? outputHigh : outputLow -``` - -## Complexity & memory - -- Time: `O(1)` per sample — at most two comparisons and a select. -- Memory: `O(1)` — four thresholds/levels plus a one-bit state. - -## Numerical / embedded notes - -- The dead-band `[lowThreshold, highThreshold]` sets the switching hysteresis; a wider band - trades tracking accuracy for fewer switching events (relay chatter). -- Signal path is comparison-only (no arithmetic), so the relay introduces no numerical error. -- Switching frequency is bounded by the band width and the signal slope; size the band from the - actuator's minimum on/off time to protect relays and power stages. -- `really_assert(highThreshold > lowThreshold)` in the constructor to reject an inverted band - that would latch the output. -- Deterministic branchless variant: precompute `outputHigh−outputLow` and blend by the state bit - to avoid a data-dependent branch in tight loops. -- Float-only: `static_assert(std::is_floating_point_v)`; the generic `T` signature keeps a - `Q15`/`Q31` specialisation cheap to add later. - -## Deployment - -- Header: `numerical/controllers/implementations/BangBangHysteresis.hpp` — `#pragma once` → - `#pragma GCC optimize("O3","fast-math")`, `OPTIMIZE_FOR_SPEED` on `Update`, and - `extern template class BangBangHysteresis;` under `#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD`. -- Coverage: `numerical/controllers/implementations/BangBangHysteresis.cpp` → - `template class BangBangHysteresis;` -- Test: `numerical/controllers/implementations/test/TestBangBangHysteresis.cpp` -- Doc: `doc/controllers/BangBangHysteresis.md` (expand to follow `doc/TEMPLATE.md`) -- CMake: `.hpp` → `target_sources`; `.cpp` → `numerical_add_coverage_sources`; - `TestBangBangHysteresis.cpp` → the `_test` target. -- Generic pattern: see `roadmap/README.md` → "Deployment shape". diff --git a/roadmap/controllers/BangBangHysteresis/tests.md b/roadmap/controllers/BangBangHysteresis/tests.md deleted file mode 100644 index 1dccf441..00000000 --- a/roadmap/controllers/BangBangHysteresis/tests.md +++ /dev/null @@ -1,59 +0,0 @@ -# Bang-Bang / Hysteresis (Relay) Controller — Unit Test Plan (Pseudocode) - -> GoogleTest · `TEST_F` (`float`) · `StrictMock` only · no heap. - -## Fixture - -``` -class TestBangBangHysteresis : public ::testing::Test: - # band [-0.2, 0.2], outputs {0, 1} - BangBangHysteresis relay{ -0.2f, 0.2f, 0.0f, 1.0f } -# each case below is a TEST_F(TestBangBangHysteresis, ) -``` - -## Test cases (Arrange / Act / Assert) - -``` -starts_in_low_state: - Assert: State() == Low and Update(0) == outputLow - -switches_high_at_upper_threshold: - Arrange: from Low, feed x = 0.2 - Assert: output becomes outputHigh, State() == High - -stays_high_inside_band: - Arrange: from High, feed x = 0.0 (inside band) - Assert: output remains outputHigh (no premature switch) - -switches_low_at_lower_threshold: - Arrange: from High, feed x = -0.2 - Assert: output becomes outputLow, State() == Low - -hysteresis_prevents_chatter: - Arrange: feed a sequence dithering around 0 within (-0.2, 0.2) - Assert: no state change occurs - -full_cycle_sequence: - Arrange: x = [0, 0.3, 0.1, -0.3, 0.0] - Assert: states = [Low, High, High, Low, Low] - -reset_restores_initial_state: - Arrange: drive to High, Reset(Low) - Assert: State() == Low - -custom_output_levels: - Arrange: outputs {-1, +1} - Assert: Low emits -1, High emits +1 -``` - -## Reference vectors - -- band [-0.2, 0.2]: a rising input crosses to High only at `x ≥ 0.2`; a falling input returns to - Low only at `x ≤ -0.2`. -- Inside `(-0.2, 0.2)` the output equals its previous value (memory / latch behaviour). - -## Edge cases - -- Exactly-on-threshold values (`x == highThreshold`, `x == lowThreshold`) switch (inclusive). -- Zero-width band collapses to a comparator (still valid but no hysteresis). -- Custom levels including negative outputs must pass through unchanged. From a130eca3bc119547d379cb8be001a957a871b028 Mon Sep 17 00:00:00 2001 From: gfs Date: Sun, 26 Jul 2026 19:23:16 +0200 Subject: [PATCH 3/4] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/controllers/BangBangHysteresis.md | 40 +++++++++++++-------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/doc/controllers/BangBangHysteresis.md b/doc/controllers/BangBangHysteresis.md index 98589392..12e8897e 100644 --- a/doc/controllers/BangBangHysteresis.md +++ b/doc/controllers/BangBangHysteresis.md @@ -45,9 +45,9 @@ A wider band reduces $f_s$ (protecting relays and power stages) at the cost of a ## Complexity Analysis -| Case | Time | Space | Notes | -|-------|---------|---------|------------------------------------| -| All | $O(1)$ | $O(1)$ | Two comparisons, one state bit, one select | +| Case | Time | Space | Notes | +|------|--------|--------|--------------------------------------------| +| All | $O(1)$ | $O(1)$ | Two comparisons, one state bit, one select | No arithmetic on the signal path — only comparisons — so the relay introduces no numerical error and is exactly representable in any floating-point format. @@ -55,13 +55,13 @@ No arithmetic on the signal path — only comparisons — so the relay introduce **Setup:** band $[\theta_L, \theta_H] = [-0.2, 0.2]$, outputs $u_L = 0$, $u_H = 1$, initial state Low. -| Step | $x[k]$ | Condition | $s[k]$ | $u[k]$ | -|------|--------|----------------------------|--------|--------| -| 1 | 0.0 | Low, $x < 0.2$ | Low | 0 | -| 2 | 0.3 | Low, $x \geq 0.2$ → switch | High | 1 | -| 3 | 0.1 | High, $x > -0.2$ → hold | High | 1 | -| 4 | −0.3 | High, $x \leq -0.2$ → switch | Low | 0 | -| 5 | 0.0 | Low, $x < 0.2$ → hold | Low | 0 | +| Step | $x[k]$ | Condition | $s[k]$ | $u[k]$ | +|------|--------|------------------------------|--------|--------| +| 1 | 0.0 | Low, $x < 0.2$ | Low | 0 | +| 2 | 0.3 | Low, $x \geq 0.2$ → switch | High | 1 | +| 3 | 0.1 | High, $x > -0.2$ → hold | High | 1 | +| 4 | −0.3 | High, $x \leq -0.2$ → switch | Low | 0 | +| 5 | 0.0 | Low, $x < 0.2$ → hold | Low | 0 | ## Pitfalls & Edge Cases @@ -73,12 +73,12 @@ No arithmetic on the signal path — only comparisons — so the relay introduce ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Plain comparator** | $\Delta = 0$; no memory, chatters on noise | -| **Asymmetric band** | $\theta_H$ and $\theta_L$ not symmetric around the set-point; biases the duty cycle | -| **Three-state relay** | Adds a dead-band output level $u_0$; used in motor direction control | -| **Adaptive hysteresis** | Band width tracks signal variance online to maintain a target switching rate | +| Variant | Key Difference | +|-------------------------------------------|-----------------------------------------------------------------------------------------------------------| +| **Plain comparator** | $\Delta = 0$; no memory, chatters on noise | +| **Asymmetric band** | $\theta_H$ and $\theta_L$ not symmetric around the set-point; biases the duty cycle | +| **Three-state relay** | Adds a dead-band output level $u_0$; used in motor direction control | +| **Adaptive hysteresis** | Band width tracks signal variance online to maintain a target switching rate | | **Relay feedback test (Åström–Hägglund)** | Deliberate oscillation under relay feedback to identify the ultimate gain/period for automatic PID tuning | ## Applications @@ -91,10 +91,10 @@ No arithmetic on the signal path — only comparisons — so the relay introduce ## Connections to Other Algorithms -| Algorithm | Relationship | -|-----------|-------------| -| [PID Controller](Pid.md) | The relay's limit cycle can be used to identify PID tuning parameters via the Åström–Hägglund relay-feedback test | -| [Saturation / Rate Limiter](SaturationRateLimiter.md) | Continuous-output counterpart for actuator constraint; often combined with a relay in cascaded loops | +| Algorithm | Relationship | +|-------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------| +| [PID Controller](Pid.md) | The relay's limit cycle can be used to identify PID tuning parameters via the Åström–Hägglund relay-feedback test | +| [Saturation / Rate Limiter](SaturationRateLimiter.md) | Continuous-output counterpart for actuator constraint; often combined with a relay in cascaded loops | ## References & Further Reading From c4f2518ceeca08f94409d1fb6684c5ba0268eda1 Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Sun, 26 Jul 2026 17:35:11 +0000 Subject: [PATCH 4/4] add missing include --- .../controllers/implementations/test/TestBangBangHysteresis.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/numerical/controllers/implementations/test/TestBangBangHysteresis.cpp b/numerical/controllers/implementations/test/TestBangBangHysteresis.cpp index b2500101..0d0c7770 100644 --- a/numerical/controllers/implementations/test/TestBangBangHysteresis.cpp +++ b/numerical/controllers/implementations/test/TestBangBangHysteresis.cpp @@ -1,5 +1,6 @@ #include "numerical/controllers/implementations/BangBangHysteresis.hpp" #include "gtest/gtest.h" +#include namespace {