1use alloc::collections::BTreeMap;
4use alloc::vec::Vec;
5use core::fmt;
6use portable_atomic::{AtomicU64, Ordering};
7
8use nalgebra::{DMatrix, DVector};
9
10mod decide;
11mod hull;
12
13use crate::interval_matrix::uncertainty_generators;
14use crate::reduce::{self, Reduction};
15use crate::round::{self, RowErrors};
16use crate::{Interval, IntervalBox, IntervalMatrix, Zonotope, from_column_list, hcat};
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
20pub struct FactorId(u64);
21
22static NEXT_FACTOR: AtomicU64 = AtomicU64::new(0);
27
28impl FactorId {
29 #[must_use]
31 pub fn fresh() -> Self {
32 Self(NEXT_FACTOR.fetch_add(1, Ordering::Relaxed))
33 }
34
35 #[must_use]
37 pub fn fresh_n(n: usize) -> Vec<Self> {
38 (0..n).map(|_| Self::fresh()).collect()
39 }
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum ShapeError {
45 GeneratorRows,
47 IndependentRows,
49 ExponentColumns,
51 ExponentRows,
53 DuplicateId,
55}
56
57impl fmt::Display for ShapeError {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 f.write_str(match self {
60 Self::GeneratorRows => "dependent generator rows must equal the dimension",
61 Self::IndependentRows => "independent generator rows must equal the dimension",
62 Self::ExponentColumns => "exponent matrix needs one column per dependent generator",
63 Self::ExponentRows => "exponent matrix needs one row per factor id",
64 Self::DuplicateId => "factor ids must be distinct",
65 })
66 }
67}
68
69impl core::error::Error for ShapeError {}
70
71#[derive(Clone, Debug, PartialEq)]
73pub struct SparsePolyZonotope {
78 c: DVector<f64>,
80 g: DMatrix<f64>,
82 gi: DMatrix<f64>,
84 e: DMatrix<u32>,
86 id: Vec<FactorId>,
88}
89
90enum MonomialRange {
92 Constant,
94 UnitRange,
96 Symmetric,
98}
99
100impl MonomialRange {
101 fn scaled_bounds(&self, g: f64) -> Interval {
103 match self {
104 Self::Constant => Interval::point(g),
105 Self::UnitRange => Interval::new(g.min(0.0), g.max(0.0)),
106 Self::Symmetric => Interval::new(-g.abs(), g.abs()),
107 }
108 }
109}
110
111impl SparsePolyZonotope {
112 pub fn new(
122 c: DVector<f64>,
123 g: DMatrix<f64>,
124 gi: DMatrix<f64>,
125 e: DMatrix<u32>,
126 id: Vec<FactorId>,
127 ) -> Result<Self, ShapeError> {
128 let n = c.len();
129 if g.nrows() != n {
130 return Err(ShapeError::GeneratorRows);
131 }
132
133 if gi.nrows() != n {
134 return Err(ShapeError::IndependentRows);
135 }
136
137 if e.ncols() != g.ncols() {
138 return Err(ShapeError::ExponentColumns);
139 }
140
141 if e.nrows() != id.len() {
142 return Err(ShapeError::ExponentRows);
143 }
144
145 let mut sorted = id.clone();
146 sorted.sort_unstable();
147 if sorted.windows(2).any(|w| w[0] == w[1]) {
148 return Err(ShapeError::DuplicateId);
149 }
150
151 Ok(Self { c, g, gi, e, id })
152 }
153
154 #[must_use]
156 pub fn from_zonotope(z: &Zonotope) -> Self {
157 let m = z.num_generators();
158 Self {
159 c: z.center().clone(),
160 g: z.generators().clone(),
161 gi: DMatrix::zeros(z.dim(), 0),
162 e: DMatrix::identity(m, m),
163 id: FactorId::fresh_n(m),
164 }
165 }
166
167 #[must_use]
169 pub fn dim(&self) -> usize {
170 self.c.len()
171 }
172
173 #[must_use]
175 pub fn center(&self) -> &DVector<f64> {
176 &self.c
177 }
178
179 #[must_use]
181 pub fn dependent_generators(&self) -> &DMatrix<f64> {
182 &self.g
183 }
184
185 #[must_use]
187 pub fn independent_generators(&self) -> &DMatrix<f64> {
188 &self.gi
189 }
190
191 #[must_use]
193 pub fn exponents(&self) -> &DMatrix<u32> {
194 &self.e
195 }
196
197 #[must_use]
199 pub fn ids(&self) -> &[FactorId] {
200 &self.id
201 }
202
203 #[must_use]
210 pub fn evaluate_with(&self, alpha: impl Fn(FactorId) -> f64, beta: &[f64]) -> DVector<f64> {
211 assert_eq!(
212 beta.len(),
213 self.gi.ncols(),
214 "one β per independent generator"
215 );
216
217 let a: Vec<f64> = self.id.iter().map(|&k| alpha(k)).collect();
218
219 self.evaluate_positional(&a, beta)
220 }
221
222 fn evaluate_positional(&self, a: &[f64], beta: &[f64]) -> DVector<f64> {
227 let mut p = &self.c + &self.gi * DVector::from_column_slice(beta);
228 for i in 0..self.g.ncols() {
229 p += self.g.column(i) * self.monomial_value(i, a);
230 }
231
232 p
233 }
234
235 fn monomial_value(&self, i: usize, a: &[f64]) -> f64 {
237 a.iter()
238 .zip(self.e.column(i).iter())
239 .map(|(&x, &d)| powu(x, d))
240 .product()
241 }
242
243 #[must_use]
250 pub fn evaluate(&self, alpha: &[f64], beta: &[f64]) -> DVector<f64> {
251 assert_eq!(alpha.len(), self.id.len(), "one α per factor");
252 assert_eq!(
253 beta.len(),
254 self.gi.ncols(),
255 "one β per independent generator"
256 );
257
258 self.evaluate_positional(alpha, beta)
259 }
260
261 #[must_use]
267 pub fn linear_map(&self, m: &DMatrix<f64>) -> Self {
268 let mut errs = RowErrors::new(m.nrows());
269 let c = round::mat_vec(m, &self.c, &mut errs);
270 let g = round::mat_mul(m, &self.g, &mut errs);
271 let gi = round::mat_mul(m, &self.gi, &mut errs);
272
273 Self {
274 c,
275 g,
276 gi: hcat(&gi, &errs.generators()),
277 e: self.e.clone(),
278 id: self.id.clone(),
279 }
280 }
281
282 #[must_use]
291 pub fn interval_map(&self, m: &IntervalMatrix) -> Self {
292 let (center, radius) = m.center_radius();
293 let spread = uncertainty_generators(&radius, &self.interval_hull());
294 let mapped = self.linear_map(¢er);
295
296 Self {
297 gi: hcat(&mapped.gi, &spread),
298 ..mapped
299 }
300 }
301
302 #[must_use]
308 pub fn translate(&self, v: &DVector<f64>) -> Self {
309 let mut errs = RowErrors::new(self.dim());
310 let c = round::vec_add(&self.c, v, &mut errs);
311
312 Self {
313 c,
314 g: self.g.clone(),
315 gi: hcat(&self.gi, &errs.generators()),
316 e: self.e.clone(),
317 id: self.id.clone(),
318 }
319 }
320
321 #[must_use]
323 pub fn with_fresh_ids(&self) -> Self {
324 Self {
325 id: FactorId::fresh_n(self.id.len()),
326 ..self.clone()
327 }
328 }
329
330 #[must_use]
336 pub fn minkowski_sum(&self, other: &Self) -> Self {
337 self.exact_plus(&other.with_fresh_ids())
338 }
339
340 #[must_use]
346 pub fn exact_plus(&self, other: &Self) -> Self {
347 let (id, e1, e2) = merge_ids(self, other);
348 let mut errs = RowErrors::new(self.dim());
349 let c = round::vec_add(&self.c, &other.c, &mut errs);
350 Self {
351 c,
352 g: hcat(&self.g, &other.g),
353 gi: hcat(&hcat(&self.gi, &other.gi), &errs.generators()),
354 e: hcat(&e1, &e2),
355 id,
356 }
357 .compact()
358 }
359
360 #[must_use]
364 pub fn cartesian_product(&self, other: &Self) -> Self {
365 let (id, e1, e2) = merge_ids(self, other);
366 let (n1, n2) = (self.dim(), other.dim());
367 let block = |a: &DMatrix<f64>, b: &DMatrix<f64>| {
368 DMatrix::from_fn(n1 + n2, a.ncols() + b.ncols(), |i, j| {
369 match (i < n1, j < a.ncols()) {
370 (true, true) => a[(i, j)],
371 (false, false) => b[(i - n1, j - a.ncols())],
372 _ => 0.0,
373 }
374 })
375 };
376 Self {
377 c: DVector::from_iterator(n1 + n2, self.c.iter().chain(other.c.iter()).copied()),
378 g: block(&self.g, &other.g),
379 gi: block(&self.gi, &other.gi),
380 e: hcat(&e1, &e2),
381 id,
382 }
383 .compact()
384 }
385
386 #[must_use]
398 pub fn compact(&self) -> Self {
399 let n = self.dim();
400 let mut c = self.c.clone();
401 let mut errs = RowErrors::new(n);
402 let mut columns: Vec<(Vec<u32>, DVector<f64>)> = Vec::new();
403 let mut index: BTreeMap<Vec<u32>, usize> = BTreeMap::new();
404 for i in 0..self.g.ncols() {
405 let exp: Vec<u32> = self.e.column(i).iter().copied().collect();
406 let gv = self.g.column(i).into_owned();
407 if exp.iter().all(|&x| x == 0) {
408 round::add_into(&mut c, &gv, &mut errs);
409 } else if let Some(&j) = index.get(&exp) {
410 round::add_into(&mut columns[j].1, &gv, &mut errs);
411 } else {
412 index.insert(exp.clone(), columns.len());
413 columns.push((exp, gv));
414 }
415 }
416
417 columns.retain(|(_, g)| g.iter().any(|&x| x != 0.0));
418 let used: Vec<usize> = (0..self.id.len())
419 .filter(|&k| columns.iter().any(|(e, _)| e[k] != 0))
420 .collect();
421 Self {
422 c,
423 g: DMatrix::from_fn(n, columns.len(), |i, j| columns[j].1[i]),
424 gi: hcat(&self.gi, &errs.generators()),
425 e: DMatrix::from_fn(used.len(), columns.len(), |k, j| columns[j].0[used[k]]),
426 id: used.iter().map(|&k| self.id[k]).collect(),
427 }
428 }
429
430 fn monomial_range(&self, col: usize) -> MonomialRange {
432 let exps = self.e.column(col);
433 if exps.iter().all(|&x| x == 0) {
434 MonomialRange::Constant
435 } else if exps.iter().all(|&x| x % 2 == 0) {
436 MonomialRange::UnitRange
437 } else {
438 MonomialRange::Symmetric
439 }
440 }
441
442 #[must_use]
446 pub fn interval_hull(&self) -> IntervalBox {
447 let mut iv: Vec<Interval> = self.c.iter().map(|&x| Interval::point(x)).collect();
448 for j in 0..self.g.ncols() {
449 let range = self.monomial_range(j);
450 for (i, &g) in self.g.column(j).iter().enumerate() {
451 iv[i] = iv[i] + range.scaled_bounds(g);
452 }
453 }
454
455 for (i, row) in self.gi.row_iter().enumerate() {
456 let r = round::abs_sum_up(row.iter());
457 iv[i] = iv[i] + Interval::new(-r, r);
458 }
459
460 IntervalBox(iv)
461 }
462
463 #[must_use]
469 pub fn to_zonotope(&self) -> Zonotope {
470 let mut enclosed = self.enclose_monomials(|_| true);
471 enclosed
472 .generators
473 .extend(self.gi.column_iter().map(nalgebra::Matrix::into_owned));
474 enclosed.generators.retain(|g| g.iter().any(|&x| x != 0.0));
475 let gens = from_column_list(self.dim(), &enclosed.generators);
476
477 Zonotope::new(enclosed.center, hcat(&gens, &enclosed.errs.generators()))
478 }
479
480 fn enclose_monomials(&self, pick: impl Fn(usize) -> bool) -> Enclosed {
484 let mut out = Enclosed {
485 center: self.c.clone(),
486 kept: Vec::new(),
487 generators: Vec::new(),
488 errs: RowErrors::new(self.dim()),
489 };
490 for j in 0..self.g.ncols() {
491 if !pick(j) {
492 out.kept.push(j);
493 continue;
494 }
495
496 let g = self.g.column(j).into_owned();
497 match self.monomial_range(j) {
498 MonomialRange::Constant => round::add_into(&mut out.center, &g, &mut out.errs),
499 MonomialRange::UnitRange => {
500 let half = round::halves(&g, &mut out.errs);
501 round::add_into(&mut out.center, &half, &mut out.errs);
502 out.generators.push(half);
503 }
504 MonomialRange::Symmetric => out.generators.push(g),
505 }
506 }
507
508 out
509 }
510
511 fn enclose_factors(&self, factors: &[FactorId]) -> Self {
515 let rows: Vec<usize> = (0..self.id.len())
516 .filter(|&k| factors.contains(&self.id[k]))
517 .collect();
518 let enclosed = self.enclose_monomials(|j| rows.iter().any(|&k| self.e[(k, j)] != 0));
519 let keep_ids: Vec<usize> = (0..self.id.len()).filter(|k| !rows.contains(k)).collect();
520 let n = self.dim();
521 let gi = hcat(&self.gi, &from_column_list(n, &enclosed.generators));
522
523 Self {
524 c: enclosed.center,
525 g: DMatrix::from_fn(n, enclosed.kept.len(), |i, j| self.g[(i, enclosed.kept[j])]),
526 gi: hcat(&gi, &enclosed.errs.generators()),
527 e: DMatrix::from_fn(keep_ids.len(), enclosed.kept.len(), |k, j| {
528 self.e[(keep_ids[k], enclosed.kept[j])]
529 }),
530 id: keep_ids.iter().map(|&k| self.id[k]).collect(),
531 }
532 }
533
534 #[must_use]
547 pub fn quadratic_map(&self, maps: &[DMatrix<f64>]) -> Self {
548 let dim = self.dim();
549 assert!(
550 maps.iter().all(|m| m.shape() == (dim, dim)),
551 "every matrix of a quadratic map must be dim × dim"
552 );
553
554 let (temp, columns, exponents) = self.promoted();
555 let mut errs = RowErrors::new(maps.len());
556 let center = DVector::from_fn(maps.len(), |i, _| {
557 round::bilinear(&self.c, &maps[i], &self.c, i, &mut errs)
558 });
559 let mut gens = Vec::new();
560 let mut exps = Vec::new();
561 for t in 0..columns.len() {
562 gens.push(symmetric_products(maps, &self.c, &columns[t], &mut errs));
564 exps.push(exponents[t].clone());
565 for u in t..columns.len() {
566 gens.push(if t == u {
567 DVector::from_fn(maps.len(), |i, _| {
568 round::bilinear(&columns[t], &maps[i], &columns[t], i, &mut errs)
569 })
570 } else {
571 symmetric_products(maps, &columns[t], &columns[u], &mut errs)
572 });
573 exps.push(add_exponents(&exponents[t], &exponents[u]));
574 }
575 }
576
577 let mut id = self.id.clone();
578 id.extend_from_slice(&temp);
579 Self {
580 c: center,
581 g: from_column_list(maps.len(), &gens),
582 gi: errs.generators(),
583 e: from_column_list(id.len(), &exps),
584 id,
585 }
586 .compact()
587 .enclose_factors(&temp)
588 }
589
590 #[must_use]
606 pub fn cubic_map(&self, maps: &[Vec<DMatrix<f64>>]) -> Self {
607 let dim = self.dim();
608 assert!(
609 maps.iter()
610 .all(|t| t.len() == dim && t.iter().all(|m| m.shape() == (dim, dim))),
611 "every cubic form must have dim slices of size dim × dim"
612 );
613
614 let (temp, mut columns, mut exponents) = self.promoted();
615 columns.insert(0, self.c.clone());
618 exponents.insert(0, alloc::vec![0; self.id.len() + temp.len()]);
619
620 let mut errs = RowErrors::new(maps.len());
621 let mut center = DVector::zeros(maps.len());
622 let mut gens = Vec::new();
623 let mut exps = Vec::new();
624 for t in 0..columns.len() {
625 for u in t..columns.len() {
626 for v in u..columns.len() {
627 let triple = [&columns[t], &columns[u], &columns[v]];
628 let coefficient = symmetric_triple_products(maps, triple, &mut errs);
629 if v == 0 {
630 center = coefficient;
631 } else {
632 gens.push(coefficient);
633 let pair = add_exponents(&exponents[t], &exponents[u]);
634 exps.push(add_exponents(&pair, &exponents[v]));
635 }
636 }
637 }
638 }
639
640 let mut id = self.id.clone();
641 id.extend_from_slice(&temp);
642 Self {
643 c: center,
644 g: from_column_list(maps.len(), &gens),
645 gi: errs.generators(),
646 e: from_column_list(id.len(), &exps),
647 id,
648 }
649 .compact()
650 .enclose_factors(&temp)
651 }
652
653 fn promoted(&self) -> (Vec<FactorId>, Vec<DVector<f64>>, Vec<Vec<u32>>) {
659 let temp = FactorId::fresh_n(self.gi.ncols());
660 let all = hcat(&self.g, &self.gi);
661 let (ids, dep) = (self.id.len(), self.g.ncols());
662 let promoted = DMatrix::from_fn(ids + temp.len(), all.ncols(), |k, t| {
663 match (k < ids, t < dep) {
664 (true, true) => self.e[(k, t)],
665 (false, false) => u32::from(k - ids == t - dep),
666 _ => 0,
667 }
668 });
669 let columns = all
670 .column_iter()
671 .map(nalgebra::Matrix::into_owned)
672 .collect();
673 let exponents = promoted
674 .column_iter()
675 .map(|c| c.iter().copied().collect())
676 .collect();
677
678 (temp, columns, exponents)
679 }
680
681 #[must_use]
699 pub fn reduce(&self, order: f64, method: Reduction) -> Self {
700 self.compact().reduce_compacted(order, method)
703 }
704
705 fn reduce_compacted(&self, order: f64, method: Reduction) -> Self {
707 let (h, n) = (self.g.ncols(), self.dim());
708 let column = |j: usize| {
709 if j < h {
710 self.g.column(j)
711 } else {
712 self.gi.column(j - h)
713 }
714 };
715 let count = h + self.gi.ncols();
716 let Some((kept, dropped)) =
717 reduce::select(count, n, order, |j| reduce::girard_metric(column(j).iter()))
718 else {
719 return self.clone();
720 };
721
722 let mut enclosed = self.enclose_monomials(|j| dropped.binary_search(&j).is_ok());
723 let dropped_independent = dropped.iter().filter(|&&j| j >= h);
724 enclosed
725 .generators
726 .extend(dropped_independent.map(|&j| column(j).into_owned()));
727 let enclosure = reduce::enclose(
728 &from_column_list(n, &enclosed.generators),
729 method,
730 &mut enclosed.errs,
731 );
732 let kept_independent: Vec<usize> =
733 kept.iter().filter(|&&j| j >= h).map(|&j| j - h).collect();
734 let gi = hcat(&self.gi.select_columns(&kept_independent), &enclosure);
735
736 Self {
737 c: enclosed.center,
738 g: self.g.select_columns(&enclosed.kept),
739 gi: hcat(&gi, &enclosed.errs.generators()),
740 e: self.e.select_columns(&enclosed.kept),
741 id: self.id.clone(),
742 }
743 .compact()
744 }
745
746 #[must_use]
756 pub fn split(&self, factor: FactorId) -> (Self, Self) {
757 let k = self
758 .id
759 .iter()
760 .position(|&x| x == factor)
761 .expect("factor not in this set");
762
763 (self.half_domain(k, -1.0), self.half_domain(k, 1.0))
764 }
765
766 fn half_domain(&self, k: usize, sign: f64) -> Self {
769 let mut gens: Vec<DVector<f64>> = Vec::new();
770 let mut exps: Vec<Vec<u32>> = Vec::new();
771 let mut errs = RowErrors::new(self.dim());
772 for i in 0..self.g.ncols() {
773 let column = self.g.column(i).into_owned();
774 for (exp, coef) in self.expand_rescaled(i, k, sign) {
775 exps.push(exp);
776 gens.push(round::scaled(&column, coef, &mut errs));
777 }
778 }
779
780 let mut id = self.id.clone();
781 id[k] = FactorId::fresh();
782 let (n, p) = (self.dim(), id.len());
783
784 Self {
785 c: self.c.clone(),
786 g: from_column_list(n, &gens),
787 gi: hcat(&self.gi, &errs.generators()),
788 e: from_column_list(p, &exps),
789 id,
790 }
791 .compact()
792 }
793
794 fn expand_rescaled(&self, i: usize, k: usize, sign: f64) -> Vec<(Vec<u32>, f64)> {
799 let d = self.e[(k, i)];
800 assert!(
801 d <= MAX_SPLIT_EXPONENT,
802 "split needs exponents of at most {MAX_SPLIT_EXPONENT}, found {d}"
803 );
804
805 (0..=d)
807 .map(|j| {
808 let coef = binomial(d, j) * pow_by_squaring(0.5, d) * pow_by_squaring(sign, d - j);
809 let mut exp: Vec<u32> = self.e.column(i).iter().copied().collect();
810 exp[k] = j;
811 (exp, coef)
812 })
813 .collect()
814 }
815}
816
817struct Enclosed {
819 center: DVector<f64>,
821 kept: Vec<usize>,
823 generators: Vec<DVector<f64>>,
825 errs: RowErrors,
827}
828
829fn symmetric_products(
831 q: &[DMatrix<f64>],
832 a: &DVector<f64>,
833 b: &DVector<f64>,
834 errs: &mut RowErrors,
835) -> DVector<f64> {
836 DVector::from_fn(q.len(), |i, _| {
837 let a_b = round::bilinear(a, &q[i], b, i, errs);
838 let b_a = round::bilinear(b, &q[i], a, i, errs);
839 round::add(a_b, b_a, i, errs)
840 })
841}
842
843fn symmetric_triple_products(
848 maps: &[Vec<DMatrix<f64>>],
849 [a, b, c]: [&DVector<f64>; 3],
850 errs: &mut RowErrors,
851) -> DVector<f64> {
852 let mut orderings = alloc::vec![[a, b, c]];
853 for ordering in [[a, c, b], [b, a, c], [b, c, a], [c, a, b], [c, b, a]] {
854 if !orderings.iter().any(|o| same_columns(o, &ordering)) {
855 orderings.push(ordering);
856 }
857 }
858
859 DVector::from_fn(maps.len(), |i, _| {
860 orderings.iter().fold(0.0, |acc, [p, q, r]| {
861 let term = round::trilinear(p, &maps[i], q, r, i, errs);
862 round::add(acc, term, i, errs)
863 })
864 })
865}
866
867fn same_columns(x: &[&DVector<f64>; 3], y: &[&DVector<f64>; 3]) -> bool {
869 x.iter().zip(y).all(|(p, q)| core::ptr::eq(*p, *q))
870}
871
872fn add_exponents(a: &[u32], b: &[u32]) -> Vec<u32> {
878 a.iter()
879 .zip(b)
880 .map(|(x, y)| x.checked_add(*y).expect("exponent overflows u32"))
881 .collect()
882}
883
884fn powu(x: f64, n: u32) -> f64 {
888 #[cfg(feature = "std")]
889 if let Ok(n) = i32::try_from(n) {
890 return x.powi(n);
891 }
892
893 pow_by_squaring(x, n)
894}
895
896fn pow_by_squaring(mut x: f64, mut n: u32) -> f64 {
898 let mut acc = 1.0;
899 while n > 0 {
900 if n & 1 == 1 {
901 acc *= x;
902 }
903
904 x *= x;
905 n >>= 1;
906 }
907
908 acc
909}
910
911impl SparsePolyZonotope {
912 #[must_use]
917 pub fn can_split(&self, factor: FactorId) -> bool {
918 self.id
919 .iter()
920 .position(|&x| x == factor)
921 .is_some_and(|k| self.can_split_row(k))
922 }
923
924 pub(crate) fn can_split_row(&self, k: usize) -> bool {
926 self.e.row(k).iter().all(|&d| d <= MAX_SPLIT_EXPONENT)
927 }
928}
929
930const MAX_SPLIT_EXPONENT: u32 = 56;
934
935#[expect(
940 clippy::cast_precision_loss,
941 reason = "C(n, k) < 2^53 for n <= MAX_SPLIT_EXPONENT, so the conversion is exact"
942)]
943fn binomial(n: u32, k: u32) -> f64 {
944 (0..k).fold(1u64, |acc, i| acc * u64::from(n - i) / u64::from(i + 1)) as f64
945}
946
947fn merge_ids(
949 a: &SparsePolyZonotope,
950 b: &SparsePolyZonotope,
951) -> (Vec<FactorId>, DMatrix<u32>, DMatrix<u32>) {
952 let mut id = a.id.clone();
953 let mut pos: BTreeMap<FactorId, usize> = id.iter().enumerate().map(|(i, &k)| (k, i)).collect();
954 for &k in &b.id {
955 pos.entry(k).or_insert_with(|| {
956 id.push(k);
957 id.len() - 1
958 });
959 }
960
961 let p = id.len();
962 let e1 = DMatrix::from_fn(p, a.e.ncols(), |r, c| {
963 if r < a.e.nrows() { a.e[(r, c)] } else { 0 }
964 });
965 let mut e2 = DMatrix::zeros(p, b.e.ncols());
966 for (r, k) in b.id.iter().enumerate() {
967 for c in 0..b.e.ncols() {
968 e2[(pos[k], c)] = b.e[(r, c)];
969 }
970 }
971
972 (id, e1, e2)
973}
974
975#[cfg(test)]
978mod tests {
979 use super::{pow_by_squaring, powu};
980
981 fn naive_pow(x: f64, n: u32) -> f64 {
983 (0..n).fold(1.0, |acc, _| acc * x)
984 }
985
986 #[test]
988 fn pow_by_squaring_matches_repeated_multiplication() {
989 for x in [0.0, 1.0, -1.0, 0.5, -1.5, 0.3] {
990 for n in 0..=40 {
991 let (got, want) = (pow_by_squaring(x, n), naive_pow(x, n));
992 assert!(
993 (got - want).abs() <= 1e-12 * want.abs(),
994 "{x}^{n}: {got} vs {want}"
995 );
996 }
997 }
998 }
999
1000 #[test]
1002 fn powu_handles_exponents_beyond_i32_max() {
1003 assert!((powu(1.0, u32::MAX) - 1.0).abs() < f64::EPSILON);
1004 assert!((powu(-1.0, u32::MAX) + 1.0).abs() < f64::EPSILON);
1005 assert!(powu(0.5, u32::MAX).abs() < f64::EPSILON);
1006 }
1007}