plcopen 0.22.0
载入中...
搜索中...
未找到
master_filter.h
浏览该文件的文档.
1#pragma once
2
3// Math-Max Step 4A (T6, KB-108): deterministic, allocation-free discrete-time
4// alpha-beta-gamma steady-state PLL master tracking filter with decoupled
5// exact-turn/phase modulo encoder unwrapping and phase-lead extrapolation.
6// Normative spec: doc/compliance/control-physics-operators-semantics.md (D01-D05).
7//
8// RT-SAFE: no heap allocation, no locks, no exceptions, no OS calls, no
9// wall-clock access, no floating-point time accumulation. All rates are in the
10// normalized cycle domain (1 tick = 1 cycle).
11
12#include <cmath>
13#include <cstdint>
14#include <cstdlib>
15#include <limits>
16
17#include "rt/error.h"
18
20{
21
23{
24 raw = 0,
27};
28
30{
31 none = 0,
32 linear = 1,
34};
35
37{
40
41 // Critically-damped pole radius lambda in (0, 0.9999] when
42 // use_explicit_gains == false. Larger lambda gives stronger noise
43 // attenuation; smaller lambda gives faster transient tracking.
44 double pole_radius = 0.7;
45
46 // Optional explicit (alpha, beta, gamma) gains validated against a strict
47 // interior subset of the exact discrete Jury stability domain.
48 bool use_explicit_gains = false;
49 double alpha = 0.0;
50 double beta = 0.0;
51 double gamma = 0.0;
52
53 // Deterministic phase-lead extrapolation horizon in cycles: [0.0, 16.0].
54 double lead_cycles = 0.0;
55
56 // Optional modulo period M >= 2*DBL_MIN for rotary/multi-turn encoder
57 // unwrapping (0.0 disables wrapping). Unwrapping tracks exact integer turns
58 // and exact IEEE-754 signed remainder phase in [-M/2, +M/2) independently
59 // of accumulated floating-point position rounding, using Sterbenz-exact
60 // half-turn comparisons so consecutive raw displacements with |dz| < M/2
61 // never slip a turn across the entire allowed turn range.
62 double modulo_period = 0.0;
63};
64
66{
67 double position = 0.0;
68 double velocity = 0.0;
69 double acceleration = 0.0;
70 double innovation = 0.0;
71 bool primed = false;
72};
73
75{
76public:
77 static constexpr double MaxPoleRadius = 0.9999;
78 static constexpr double MaxLeadCycles = 16.0;
79 static constexpr double MaxModuloTurns = 1.0e12;
80 static constexpr std::int64_t MaxModuloTurnsInt = 1000000000000LL;
81 static constexpr double MinModuloPeriod = 2.0 * std::numeric_limits<double>::min();
82
84 {
85 switch(config.mode) {
89 break;
90 default:
92 }
93 switch(config.extrapolation_order) {
97 break;
98 default:
100 }
101 if(!std::isfinite(config.lead_cycles) || config.lead_cycles < 0.0 ||
102 config.lead_cycles > MaxLeadCycles ||
103 !std::isfinite(config.modulo_period) || config.modulo_period < 0.0 ||
104 (config.modulo_period > 0.0 && config.modulo_period < MinModuloPeriod)) {
106 }
107
108 double a = 0.0;
109 double b = 0.0;
110 double g = 0.0;
111
112 if(config.mode != MasterFilterMode::raw) {
113 if(!config.use_explicit_gains) {
114 if(!std::isfinite(config.pole_radius) ||
115 config.pole_radius <= 0.0 ||
116 config.pole_radius > MaxPoleRadius) {
118 }
119 const double lam = config.pole_radius;
120 const double om = 1.0 - lam;
122 a = 1.0 - lam * lam;
123 b = om * om;
124 g = 0.0;
125 } else {
126 a = 1.0 - lam * lam * lam;
127 b = 1.5 * om * om * (1.0 + lam);
128 g = om * om * om;
129 }
130 } else {
131 if(!std::isfinite(config.alpha) || !std::isfinite(config.beta) ||
132 !std::isfinite(config.gamma)) {
134 }
135 a = config.alpha;
136 b = config.beta;
137 g = config.gamma;
138 // Strict interior subset of the exact discrete Jury stability
139 // conditions with explicit numerical safety margins:
140 // 2nd-order (gamma == 0): 0 < a < 2, b > 0, 2a + b < 4.
141 // 3rd-order (gamma > 0): 0 < a < 2, b > 0, g > 0, 2a + b < 4,
142 // and a * b > 0.5 * (2 - a) * g.
143 constexpr double kGainMargin = 1.0e-12;
144 constexpr double kGammaFloor = 1.0e-15;
145 constexpr double kRelMargin = 1.0e-9;
146 if(!(a > kGainMargin && a < 2.0 - kGainMargin) ||
147 !(b > kGainMargin) ||
148 !(4.0 - 2.0 * a - b > kGainMargin)) {
150 }
152 if(g != 0.0) {
154 }
155 } else {
156 if(!(g > kGammaFloor)) {
158 }
159 const double lhs = a * b;
160 const double rhs = 0.5 * (2.0 - a) * g;
161 if(!std::isfinite(lhs) || !std::isfinite(rhs) ||
162 !(lhs > rhs * (1.0 + kRelMargin)) ||
163 !(lhs - rhs > kGammaFloor)) {
165 }
166 }
167 }
168 }
169
170 // Atomic commit after all validation succeeds.
171 config_ = config;
172 alpha_ = a;
173 beta_ = b;
174 gamma_ = g;
175 configured_ = true;
176 reset();
177 return rt::ErrorCode::ok;
178 }
179
180 bool configured() const { return configured_; }
181 const MasterFilterConfig &config() const { return config_; }
182 double alpha() const { return alpha_; }
183 double beta() const { return beta_; }
184 double gamma() const { return gamma_; }
185 const MasterFilterState &state() const { return output_; }
186 const MasterFilterState &filtered_state() const { return internal_; }
187
188 void reset()
189 {
190 internal_ = MasterFilterState{};
191 output_ = MasterFilterState{};
192 unwrapped_raw_ = 0.0;
193 modulo_turns_ = 0;
194 modulo_phase_ = 0.0;
195 modulo_anchored_ = false;
196 sample_count_ = 0;
197 }
198
199 rt::ErrorCode prime(double position, double velocity = 0.0, double acceleration = 0.0)
200 {
201 if(!configured_) {
203 }
204 if(!std::isfinite(position) || !std::isfinite(velocity) ||
205 !std::isfinite(acceleration)) {
207 }
208 const double acc_clamped =
209 config_.mode == MasterFilterMode::alpha_beta ? 0.0 : acceleration;
210 MasterFilterState next_internal{};
211 next_internal.position = position;
212 next_internal.velocity = velocity;
213 next_internal.acceleration = acc_clamped;
214 next_internal.innovation = 0.0;
215 next_internal.primed = true;
216
217 MasterFilterState next_output{};
218 const rt::ErrorCode ext = compute_extrapolated(next_internal, next_output);
219 if(ext != rt::ErrorCode::ok) {
220 return ext;
221 }
222 internal_ = next_internal;
223 output_ = next_output;
224 unwrapped_raw_ = position;
225 modulo_turns_ = 0;
226 modulo_phase_ = 0.0;
227 modulo_anchored_ = false;
228 sample_count_ = 2;
229 return rt::ErrorCode::ok;
230 }
231
232 // Re-anchors the position origin (e.g. after homing or MC_SetPosition)
233 // while preserving velocity and acceleration without introducing a spike.
234 rt::ErrorCode reanchor(double new_position)
235 {
236 if(!configured_) {
238 }
239 if(!std::isfinite(new_position)) {
241 }
242 if(!internal_.primed) {
243 return prime(new_position, 0.0, 0.0);
244 }
245 MasterFilterState next_internal = internal_;
246 next_internal.position = new_position;
247 next_internal.innovation = 0.0;
248 MasterFilterState next_output{};
249 const rt::ErrorCode ext = compute_extrapolated(next_internal, next_output);
250 if(ext != rt::ErrorCode::ok) {
251 return ext;
252 }
253 internal_ = next_internal;
254 output_ = next_output;
255 unwrapped_raw_ = new_position;
256 modulo_turns_ = 0;
257 modulo_phase_ = 0.0;
258 modulo_anchored_ = false;
259 return rt::ErrorCode::ok;
260 }
261
262 // Advances the filter by one cycle with raw master measurement `measured_position`.
263 // Rejects non-finite inputs or numeric overflows atomically without
264 // mutating internal state or `out`.
265 rt::ErrorCode update(double measured_position, MasterFilterState &out)
266 {
267 if(!configured_) {
269 }
270 if(!std::isfinite(measured_position)) {
272 }
273
274 if(!internal_.primed) {
275 std::int64_t init_turns = 0;
276 double init_phase = 0.0;
277 bool init_anchored = false;
278 if(config_.modulo_period > 0.0) {
279 const rt::ErrorCode split_rc = split_to_turns_phase(
280 measured_position, config_.modulo_period, init_turns, init_phase);
281 if(split_rc != rt::ErrorCode::ok) {
282 return split_rc;
283 }
284 init_anchored = true;
285 }
286 MasterFilterState first_internal{};
287 first_internal.position = measured_position;
288 first_internal.velocity = 0.0;
289 first_internal.acceleration = 0.0;
290 first_internal.innovation = 0.0;
291 first_internal.primed = true;
292 MasterFilterState first_output{};
293 const rt::ErrorCode ext = compute_extrapolated(first_internal, first_output);
294 if(ext != rt::ErrorCode::ok) {
295 return ext;
296 }
297 internal_ = first_internal;
298 output_ = first_output;
299 unwrapped_raw_ = measured_position;
300 modulo_turns_ = init_turns;
301 modulo_phase_ = init_phase;
302 modulo_anchored_ = init_anchored;
303 sample_count_ = 1;
304 out = output_;
305 return rt::ErrorCode::ok;
306 }
307
308 double next_unwrapped = measured_position;
309 double raw_step = 0.0;
310 std::int64_t next_turns = modulo_turns_;
311 double next_phase = modulo_phase_;
312 bool next_anchored = modulo_anchored_;
313 const rt::ErrorCode unwrap_rc = unwrap_measurement(
314 measured_position, next_unwrapped, raw_step, next_turns, next_phase, next_anchored);
315 if(unwrap_rc != rt::ErrorCode::ok) {
316 return unwrap_rc;
317 }
318
319 MasterFilterState next_internal{};
320 next_internal.primed = true;
321
322 if(config_.mode == MasterFilterMode::raw) {
323 // Non-modulo raw mode passes measured_position through directly
324 // without accumulating (p_prev + (z - p_prev)) cancellation error.
325 const double p_new =
326 config_.modulo_period > 0.0 ? next_unwrapped : measured_position;
327 const double v_new = raw_step;
328 const double a_new = sample_count_ >= 2 ? (v_new - internal_.velocity) : 0.0;
329 if(!std::isfinite(p_new) || !std::isfinite(v_new) || !std::isfinite(a_new)) {
331 }
332 next_internal.position = p_new;
333 next_internal.velocity = v_new;
334 next_internal.acceleration = a_new;
335 next_internal.innovation = 0.0;
336 } else {
337 const double p_pred = internal_.position + internal_.velocity +
338 0.5 * internal_.acceleration;
339 const double v_pred = internal_.velocity + internal_.acceleration;
340 const double a_pred = internal_.acceleration;
341 if(!std::isfinite(p_pred) || !std::isfinite(v_pred) || !std::isfinite(a_pred)) {
343 }
344 const double residual = next_unwrapped - p_pred;
345 if(!std::isfinite(residual)) {
347 }
348 const double p_new = p_pred + alpha_ * residual;
349 const double v_new = v_pred + beta_ * residual;
350 const double a_new =
351 config_.mode == MasterFilterMode::alpha_beta ? 0.0 : (a_pred + gamma_ * residual);
352 if(!std::isfinite(p_new) || !std::isfinite(v_new) || !std::isfinite(a_new)) {
354 }
355 next_internal.position = p_new;
356 next_internal.velocity = v_new;
357 next_internal.acceleration = a_new;
358 next_internal.innovation = residual;
359 }
360
361 MasterFilterState next_output{};
362 const rt::ErrorCode ext = compute_extrapolated(next_internal, next_output);
363 if(ext != rt::ErrorCode::ok) {
364 return ext;
365 }
366
367 internal_ = next_internal;
368 output_ = next_output;
369 unwrapped_raw_ = next_unwrapped;
370 modulo_turns_ = next_turns;
371 modulo_phase_ = next_phase;
372 modulo_anchored_ = next_anchored;
373 if(sample_count_ < 2) {
374 ++sample_count_;
375 }
376 out = output_;
377 return rt::ErrorCode::ok;
378 }
379
380private:
381 // Exact binary64 tests for u + v >= half and u + v > half when
382 // 0 <= u, v <= half and period >= 2*DBL_MIN (so half = 0.5*period is exact):
383 // either max(u,v) < 0.5*half (forcing u + v < half strictly), or
384 // max(u,v) >= 0.5*half in which case (half - max(u,v)) is exact with zero
385 // rounding error (by Sterbenz's lemma for normal half >= 2*DBL_MIN and by
386 // exact integer multiples of DBL_TRUE_MIN for DBL_MIN <= half < 2*DBL_MIN).
387 static bool sum_ge_half(double u, double v, double half)
388 {
389 const double hi = u >= v ? u : v;
390 const double lo = u >= v ? v : u;
391 return hi >= 0.5 * half && lo >= (half - hi);
392 }
393
394 static bool sum_gt_half(double u, double v, double half)
395 {
396 const double hi = u >= v ? u : v;
397 const double lo = u >= v ? v : u;
398 return hi >= 0.5 * half && lo > (half - hi);
399 }
400
401 static rt::ErrorCode split_to_turns_phase(double value,
402 double period,
403 std::int64_t &turns_out,
404 double &phase_out)
405 {
406 const double turns_mag = std::fabs(value) / period;
407 if(!std::isfinite(turns_mag) || turns_mag > MaxModuloTurns) {
409 }
410 const double half = 0.5 * period;
411 double rem = std::remainder(value, period);
412 if(!std::isfinite(rem)) {
414 }
415 // Compute integer turn count without forming value - rem (which could
416 // overflow near DBL_MAX when rem < 0). Since |value|/period <= 1e12,
417 // value/period - rem/period is within 1e-3 of the exact integer turn.
418 double q = std::round((value / period) - (rem / period));
419 if(!std::isfinite(q)) {
421 }
422 if(rem >= half) {
423 rem = -half;
424 q += 1.0;
425 }
426 if(rem == 0.0) {
427 rem = 0.0;
428 }
429 if(std::fabs(q) > MaxModuloTurns) {
431 }
432 turns_out = static_cast<std::int64_t>(q);
433 phase_out = rem;
434 return rt::ErrorCode::ok;
435 }
436
437 rt::ErrorCode unwrap_measurement(double measured,
438 double &unwrapped_next,
439 double &raw_step,
440 std::int64_t &next_turns,
441 double &next_phase,
442 bool &next_anchored) const
443 {
444 if(config_.modulo_period > 0.0) {
445 const double period = config_.modulo_period;
446 std::int64_t cur_turns = modulo_turns_;
447 double cur_phase = modulo_phase_;
448 if(!modulo_anchored_) {
449 const rt::ErrorCode split_rc =
450 split_to_turns_phase(unwrapped_raw_, period, cur_turns, cur_phase);
451 if(split_rc != rt::ErrorCode::ok) {
452 return split_rc;
453 }
454 }
455 if(cur_turns > MaxModuloTurnsInt || cur_turns < -MaxModuloTurnsInt) {
457 }
458 const double half = 0.5 * period;
459 // IEEE-754 std::remainder is mathematically exact (zero rounding)
460 // for every finite measured and period > 0, preserving tiny
461 // negative remainders near 0 without period-addition rounding.
462 double z_rem = std::remainder(measured, period);
463 if(!std::isfinite(z_rem)) {
465 }
466 if(z_rem >= half) {
467 z_rem = -half;
468 }
469 if(z_rem == 0.0) {
470 z_rem = 0.0;
471 }
472 // Exact half-turn wrap test in real arithmetic over [-half, +half):
473 // z_rem - cur_phase >= +half <=> z_rem >= 0 && cur_phase < 0 && z_rem + (-cur_phase) >= half
474 // z_rem - cur_phase < -half <=> cur_phase > 0 && z_rem < 0 && cur_phase + (-z_rem) > half
475 double diff = 0.0;
476 std::int64_t cand_turns = cur_turns;
477 if(z_rem >= 0.0 && cur_phase < 0.0 && sum_ge_half(z_rem, -cur_phase, half)) {
478 diff = -((half - z_rem) + (half + cur_phase));
479 --cand_turns;
480 } else if(cur_phase > 0.0 && z_rem < 0.0 && sum_gt_half(cur_phase, -z_rem, half)) {
481 diff = (half - cur_phase) + (half + z_rem);
482 ++cand_turns;
483 } else {
484 diff = z_rem - cur_phase;
485 }
486 if(cand_turns > MaxModuloTurnsInt || cand_turns < -MaxModuloTurnsInt) {
488 }
489 const double cand_pos = static_cast<double>(cand_turns) * period + z_rem;
490 if(!std::isfinite(diff) || !std::isfinite(cand_pos)) {
492 }
493 const double mag_turns = std::fabs(cand_pos) / period;
494 if(!std::isfinite(mag_turns) || mag_turns > MaxModuloTurns) {
496 }
497 unwrapped_next = cand_pos;
498 raw_step = diff;
499 next_turns = cand_turns;
500 next_phase = z_rem;
501 next_anchored = true;
502 return rt::ErrorCode::ok;
503 }
504
505 const double diff = measured - unwrapped_raw_;
506 if(!std::isfinite(diff)) {
508 }
509 unwrapped_next = measured;
510 raw_step = diff;
511 next_turns = 0;
512 next_phase = 0.0;
513 next_anchored = false;
514 return rt::ErrorCode::ok;
515 }
516
517 rt::ErrorCode compute_extrapolated(const MasterFilterState &src,
518 MasterFilterState &dst) const
519 {
520 dst = src;
521 const double lead = config_.lead_cycles;
522 if(lead == 0.0 || config_.extrapolation_order == ExtrapolationOrder::none) {
523 return rt::ErrorCode::ok;
524 }
525 if(config_.extrapolation_order == ExtrapolationOrder::linear) {
526 dst.position = src.position + src.velocity * lead;
527 } else {
528 dst.position = src.position + src.velocity * lead +
529 0.5 * src.acceleration * lead * lead;
530 dst.velocity = src.velocity + src.acceleration * lead;
531 }
532 if(!std::isfinite(dst.position) || !std::isfinite(dst.velocity) ||
533 !std::isfinite(dst.acceleration)) {
535 }
536 return rt::ErrorCode::ok;
537 }
538
539 MasterFilterConfig config_{};
540 double alpha_ = 0.0;
541 double beta_ = 0.0;
542 double gamma_ = 0.0;
543 double unwrapped_raw_ = 0.0;
544 std::int64_t modulo_turns_ = 0;
545 double modulo_phase_ = 0.0;
546 bool modulo_anchored_ = false;
547 MasterFilterState internal_{};
548 MasterFilterState output_{};
549 std::uint8_t sample_count_ = 0;
550 bool configured_ = false;
551};
552
553} // namespace plcopen::core::exec
rt::ErrorCode reanchor(double new_position)
rt::ErrorCode prime(double position, double velocity=0.0, double acceleration=0.0)
const MasterFilterState & state() const
rt::ErrorCode update(double measured_position, MasterFilterState &out)
static constexpr std::int64_t MaxModuloTurnsInt
const MasterFilterConfig & config() const
const MasterFilterState & filtered_state() const
rt::ErrorCode configure(const MasterFilterConfig &config)