plcopen 0.22.0
载入中...
搜索中...
未找到
filter.h
浏览该文件的文档.
1#pragma once
2
3// B9 trajectory-stream online filter, first slice (approved matrix:
4// doc/compliance/trajectory-stream-semantics.md, decisions #1-#8).
5//
6// One joint: an external producer pushes sparse timestamped targets
7// (50-500 Hz); cycle() upsamples them to the interpolation cycle by
8// re-planning a time-optimal jerk-limited profile from the current output
9// state whenever the target changes (event-driven, decision #4). Velocity,
10// acceleration, and jerk limits are satisfied constructively — the envelope
11// is part of the solve, not a post-clamp. Target dropouts degrade through a
12// decaying extrapolation into a jerk-limited controlled stop (decision #7);
13// a fresh target re-enters tracking with a continuous takeover (decision #8).
14//
15// RT-SAFE cycle path: no heap allocation, no locks, no exceptions, no
16// wall-clock access; timestamps are integer cycle counts in the caller's
17// cycle domain. push_target() and cycle() are single-producer /
18// single-consumer from the same cycle context in this slice; cross-thread
19// hand-off arrives with the axis-session slice (BS1.6).
20
21#include <algorithm>
22#include <cmath>
23#include <cstdint>
24
25#include "otg/profile1d.h"
26#include "otg/time_optimal.h"
27#include "rt/cycle.h"
28#include "rt/error.h"
30
32{
33
35{
36 double position = 0.0;
37 // Optional producer-side velocity; when absent the filter estimates it by
38 // differencing consecutive accepted (post-clamp) targets (decision #1).
39 double velocity = 0.0;
40 bool has_velocity = false;
41 // Integer cycle count in the filter's cycle domain, strictly increasing
42 // across accepted targets (decision #3).
43 std::int64_t timestamp_cycles = 0;
44};
45
46struct StreamFilterConfig // NOLINT(clang-analyzer-optin.performance.Padding)
47{
49 // Optional position envelope: out-of-range targets clamp to the boundary
50 // and set the clamped() flag (decision #6).
52 double min_position = 0.0;
53 double max_position = 0.0;
54 // Watchdog: target age beyond timeout_cycles starts the dropout ladder —
55 // extrapolation_cycles of linearly decaying velocity, then a controlled
56 // stop (decision #7).
57 std::int64_t timeout_cycles = 1;
58 std::int64_t extrapolation_cycles = 0;
59 // T24 quintic fast path (algorithm contract §4, KB-064): when enabled,
60 // replan() tries a closed-form quintic Hermite before falling back to
61 // the full OTG solve. Implemented and default-off per the approved matrix.
62 bool quintic_fast_path = false;
63};
64
66{
67public:
68 enum class Mode
69 {
70 idle, // engaged, no target accepted yet: holds the reset state
71 tracking, // following the latest accepted target
72 extrapolating, // dropout: synthetic target with decaying velocity
73 stopping, // dropout: converging onto the rest target
74 stopped, // dropout: at rest, waiting for a fresh target
75 };
76
85
87 {
88 if(!can_configure(config)) {
90 }
91 config_ = config;
92 return rt::ErrorCode::ok;
93 }
94
95 // Planning-domain preflight used by fixed-capacity groups to make a
96 // shared configuration transaction all-or-nothing.
97 bool can_configure(const StreamFilterConfig &config) const
98 {
99 // Configuration belongs only to the idle setup window. A running
100 // target/profile must never observe a partial policy change.
101 if(session_started_ || mode_ != Mode::idle || have_target_ || have_profile_ ||
102 pending_dirty_) {
103 return false;
104 }
105 if(!otg::is_finite(config.limits) || config.limits.max_velocity <= 0.0 ||
106 config.limits.max_acceleration <= 0.0 || config.limits.max_deceleration <= 0.0 ||
107 config.limits.max_jerk <= 0.0 || config.timeout_cycles < 1 ||
108 config.extrapolation_cycles < 0) {
109 return false;
110 }
111 return !config.position_envelope_enabled ||
112 (std::isfinite(config.min_position) && std::isfinite(config.max_position) &&
113 config.min_position <= config.max_position);
114 }
115
116 // Engages the filter at a known output state (planning-domain call;
117 // configure() must have succeeded first). Engaging from a moving state
118 // arms the controlled-stop ladder immediately — until the first target
119 // arrives the situation is dropout-equivalent, and holding a nonzero
120 // velocity without moving would be kinematically inconsistent.
122 {
123 if(!otg::is_finite(state) || config_.limits.max_velocity <= 0.0) {
125 }
126 session_started_ = true;
127 state_ = state;
128 mode_ = Mode::idle;
129 now_ = 0;
130 have_target_ = false;
131 have_profile_ = false;
132 quintic_active_ = false;
133 profile_tick_ = 0;
134 pending_dirty_ = false;
135 clamped_ = false;
136 stream_interval_ = 1;
137 rejected_targets_ = 0;
138 dropout_count_ = 0;
139 filter_faults_ = 0;
140 if(state.velocity != 0.0 || state.acceleration != 0.0) {
141 enter_stopping();
142 }
143 return rt::ErrorCode::ok;
144 }
145
146 // Ends ownership of the current session and re-opens the planning-domain
147 // configuration window. The owner must call this only after it has stopped
148 // routing cycle output from this filter.
150 {
151 session_started_ = false;
152 mode_ = Mode::idle;
153 have_target_ = false;
154 have_profile_ = false;
155 pending_dirty_ = false;
156 quintic_active_ = false;
157 profile_tick_ = 0;
158 }
159
160 // Starts the existing dropout ladder from an externally supplied command
161 // state. Frame-direct mode uses this planning-domain transition when its
162 // group watchdog expires; normal legacy tracking never calls it.
164 {
165 if(!session_started_ || !otg::is_finite(state) ||
166 config_.limits.max_velocity <= 0.0) {
168 }
169
170 state_ = state;
171 have_target_ = false;
172 have_profile_ = false;
173 quintic_active_ = false;
174 profile_tick_ = 0;
175 pending_dirty_ = false;
176 ++dropout_count_;
177 if(config_.extrapolation_cycles > 0 && state.velocity != 0.0) {
178 mode_ = Mode::extrapolating;
179 extrapolation_tick_ = 0;
180 extrapolation_start_velocity_ = state.velocity;
181 synthetic_position_ = state.position;
182 } else if(state.velocity != 0.0 || state.acceleration != 0.0) {
183 enter_stopping();
184 } else {
185 mode_ = Mode::stopped;
186 }
187 return rt::ErrorCode::ok;
188 }
189
190 // Producer side. Rejections (non-finite input, non-monotonic timestamp)
191 // never disturb the running filter; they are counted and reported to the
192 // producer through the return code.
194 {
195 if(!std::isfinite(target.position) ||
196 (target.has_velocity && !std::isfinite(target.velocity))) {
198 }
199 if(have_target_ && target.timestamp_cycles <= latest_timestamp_) {
200 ++rejected_targets_;
202 }
203 const std::uint64_t timestamp_delta =
204 have_target_ ? positive_cycle_delta(target.timestamp_cycles, latest_timestamp_) : 0;
205
206 double position = target.position;
207 bool clamped = false;
208 if(config_.position_envelope_enabled) {
209 if(position < config_.min_position) {
210 position = config_.min_position;
211 clamped = true;
212 } else if(position > config_.max_position) {
213 position = config_.max_position;
214 clamped = true;
215 }
216 }
217
218 double velocity = 0.0;
219 if(target.has_velocity) {
220 velocity = clamp_velocity(target.velocity);
221 } else if(have_target_) {
222 const double span = static_cast<double>(timestamp_delta);
223 velocity = clamp_velocity((position - latest_position_) / span);
224 }
225 if(have_target_) {
226 // Observed stream interval: the tracking horizon (see replan()).
227 stream_interval_ = timestamp_delta > 256
228 ? 256
229 : static_cast<std::int64_t>(timestamp_delta);
230 }
231
232 const bool repeated_rest_target =
233 have_target_ && mode_ == Mode::tracking &&
234 position == latest_position_ && velocity == 0.0 &&
235 latest_velocity_ == 0.0;
236
237 latest_position_ = position;
238 latest_velocity_ = velocity;
239 latest_timestamp_ = target.timestamp_cycles;
240 have_target_ = true;
241 clamped_ = clamped;
242
243 // The pending target is evaluated on the target line at solve time
244 // (see the tracking branch in cycle()); a repeated stationary frame
245 // refreshes the watchdog without restarting the same trajectory.
246 if(!repeated_rest_target) {
247 pending_position_ = position;
248 pending_velocity_ = velocity;
249 pending_dirty_ = true;
250 }
251 mode_ = Mode::tracking;
252 return rt::ErrorCode::ok;
253 }
254
255 // RT cycle path: advances one interpolation cycle and returns the
256 // setpoint state. The output stream never breaks (decision #5).
258 {
260 return cycle_with_replan_budget(true, result);
261 }
262
263 // Group frame mode may defer a full OTG solve after first attempting the
264 // fixed-cost quintic path. A deferred member keeps sampling its previous
265 // proven profile and retains the pending target for a later cycle.
267 ReplanResult &replan_result)
268 {
269 replan_result = ReplanResult::none;
270 if(now_ < INT64_MAX) {
271 ++now_;
272 }
273
274 if(mode_ == Mode::tracking && now_ > latest_timestamp_ &&
275 positive_cycle_delta(now_, latest_timestamp_) >
276 static_cast<std::uint64_t>(config_.timeout_cycles)) {
277 ++dropout_count_;
278 if(config_.extrapolation_cycles > 0 && state_.velocity != 0.0) {
279 mode_ = Mode::extrapolating;
280 extrapolation_tick_ = 0;
281 extrapolation_start_velocity_ = state_.velocity;
282 synthetic_position_ = state_.position;
283 } else {
284 enter_stopping();
285 }
286 }
287
288 if(mode_ == Mode::extrapolating) {
289 ++extrapolation_tick_;
290 const double fraction =
291 1.0 - static_cast<double>(extrapolation_tick_) /
292 static_cast<double>(config_.extrapolation_cycles);
293 if(fraction <= 0.0) {
294 enter_stopping();
295 } else {
296 const double velocity = extrapolation_start_velocity_ * fraction;
297 synthetic_position_ += velocity;
298 pending_position_ = synthetic_position_;
299 pending_velocity_ = velocity;
300 pending_dirty_ = true;
301 }
302 } else if(mode_ == Mode::tracking && pending_velocity_ != 0.0 && have_target_) {
303 // A moving target is a line: the pending position is the line
304 // point of the current cycle (a profile's first sample lands in
305 // this cycle). The solve itself stays event-driven: the running
306 // profile chases the line and the coast after arrival rides it
307 // exactly, so re-planning happens on fresh targets (push) or
308 // when the coast drifts off the line (checked after advance()).
309 // Re-planning every cycle would also reset the entry
310 // acceleration each cycle through the solver's zeroing-ramp
311 // reduction (A9 v1) and stall the pursuit.
312 pending_position_ = latest_position_;
313 if(now_ > latest_timestamp_) {
314 const double displacement =
315 pending_velocity_ * static_cast<double>(
316 positive_cycle_delta(now_, latest_timestamp_));
317 const double projected_position = latest_position_ + displacement;
318 if(std::isfinite(displacement) && std::isfinite(projected_position)) {
319 pending_position_ = projected_position;
320 } else {
321 // The line cannot be represented in double precision.
322 // Fall back to its last finite point and solve to rest.
323 pending_velocity_ = 0.0;
324 pending_dirty_ = true;
325 }
326 }
327 if(config_.position_envelope_enabled) {
328 if(pending_position_ < config_.min_position) {
329 pending_position_ = config_.min_position;
330 } else if(pending_position_ > config_.max_position) {
331 pending_position_ = config_.max_position;
332 }
333 }
334 }
335
336 if(mode_ == Mode::tracking && !pending_dirty_ && have_profile_ &&
337 config_.position_envelope_enabled && state_.velocity != 0.0) {
338 const std::int64_t profile_duration =
339 quintic_active_ ? quintic_profile_.h : profile_.duration_cycles();
340 if(profile_tick_ >= profile_duration) {
341 const double stopping_reach =
342 otg::detail::ramp_between(state_.velocity, 0.0, config_.limits).distance;
343 const double next_position = state_.position + state_.velocity;
344 if((state_.velocity > 0.0 &&
345 next_position + stopping_reach >= config_.max_position) ||
346 (state_.velocity < 0.0 &&
347 next_position + stopping_reach <= config_.min_position)) {
348 pending_position_ = state_.velocity > 0.0 ? config_.max_position
349 : config_.min_position;
350 pending_velocity_ = 0.0;
351 pending_dirty_ = true;
352 }
353 }
354 }
355
356 if(pending_dirty_) {
357 replan_result = replan(allow_slow_replan);
358 }
359 advance();
360
361 // Coast-drift guard: once the profile is exhausted, the coast should
362 // ride the target line exactly; measurable drift re-arms one solve.
363 const std::int64_t profile_duration =
364 quintic_active_ ? quintic_profile_.h : profile_.duration_cycles();
365 if(mode_ == Mode::tracking && !pending_dirty_ && have_profile_ &&
366 profile_tick_ > profile_duration &&
367 std::fabs(state_.position - pending_position_) >
368 1e-9 * (1.0 + std::fabs(pending_position_))) {
369 pending_dirty_ = true;
370 }
371
372 if(mode_ == Mode::stopping && have_profile_ &&
373 profile_tick_ >= profile_.duration_cycles() && state_.velocity == 0.0) {
374 mode_ = Mode::stopped;
375 }
376 return state_;
377 }
378
379 bool replan_pending() const
380 {
381 return pending_dirty_;
382 }
383
385 {
386 return state_;
387 }
388
389 Mode mode() const
390 {
391 return mode_;
392 }
393
394 // Current cycle count of the filter's time domain (increments once per
395 // cycle() since reset). Producers stamp targets relative to this.
396 std::int64_t now_cycles() const
397 {
398 return now_;
399 }
400
401 // True while the latest accepted target required a position clamp.
402 bool clamped() const
403 {
404 return clamped_;
405 }
406
407 std::uint32_t rejected_targets() const
408 {
409 return rejected_targets_;
410 }
411
412 std::uint32_t dropout_count() const
413 {
414 return dropout_count_;
415 }
416
417 std::uint32_t filter_faults() const
418 {
419 return filter_faults_;
420 }
421
422private:
423 static std::uint64_t positive_cycle_delta(std::int64_t later, std::int64_t earlier)
424 {
425 // Callers establish later > earlier in signed ordering. Unsigned
426 // subtraction then yields the exact mathematical distance even across
427 // INT64_MIN -> INT64_MAX without signed-overflow UB.
428 return static_cast<std::uint64_t>(later) - static_cast<std::uint64_t>(earlier);
429 }
430
431 static bool representable_cycle_count(double cycles, std::int64_t &result)
432 {
433 // 2^63 is exactly representable as double; INT64_MAX is not. Keep the
434 // upper bound exclusive before the conversion.
435 constexpr double Int64UpperExclusive = 9223372036854775808.0;
436 if(!std::isfinite(cycles) || cycles < 1.0 || cycles >= Int64UpperExclusive) {
437 return false;
438 }
439 result = static_cast<std::int64_t>(cycles);
440 return true;
441 }
442
443 double clamp_to_envelope(double position) const
444 {
445 if(!config_.position_envelope_enabled) {
446 return position;
447 }
448 if(position < config_.min_position) {
449 return config_.min_position;
450 }
451 if(position > config_.max_position) {
452 return config_.max_position;
453 }
454 return position;
455 }
456
457 double clamp_velocity(double velocity) const
458 {
459 if(velocity > config_.limits.max_velocity) {
460 return config_.limits.max_velocity;
461 }
462 if(velocity < -config_.limits.max_velocity) {
463 return -config_.limits.max_velocity;
464 }
465 return velocity;
466 }
467
468 bool position_in_envelope(double position) const
469 {
470 return !config_.position_envelope_enabled ||
471 (position >= config_.min_position && position <= config_.max_position);
472 }
473
474 static bool normalize_segment(const otg::Segment1D &segment, double coefficients[6])
475 {
476 const double duration = static_cast<double>(segment.duration_cycles);
477 if(duration <= 0.0 || !std::isfinite(duration)) {
478 return false;
479 }
480
481 coefficients[0] = segment.c0;
482 coefficients[1] = segment.c1;
483 coefficients[2] = segment.c2;
484 coefficients[3] = segment.c3;
485 coefficients[4] = segment.c4;
486 coefficients[5] = segment.c5;
487 for(int degree = 1; degree <= 5; ++degree) {
488 for(int power = 0; power < degree; ++power) {
489 coefficients[degree] *= duration;
490 }
491 }
492 for(int degree = 0; degree <= 5; ++degree) {
493 if(!std::isfinite(coefficients[degree])) {
494 return false;
495 }
496 }
497 return true;
498 }
499
500 static double normalized_position(const double coefficients[6], double sigma)
501 {
502 return coefficients[0] +
503 sigma * (coefficients[1] +
504 sigma * (coefficients[2] +
505 sigma * (coefficients[3] +
506 sigma * (coefficients[4] +
507 sigma * coefficients[5]))));
508 }
509
510 static double normalized_velocity(const double coefficients[6], double sigma)
511 {
512 return coefficients[1] +
513 sigma * (2.0 * coefficients[2] +
514 sigma * (3.0 * coefficients[3] +
515 sigma * (4.0 * coefficients[4] +
516 sigma * 5.0 * coefficients[5])));
517 }
518
519 static bool solve_quadratic_for_proof(double a, double b, double c,
520 double roots[3], int &count)
521 {
522 if(!std::isfinite(a) || !std::isfinite(b) || !std::isfinite(c)) {
523 return false;
524 }
525 if(a == 0.0) {
526 if(b == 0.0) {
527 count = 0;
528 return true;
529 }
530 roots[0] = -c / b;
531 count = 1;
532 return std::isfinite(roots[0]);
533 }
534
535 const double scale = std::max(std::fabs(a), std::max(std::fabs(b), std::fabs(c)));
536 a /= scale;
537 b /= scale;
538 c /= scale;
539 // The shared solver uses an absolute 1e-30 degree threshold. After
540 // relative scaling, a smaller leading term cannot be reduced safely;
541 // reject the proof instead of silently dropping a real extremum.
542 if(std::fabs(a) < 1e-30) {
543 return false;
544 }
545 count = quintic_detail::solve_quadratic(a, b, c, roots);
546 for(int i = 0; i < count; ++i) {
547 if(!std::isfinite(roots[i])) {
548 return false;
549 }
550 }
551 return true;
552 }
553
554 static bool solve_cubic_for_proof(double a3, double a2, double a1, double a0,
555 double roots[3], int &count)
556 {
557 if(!std::isfinite(a3) || !std::isfinite(a2) || !std::isfinite(a1) ||
558 !std::isfinite(a0)) {
559 return false;
560 }
561 if(a3 == 0.0) {
562 return solve_quadratic_for_proof(a2, a1, a0, roots, count);
563 }
564
565 const double scale =
566 std::max(std::fabs(a3),
567 std::max(std::fabs(a2), std::max(std::fabs(a1), std::fabs(a0))));
568 a3 /= scale;
569 a2 /= scale;
570 a1 /= scale;
571 a0 /= scale;
572 if(std::fabs(a3) < 1e-30) {
573 return false;
574 }
575 count = quintic_detail::solve_cubic(a3, a2, a1, a0, roots);
576 for(int i = 0; i < count; ++i) {
577 if(!std::isfinite(roots[i])) {
578 return false;
579 }
580 }
581 return true;
582 }
583
584 bool segment_in_envelope(const otg::Segment1D &segment) const
585 {
586 double coefficients[6];
587 if(!normalize_segment(segment, coefficients)) {
588 return false;
589 }
590 if(!position_in_envelope(segment.start.position) ||
591 !position_in_envelope(segment.finish.position) ||
592 !position_in_envelope(normalized_position(coefficients, 0.0)) ||
593 !position_in_envelope(normalized_position(coefficients, 1.0))) {
594 return false;
595 }
596
597 double roots[3];
598 if(coefficients[4] == 0.0 && coefficients[5] == 0.0) {
599 // Constant-jerk segment: every position extremum is a quadratic
600 // root of v(sigma), so endpoints plus those roots are the full proof.
601 int count = 0;
602 if(!solve_quadratic_for_proof(3.0 * coefficients[3],
603 2.0 * coefficients[2], coefficients[1],
604 roots, count)) {
605 return false;
606 }
607 for(int i = 0; i < count; ++i) {
608 if(roots[i] > 0.0 && roots[i] < 1.0 &&
609 !position_in_envelope(normalized_position(coefficients, roots[i]))) {
610 return false;
611 }
612 }
613 return true;
614 }
615
616 // A quintic's position extrema require quartic roots. Instead prove
617 // monotonicity by checking velocity at all of its extrema (the cubic
618 // roots of acceleration); non-monotone candidates fall back.
619 double minimum_velocity = segment.start.velocity;
620 if(!std::isfinite(minimum_velocity) ||
621 !std::isfinite(segment.finish.velocity)) {
622 return false;
623 }
624 double maximum_velocity = minimum_velocity;
625 if(segment.finish.velocity < minimum_velocity) {
626 minimum_velocity = segment.finish.velocity;
627 }
628 if(segment.finish.velocity > maximum_velocity) {
629 maximum_velocity = segment.finish.velocity;
630 }
631 int count = 0;
632 if(!solve_cubic_for_proof(20.0 * coefficients[5], 12.0 * coefficients[4],
633 6.0 * coefficients[3], 2.0 * coefficients[2],
634 roots, count)) {
635 return false;
636 }
637 for(int i = 0; i < count; ++i) {
638 const double sigma = roots[i];
639 if(sigma < 0.0 || sigma > 1.0) {
640 continue;
641 }
642 const double velocity =
643 sigma == 0.0 ? segment.start.velocity
644 : (sigma == 1.0
645 ? segment.finish.velocity
646 : normalized_velocity(coefficients, sigma));
647 if(!std::isfinite(velocity)) {
648 return false;
649 }
650 if(velocity < minimum_velocity) {
651 minimum_velocity = velocity;
652 }
653 if(velocity > maximum_velocity) {
654 maximum_velocity = velocity;
655 }
656 }
657 // Deliberately no numerical tolerance: a tiny accepted reversal can
658 // integrate into a real position overshoot on a long profile. Dust
659 // therefore causes only a conservative solver fallback.
660 return minimum_velocity >= 0.0 || maximum_velocity <= 0.0;
661 }
662
663 bool profile_in_envelope(const otg::Profile1D &profile) const
664 {
665 if(!config_.position_envelope_enabled) {
666 return true;
667 }
668 for(std::size_t i = 0; i < profile.segment_count(); ++i) {
669 if(!segment_in_envelope(profile.segment(i))) {
670 return false;
671 }
672 }
673 return true;
674 }
675
676 bool quintic_in_envelope(const QuinticProfile &profile) const
677 {
678 if(!config_.position_envelope_enabled) {
679 return true;
680 }
681 // QuinticProfile uses normalized time sigma in [0, 1]. Map it to the
682 // same polynomial proof used for a Profile1D quintic segment.
683 otg::Segment1D segment{};
684 segment.duration_cycles = 1;
685 segment.c0 = profile.d[0];
686 segment.c1 = profile.d[1];
687 segment.c2 = profile.d[2];
688 segment.c3 = profile.d[3];
689 segment.c4 = profile.d[4];
690 segment.c5 = profile.d[5];
691 segment.start.position = profile.d[0];
692 segment.finish.position = profile.d[0] + profile.d[1] + profile.d[2] +
693 profile.d[3] + profile.d[4] + profile.d[5];
694 return segment_in_envelope(segment);
695 }
696
697 void enter_stopping()
698 {
699 mode_ = Mode::stopping;
700 pending_position_ =
701 state_.position +
702 otg::detail::ramp_between(state_.velocity, 0.0, config_.limits).distance;
703 pending_velocity_ = 0.0;
704 pending_dirty_ = true;
705 }
706
707 rt::Result<otg::Profile1D> plan_controlled_stop(otg::State1D from) const
708 {
709 otg::Profile1D profile{};
710 otg::State1D state = from;
711 if(state.acceleration != 0.0) {
712 const double cycles =
713 std::ceil(std::fabs(state.acceleration) /
714 config_.limits.max_jerk);
715 const double finish_velocity =
716 state.velocity + 0.5 * state.acceleration * cycles;
718 profile, state, -state.acceleration / cycles, cycles, true,
719 finish_velocity, 0.0);
720 if(zeroed != rt::ErrorCode::ok) {
722 }
723 }
724 if(state.velocity != 0.0) {
726 profile, state, 0.0, config_.limits,
730 }
731 }
732 if(profile.segment_count() == 0 || state.velocity != 0.0 ||
733 state.acceleration != 0.0) {
736 }
737 for(std::size_t i = 0; i < profile.segment_count(); ++i) {
738 if(!otg::within_limits(profile.segment(i), config_.limits)) {
741 }
742 }
744 }
745
746 ReplanResult replan(bool allow_slow_replan)
747 {
748 // Numerical-dust guard: sampled profiles keep the state inside the
749 // envelope up to the planner's sampling tolerance; the re-plan entry
750 // state must be strictly admissible.
751 otg::State1D from = state_;
752 from.velocity = clamp_velocity(from.velocity);
753 if(from.acceleration > config_.limits.max_acceleration) {
754 from.acceleration = config_.limits.max_acceleration;
755 } else if(from.acceleration < -config_.limits.max_deceleration) {
756 from.acceleration = -config_.limits.max_deceleration;
757 }
758 if(!otg::is_finite(from) || !std::isfinite(pending_position_) ||
759 !std::isfinite(pending_velocity_)) {
760 pending_dirty_ = false;
761 ++filter_faults_;
762 return ReplanResult::fault;
763 }
764
765 // Tracking law for moving targets: aim at the line point one stream
766 // interval ahead, line(now + H). Aiming at line(now) leaves a
767 // pursuit-lag fixed point of v·(T-1); the H-horizon makes the lock
768 // an exact (H+1)-cycle linear ride with zero steady-state lag and a
769 // geometric approach from behind. The merge floor keeps the aim at
770 // least one deceleration reach ahead, so the solve never swings
771 // backward or brakes toward rest while the line escapes.
772 double through_velocity = pending_velocity_;
773 double aim = pending_position_;
774 std::int64_t rendezvous_cycles = 0;
775 if(through_velocity != 0.0) {
776 // The horizon must be deep enough that a one-quantum (one cycle
777 // of line displacement) recovery bump fits the jerk and
778 // acceleration limits — a quintic bump of extra displacement e
779 // over n cycles peaks at 60·e/n³ jerk and 5.77·e/n² acceleration.
780 // Below that depth the lock has neutral plateaus at whole-cycle
781 // lags (B9 tuning finding).
782 const double quantum = 1.2 * std::fabs(through_velocity);
783 const double jerk_depth = std::cbrt(60.0 * quantum / config_.limits.max_jerk);
784 const double accel_depth =
785 std::sqrt(5.77 * quantum / config_.limits.max_acceleration);
786 double horizon = static_cast<double>(stream_interval_);
787 if(jerk_depth > horizon) {
788 horizon = jerk_depth;
789 }
790 if(accel_depth > horizon) {
791 horizon = accel_depth;
792 }
793 const double horizon_ceil = std::ceil(horizon);
794 double horizon_displacement = through_velocity * horizon_ceil;
795 double horizon_aim = pending_position_ + horizon_displacement;
796 bool representable =
797 representable_cycle_count(horizon_ceil, rendezvous_cycles) &&
798 std::isfinite(horizon_displacement) && std::isfinite(horizon_aim);
799 if(representable) {
800 aim = horizon_aim;
801 const double reach =
802 otg::detail::ramp_between(from.velocity, through_velocity, config_.limits)
803 .distance;
804 const double needed = from.position + reach;
805 representable = std::isfinite(reach) && std::isfinite(needed);
806 if(representable &&
807 ((through_velocity > 0.0 && needed > aim) ||
808 (through_velocity < 0.0 && needed < aim))) {
809 const double merge_span = needed - pending_position_;
810 const double merge_cycles = std::ceil(merge_span / through_velocity);
811 std::int64_t merge_count = 0;
812 const double merge_displacement = through_velocity * merge_cycles;
813 const double merge_aim = pending_position_ + merge_displacement;
814 representable = std::isfinite(merge_span) &&
815 representable_cycle_count(merge_cycles, merge_count) &&
816 std::isfinite(merge_displacement) &&
817 std::isfinite(merge_aim);
818 if(representable) {
819 aim = merge_aim;
820 rendezvous_cycles = merge_count;
821 }
822 }
823 }
824 if(!representable) {
825 // The moving rendezvous cannot be represented safely. Make
826 // the accepted target stationary as well as this candidate so
827 // later coast-drift cycles do not retry the same invalid math.
828 pending_velocity_ = 0.0;
829 through_velocity = 0.0;
830 aim = pending_position_;
831 rendezvous_cycles = 0;
832 } else if((through_velocity > 0.0 && aim < from.position) ||
833 (through_velocity < 0.0 && aim > from.position)) {
834 through_velocity = 0.0;
835 aim = pending_position_;
836 rendezvous_cycles = 0;
837 }
838 }
839
840 double constrained_aim = clamp_to_envelope(aim);
841 if(config_.position_envelope_enabled && through_velocity != 0.0) {
842 const double stopping_reach =
843 otg::detail::ramp_between(through_velocity, 0.0, config_.limits).distance;
844 const double stopping_position = constrained_aim + stopping_reach;
845 if(!std::isfinite(stopping_reach) || !std::isfinite(stopping_position)) {
846 constrained_aim =
847 through_velocity > 0.0 ? config_.max_position : config_.min_position;
848 through_velocity = 0.0;
849 rendezvous_cycles = 0;
850 } else if(through_velocity > 0.0 &&
851 stopping_position >= config_.max_position) {
852 constrained_aim = config_.max_position;
853 through_velocity = 0.0;
854 rendezvous_cycles = 0;
855 } else if(through_velocity < 0.0 &&
856 stopping_position <= config_.min_position) {
857 constrained_aim = config_.min_position;
858 through_velocity = 0.0;
859 rendezvous_cycles = 0;
860 }
861 }
862 otg::Target1D to{constrained_aim, through_velocity, 0.0};
863
864 // T24 quintic fast path (KB-064): attempt closed-form quintic first
865 // when the config enables it and there's a valid rendezvous horizon.
866 if(config_.quintic_fast_path && rendezvous_cycles > 0) {
867 QuinticProfile qp;
868 if(solve_quintic(from, to.position, to.velocity, rendezvous_cycles, qp) &&
869 check_quintic_limits(qp, config_.limits) && quintic_in_envelope(qp)) {
870 quintic_profile_ = qp;
871 quintic_active_ = true;
872 profile_tick_ = 0;
873 have_profile_ = true;
874 pending_dirty_ = false;
875 return ReplanResult::fast;
876 }
877 }
878
879 if(!allow_slow_replan) {
881 }
882 pending_dirty_ = false;
883
884 rt::Result<otg::Profile1D> planned =
885 rendezvous_cycles > 0
886 ? otg::solve_fixed_time(from, to, config_.limits,
887 rendezvous_cycles)
888 : rt::Result<otg::Profile1D>::failure(
889 rt::ErrorCode::infeasible);
890 if(planned && !profile_in_envelope(planned.value())) {
891 planned = rt::Result<otg::Profile1D>::failure(rt::ErrorCode::infeasible);
892 }
893 if(!planned) {
894 planned = otg::plan_time_optimal(from, to, config_.limits);
895 if(planned && !profile_in_envelope(planned.value())) {
896 planned = rt::Result<otg::Profile1D>::failure(rt::ErrorCode::infeasible);
897 }
898 }
899
900 if(!planned) {
901 // Decision #5: clamp the target harder to a rest target. Unsafe
902 // time-optimal candidates fall through to the baseline quintic;
903 // if neither has an envelope proof, keep the previous profile.
904 to.velocity = 0.0;
905 planned = otg::plan_time_optimal(from, to, config_.limits);
906 if(planned && !profile_in_envelope(planned.value())) {
908 }
909 }
910 if(!planned) {
911 planned = otg::plan(from, to, config_.limits);
912 if(planned && !profile_in_envelope(planned.value())) {
914 }
915 }
916 if(!planned && mode_ == Mode::stopping) {
917 planned = plan_controlled_stop(from);
918 if(planned && !profile_in_envelope(planned.value())) {
919 planned =
922 }
923 }
924 if(!planned) {
925 ++filter_faults_;
926 return ReplanResult::slow;
927 }
928 profile_ = planned.value();
929 quintic_active_ = false;
930 profile_tick_ = 0;
931 have_profile_ = true;
932 return ReplanResult::slow;
933 }
934
935 void advance()
936 {
937 if(!have_profile_) {
938 return;
939 }
940 ++profile_tick_;
941
942 if(quintic_active_) {
943 if(profile_tick_ <= quintic_profile_.h) {
944 commit_sample(sample_quintic(quintic_profile_, profile_tick_));
945 return;
946 }
947 const otg::State1D finish =
948 sample_quintic(quintic_profile_, quintic_profile_.h);
949 if(finish.velocity != 0.0) {
950 commit_sample(
951 {state_.position + finish.velocity, finish.velocity, 0.0});
952 } else {
953 commit_sample(finish);
954 }
955 return;
956 }
957
958 if(profile_tick_ <= profile_.duration_cycles()) {
959 commit_sample(
960 otg::sample(profile_, rt::CycleTick::from_cycles(profile_tick_)));
961 return;
962 }
963 // Past the profile end: a nonzero end velocity coasts (the target
964 // stream implies steady motion between updates); a rest end holds.
965 const otg::State1D finish =
966 profile_.segment(profile_.segment_count() - 1).finish;
967 if(finish.velocity != 0.0) {
968 commit_sample({state_.position + finish.velocity, finish.velocity, 0.0});
969 } else {
970 commit_sample(finish);
971 }
972 }
973
974 void commit_sample(otg::State1D candidate)
975 {
976 if(otg::is_finite(candidate)) {
977 state_ = candidate;
978 return;
979 }
980
981 // A planner may be representable while an architecture-specific
982 // floating-point sample overflows. Preserve the last finite output;
983 // the stream contract never publishes a non-finite state.
984 ++filter_faults_;
985 have_profile_ = false;
986 quintic_active_ = false;
987 }
988
989 std::int64_t now_ = 0;
990 double latest_position_ = 0.0;
991 double latest_velocity_ = 0.0;
992 std::int64_t latest_timestamp_ = 0;
993 double pending_position_ = 0.0;
994 double pending_velocity_ = 0.0;
995 std::int64_t profile_tick_ = 0;
996 std::int64_t extrapolation_tick_ = 0;
997 double extrapolation_start_velocity_ = 0.0;
998 double synthetic_position_ = 0.0;
999 std::int64_t stream_interval_ = 1;
1000 otg::State1D state_{};
1001 QuinticProfile quintic_profile_{};
1002 StreamFilterConfig config_{};
1003 otg::Profile1D profile_{};
1004 Mode mode_ = Mode::idle;
1005 std::uint32_t rejected_targets_ = 0;
1006 std::uint32_t dropout_count_ = 0;
1007 std::uint32_t filter_faults_ = 0;
1008 bool have_target_ = false;
1009 bool session_started_ = false;
1010 bool pending_dirty_ = false;
1011 bool quintic_active_ = false;
1012 bool have_profile_ = false;
1013 bool clamped_ = false;
1014};
1015
1016} // namespace plcopen::core::stream
static constexpr CycleTick from_cycles(std::int64_t cycles)
定义 cycle.h:42
static constexpr Result success(const T &value)
定义 error.h:24
static constexpr Result failure(ErrorCode error)
定义 error.h:29
rt::ErrorCode begin_dropout_from(otg::State1D state)
rt::ErrorCode reset(otg::State1D state)
rt::ErrorCode push_target(StreamTarget target)
bool can_configure(const StreamFilterConfig &config) const
std::uint32_t rejected_targets() const
rt::ErrorCode configure(const StreamFilterConfig &config)
otg::State1D cycle_with_replan_budget(bool allow_slow_replan, ReplanResult &replan_result)
rt::ErrorCode push_cubic_phase(Profile1D &profile, State1D &state, double jerk, double continuous_duration, bool force_finish_derivatives=false, double finish_velocity=0.0, double finish_acceleration=0.0)
RampTiming ramp_between(double va, double vb, const Limits1D &limits)
rt::ErrorCode push_ramp(Profile1D &profile, State1D &state, double vb, const Limits1D &limits, RampRounding rounding, bool force_finish_derivatives=false)
rt::Result< Profile1D > plan(State1D from, Target1D to, Limits1D limits)
rt::Result< Profile1D > plan_time_optimal(State1D from, Target1D to, Limits1D limits)
rt::Result< Profile1D > solve_fixed_time(State1D from, Target1D to, Limits1D limits, std::int64_t total_cycles)
bool is_finite(State1D state)
bool within_limits(const Segment1D &segment, Limits1D limits)
State1D sample(const Profile1D &profile, rt::CycleTick tick)
int solve_quadratic(double a, double b, double c, double roots[3])
int solve_cubic(double a3, double a2, double a1, double a0, double roots[3])
bool solve_quintic(otg::State1D from, double target_position, double target_velocity, std::int64_t h, QuinticProfile &out)
otg::State1D sample_quintic(const QuinticProfile &q, std::int64_t tick)
bool check_quintic_limits(const QuinticProfile &qp, const otg::Limits1D &limits)