plcopen 0.22.0
载入中...
搜索中...
未找到
input_shaper.h
浏览该文件的文档.
1#pragma once
2
3// Math-Max Step 4B (T11a, KB-108): deterministic, allocation-free discrete-time
4// positive-weight input shaper (ZV / ZVD / ZVDD / EI, 1- or 2-mode cascade)
5// using exact two-tap phasor impulse splitting and branch-and-bound verified
6// discrete two-zero EI cascade.
7// Normative spec: doc/compliance/control-physics-operators-semantics.md (D06-D09).
8//
9// RT-SAFE: fixed-capacity sparse impulse taps and ring buffer, zero heap
10// allocation, no locks, no exceptions, no OS calls, no floating-point time
11// accumulation. All frequencies are normalized to cycles^-1 (freq_hz / rate_hz).
12
13#include <cmath>
14#include <cstddef>
15#include <cstdint>
16#include <limits>
17
18#include "otg/profile1d.h"
19#include "rt/error.h"
20
22{
23
25{
26 bypass = 0,
27 zv = 1,
28 zvd = 2,
29 zvdd = 3,
30 ei = 4,
31};
32
34{
36 // Normalized natural frequency f_n = freq_hz / sample_rate_hz (cycles^-1).
37 double natural_freq_cycles = 0.0;
38 // Viscous damping ratio zeta in [0.0, 0.45].
39 double damping_ratio = 0.0;
40 // Residual vibration tolerance V_tol in [0.001, 0.25] (used only by EI).
41 double residual_tolerance = 0.05;
42};
43
45{
46 static constexpr std::size_t MaxModes = 2;
47
48 std::size_t mode_count = 0;
50};
51
53{
54 std::uint16_t delay_cycles = 0;
55 double weight = 0.0;
56};
57
58// Helper for converting Hz + loop rate (Hz) into normalized cycles^-1.
59inline rt::Result<double> freq_cycles_from_hz(double freq_hz, double sample_rate_hz)
60{
61 if(!std::isfinite(freq_hz) || !std::isfinite(sample_rate_hz) ||
62 freq_hz <= 0.0 || sample_rate_hz <= 0.0) {
64 }
65 const double normalized = freq_hz / sample_rate_hz;
66 if(!std::isfinite(normalized) || normalized <= 0.0) {
68 }
69 return rt::Result<double>::success(normalized);
70}
71
73{
74public:
75 static constexpr std::size_t MaxDelayCycles = 512;
76 static constexpr std::size_t MaxHistory = MaxDelayCycles + 1;
77 static constexpr std::size_t MaxTaps = 128;
78 static constexpr double MaxDampingRatio = 0.45;
79 static constexpr double MinEiTolerance = 1.0e-3;
80 static constexpr double MaxEiTolerance = 0.25;
81
83 {
84 taps_[0] = ShaperTap{0, 1.0};
85 tap_count_ = 1;
86 settling_cycles_ = 0;
87 mean_delay_cycles_ = 0.0;
88 }
89
91 {
92 if(config.mode_count > InputShaperConfig::MaxModes) {
94 }
95
96 double combined[MaxHistory] = {};
97 combined[0] = 1.0;
98 std::size_t combined_max_delay = 0;
99
100 bool has_ei_band[InputShaperConfig::MaxModes] = {};
101 double ei_band_lo[InputShaperConfig::MaxModes] = {};
102 double ei_band_hi[InputShaperConfig::MaxModes] = {};
103
104 for(std::size_t m = 0; m < config.mode_count; ++m) {
105 const ShaperModeConfig &mc = config.mode[m];
106 switch(mc.type) {
108 continue;
113 break;
114 default:
116 }
117
118 double mode_kernel[MaxHistory] = {};
119 std::size_t mode_max_delay = 0;
120 double cert_lo = 0.0;
121 double cert_hi = 0.0;
122 const rt::ErrorCode built =
123 build_mode_kernel(mc, mode_kernel, mode_max_delay, cert_lo, cert_hi);
124 if(built != rt::ErrorCode::ok) {
125 return built;
126 }
127 if(mc.type == InputShaperType::ei) {
128 has_ei_band[m] = true;
129 ei_band_lo[m] = cert_lo;
130 ei_band_hi[m] = cert_hi;
131 }
132 if(combined_max_delay + mode_max_delay > MaxDelayCycles) {
134 }
135
136 double next_combined[MaxHistory] = {};
137 const std::size_t next_max = combined_max_delay + mode_max_delay;
138 for(std::size_t i = 0; i <= combined_max_delay; ++i) {
139 if(combined[i] == 0.0) {
140 continue;
141 }
142 for(std::size_t j = 0; j <= mode_max_delay; ++j) {
143 if(mode_kernel[j] == 0.0) {
144 continue;
145 }
146 next_combined[i + j] += combined[i] * mode_kernel[j];
147 }
148 }
149 for(std::size_t k = 0; k <= next_max; ++k) {
150 combined[k] = next_combined[k];
151 }
152 for(std::size_t k = next_max + 1; k < MaxHistory; ++k) {
153 combined[k] = 0.0;
154 }
155 combined_max_delay = next_max;
156 }
157
158 // Normalize and pack sparse non-zero positive taps.
159 double weight_sum = 0.0;
160 for(std::size_t k = 0; k <= combined_max_delay; ++k) {
161 if(!std::isfinite(combined[k]) || combined[k] < -1.0e-15) {
163 }
164 if(combined[k] > 1.0e-15) {
165 weight_sum += combined[k];
166 }
167 }
168 if(!std::isfinite(weight_sum) || !(weight_sum > 0.0)) {
170 }
171
172 ShaperTap staged_taps[MaxTaps]{};
173 std::size_t staged_count = 0;
174 std::size_t staged_settling = 0;
175 double staged_mean_delay = 0.0;
176 for(std::size_t k = 0; k <= combined_max_delay; ++k) {
177 if(combined[k] <= 1.0e-15) {
178 continue;
179 }
180 if(staged_count >= MaxTaps) {
182 }
183 const double normalized_w = combined[k] / weight_sum;
184 if(!std::isfinite(normalized_w) || !(normalized_w > 0.0)) {
186 }
187 staged_taps[staged_count] = ShaperTap{static_cast<std::uint16_t>(k), normalized_w};
188 ++staged_count;
189 staged_settling = k;
190 staged_mean_delay += static_cast<double>(k) * normalized_w;
191 }
192 if(staged_count == 0 || !std::isfinite(staged_mean_delay)) {
194 }
195
196 // Certify the ACTUAL final published taps (post pruning & re-normalization)
197 // on the continuous two-zero interval [ei_band_lo, ei_band_hi] of every
198 // active EI mode via exact second-order C^inf branch-and-bound on |H(z)|^2.
199 for(std::size_t m = 0; m < config.mode_count; ++m) {
200 if(!has_ei_band[m]) {
201 continue;
202 }
203 const ShaperModeConfig &mc = config.mode[m];
204 if(!certify_continuum_bound(staged_taps, staged_count, staged_settling,
205 ei_band_lo[m], ei_band_hi[m],
208 }
209 }
210
211 // Atomic commit.
212 config_ = config;
213 for(std::size_t i = 0; i < staged_count; ++i) {
214 taps_[i] = staged_taps[i];
215 }
216 tap_count_ = staged_count;
217 settling_cycles_ = staged_settling;
218 mean_delay_cycles_ = staged_mean_delay;
219 reset();
220 return rt::ErrorCode::ok;
221 }
222
223 const InputShaperConfig &config() const { return config_; }
224 std::size_t tap_count() const { return tap_count_; }
225 ShaperTap tap(std::size_t index) const
226 {
227 return index < tap_count_ ? taps_[index] : ShaperTap{};
228 }
229 // Finite-support kernel length / terminal drain duration: once the input
230 // reaches rest at the target, feed `settling_cycles()` rest cycles to
231 // converge fully to the target. This is NOT a uniform phase delay.
232 std::size_t settling_cycles() const { return settling_cycles_; }
233 // Impulse centroid sum_j (delay_j * weight_j): exact steady-state lag for
234 // a constant-velocity ramp (e.g. 5.0 cycles for undamped ZV with D = 10).
235 double mean_delay_cycles() const { return mean_delay_cycles_; }
236 bool primed() const { return primed_; }
237
238 void reset()
239 {
240 for(std::size_t i = 0; i < MaxHistory; ++i) {
241 history_[i] = otg::State1D{};
242 }
243 write_index_ = 0;
244 primed_ = false;
245 }
246
247 // Fills the entire delay ring with `state` so the first shaped output
248 // starts smoothly from `state` with zero startup step.
250 {
251 if(!otg::is_finite(state)) {
253 }
254 for(std::size_t i = 0; i < MaxHistory; ++i) {
255 history_[i] = state;
256 }
257 write_index_ = 0;
258 primed_ = true;
259 return rt::ErrorCode::ok;
260 }
261
262 rt::ErrorCode prime(double position)
263 {
264 return prime(otg::State1D{position, 0.0, 0.0});
265 }
266
267 // Applies the convex positive-weight FIR convolution to a full-order state.
268 // Preserves position/velocity/acceleration/jerk envelopes identically and
269 // rejects non-finite inputs atomically without advancing the ring buffer.
271 {
272 if(!otg::is_finite(input)) {
274 }
275 if(!primed_) {
276 const rt::ErrorCode pr = prime(input);
277 if(pr != rt::ErrorCode::ok) {
278 return pr;
279 }
280 output = input;
281 return rt::ErrorCode::ok;
282 }
283
284 const otg::State1D saved_slot = history_[write_index_];
285 history_[write_index_] = input;
286
287 // Center position accumulation around `input.position` so constant-position
288 // steady state preserves exact 0-ULP DC precision even at huge offsets.
289 double pos_delta = 0.0;
290 double vel_sum = 0.0;
291 double acc_sum = 0.0;
292 for(std::size_t j = 0; j < tap_count_; ++j) {
293 const std::size_t delay = static_cast<std::size_t>(taps_[j].delay_cycles);
294 const std::size_t idx = (write_index_ + MaxHistory - delay) % MaxHistory;
295 const double w = taps_[j].weight;
296 const otg::State1D &h = history_[idx];
297 pos_delta += w * (h.position - input.position);
298 vel_sum += w * h.velocity;
299 acc_sum += w * h.acceleration;
300 }
301
302 const otg::State1D candidate{input.position + pos_delta, vel_sum, acc_sum};
303 if(!otg::is_finite(candidate)) {
304 history_[write_index_] = saved_slot;
306 }
307
308 write_index_ = (write_index_ + 1) % MaxHistory;
309 output = candidate;
310 return rt::ErrorCode::ok;
311 }
312
313 // Evaluates exact discrete-time residual vibration amplitude V(f, zeta) at
314 // tick D = settling_cycles_ for a test damped oscillator (f in cycles^-1).
316 double damping_ratio) const
317 {
318 if(!std::isfinite(freq_cycles) || freq_cycles <= 0.0 ||
319 !std::isfinite(damping_ratio) || damping_ratio < 0.0 ||
320 damping_ratio >= 1.0) {
322 }
323 const double v = eval_taps_residual(
324 taps_, tap_count_, settling_cycles_, freq_cycles, damping_ratio);
325 if(!std::isfinite(v)) {
327 }
329 }
330
331private:
332 static constexpr double Pi = 3.14159265358979323846;
333
334 static double eval_taps_residual(const ShaperTap *taps,
335 std::size_t tap_count,
336 std::size_t settling_cycles,
337 double freq_cycles,
338 double damping_ratio)
339 {
340 const double omega_n = 2.0 * Pi * freq_cycles;
341 const double sigma = damping_ratio * omega_n;
342 const double omega_d = omega_n * std::sqrt(1.0 - damping_ratio * damping_ratio);
343 if(!std::isfinite(omega_n) || !std::isfinite(omega_d) || !(omega_d > 0.0)) {
344 return std::numeric_limits<double>::quiet_NaN();
345 }
346 const double d_max = static_cast<double>(settling_cycles);
347 double sum_c = 0.0;
348 double sum_s = 0.0;
349 for(std::size_t j = 0; j < tap_count; ++j) {
350 const double d_j = static_cast<double>(taps[j].delay_cycles);
351 // Fold exp(-sigma * D) inside as exp(-sigma * (D - d_j)) in (0, 1]
352 // to prevent exponential overflow at large settling_cycles.
353 const double scale = taps[j].weight * std::exp(-sigma * (d_max - d_j));
354 const double phase = omega_d * d_j;
355 sum_c += scale * std::cos(phase);
356 sum_s += scale * std::sin(phase);
357 }
358 return std::hypot(sum_c, sum_s);
359 }
360
361 // Bounded numerical branch-and-bound verification of
362 // sup_{f in [f_lo, f_hi]} V(f, z) <= v_tol with an explicit floating-point
363 // evaluation enclosure margin, using the second-derivative bound on
364 // P(f) = V(f, z)^2 = |Z(f)|^2:
365 // |Z'(f)| <= L1 = 2*pi * sum_j w_j * r_j
366 // |Z''(f)| <= L2 = (2*pi)^2 * sum_j w_j * r_j^2
367 // |P''(f)| <= M2 = 2 * (L2 * V_ub + L1^2), V_ub = min(w_ub, max(V_a, V_b) + eps_eval + 0.5*L1*h)
368 // sup_{[a,b]} P(f) <= max(P_ub(a), P_ub(b)) + (1/8) * M2 * (b - a)^2.
369 // Makes ZERO unimodality assumption and verifies the exact published taps.
370 static bool certify_continuum_bound(const ShaperTap *taps,
371 std::size_t tap_count,
372 std::size_t settling_cycles,
373 double f_lo,
374 double f_hi,
375 double damping_ratio,
376 double v_tol)
377 {
378 if(!std::isfinite(f_lo) || !std::isfinite(f_hi) || !(f_lo > 0.0) ||
379 f_hi < f_lo || !std::isfinite(v_tol) || !(v_tol > 0.0)) {
380 return false;
381 }
382 const double d_max = static_cast<double>(settling_cycles);
383 const double z2 = damping_ratio * damping_ratio;
384 const double one_m_z2 = 1.0 - z2;
385 double w_sum = 0.0;
386 double sum_r1 = 0.0;
387 double sum_r2 = 0.0;
388 for(std::size_t j = 0; j < tap_count; ++j) {
389 const double dj = static_cast<double>(taps[j].delay_cycles);
390 const double rem = d_max - dj;
391 const double r2 = z2 * rem * rem + one_m_z2 * dj * dj;
392 w_sum += taps[j].weight;
393 sum_r1 += taps[j].weight * std::sqrt(r2);
394 sum_r2 += taps[j].weight * r2;
395 }
396 constexpr double kEps = std::numeric_limits<double>::epsilon();
397 const double w_ub = w_sum * (1.0 + 16.0 * static_cast<double>(tap_count + 1) * kEps);
398 // Conservative per-evaluation floating-point enclosure margin covering
399 // omega_n/sigma/omega_d phase and decay amplification up to d_max,
400 // libm trig/exp, weighted summation, and hypot rounding.
401 const double two_pi = 2.0 * Pi;
402 const double eps_eval =
403 (32.0 * static_cast<double>(tap_count + 1) + 64.0 * two_pi * d_max) * kEps * w_ub;
404 const double l1 = two_pi * sum_r1 * 1.001;
405 const double l2 = two_pi * two_pi * sum_r2 * 1.001;
406 const double p_tol_lo = (v_tol * v_tol) * (1.0 - 16.0 * kEps);
407 if(!std::isfinite(w_ub) || !std::isfinite(eps_eval) ||
408 !std::isfinite(l1) || !std::isfinite(l2) ||
409 !std::isfinite(p_tol_lo) || !(p_tol_lo > 0.0)) {
410 return false;
411 }
412
413 auto interval_certified = [&](double a, double b, double va, double vb) -> bool {
414 const double vmax_ub = (va > vb ? va : vb) + eps_eval;
415 if(!std::isfinite(vmax_ub) || vmax_ub > v_tol) {
416 return false;
417 }
418 const double span = b - a;
419 double v_ub = vmax_ub + 0.5 * l1 * span;
420 if(v_ub > w_ub) v_ub = w_ub;
421 const double m2 = 2.0 * (l2 * v_ub + l1 * l1) * 1.001;
422 const double p_ub = (vmax_ub * vmax_ub + 0.125 * m2 * span * span) * (1.0 + 16.0 * kEps);
423 return std::isfinite(p_ub) && p_ub <= p_tol_lo;
424 };
425
426 const double va0 = eval_taps_residual(taps, tap_count, settling_cycles, f_lo, damping_ratio);
427 const double vb0 = eval_taps_residual(taps, tap_count, settling_cycles, f_hi, damping_ratio);
428 if(!std::isfinite(va0) || !std::isfinite(vb0) ||
429 (va0 + eps_eval) > v_tol || (vb0 + eps_eval) > v_tol) {
430 return false;
431 }
432 if(f_hi == f_lo) {
433 return true;
434 }
435
436 struct Span
437 {
438 double a;
439 double b;
440 double va;
441 double vb;
442 };
443 constexpr std::size_t kInitBins = 32;
444 constexpr std::size_t kStackCap = 128;
445 Span stack[kStackCap]{};
446 std::size_t sp = 0;
447
448 double prev_f = f_lo;
449 double prev_v = va0;
450 for(std::size_t i = 1; i <= kInitBins; ++i) {
451 const double cur_f =
452 (i == kInitBins)
453 ? f_hi
454 : (f_lo + (f_hi - f_lo) * (static_cast<double>(i) / static_cast<double>(kInitBins)));
455 const double cur_v =
456 (i == kInitBins)
457 ? vb0
458 : eval_taps_residual(taps, tap_count, settling_cycles, cur_f, damping_ratio);
459 if(!std::isfinite(cur_v) || (cur_v + eps_eval) > v_tol) {
460 return false;
461 }
462 if(!interval_certified(prev_f, cur_f, prev_v, cur_v)) {
463 if(sp >= kStackCap) return false;
464 stack[sp++] = Span{prev_f, cur_f, prev_v, cur_v};
465 }
466 prev_f = cur_f;
467 prev_v = cur_v;
468 }
469
470 int splits = 0;
471 constexpr int kMaxSplits = 2048;
472 while(sp > 0) {
473 if(splits >= kMaxSplits) {
474 return false;
475 }
476 const Span cur = stack[--sp];
477 const double mid = 0.5 * (cur.a + cur.b);
478 if(!(mid > cur.a && mid < cur.b)) {
479 return false;
480 }
481 const double vm = eval_taps_residual(taps, tap_count, settling_cycles, mid, damping_ratio);
482 if(!std::isfinite(vm) || (vm + eps_eval) > v_tol) {
483 return false;
484 }
485 ++splits;
486 if(!interval_certified(cur.a, mid, cur.va, vm)) {
487 if(sp >= kStackCap) return false;
488 stack[sp++] = Span{cur.a, mid, cur.va, vm};
489 }
490 if(!interval_certified(mid, cur.b, vm, cur.vb)) {
491 if(sp >= kStackCap) return false;
492 stack[sp++] = Span{mid, cur.b, vm, cur.vb};
493 }
494 }
495 return true;
496 }
497
498 static rt::ErrorCode add_split_impulse(double *dense,
499 std::size_t &max_idx,
500 double amplitude,
501 double delay_cycles,
502 double sigma,
503 double omega_d)
504 {
505 if(!std::isfinite(amplitude) || amplitude < 0.0 ||
506 !std::isfinite(delay_cycles) || delay_cycles < 0.0) {
508 }
509 if(delay_cycles > static_cast<double>(MaxDelayCycles) + 1.0e-14) {
511 }
512 const double floor_d = std::floor(delay_cycles);
513 const std::size_t m = static_cast<std::size_t>(floor_d);
514 const double delta = delay_cycles - floor_d;
515
516 if(delta <= 1.0e-14) {
517 if(m > MaxDelayCycles) {
519 }
520 dense[m] += amplitude;
521 if(m > max_idx) max_idx = m;
522 return rt::ErrorCode::ok;
523 }
524 if(1.0 - delta <= 1.0e-14) {
525 if(m + 1 > MaxDelayCycles) {
527 }
528 dense[m + 1] += amplitude;
529 if(m + 1 > max_idx) max_idx = m + 1;
530 return rt::ErrorCode::ok;
531 }
532 if(m + 1 > MaxDelayCycles) {
534 }
535 const double sin_wd = std::sin(omega_d);
536 if(!std::isfinite(sin_wd) || !(sin_wd > 0.0)) {
538 }
539 const double w_m =
540 amplitude * std::exp(sigma * delta) * (std::sin(omega_d * (1.0 - delta)) / sin_wd);
541 const double w_m1 =
542 amplitude * std::exp(-sigma * (1.0 - delta)) * (std::sin(omega_d * delta) / sin_wd);
543 if(!std::isfinite(w_m) || !std::isfinite(w_m1) || w_m < 0.0 || w_m1 < 0.0) {
545 }
546 dense[m] += w_m;
547 dense[m + 1] += w_m1;
548 if(m + 1 > max_idx) max_idx = m + 1;
549 return rt::ErrorCode::ok;
550 }
551
552 static rt::ErrorCode convolve_self(const double *a, std::size_t max_a,
553 const double *b, std::size_t max_b,
554 double *out, std::size_t &max_out)
555 {
556 if(max_a + max_b > MaxDelayCycles) {
558 }
559 max_out = max_a + max_b;
560 for(std::size_t k = 0; k <= max_out; ++k) {
561 out[k] = 0.0;
562 }
563 for(std::size_t i = 0; i <= max_a; ++i) {
564 if(a[i] == 0.0) continue;
565 for(std::size_t j = 0; j <= max_b; ++j) {
566 if(b[j] == 0.0) continue;
567 out[i + j] += a[i] * b[j];
568 }
569 }
570 return rt::ErrorCode::ok;
571 }
572
573 static rt::ErrorCode normalize_kernel(double *dense, std::size_t max_idx)
574 {
575 double sum = 0.0;
576 for(std::size_t k = 0; k <= max_idx; ++k) {
577 if(!std::isfinite(dense[k]) || dense[k] < -1.0e-15) {
579 }
580 if(dense[k] < 0.0) dense[k] = 0.0;
581 sum += dense[k];
582 }
583 if(!std::isfinite(sum) || !(sum > 0.0)) {
585 }
586 for(std::size_t k = 0; k <= max_idx; ++k) {
587 dense[k] /= sum;
588 }
589 return rt::ErrorCode::ok;
590 }
591
592 static rt::ErrorCode build_zv_kernel(double freq_cycles,
593 double damping_ratio,
594 double *zv,
595 std::size_t &zv_max)
596 {
597 const double omega_n = 2.0 * Pi * freq_cycles;
598 const double sigma = damping_ratio * omega_n;
599 const double omega_d = omega_n * std::sqrt(1.0 - damping_ratio * damping_ratio);
600 if(!std::isfinite(omega_n) || !std::isfinite(omega_d) ||
601 omega_d <= 1.0e-9 || omega_d >= Pi - 1.0e-6) {
603 }
604 const double half_period = Pi / omega_d;
605 if(!std::isfinite(half_period) ||
606 half_period > static_cast<double>(MaxDelayCycles) + 1.0) {
608 }
609 const double k_decay = std::exp(-sigma * half_period);
610 if(!std::isfinite(k_decay) || !(k_decay > 0.0)) {
612 }
613 for(std::size_t k = 0; k < MaxHistory; ++k) {
614 zv[k] = 0.0;
615 }
616 zv_max = 0;
617 const double inv_sum = 1.0 / (1.0 + k_decay);
618 rt::ErrorCode rc = add_split_impulse(zv, zv_max, inv_sum, 0.0, sigma, omega_d);
619 if(rc != rt::ErrorCode::ok) return rc;
620 rc = add_split_impulse(zv, zv_max, k_decay * inv_sum, half_period, sigma, omega_d);
621 if(rc != rt::ErrorCode::ok) return rc;
622 return normalize_kernel(zv, zv_max);
623 }
624
625 // Builds exact discrete two-zero cascade ZV(f_n*(1-delta), z) * ZV(f_n*(1+delta), z),
626 // packs its exact pruned/normalized taps, and evaluates both its peak estimate and
627 // whether the continuum on [f_n*(1-delta), f_n*(1+delta)] is certified <= v_cert.
628 static rt::ErrorCode eval_ei_candidate(double freq_cycles,
629 double damping_ratio,
630 double delta,
631 double v_cert,
632 double *ker,
633 std::size_t &max_d,
634 double &peak_v,
635 bool &certified)
636 {
637 certified = false;
638 double z_lo[MaxHistory] = {};
639 double z_hi[MaxHistory] = {};
640 std::size_t max_lo = 0;
641 std::size_t max_hi = 0;
642 const double f_lo = freq_cycles * (1.0 - delta);
643 const double f_hi = freq_cycles * (1.0 + delta);
644 rt::ErrorCode rc = build_zv_kernel(f_lo, damping_ratio, z_lo, max_lo);
645 if(rc != rt::ErrorCode::ok) return rc;
646 rc = build_zv_kernel(f_hi, damping_ratio, z_hi, max_hi);
647 if(rc != rt::ErrorCode::ok) return rc;
648 rc = convolve_self(z_lo, max_lo, z_hi, max_hi, ker, max_d);
649 if(rc != rt::ErrorCode::ok) return rc;
650 rc = normalize_kernel(ker, max_d);
651 if(rc != rt::ErrorCode::ok) return rc;
652
653 // Pack pruned/re-normalized sparse taps matching configure()'s exact tap rule.
654 double w_sum = 0.0;
655 for(std::size_t k = 0; k <= max_d; ++k) {
656 if(ker[k] > 1.0e-15) {
657 w_sum += ker[k];
658 }
659 }
660 if(!std::isfinite(w_sum) || !(w_sum > 0.0)) {
662 }
663 ShaperTap sparse[16]{};
664 std::size_t sparse_n = 0;
665 std::size_t actual_max = 0;
666 for(std::size_t k = 0; k <= max_d; ++k) {
667 if(ker[k] > 1.0e-15) {
668 if(sparse_n >= 16) {
670 }
671 sparse[sparse_n] = ShaperTap{static_cast<std::uint16_t>(k), ker[k] / w_sum};
672 ++sparse_n;
673 actual_max = k;
674 }
675 }
676 max_d = actual_max;
677 if(delta <= 0.0) {
678 peak_v = eval_taps_residual(sparse, sparse_n, actual_max, freq_cycles, damping_ratio);
679 if(!std::isfinite(peak_v)) return rt::ErrorCode::invalid_argument;
680 certified = peak_v <= v_cert;
681 return rt::ErrorCode::ok;
682 }
683
684 constexpr int kGrid = 64;
685 double best_v = -1.0;
686 for(int i = 0; i <= kGrid; ++i) {
687 const double f = f_lo + (f_hi - f_lo) * (static_cast<double>(i) / static_cast<double>(kGrid));
688 const double v = eval_taps_residual(sparse, sparse_n, actual_max, f, damping_ratio);
689 if(!std::isfinite(v)) return rt::ErrorCode::invalid_argument;
690 if(v > best_v) {
691 best_v = v;
692 }
693 }
694 peak_v = best_v;
695 if(best_v > v_cert) {
696 certified = false;
697 return rt::ErrorCode::ok;
698 }
699 certified = certify_continuum_bound(
700 sparse, sparse_n, actual_max, f_lo, f_hi, damping_ratio, v_cert);
701 return rt::ErrorCode::ok;
702 }
703
704 static rt::ErrorCode build_ei_kernel(double freq_cycles,
705 double damping_ratio,
706 double v_tol,
707 double *kernel,
708 std::size_t &max_delay,
709 double &cert_lo,
710 double &cert_hi)
711 {
712 if(!std::isfinite(v_tol) || v_tol < MinEiTolerance || v_tol > MaxEiTolerance) {
714 }
715 const double wd_scale = 2.0 * Pi * std::sqrt(1.0 - damping_ratio * damping_ratio);
716 const double f_nyq = (Pi - 1.0e-6) / wd_scale;
717 if(!std::isfinite(f_nyq) || !(freq_cycles < f_nyq)) {
719 }
720 const double nyq_delta = (f_nyq / freq_cycles) - 1.0 - 1.0e-6;
721 if(!std::isfinite(nyq_delta) || !(nyq_delta > 1.0e-6)) {
723 }
724 const double hi_cap = nyq_delta < 0.75 ? nyq_delta : 0.75;
725
726 // Solve against a tiny 0.1% backoff (0.999 * v_tol) so final published
727 // taps pass continuum certification against v_tol cleanly with bounded splits.
728 const double v_target = v_tol * (1.0 - 1.0e-3);
729
730 // Baseline delta == 0 (ZVD) must fit within MaxDelayCycles AND satisfy v_target.
731 double best_pk = 0.0;
732 bool best_cert = false;
733 rt::ErrorCode rc0 = eval_ei_candidate(
734 freq_cycles, damping_ratio, 0.0, v_target, kernel, max_delay, best_pk, best_cert);
735 if(rc0 != rt::ErrorCode::ok) {
736 return rc0;
737 }
738 if(!best_cert || !(best_pk <= v_target)) {
740 }
741
742 double lo = 0.0;
743 double hi = hi_cap;
744 double trial[MaxHistory] = {};
745 for(int it = 0; it < 44; ++it) {
746 const double mid = 0.5 * (lo + hi);
747 std::size_t trial_max = 0;
748 double trial_pk = 0.0;
749 bool trial_cert = false;
750 const rt::ErrorCode rc = eval_ei_candidate(
751 freq_cycles, damping_ratio, mid, v_target, trial, trial_max, trial_pk, trial_cert);
752 if(rc == rt::ErrorCode::ok && trial_cert) {
753 lo = mid;
754 best_pk = trial_pk;
755 max_delay = trial_max;
756 for(std::size_t k = 0; k <= trial_max; ++k) {
757 kernel[k] = trial[k];
758 }
759 for(std::size_t k = trial_max + 1; k < MaxHistory; ++k) {
760 kernel[k] = 0.0;
761 }
762 } else {
763 hi = mid;
764 }
765 }
766
767 // If convergence stopped strictly below v_target and strictly below the
768 // Nyquist cap because increasing delta hits MaxDelayCycles, report
769 // out_of_range rather than silently returning a delay-truncated EI.
770 if(lo + 1.0e-4 < hi_cap && best_pk < 0.99 * v_target) {
771 std::size_t probe_max = 0;
772 double probe_pk = 0.0;
773 bool probe_cert = false;
774 const rt::ErrorCode probe_rc = eval_ei_candidate(
775 freq_cycles, damping_ratio, lo + 1.0e-4, v_target,
776 trial, probe_max, probe_pk, probe_cert);
777 if(probe_rc == rt::ErrorCode::out_of_range) {
779 }
780 }
781 cert_lo = freq_cycles * (1.0 - lo);
782 cert_hi = freq_cycles * (1.0 + lo);
783 return rt::ErrorCode::ok;
784 }
785
786 static rt::ErrorCode build_mode_kernel(const ShaperModeConfig &mc,
787 double *kernel,
788 std::size_t &max_delay,
789 double &cert_lo,
790 double &cert_hi)
791 {
792 cert_lo = 0.0;
793 cert_hi = 0.0;
794 if(!std::isfinite(mc.natural_freq_cycles) || mc.natural_freq_cycles <= 0.0 ||
795 !std::isfinite(mc.damping_ratio) || mc.damping_ratio < 0.0 ||
796 mc.damping_ratio > MaxDampingRatio) {
798 }
799 if(mc.type == InputShaperType::ei) {
800 return build_ei_kernel(
801 mc.natural_freq_cycles, mc.damping_ratio, mc.residual_tolerance,
802 kernel, max_delay, cert_lo, cert_hi);
803 }
804
805 // Build exact discrete ZV kernel first: H_ZV(z0) = 0 to machine precision.
806 double zv[MaxHistory] = {};
807 std::size_t zv_max = 0;
808 rt::ErrorCode rc = build_zv_kernel(mc.natural_freq_cycles, mc.damping_ratio, zv, zv_max);
809 if(rc != rt::ErrorCode::ok) return rc;
810
811 if(mc.type == InputShaperType::zv) {
812 for(std::size_t k = 0; k <= zv_max; ++k) kernel[k] = zv[k];
813 max_delay = zv_max;
814 return rt::ErrorCode::ok;
815 }
816
817 // Discrete ZVD = ZV * ZV (exact double root at discrete mode pole z0).
818 double zvd[MaxHistory] = {};
819 std::size_t zvd_max = 0;
820 rc = convolve_self(zv, zv_max, zv, zv_max, zvd, zvd_max);
821 if(rc != rt::ErrorCode::ok) return rc;
822 rc = normalize_kernel(zvd, zvd_max);
823 if(rc != rt::ErrorCode::ok) return rc;
824
825 if(mc.type == InputShaperType::zvd) {
826 for(std::size_t k = 0; k <= zvd_max; ++k) kernel[k] = zvd[k];
827 max_delay = zvd_max;
828 return rt::ErrorCode::ok;
829 }
830
831 // Discrete ZVDD = ZVD * ZV (exact triple root at discrete mode pole z0).
832 rc = convolve_self(zvd, zvd_max, zv, zv_max, kernel, max_delay);
833 if(rc != rt::ErrorCode::ok) return rc;
834 return normalize_kernel(kernel, max_delay);
835 }
836
837 InputShaperConfig config_{};
838 ShaperTap taps_[MaxTaps]{};
839 std::size_t tap_count_ = 1;
840 std::size_t settling_cycles_ = 0;
841 double mean_delay_cycles_ = 0.0;
842 otg::State1D history_[MaxHistory]{};
843 std::size_t write_index_ = 0;
844 bool primed_ = false;
845};
846
847} // namespace plcopen::core::stream
static constexpr Result success(const T &value)
定义 error.h:24
static constexpr Result failure(ErrorCode error)
定义 error.h:29
rt::Result< double > evaluate_residual_vibration(double freq_cycles, double damping_ratio) const
static constexpr std::size_t MaxDelayCycles
const InputShaperConfig & config() const
rt::ErrorCode prime(otg::State1D state)
ShaperTap tap(std::size_t index) const
rt::ErrorCode configure(const InputShaperConfig &config)
rt::ErrorCode step(otg::State1D input, otg::State1D &output)
rt::ErrorCode prime(double position)
static constexpr std::size_t MaxTaps
static constexpr std::size_t MaxHistory
bool is_finite(State1D state)
rt::Result< double > freq_cycles_from_hz(double freq_hz, double sample_rate_hz)