Repository navigation
feat: add bang bang controller #167
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
563de96
add bang bang controller
gabrielfrasantos 5c34be4
remove old files from roadmap
gabrielfrasantos a3583ec
Merge branch 'main' into feature/add-bang-bang-controller
gabrielfrasantos a130eca
Apply suggestions from code review
gabrielfrasantos c4f2518
add missing include
gabrielfrasantos d6723da
merge main
gabrielfrasantos File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
|
gabrielfrasantos marked this conversation as resolved.
Resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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. |
|
gabrielfrasantos marked this conversation as resolved.
Resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| #include "numerical/controllers/implementations/BangBangHysteresis.hpp" | ||
|
|
||
| namespace controllers | ||
| { | ||
| template class BangBangHysteresis<float>; | ||
| } |
75 changes: 75 additions & 0 deletions
75
numerical/controllers/implementations/BangBangHysteresis.hpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 <type_traits> | ||
|
|
||
| namespace controllers | ||
| { | ||
| enum class RelayState | ||
| { | ||
| Low, | ||
| High | ||
| }; | ||
|
|
||
| template<typename T> | ||
| class BangBangHysteresis | ||
| { | ||
| public: | ||
| static_assert(std::is_floating_point_v<T>, "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<typename T> | ||
| BangBangHysteresis<T>::BangBangHysteresis(T lowThreshold, T highThreshold, T outputLow, T outputHigh) | ||
| : lowThreshold{ lowThreshold } | ||
| , highThreshold{ highThreshold } | ||
| , outputLow{ outputLow } | ||
| , outputHigh{ outputHigh } | ||
| { | ||
| really_assert(highThreshold > lowThreshold); | ||
| } | ||
|
|
||
| template<typename T> | ||
| OPTIMIZE_FOR_SPEED T BangBangHysteresis<T>::Update(T measurement) | ||
| { | ||
|
Check warning on line 51 in numerical/controllers/implementations/BangBangHysteresis.hpp
|
||
| 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<typename T> | ||
| void BangBangHysteresis<T>::Reset(RelayState initial) | ||
| { | ||
| state = initial; | ||
| } | ||
|
|
||
| template<typename T> | ||
| RelayState BangBangHysteresis<T>::State() const | ||
| { | ||
| return state; | ||
| } | ||
|
|
||
| #ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD | ||
| extern template class BangBangHysteresis<float>; | ||
| #endif | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
93 changes: 93 additions & 0 deletions
93
numerical/controllers/implementations/test/TestBangBangHysteresis.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| #include "numerical/controllers/implementations/BangBangHysteresis.hpp" | ||
| #include "gtest/gtest.h" | ||
| #include <array> | ||
|
|
||
| namespace | ||
| { | ||
| class TestBangBangHysteresis | ||
| : public ::testing::Test | ||
| { | ||
| public: | ||
| controllers::BangBangHysteresis<float> 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<float, 5> 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<float, 5> inputs{ 0.0f, 0.3f, 0.1f, -0.3f, 0.0f }; | ||
| std::array<controllers::RelayState, 5> 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<float> 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); | ||
| } |
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.