feedback_machines 0.1.4 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +69 -0
- data/Cargo.lock +307 -0
- data/Cargo.toml +2 -0
- data/README.md +90 -33
- data/ext/feedback_machines_native/core/CHANGELOG.md +44 -0
- data/ext/feedback_machines_native/core/Cargo.toml +4 -2
- data/ext/feedback_machines_native/core/README.md +50 -3
- data/ext/feedback_machines_native/core/src/lib.rs +172 -18
- data/ext/feedback_machines_native/ffi/Cargo.toml +2 -1
- data/ext/feedback_machines_native/ffi/src/bindings.rs +199 -36
- data/lib/feedback_machines/version.rb +1 -1
- data/lib/feedback_machines.rb +38 -8
- data/sig/feedback_machines.rbs +92 -4
- metadata +2 -1
|
@@ -1,5 +1,49 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.6.0](https://github.com/seuros/feedback_machines/compare/feedback-machines-v0.5.0...feedback-machines-v0.6.0) (2026-11-16)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### ⚠ BREAKING CHANGES
|
|
7
|
+
|
|
8
|
+
* add Pid/Hysteresis restored and seal both controllers
|
|
9
|
+
|
|
10
|
+
### Features
|
|
11
|
+
|
|
12
|
+
* add Pid/Hysteresis restored and seal both controllers ([c5dc3b7](https://github.com/seuros/feedback_machines/commit/c5dc3b7d97857ccd596562f6364c6918cb63b173))
|
|
13
|
+
|
|
14
|
+
## [0.5.0](https://github.com/seuros/feedback_machines/compare/feedback-machines-v0.4.0...feedback-machines-v0.5.0) (2026-11-14)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
### ⚠ BREAKING CHANGES
|
|
18
|
+
|
|
19
|
+
* build the binding on matryona-machines 0.2; read Gains and Limits from the struct; compiler-checked symbols; ship no test files
|
|
20
|
+
|
|
21
|
+
### Features
|
|
22
|
+
|
|
23
|
+
* build the binding on matryona-machines 0.2; read Gains and Limits from the struct; compiler-checked symbols; ship no test files ([19023a5](https://github.com/seuros/feedback_machines/commit/19023a591da9a54ecb606eab51a9cc035eccf7a7))
|
|
24
|
+
|
|
25
|
+
## [0.4.0](https://github.com/seuros/feedback_machines/compare/feedback-machines-v0.3.0...feedback-machines-v0.4.0) (2026-11-14)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
### ⚠ BREAKING CHANGES
|
|
29
|
+
|
|
30
|
+
* seal Gains and Limits, re-validate them at the binding, hold no borrow while Limits.new runs
|
|
31
|
+
|
|
32
|
+
### Features
|
|
33
|
+
|
|
34
|
+
* seal Gains and Limits, re-validate them at the binding, hold no borrow while Limits.new runs ([8aee9ef](https://github.com/seuros/feedback_machines/commit/8aee9efe086af88530c672abd235f92f64d4fb32))
|
|
35
|
+
|
|
36
|
+
## [0.3.0](https://github.com/seuros/feedback_machines/compare/feedback-machines-v0.2.2...feedback-machines-v0.3.0) (2026-11-13)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
### ⚠ BREAKING CHANGES
|
|
40
|
+
|
|
41
|
+
* converted to the fleet conventions. One exhaustive Refusal per crate, Result from every operation that can refuse, a refusal changes nothing, provable idempotent repeats are honoured, Ruby mirrors the core. No compatibility aliases. step and observe return Result; Ruby takes Gains and Limits values.
|
|
42
|
+
|
|
43
|
+
### Features
|
|
44
|
+
|
|
45
|
+
* refuse bad samples with Refusal and take elapsed as Integer nanoseconds in Ruby ([cc23741](https://github.com/seuros/feedback_machines/commit/cc23741e0f1309717910b8752b14e6bbef1dcf13))
|
|
46
|
+
|
|
3
47
|
## [0.2.2](https://github.com/seuros/feedback_machines/compare/feedback-machines-v0.2.1...feedback-machines-v0.2.2) (2026-11-06)
|
|
4
48
|
|
|
5
49
|
|
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "feedback-machines"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.6.0"
|
|
4
4
|
edition.workspace = true
|
|
5
5
|
rust-version.workspace = true
|
|
6
6
|
license.workspace = true
|
|
7
7
|
description = "Finite-input PID and hysteresis control primitives"
|
|
8
8
|
readme = "README.md"
|
|
9
|
-
exclude = ["src/**/tests.rs", "tests/"]
|
|
9
|
+
exclude = ["src/**/tests.rs", "src/tests/", "tests/"]
|
|
10
10
|
keywords = ["pid", "control", "hysteresis", "anti-windup", "no-std"]
|
|
11
11
|
categories = ["no-std", "algorithms", "science"]
|
|
12
|
+
[dev-dependencies]
|
|
13
|
+
matryona-machines = { workspace = true, features = ["testing"] }
|
|
12
14
|
[lints]
|
|
13
15
|
workspace = true
|
|
@@ -6,7 +6,7 @@ Engine-room flight manual: turn measured drift into bounded control recommendati
|
|
|
6
6
|
|
|
7
7
|
Dependency-free, allocation-free `no_std` controllers.
|
|
8
8
|
|
|
9
|
-
PID accepts explicit error and elapsed time,
|
|
9
|
+
PID accepts explicit error and elapsed time, and refuses nonfinite inputs, zero
|
|
10
10
|
sampling intervals, and overflowing intermediate calculations without changing
|
|
11
11
|
state. Derivative is taken on error; the first sample has zero derivative.
|
|
12
12
|
Output is clamped and conditional integration prevents windup while saturation
|
|
@@ -20,11 +20,58 @@ generic signed floating-point measurements, not queue occupancy.
|
|
|
20
20
|
|
|
21
21
|
```rust
|
|
22
22
|
use core::time::Duration;
|
|
23
|
-
use feedback_machines::{Gains, Limits, Pid};
|
|
23
|
+
use feedback_machines::{Gains, Limits, Pid, Refusal};
|
|
24
24
|
# fn example() -> Option<()> {
|
|
25
25
|
let mut controller = Pid::new(Gains::new(2.0, 0.0, 0.0)?, Limits::new(0.0, 10.0)?);
|
|
26
|
-
assert_eq!(controller.step(2.0, Duration::from_secs(1)),
|
|
26
|
+
assert_eq!(controller.step(2.0, Duration::from_secs(1)), Ok(4.0));
|
|
27
|
+
assert_eq!(controller.step(f64::NAN, Duration::from_secs(1)), Err(Refusal::NotFinite));
|
|
28
|
+
assert_eq!(controller.step(2.0, Duration::ZERO), Err(Refusal::InvalidDuration));
|
|
27
29
|
# Some(())
|
|
28
30
|
# }
|
|
29
31
|
# assert_eq!(example(), Some(()));
|
|
30
32
|
```
|
|
33
|
+
|
|
34
|
+
## Contract
|
|
35
|
+
|
|
36
|
+
- **Configuration.** `Gains::new(p, i, d)` and `Limits::new(min, max)` are
|
|
37
|
+
constructors that validate and answer `None`: gains must be finite and
|
|
38
|
+
nonnegative (a negative zero is stored as zero), limits finite with
|
|
39
|
+
`min < max`. `Pid::new(gains, limits)` and
|
|
40
|
+
`Hysteresis::new(limits)` take validated values and cannot fail. Readers:
|
|
41
|
+
`Gains::{p, i, d}`, `Limits::{min, max}`,
|
|
42
|
+
`Pid::{gains, limits, integral, previous_error}`,
|
|
43
|
+
`Hysteresis::{limits, state}`.
|
|
44
|
+
- **Restoring.** `Pid::restored(gains, limits, integral, previous_error)`
|
|
45
|
+
resumes a controller from its readers and answers `None` unless the integral
|
|
46
|
+
and the previous error (when present) are finite; it compares equal to the
|
|
47
|
+
controller it was saved from and steps identically.
|
|
48
|
+
`Hysteresis::restored(limits, state)` cannot fail: every side is valid for
|
|
49
|
+
every band.
|
|
50
|
+
- **Refusals.** `Refusal` is the one refusal type. `Pid::step` answers
|
|
51
|
+
`Result<f64, Refusal>` and `Hysteresis::observe` answers
|
|
52
|
+
`Result<Band, Refusal>`; `Ok` is always an honoured sample.
|
|
53
|
+
- `NotFinite`: the sample (`error` or `value`) is NaN or infinite. Checked
|
|
54
|
+
first, so a bad sample is `NotFinite` whatever the interval.
|
|
55
|
+
- `InvalidDuration`: `elapsed` is zero. `step` only.
|
|
56
|
+
- `Overflow`: the sample is finite but the derivative, the integral or the
|
|
57
|
+
output is not. `step` only.
|
|
58
|
+
- **A refusal changes nothing.** Not the integral, not the derivative history,
|
|
59
|
+
not the band's side: the value compares equal to a clone taken before the
|
|
60
|
+
call. Skip the sample and carry on.
|
|
61
|
+
- **No repeats.** Every honoured `step` is a new sample that advances the
|
|
62
|
+
integral and the derivative history; the controller keeps no record of past
|
|
63
|
+
calls, so there is no idempotent repeat to recognise. Observing the same
|
|
64
|
+
measurement twice is simply two observations with the same answer.
|
|
65
|
+
- **Time.** `elapsed` is a `core::time::Duration`: the span since the previous
|
|
66
|
+
sample, not an instant. The controllers read no clock and keep none. `error`,
|
|
67
|
+
the gains, the limits and the output are `f64` control quantities, not time.
|
|
68
|
+
- **No recorded clock.** The rule "an honoured call records `now` exactly when
|
|
69
|
+
its answer depends on `now`" has nothing to act on here: no method takes an
|
|
70
|
+
instant, and neither controller keeps one.
|
|
71
|
+
- **No unreachable arms.** The crate has no `panic!`, `assert!`,
|
|
72
|
+
`unreachable!` or `expect`, and no refusal that cannot occur.
|
|
73
|
+
- **Exhaustive.** `Band` and `Refusal` are exhaustive enums; a new variant is a
|
|
74
|
+
breaking change.
|
|
75
|
+
- **No ids.** Nothing is issued, so there are no scopes and no sequence to
|
|
76
|
+
resume. A controller's state is its readers, and is not persisted for you:
|
|
77
|
+
save them and pass them to `restored`.
|
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
#![no_std]
|
|
2
|
+
#![cfg_attr(not(test), deny(clippy::indexing_slicing))]
|
|
2
3
|
#![doc = include_str!("../README.md")]
|
|
3
4
|
|
|
5
|
+
use core::{fmt, time::Duration};
|
|
6
|
+
|
|
7
|
+
/// Why a call changed nothing.
|
|
8
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
9
|
+
pub enum Refusal {
|
|
10
|
+
/// The sample (a PID error or a hysteresis measurement) is NaN or infinite.
|
|
11
|
+
NotFinite,
|
|
12
|
+
/// The elapsed time is zero: no interval to integrate or differentiate over.
|
|
13
|
+
InvalidDuration,
|
|
14
|
+
/// The sample is finite but a term of the calculation is not.
|
|
15
|
+
Overflow,
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
impl fmt::Display for Refusal {
|
|
19
|
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
20
|
+
f.write_str(match self {
|
|
21
|
+
Self::NotFinite => "the sample is NaN or infinite",
|
|
22
|
+
Self::InvalidDuration => "the elapsed time is zero",
|
|
23
|
+
Self::Overflow => "a term of the calculation is not finite",
|
|
24
|
+
})
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
impl core::error::Error for Refusal {}
|
|
29
|
+
|
|
4
30
|
/// Finite, nonnegative proportional/integral/derivative gains.
|
|
5
31
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
|
6
32
|
pub struct Gains {
|
|
@@ -10,13 +36,42 @@ pub struct Gains {
|
|
|
10
36
|
}
|
|
11
37
|
|
|
12
38
|
impl Gains {
|
|
13
|
-
/// Validate gain coefficients
|
|
39
|
+
/// Validate gain coefficients: `None` unless all are finite and
|
|
40
|
+
/// nonnegative. A negative zero is stored as zero.
|
|
14
41
|
#[must_use]
|
|
15
|
-
pub fn new(p: f64, i: f64, d: f64) -> Option<Self> {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
42
|
+
pub const fn new(p: f64, i: f64, d: f64) -> Option<Self> {
|
|
43
|
+
match (gain(p), gain(i), gain(d)) {
|
|
44
|
+
(Some(p), Some(i), Some(d)) => Some(Self { p, i, d }),
|
|
45
|
+
_ => None,
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/// Proportional gain.
|
|
50
|
+
#[must_use]
|
|
51
|
+
pub const fn p(&self) -> f64 {
|
|
52
|
+
self.p
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/// Integral gain.
|
|
56
|
+
#[must_use]
|
|
57
|
+
pub const fn i(&self) -> f64 {
|
|
58
|
+
self.i
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// Derivative gain.
|
|
62
|
+
#[must_use]
|
|
63
|
+
pub const fn d(&self) -> f64 {
|
|
64
|
+
self.d
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/// `value` as a gain: `None` unless finite and nonnegative, a negative zero
|
|
69
|
+
/// as zero.
|
|
70
|
+
const fn gain(value: f64) -> Option<f64> {
|
|
71
|
+
if value.is_finite() && value >= 0.0 {
|
|
72
|
+
Some(if value == 0.0 { 0.0 } else { value })
|
|
73
|
+
} else {
|
|
74
|
+
None
|
|
20
75
|
}
|
|
21
76
|
}
|
|
22
77
|
|
|
@@ -28,7 +83,7 @@ pub struct Limits {
|
|
|
28
83
|
}
|
|
29
84
|
|
|
30
85
|
impl Limits {
|
|
31
|
-
/// Validate a nonempty finite
|
|
86
|
+
/// Validate a nonempty finite range: `None` unless `min < max`, both finite.
|
|
32
87
|
#[must_use]
|
|
33
88
|
pub const fn new(min: f64, max: f64) -> Option<Self> {
|
|
34
89
|
if min.is_finite() && max.is_finite() && min < max {
|
|
@@ -37,6 +92,18 @@ impl Limits {
|
|
|
37
92
|
None
|
|
38
93
|
}
|
|
39
94
|
}
|
|
95
|
+
|
|
96
|
+
/// Lower limit.
|
|
97
|
+
#[must_use]
|
|
98
|
+
pub const fn min(&self) -> f64 {
|
|
99
|
+
self.min
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/// Upper limit.
|
|
103
|
+
#[must_use]
|
|
104
|
+
pub const fn max(&self) -> f64 {
|
|
105
|
+
self.max
|
|
106
|
+
}
|
|
40
107
|
}
|
|
41
108
|
|
|
42
109
|
/// Explicit-sampling PID with conditional-integration anti-windup.
|
|
@@ -60,13 +127,77 @@ impl Pid {
|
|
|
60
127
|
}
|
|
61
128
|
}
|
|
62
129
|
|
|
63
|
-
///
|
|
130
|
+
/// A controller resuming saved state: the [`Pid::integral`] and
|
|
131
|
+
/// [`Pid::previous_error`] read from one before it was put away.
|
|
132
|
+
///
|
|
133
|
+
/// `None` unless `integral` and `previous_error` (when present) are
|
|
134
|
+
/// finite. A negative zero integral is stored as zero, as `step` would
|
|
135
|
+
/// have left it.
|
|
64
136
|
#[must_use]
|
|
65
|
-
pub fn
|
|
66
|
-
|
|
67
|
-
|
|
137
|
+
pub const fn restored(
|
|
138
|
+
gains: Gains,
|
|
139
|
+
limits: Limits,
|
|
140
|
+
integral: f64,
|
|
141
|
+
previous_error: Option<f64>,
|
|
142
|
+
) -> Option<Self> {
|
|
143
|
+
if !integral.is_finite() {
|
|
68
144
|
return None;
|
|
69
145
|
}
|
|
146
|
+
if let Some(previous) = previous_error
|
|
147
|
+
&& !previous.is_finite()
|
|
148
|
+
{
|
|
149
|
+
return None;
|
|
150
|
+
}
|
|
151
|
+
Some(Self {
|
|
152
|
+
gains,
|
|
153
|
+
limits,
|
|
154
|
+
integral: if integral == 0.0 { 0.0 } else { integral },
|
|
155
|
+
previous: previous_error,
|
|
156
|
+
})
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/// The accumulated error-seconds the integral term multiplies.
|
|
160
|
+
#[must_use]
|
|
161
|
+
pub const fn integral(&self) -> f64 {
|
|
162
|
+
self.integral
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/// The error of the previous honoured sample, which the derivative term
|
|
166
|
+
/// differences against: `None` before the first.
|
|
167
|
+
#[must_use]
|
|
168
|
+
pub const fn previous_error(&self) -> Option<f64> {
|
|
169
|
+
self.previous
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/// The gains this controller was built with.
|
|
173
|
+
#[must_use]
|
|
174
|
+
pub const fn gains(&self) -> Gains {
|
|
175
|
+
self.gains
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/// The output limits this controller was built with.
|
|
179
|
+
#[must_use]
|
|
180
|
+
pub const fn limits(&self) -> Limits {
|
|
181
|
+
self.limits
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/// Observe one sample taken `elapsed` after the previous one and answer
|
|
185
|
+
/// the clamped output.
|
|
186
|
+
///
|
|
187
|
+
/// # Errors
|
|
188
|
+
///
|
|
189
|
+
/// [`Refusal::NotFinite`] for a NaN or infinite `error`,
|
|
190
|
+
/// [`Refusal::InvalidDuration`] for a zero `elapsed`, [`Refusal::Overflow`]
|
|
191
|
+
/// when a term of the calculation is not finite. Nothing changed: neither
|
|
192
|
+
/// the integral nor the derivative history.
|
|
193
|
+
pub fn step(&mut self, error: f64, elapsed: Duration) -> Result<f64, Refusal> {
|
|
194
|
+
if !error.is_finite() {
|
|
195
|
+
return Err(Refusal::NotFinite);
|
|
196
|
+
}
|
|
197
|
+
if elapsed.is_zero() {
|
|
198
|
+
return Err(Refusal::InvalidDuration);
|
|
199
|
+
}
|
|
200
|
+
let dt = elapsed.as_secs_f64();
|
|
70
201
|
let derivative = self
|
|
71
202
|
.previous
|
|
72
203
|
.map_or(0.0, |previous| (error - previous) / dt);
|
|
@@ -77,14 +208,14 @@ impl Pid {
|
|
|
77
208
|
.iter()
|
|
78
209
|
.all(|x| x.is_finite())
|
|
79
210
|
{
|
|
80
|
-
return
|
|
211
|
+
return Err(Refusal::Overflow);
|
|
81
212
|
}
|
|
82
213
|
let winding_up = (proposed > self.limits.max && error > 0.0)
|
|
83
214
|
|| (proposed < self.limits.min && error < 0.0);
|
|
84
215
|
let integral = if winding_up { self.integral } else { candidate };
|
|
85
216
|
self.integral = integral;
|
|
86
217
|
self.previous = Some(error);
|
|
87
|
-
|
|
218
|
+
Ok(proposed.clamp(self.limits.min, self.limits.max))
|
|
88
219
|
}
|
|
89
220
|
}
|
|
90
221
|
|
|
@@ -97,7 +228,6 @@ pub struct Hysteresis {
|
|
|
97
228
|
|
|
98
229
|
/// Which side of the hysteresis band is active.
|
|
99
230
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
100
|
-
#[non_exhaustive]
|
|
101
231
|
pub enum Band {
|
|
102
232
|
/// Below the band.
|
|
103
233
|
Low,
|
|
@@ -115,18 +245,42 @@ impl Hysteresis {
|
|
|
115
245
|
}
|
|
116
246
|
}
|
|
117
247
|
|
|
118
|
-
///
|
|
248
|
+
/// A band resuming saved state: on `state`, the [`Hysteresis::state`]
|
|
249
|
+
/// read from one before it was put away. Every side is valid for every
|
|
250
|
+
/// band.
|
|
119
251
|
#[must_use]
|
|
120
|
-
pub fn
|
|
252
|
+
pub const fn restored(limits: Limits, state: Band) -> Self {
|
|
253
|
+
Self { limits, state }
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/// The thresholds this band was built with.
|
|
257
|
+
#[must_use]
|
|
258
|
+
pub const fn limits(&self) -> Limits {
|
|
259
|
+
self.limits
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/// The side the band is on now.
|
|
263
|
+
#[must_use]
|
|
264
|
+
pub const fn state(&self) -> Band {
|
|
265
|
+
self.state
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/// Observe a measurement and answer the side the band is on after it.
|
|
269
|
+
///
|
|
270
|
+
/// # Errors
|
|
271
|
+
///
|
|
272
|
+
/// [`Refusal::NotFinite`] for a NaN or infinite `value`; the band keeps
|
|
273
|
+
/// its side.
|
|
274
|
+
pub fn observe(&mut self, value: f64) -> Result<Band, Refusal> {
|
|
121
275
|
if !value.is_finite() {
|
|
122
|
-
return
|
|
276
|
+
return Err(Refusal::NotFinite);
|
|
123
277
|
}
|
|
124
278
|
if value >= self.limits.max {
|
|
125
279
|
self.state = Band::High;
|
|
126
280
|
} else if value <= self.limits.min {
|
|
127
281
|
self.state = Band::Low;
|
|
128
282
|
}
|
|
129
|
-
|
|
283
|
+
Ok(self.state)
|
|
130
284
|
}
|
|
131
285
|
}
|
|
132
286
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "feedback_machines_native"
|
|
3
|
-
version = "0.1.
|
|
3
|
+
version = "0.1.7"
|
|
4
4
|
edition.workspace = true
|
|
5
5
|
rust-version.workspace = true
|
|
6
6
|
license.workspace = true
|
|
@@ -13,5 +13,6 @@ doctest = false
|
|
|
13
13
|
feedback-machines.workspace = true
|
|
14
14
|
magnus.workspace = true
|
|
15
15
|
rb-sys.workspace = true
|
|
16
|
+
matryona-machines = { workspace = true, features = ["ruby"] }
|
|
16
17
|
[lints]
|
|
17
18
|
workspace = true
|
|
@@ -1,39 +1,160 @@
|
|
|
1
|
-
use feedback_machines::{Band, Gains, Hysteresis, Limits, Pid};
|
|
1
|
+
use feedback_machines::{Band, Gains, Hysteresis, Limits, Pid, Refusal};
|
|
2
2
|
use magnus::typed_data::Obj;
|
|
3
|
-
use magnus::{Error, Ruby, Symbol, function, method, prelude::*};
|
|
4
|
-
use
|
|
3
|
+
use magnus::{Error, IntoValue, RModule, Ruby, Symbol, Value, function, method, prelude::*};
|
|
4
|
+
use matryona_machines::ruby::{Class, Registry, Symbols, duration, exact_fields, real};
|
|
5
|
+
use std::cell::RefCell;
|
|
5
6
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
7
|
+
/// The `Data` classes the binding builds and reads, resolved once at init.
|
|
8
|
+
struct Classes {
|
|
9
|
+
gains: Class,
|
|
10
|
+
limits: Class,
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
static CLASSES: Registry<Classes> = Registry::new("feedback_machines");
|
|
14
|
+
|
|
15
|
+
/// Resolves the classes `lib/feedback_machines.rb` defined before it loaded
|
|
16
|
+
/// the extension. Called once, from init.
|
|
17
|
+
fn resolve(ruby: &Ruby, module: RModule) -> Result<(), Error> {
|
|
18
|
+
let classes = Classes {
|
|
19
|
+
gains: Class::resolve(ruby, module, "Gains")?,
|
|
20
|
+
limits: Class::resolve(ruby, module, "Limits")?,
|
|
21
|
+
};
|
|
22
|
+
CLASSES.set(ruby, classes).map(drop)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
matryona_machines::symbols! {
|
|
26
|
+
/// The core's refusals as Symbols: the snake case of each variant.
|
|
27
|
+
Refusals for Refusal as "a refusal" {
|
|
28
|
+
NotFinite => "not_finite",
|
|
29
|
+
InvalidDuration => "invalid_duration",
|
|
30
|
+
Overflow => "overflow",
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
matryona_machines::symbols! {
|
|
35
|
+
/// The hysteresis bands as Symbols.
|
|
36
|
+
Bands for Band as "a band" {
|
|
37
|
+
Low => "low",
|
|
38
|
+
High => "high",
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/// The value the core's constructor built, or `RangeError` where it answered
|
|
43
|
+
/// `None`.
|
|
44
|
+
fn validated<T>(ruby: &Ruby, value: Option<T>, message: &'static str) -> Result<T, Error> {
|
|
45
|
+
value.ok_or_else(|| Error::new(ruby.exception_range_error(), message))
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/// The core's `Gains` of three reals (exactly a Float or an Integer each,
|
|
49
|
+
/// no `to_f` run; NaN and the infinities are the core's to refuse).
|
|
50
|
+
fn gains(ruby: &Ruby, p: Value, i: Value, d: Value) -> Result<Gains, Error> {
|
|
51
|
+
let (p, i, d) = (real(p, "p")?, real(i, "i")?, real(d, "d")?);
|
|
52
|
+
let message = "gains must be finite and nonnegative";
|
|
53
|
+
validated(ruby, Gains::new(p, i, d), message)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/// The core's `Limits` of two reals, read like [`gains`].
|
|
57
|
+
fn limits(ruby: &Ruby, min: Value, max: Value) -> Result<Limits, Error> {
|
|
58
|
+
let (min, max) = (real(min, "min")?, real(max, "max")?);
|
|
59
|
+
let message = "limits must be finite and min < max";
|
|
60
|
+
validated(ruby, Limits::new(min, max), message)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/// The core's `Gains` of a `FeedbackMachines::Gains`: `TypeError` for
|
|
64
|
+
/// anything but an instance of exactly that class, its members read from the
|
|
65
|
+
/// struct itself (no reader runs) and re-validated through `Gains::new`, so a
|
|
66
|
+
/// forged value never reaches the core.
|
|
67
|
+
fn gains_from(ruby: &Ruby, value: Value) -> Result<Gains, Error> {
|
|
68
|
+
let class = CLASSES.get(ruby)?.gains.get(ruby);
|
|
69
|
+
let message = "gains must be a FeedbackMachines::Gains";
|
|
70
|
+
let [p, i, d] = exact_fields::<3>(ruby, value, class, message)?;
|
|
71
|
+
gains(ruby, p, i, d)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/// The core's `Limits` of a `FeedbackMachines::Limits`, checked like
|
|
75
|
+
/// [`gains_from`].
|
|
76
|
+
fn limits_from(ruby: &Ruby, value: Value) -> Result<Limits, Error> {
|
|
77
|
+
let class = CLASSES.get(ruby)?.limits.get(ruby);
|
|
78
|
+
let message = "limits must be a FeedbackMachines::Limits";
|
|
79
|
+
let [min, max] = exact_fields::<2>(ruby, value, class, message)?;
|
|
80
|
+
limits(ruby, min, max)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/// A `FeedbackMachines::Limits` for `limits`. Callers copy the limits out
|
|
84
|
+
/// first: no borrow is held while `Limits.new` runs.
|
|
85
|
+
fn limits_value(ruby: &Ruby, limits: Limits) -> Result<Value, Error> {
|
|
86
|
+
let class = CLASSES.get(ruby)?.limits.get(ruby);
|
|
87
|
+
class.funcall("new", (limits.min(), limits.max()))
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/// What `Gains.new` stores: the validated coefficients as Floats.
|
|
91
|
+
fn checked_gains(ruby: &Ruby, p: Value, i: Value, d: Value) -> Result<(f64, f64, f64), Error> {
|
|
92
|
+
gains(ruby, p, i, d).map(|gains| (gains.p(), gains.i(), gains.d()))
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// What `Limits.new` stores: the validated range as Floats.
|
|
96
|
+
fn checked_limits(ruby: &Ruby, min: Value, max: Value) -> Result<(f64, f64), Error> {
|
|
97
|
+
limits(ruby, min, max).map(|limits| (limits.min(), limits.max()))
|
|
13
98
|
}
|
|
14
99
|
|
|
15
100
|
#[magnus::wrap(class = "FeedbackMachines::Pid", free_immediately, size)]
|
|
16
101
|
struct Controller(RefCell<Pid>);
|
|
17
102
|
|
|
18
103
|
impl Controller {
|
|
19
|
-
fn new(ruby: &Ruby,
|
|
20
|
-
let gains =
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
104
|
+
fn new(ruby: &Ruby, gains: Value, limits: Value) -> Result<Self, Error> {
|
|
105
|
+
let (gains, limits) = (gains_from(ruby, gains)?, limits_from(ruby, limits)?);
|
|
106
|
+
Ok(Self(RefCell::new(Pid::new(gains, limits))))
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/// `Pid.restored(gains, limits, integral, previous_error)`: `RangeError`
|
|
110
|
+
/// where the core's `Pid::restored` answers `None`.
|
|
111
|
+
fn restored(
|
|
112
|
+
ruby: &Ruby,
|
|
113
|
+
gains: Value,
|
|
114
|
+
limits: Value,
|
|
115
|
+
integral: Value,
|
|
116
|
+
previous_error: Value,
|
|
117
|
+
) -> Result<Self, Error> {
|
|
118
|
+
let (gains, limits) = (gains_from(ruby, gains)?, limits_from(ruby, limits)?);
|
|
119
|
+
let integral = real(integral, "integral")?;
|
|
120
|
+
let previous_error = if previous_error.is_nil() {
|
|
121
|
+
None
|
|
122
|
+
} else {
|
|
123
|
+
Some(real(previous_error, "previous_error")?)
|
|
124
|
+
};
|
|
125
|
+
let message = "integral and previous_error must be finite";
|
|
126
|
+
let pid = Pid::restored(gains, limits, integral, previous_error);
|
|
127
|
+
validated(ruby, pid, message).map(|pid| Self(RefCell::new(pid)))
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
fn integral(&self) -> f64 {
|
|
131
|
+
self.0.borrow().integral()
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
fn previous_error(&self) -> Option<f64> {
|
|
135
|
+
self.0.borrow().previous_error()
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
fn gains(ruby: &Ruby, this: &Self) -> Result<Value, Error> {
|
|
139
|
+
let gains = this.0.borrow().gains();
|
|
140
|
+
let class = CLASSES.get(ruby)?.gains.get(ruby);
|
|
141
|
+
class.funcall("new", (gains.p(), gains.i(), gains.d()))
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
fn limits(ruby: &Ruby, this: &Self) -> Result<Value, Error> {
|
|
145
|
+
let limits = this.0.borrow().limits();
|
|
146
|
+
limits_value(ruby, limits)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
fn step(ruby: &Ruby, this: Obj<Self>, error: Value, elapsed: Value) -> Result<Value, Error> {
|
|
29
150
|
this.check_frozen()?;
|
|
30
|
-
let
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
)
|
|
35
|
-
|
|
36
|
-
|
|
151
|
+
let error = real(error, "error")?;
|
|
152
|
+
let elapsed = duration(elapsed, "elapsed")?;
|
|
153
|
+
let outcome = this.0.borrow_mut().step(error, elapsed);
|
|
154
|
+
Ok(match outcome {
|
|
155
|
+
Ok(output) => output.into_value_with(ruby),
|
|
156
|
+
Err(refused) => Refusals::symbol(ruby, refused).as_value(),
|
|
157
|
+
})
|
|
37
158
|
}
|
|
38
159
|
}
|
|
39
160
|
|
|
@@ -41,23 +162,65 @@ impl Controller {
|
|
|
41
162
|
struct BandController(RefCell<Hysteresis>);
|
|
42
163
|
|
|
43
164
|
impl BandController {
|
|
44
|
-
fn new(ruby: &Ruby,
|
|
45
|
-
Ok(Self(RefCell::new(Hysteresis::new(
|
|
165
|
+
fn new(ruby: &Ruby, limits: Value) -> Result<Self, Error> {
|
|
166
|
+
Ok(Self(RefCell::new(Hysteresis::new(limits_from(
|
|
167
|
+
ruby, limits,
|
|
168
|
+
)?))))
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/// `Hysteresis.restored(limits, state)`: every side is valid for every
|
|
172
|
+
/// band, so only a non-Symbol (`TypeError`) or an unknown one
|
|
173
|
+
/// (`RangeError`) raises.
|
|
174
|
+
fn restored(ruby: &Ruby, limits: Value, state: Value) -> Result<Self, Error> {
|
|
175
|
+
let limits = limits_from(ruby, limits)?;
|
|
176
|
+
let state = Bands::parse(ruby, state)?;
|
|
177
|
+
Ok(Self(RefCell::new(Hysteresis::restored(limits, state))))
|
|
46
178
|
}
|
|
47
|
-
|
|
179
|
+
|
|
180
|
+
fn limits(ruby: &Ruby, this: &Self) -> Result<Value, Error> {
|
|
181
|
+
let limits = this.0.borrow().limits();
|
|
182
|
+
limits_value(ruby, limits)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
fn state(ruby: &Ruby, this: &Self) -> Symbol {
|
|
186
|
+
Bands::symbol(ruby, this.0.borrow().state())
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
fn observe(ruby: &Ruby, this: Obj<Self>, value: Value) -> Result<Symbol, Error> {
|
|
48
190
|
this.check_frozen()?;
|
|
49
|
-
let
|
|
50
|
-
|
|
191
|
+
let value = real(value, "value")?;
|
|
192
|
+
let outcome = this.0.borrow_mut().observe(value);
|
|
193
|
+
Ok(match outcome {
|
|
194
|
+
Ok(band) => Bands::symbol(ruby, band),
|
|
195
|
+
Err(refused) => Refusals::symbol(ruby, refused),
|
|
196
|
+
})
|
|
51
197
|
}
|
|
52
198
|
}
|
|
53
199
|
|
|
54
200
|
#[magnus::init]
|
|
55
201
|
fn init(ruby: &Ruby) -> Result<(), Error> {
|
|
56
202
|
let module = ruby.define_module("FeedbackMachines")?;
|
|
203
|
+
resolve(ruby, module)?;
|
|
204
|
+
module.define_singleton_method("__gains", function!(checked_gains, 3))?;
|
|
205
|
+
module.define_singleton_method("__limits", function!(checked_limits, 2))?;
|
|
57
206
|
let pid = module.define_class("Pid", ruby.class_object())?;
|
|
58
|
-
pid.
|
|
59
|
-
pid.
|
|
207
|
+
pid.undef_default_alloc_func();
|
|
208
|
+
pid.define_singleton_method("new", function!(Controller::new, 2))?;
|
|
209
|
+
pid.define_singleton_method("restored", function!(Controller::restored, 4))?;
|
|
210
|
+
pid.define_method("integral", method!(Controller::integral, 0))?;
|
|
211
|
+
pid.define_method("previous_error", method!(Controller::previous_error, 0))?;
|
|
212
|
+
pid.define_method("gains", method!(Controller::gains, 0))?;
|
|
213
|
+
pid.define_method("limits", method!(Controller::limits, 0))?;
|
|
214
|
+
pid.define_method("step", method!(Controller::step, 2))?;
|
|
60
215
|
let band = module.define_class("Hysteresis", ruby.class_object())?;
|
|
61
|
-
band.
|
|
62
|
-
band.
|
|
216
|
+
band.undef_default_alloc_func();
|
|
217
|
+
band.define_singleton_method("new", function!(BandController::new, 1))?;
|
|
218
|
+
band.define_singleton_method("restored", function!(BandController::restored, 2))?;
|
|
219
|
+
band.define_method("limits", method!(BandController::limits, 0))?;
|
|
220
|
+
band.define_method("state", method!(BandController::state, 0))?;
|
|
221
|
+
band.define_method("observe", method!(BandController::observe, 1))?;
|
|
222
|
+
// `new` and `restored` answer these: their classes are fixed now, so
|
|
223
|
+
// building a controller never runs `Object.const_get`.
|
|
224
|
+
Class::pin_wrapped::<Controller>(ruby, pid)?;
|
|
225
|
+
Class::pin_wrapped::<BandController>(ruby, band).map(drop)
|
|
63
226
|
}
|