1use super::DccError;
27
28#[derive(Debug, Clone, PartialEq)]
33pub struct DccAdaptiveParameters {
34 pub alpha: f64,
37 pub beta: f64,
40 pub cbr_target: f64,
43 pub delta_max: f64,
47 pub delta_min: f64,
51 pub delta_up_max: f64,
54 pub delta_down_max: f64,
57}
58
59impl Default for DccAdaptiveParameters {
60 fn default() -> Self {
61 Self {
62 alpha: 0.016,
63 beta: 0.0012,
64 cbr_target: 0.68,
65 delta_max: 0.03,
66 delta_min: 0.0006,
67 delta_up_max: 0.0005,
68 delta_down_max: -0.00025,
69 }
70 }
71}
72
73#[derive(Debug, Clone, PartialEq)]
89pub struct DccAdaptive {
90 pub parameters: DccAdaptiveParameters,
92 pub cbr_its_s: f64,
94 pub delta: f64,
96}
97
98impl Default for DccAdaptive {
99 fn default() -> Self {
100 Self::new(DccAdaptiveParameters::default())
101 }
102}
103
104impl DccAdaptive {
105 pub fn new(parameters: DccAdaptiveParameters) -> Self {
107 let delta = parameters.delta_min;
108 Self {
109 parameters,
110 cbr_its_s: 0.0,
111 delta,
112 }
113 }
114
115 pub fn update(
131 &mut self,
132 cbr_local: f64,
133 cbr_local_previous: f64,
134 cbr_global: Option<f64>,
135 cbr_global_previous: Option<f64>,
136 ) -> Result<f64, DccError> {
137 if !(0.0..=1.0).contains(&cbr_local) {
138 return Err(DccError::InvalidCbr {
139 name: "cbr_local",
140 value: cbr_local,
141 });
142 }
143 if !(0.0..=1.0).contains(&cbr_local_previous) {
144 return Err(DccError::InvalidCbr {
145 name: "cbr_local_previous",
146 value: cbr_local_previous,
147 });
148 }
149 if let Some(cg) = cbr_global {
150 if !(0.0..=1.0).contains(&cg) {
151 return Err(DccError::InvalidCbr {
152 name: "cbr_global",
153 value: cg,
154 });
155 }
156 }
157 if let Some(cgp) = cbr_global_previous {
158 if !(0.0..=1.0).contains(&cgp) {
159 return Err(DccError::InvalidCbr {
160 name: "cbr_global_previous",
161 value: cgp,
162 });
163 }
164 }
165
166 let p = &self.parameters;
167
168 let cbr_avg = match (cbr_global, cbr_global_previous) {
171 (Some(cg), Some(cgp)) => (cg + cgp) / 2.0,
172 _ => (cbr_local + cbr_local_previous) / 2.0,
173 };
174 self.cbr_its_s = 0.5 * self.cbr_its_s + 0.5 * cbr_avg;
175
176 let diff = p.cbr_target - self.cbr_its_s;
178 let delta_offset = if diff > 0.0 {
179 (p.beta * diff).min(p.delta_up_max)
181 } else {
182 (p.beta * diff).max(p.delta_down_max)
184 };
185
186 self.delta = (1.0 - p.alpha) * self.delta + delta_offset;
188
189 if self.delta > p.delta_max {
191 self.delta = p.delta_max;
192 }
193 if self.delta < p.delta_min {
194 self.delta = p.delta_min;
195 }
196
197 Ok(self.delta)
198 }
199
200 pub fn update_local(
202 &mut self,
203 cbr_local: f64,
204 cbr_local_previous: f64,
205 ) -> Result<f64, DccError> {
206 self.update(cbr_local, cbr_local_previous, None, None)
207 }
208}
209
210#[derive(Debug, Clone, PartialEq)]
227pub struct GateKeeper {
228 delta: f64,
229 t_pg: Option<f64>,
230 t_go: Option<f64>,
231}
232
233impl GateKeeper {
234 pub const GATE_OPEN_MIN_INTERVAL_S: f64 = 0.025;
236 pub const GATE_OPEN_MAX_INTERVAL_S: f64 = 1.0;
238 pub const T_EPSILON: f64 = 1e-9;
240
241 pub fn new(delta: f64) -> Self {
243 Self {
244 delta,
245 t_pg: None,
246 t_go: None,
247 }
248 }
249
250 pub fn delta(&self) -> f64 {
252 self.delta
253 }
254
255 pub fn t_pg(&self) -> Option<f64> {
257 self.t_pg
258 }
259
260 pub fn t_go(&self) -> Option<f64> {
262 self.t_go
263 }
264
265 pub fn is_open(&self, t: f64) -> bool {
270 match self.t_go {
271 None => true,
272 Some(t_go) => t >= t_go - Self::T_EPSILON,
273 }
274 }
275
276 pub fn admit_packet(&mut self, t: f64, t_on: f64) -> Result<bool, DccError> {
293 if t_on <= 0.0 {
294 return Err(DccError::InvalidTon(t_on));
295 }
296 if !self.is_open(t) {
297 return Ok(false);
298 }
299
300 self.t_pg = Some(t);
301 let interval = (t_on / self.delta).clamp(
302 Self::GATE_OPEN_MIN_INTERVAL_S,
303 Self::GATE_OPEN_MAX_INTERVAL_S,
304 );
305 self.t_go = Some(t + interval);
306 Ok(true)
307 }
308
309 pub fn update_delta(&mut self, t: f64, delta_new: f64) -> Result<(), DccError> {
326 if delta_new <= 0.0 {
327 return Err(DccError::InvalidDelta(delta_new));
328 }
329
330 let delta_old = self.delta;
331 self.delta = delta_new;
332
333 if self.t_pg.is_none() || self.t_go.is_none() || self.is_open(t) {
335 return Ok(());
336 }
337
338 let t_pg = self.t_pg.unwrap();
340 let t_go = self.t_go.unwrap();
341 let old_interval = t_go - t_pg;
342 let new_interval = (delta_old / delta_new) * old_interval;
343 let interval = new_interval.clamp(
344 Self::GATE_OPEN_MIN_INTERVAL_S,
345 Self::GATE_OPEN_MAX_INTERVAL_S,
346 );
347 self.t_go = Some(t_pg + interval);
348
349 Ok(())
350 }
351}
352
353#[cfg(test)]
358#[allow(clippy::float_cmp)]
359mod tests {
360 use super::*;
361
362 macro_rules! assert_almost_eq {
363 ($a:expr, $b:expr) => {
364 assert!(
365 ($a - $b).abs() < 1e-9,
366 "assertion failed: ({} - {}) < 1e-9 (left: {}, right: {})",
367 stringify!($a),
368 stringify!($b),
369 $a,
370 $b
371 );
372 };
373 ($a:expr, $b:expr, $eps:expr) => {
374 assert!(
375 ($a - $b).abs() < $eps,
376 "assertion failed: ({} - {}) < {} (left: {}, right: {})",
377 stringify!($a),
378 stringify!($b),
379 stringify!($eps),
380 $a,
381 $b
382 );
383 };
384 }
385
386 #[test]
389 fn test_default_parameters() {
390 let alg = DccAdaptive::default();
391 let p = &alg.parameters;
392 assert_almost_eq!(p.alpha, 0.016);
393 assert_almost_eq!(p.beta, 0.0012);
394 assert_almost_eq!(p.cbr_target, 0.68);
395 assert_almost_eq!(p.delta_max, 0.03);
396 assert_almost_eq!(p.delta_min, 0.0006);
397 assert_almost_eq!(p.delta_up_max, 0.0005);
398 assert_almost_eq!(p.delta_down_max, -0.00025);
399 }
400
401 #[test]
402 fn test_initial_cbr_its_s_is_zero() {
403 let alg = DccAdaptive::default();
404 assert_almost_eq!(alg.cbr_its_s, 0.0);
405 }
406
407 #[test]
408 fn test_initial_delta_is_delta_min() {
409 let alg = DccAdaptive::default();
410 assert_almost_eq!(alg.delta, alg.parameters.delta_min);
411 }
412
413 #[test]
414 fn test_custom_parameters_accepted() {
415 let params = DccAdaptiveParameters {
416 alpha: 0.1,
417 beta: 0.05,
418 cbr_target: 0.5,
419 ..Default::default()
420 };
421 let alg = DccAdaptive::new(params);
422 assert_almost_eq!(alg.parameters.alpha, 0.1);
423 assert_almost_eq!(alg.parameters.cbr_target, 0.5);
424 }
425
426 #[test]
429 fn test_cbr_its_s_uses_local_average() {
430 let mut alg = DccAdaptive::default();
431 alg.update_local(0.4, 0.4).unwrap();
432 assert_almost_eq!(alg.cbr_its_s, 0.2);
434 }
435
436 #[test]
437 fn test_cbr_its_s_accumulates_over_calls() {
438 let mut alg = DccAdaptive::default();
439 alg.update_local(0.4, 0.4).unwrap();
440 alg.update_local(0.4, 0.4).unwrap();
442 assert_almost_eq!(alg.cbr_its_s, 0.3);
444 }
445
446 #[test]
447 fn test_cbr_its_s_uses_global_when_provided() {
448 let mut alg = DccAdaptive::default();
449 alg.update(0.1, 0.1, Some(0.6), Some(0.6)).unwrap();
450 assert_almost_eq!(alg.cbr_its_s, 0.3);
452 }
453
454 #[test]
455 fn test_cbr_its_s_ignores_global_when_only_one_provided() {
456 let mut alg = DccAdaptive::default();
457 alg.update(0.4, 0.4, Some(0.9), None).unwrap();
458 assert_almost_eq!(alg.cbr_its_s, 0.2);
460 }
461
462 #[test]
465 fn test_positive_diff_uses_equation_2() {
466 let mut alg = DccAdaptive {
467 cbr_its_s: 0.0,
468 ..Default::default()
469 };
470 alg.update_local(0.0, 0.0).unwrap();
471 let expected_delta = (1.0 - 0.016) * 0.0006 + 0.0005;
472 assert_almost_eq!(alg.delta, expected_delta, 1e-10);
473 }
474
475 #[test]
476 fn test_negative_diff_uses_equation_3() {
477 let mut alg = DccAdaptive {
478 cbr_its_s: 1.0,
479 ..Default::default()
480 };
481 let initial_delta = alg.delta;
482 alg.update_local(1.0, 1.0).unwrap();
483 let expected_delta = ((1.0 - 0.016) * initial_delta + (-0.00025_f64)).clamp(0.0006, 0.03);
484 assert_almost_eq!(alg.delta, expected_delta, 1e-10);
485 }
486
487 #[test]
488 fn test_small_positive_diff_not_clamped() {
489 let p = DccAdaptiveParameters::default();
490 let mut alg = DccAdaptive {
491 parameters: p.clone(),
492 cbr_its_s: 0.679,
493 delta: 0.01,
494 };
495 alg.update_local(0.679, 0.679).unwrap();
496 let diff = 0.68 - 0.679;
497 let expected_offset = p.beta * diff;
498 let expected_delta = (1.0 - p.alpha) * 0.01 + expected_offset;
499 assert_almost_eq!(alg.delta, expected_delta, 1e-10);
500 }
501
502 #[test]
503 fn test_large_negative_diff_clamped_to_down_max() {
504 let mut alg = DccAdaptive {
505 cbr_its_s: 0.99,
506 delta: 0.02,
507 ..Default::default()
508 };
509 alg.update_local(0.99, 0.99).unwrap();
510 let expected_delta = (1.0 - 0.016) * 0.02 + (-0.00025);
511 assert_almost_eq!(alg.delta, expected_delta, 1e-10);
512 }
513
514 #[test]
517 fn test_step3_exponential_filter() {
518 let mut alg = DccAdaptive {
519 cbr_its_s: 0.68,
520 delta: 0.01,
521 ..Default::default()
522 };
523 alg.update_local(0.68, 0.68).unwrap();
524 let expected = (1.0 - 0.016) * 0.01 + 0.0;
525 assert_almost_eq!(alg.delta, expected, 1e-10);
526 }
527
528 #[test]
529 fn test_step4_clamps_delta_to_max() {
530 let mut alg = DccAdaptive {
531 delta: 0.029,
532 cbr_its_s: 0.0,
533 ..Default::default()
534 };
535 alg.update_local(0.0, 0.0).unwrap();
536 assert!(alg.delta <= alg.parameters.delta_max);
537 }
538
539 #[test]
540 fn test_step5_clamps_delta_to_min() {
541 let mut alg = DccAdaptive {
542 cbr_its_s: 1.0,
543 ..Default::default()
544 };
545 alg.delta = alg.parameters.delta_min;
546 alg.update_local(1.0, 1.0).unwrap();
547 assert!(alg.delta >= alg.parameters.delta_min);
548 }
549
550 #[test]
551 fn test_delta_converges_toward_target() {
552 let mut alg = DccAdaptive::default();
553 let cbr = 0.68;
554 for _ in 0..500 {
555 alg.update_local(cbr, cbr).unwrap();
556 }
557 assert!(alg.delta >= alg.parameters.delta_min);
558 assert!(alg.delta <= alg.parameters.delta_max);
559 }
560
561 #[test]
562 fn test_delta_increases_when_cbr_below_target() {
563 let mut alg = DccAdaptive::default();
564 let prev_delta = alg.delta;
565 for _ in 0..50 {
566 alg.update_local(0.0, 0.0).unwrap();
567 }
568 assert!(alg.delta > prev_delta);
569 }
570
571 #[test]
572 fn test_delta_decreases_when_cbr_above_target() {
573 let mut alg = DccAdaptive {
574 delta: 0.02,
575 ..Default::default()
576 };
577 for _ in 0..200 {
578 alg.update_local(1.0, 1.0).unwrap();
579 }
580 assert_almost_eq!(alg.delta, alg.parameters.delta_min);
581 }
582
583 #[test]
586 fn test_cbr_local_below_zero_raises() {
587 let mut alg = DccAdaptive::default();
588 let res = alg.update_local(-0.01, 0.5);
589 assert!(matches!(
590 res,
591 Err(DccError::InvalidCbr {
592 name: "cbr_local",
593 ..
594 })
595 ));
596 }
597
598 #[test]
599 fn test_cbr_local_above_one_raises() {
600 let mut alg = DccAdaptive::default();
601 let res = alg.update_local(1.01, 0.5);
602 assert!(matches!(
603 res,
604 Err(DccError::InvalidCbr {
605 name: "cbr_local",
606 ..
607 })
608 ));
609 }
610
611 #[test]
612 fn test_cbr_local_previous_below_zero_raises() {
613 let mut alg = DccAdaptive::default();
614 let res = alg.update_local(0.5, -0.01);
615 assert!(matches!(
616 res,
617 Err(DccError::InvalidCbr {
618 name: "cbr_local_previous",
619 ..
620 })
621 ));
622 }
623
624 #[test]
625 fn test_cbr_local_previous_above_one_raises() {
626 let mut alg = DccAdaptive::default();
627 let res = alg.update_local(0.5, 1.01);
628 assert!(matches!(
629 res,
630 Err(DccError::InvalidCbr {
631 name: "cbr_local_previous",
632 ..
633 })
634 ));
635 }
636
637 #[test]
638 fn test_boundary_values_valid() {
639 let mut alg = DccAdaptive::default();
640 assert!(alg.update_local(0.0, 0.0).is_ok());
641 assert!(alg.update_local(1.0, 1.0).is_ok());
642 }
643
644 #[test]
647 fn test_gate_is_open_initially() {
648 let gk = GateKeeper::new(0.01);
649 assert!(gk.is_open(0.0));
650 }
651
652 #[test]
653 fn test_gate_is_open_at_any_time_initially() {
654 let gk = GateKeeper::new(0.01);
655 for &t in &[0.0, 100.0, -1.0] {
656 assert!(gk.is_open(t));
657 }
658 }
659
660 #[test]
663 fn test_first_packet_admitted() {
664 let mut gk = GateKeeper::new(0.01);
665 assert!(gk.admit_packet(0.0, 0.001).unwrap());
666 }
667
668 #[test]
669 fn test_gate_closed_after_admission() {
670 let mut gk = GateKeeper::new(0.01);
671 gk.admit_packet(0.0, 0.001).unwrap();
672 assert!(!gk.is_open(0.0));
673 }
674
675 #[test]
676 fn test_second_packet_rejected_when_gate_closed() {
677 let mut gk = GateKeeper::new(0.01);
678 assert!(gk.admit_packet(0.0, 0.001).unwrap());
679 assert!(!gk.admit_packet(0.0, 0.001).unwrap());
680 }
681
682 #[test]
683 fn test_gate_opens_after_t_go() {
684 let mut gk = GateKeeper::new(0.01);
685 gk.admit_packet(0.0, 0.001).unwrap(); assert!(!gk.is_open(0.099));
687 assert!(gk.is_open(0.1));
688 }
689
690 #[test]
691 fn test_minimum_interval_enforced() {
692 let mut gk = GateKeeper::new(1.0);
693 gk.admit_packet(0.0, 0.001).unwrap();
694 assert!(!gk.is_open(0.024));
695 assert!(gk.is_open(0.025));
696 }
697
698 #[test]
699 fn test_maximum_interval_enforced() {
700 let mut gk = GateKeeper::new(0.0006);
701 gk.admit_packet(0.0, 0.001).unwrap();
702 assert!(!gk.is_open(0.99));
703 assert!(gk.is_open(1.0));
704 }
705
706 #[test]
707 fn test_t_on_zero_raises() {
708 let mut gk = GateKeeper::new(0.01);
709 assert!(matches!(
710 gk.admit_packet(0.0, 0.0),
711 Err(DccError::InvalidTon(_))
712 ));
713 }
714
715 #[test]
716 fn test_t_on_negative_raises() {
717 let mut gk = GateKeeper::new(0.01);
718 assert!(matches!(
719 gk.admit_packet(0.0, -0.001),
720 Err(DccError::InvalidTon(_))
721 ));
722 }
723
724 #[test]
727 fn test_update_delta_when_gate_open_only_changes_delta() {
728 let mut gk = GateKeeper::new(0.01);
729 gk.update_delta(0.0, 0.02).unwrap();
730 assert!(gk.is_open(0.0));
731 }
732
733 #[test]
734 fn test_update_delta_rescales_interval_when_delta_increases() {
735 let mut gk = GateKeeper::new(0.01);
736 gk.admit_packet(0.0, 0.001).unwrap(); gk.update_delta(0.0, 0.02).unwrap(); assert!(!gk.is_open(0.049));
739 assert!(gk.is_open(0.05));
740 }
741
742 #[test]
743 fn test_update_delta_rescales_interval_when_delta_decreases() {
744 let mut gk = GateKeeper::new(0.02);
745 gk.admit_packet(0.0, 0.001).unwrap(); gk.update_delta(0.0, 0.01).unwrap(); assert!(!gk.is_open(0.099));
748 assert!(gk.is_open(0.1));
749 }
750
751 #[test]
752 fn test_update_delta_minimum_interval_enforced() {
753 let mut gk = GateKeeper::new(0.01);
754 gk.admit_packet(0.0, 0.001).unwrap();
755 gk.update_delta(0.0, 0.1).unwrap();
756 assert!(!gk.is_open(0.024));
757 assert!(gk.is_open(0.025));
758 }
759
760 #[test]
761 fn test_update_delta_maximum_interval_enforced() {
762 let mut gk = GateKeeper::new(0.02);
763 gk.admit_packet(0.0, 0.001).unwrap();
764 gk.update_delta(0.0, 0.0001).unwrap();
765 assert!(!gk.is_open(0.99));
766 assert!(gk.is_open(1.0));
767 }
768
769 #[test]
770 fn test_update_delta_zero_raises() {
771 let mut gk = GateKeeper::new(0.01);
772 assert!(matches!(
773 gk.update_delta(0.0, 0.0),
774 Err(DccError::InvalidDelta(_))
775 ));
776 }
777
778 #[test]
779 fn test_update_delta_negative_raises() {
780 let mut gk = GateKeeper::new(0.01);
781 assert!(matches!(
782 gk.update_delta(0.0, -0.01),
783 Err(DccError::InvalidDelta(_))
784 ));
785 }
786
787 #[test]
788 fn test_update_after_gate_reopens_no_rescheduling() {
789 let mut gk = GateKeeper::new(0.01);
790 gk.admit_packet(0.0, 0.001).unwrap(); gk.update_delta(0.5, 0.005).unwrap();
792 assert!(gk.is_open(0.5));
793 }
794
795 #[test]
798 fn test_gate_keeper_uses_updated_delta() {
799 let mut gk = GateKeeper::new(0.01);
800 gk.admit_packet(0.0, 0.001).unwrap(); assert!(gk.is_open(0.1));
803 gk.update_delta(0.1, 0.02).unwrap();
804 gk.admit_packet(0.1, 0.001).unwrap(); assert!(!gk.is_open(0.14));
806 assert!(gk.is_open(0.15));
807 }
808}