polyzonotope 0.4.2

Sparse polynomial zonotopes, zonotopes and interval boxes for set-based reachability analysis, no_std and optionally with outward rounding
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
//! Sparse polynomial zonotopes (Kochdumper & Althoff, IEEE TAC 2021).

use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use core::fmt;
use portable_atomic::{AtomicU64, Ordering};

use nalgebra::{DMatrix, DVector};

mod decide;
mod hull;

use crate::interval_matrix::uncertainty_generators;
use crate::reduce::{self, Reduction};
use crate::round::{self, RowErrors};
use crate::{Interval, IntervalBox, IntervalMatrix, Zonotope, from_column_list, hcat};

/// Global identifier of a dependent factor `α_k`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FactorId(u64);

/// Next unused [`FactorId`] value; shared process-wide so ids never collide.
///
/// `portable_atomic` rather than `core`, so targets without native 64-bit
/// atomics (Cortex-M, 32-bit RISC-V) still get a shared counter.
static NEXT_FACTOR: AtomicU64 = AtomicU64::new(0);

impl FactorId {
    /// A new id, distinct from every id handed out before in this process.
    #[must_use]
    pub fn fresh() -> Self {
        Self(NEXT_FACTOR.fetch_add(1, Ordering::Relaxed))
    }

    /// `n` new ids, distinct from each other and from every earlier id.
    #[must_use]
    pub fn fresh_n(n: usize) -> Vec<Self> {
        (0..n).map(|_| Self::fresh()).collect()
    }
}

/// Why the parts passed to [`SparsePolyZonotope::new`] do not fit together.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ShapeError {
    /// The dependent generator matrix `G` does not have one row per dimension.
    GeneratorRows,
    /// The independent generator matrix `GI` does not have one row per dimension.
    IndependentRows,
    /// The exponent matrix `E` does not have one column per dependent generator.
    ExponentColumns,
    /// The exponent matrix `E` does not have one row per factor id.
    ExponentRows,
    /// The same [`FactorId`] appears more than once.
    DuplicateId,
}

impl fmt::Display for ShapeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::GeneratorRows => "dependent generator rows must equal the dimension",
            Self::IndependentRows => "independent generator rows must equal the dimension",
            Self::ExponentColumns => "exponent matrix needs one column per dependent generator",
            Self::ExponentRows => "exponent matrix needs one row per factor id",
            Self::DuplicateId => "factor ids must be distinct",
        })
    }
}

impl core::error::Error for ShapeError {}

/// Sparse polynomial zonotope `⟨c, G, GI, E, id⟩`.
#[derive(Clone, Debug, PartialEq)]
///
/// Invariants (checked by [`new`](Self::new)): `g` and `gi` have one row per
/// entry of `c`, `e` has one column per column of `g` and one row per id, and
/// the ids are distinct.
pub struct SparsePolyZonotope {
    /// Center `c`; its length is the dimension of the set.
    c: DVector<f64>,
    /// Dependent generators `G`, one per column; column `i` is scaled by monomial `i`.
    g: DMatrix<f64>,
    /// Independent generators `GI`, one per column, each scaled by its own `β_j`.
    gi: DMatrix<f64>,
    /// Exponents `E`: entry `(k, i)` is the power of `α_k` in monomial `i`.
    e: DMatrix<u32>,
    /// Global ids of the dependent factors; row `k` of `e` belongs to `id[k]`.
    id: Vec<FactorId>,
}

/// How a dependent monomial ranges over `α ∈ [-1, 1]^p`.
enum MonomialRange {
    /// All exponents are zero: the monomial is exactly 1.
    Constant,
    /// All exponents are even: the monomial ranges over `[0, 1]`.
    UnitRange,
    /// Some exponent is odd: the monomial ranges over `[-1, 1]`.
    Symmetric,
}

impl MonomialRange {
    /// The range of `g · m` as the monomial `m` ranges over this range.
    fn scaled_bounds(&self, g: f64) -> Interval {
        match self {
            Self::Constant => Interval::point(g),
            Self::UnitRange => Interval::new(g.min(0.0), g.max(0.0)),
            Self::Symmetric => Interval::new(-g.abs(), g.abs()),
        }
    }
}

impl SparsePolyZonotope {
    /// The set `⟨c, g, gi, e, id⟩`, after checking that the shapes fit together.
    ///
    /// # Errors
    ///
    /// - [`ShapeError::GeneratorRows`] if `g` does not have `c.len()` rows.
    /// - [`ShapeError::IndependentRows`] if `gi` does not have `c.len()` rows.
    /// - [`ShapeError::ExponentColumns`] if `e` and `g` differ in column count.
    /// - [`ShapeError::ExponentRows`] if `e` does not have one row per id.
    /// - [`ShapeError::DuplicateId`] if an id appears twice.
    pub fn new(
        c: DVector<f64>,
        g: DMatrix<f64>,
        gi: DMatrix<f64>,
        e: DMatrix<u32>,
        id: Vec<FactorId>,
    ) -> Result<Self, ShapeError> {
        let n = c.len();
        if g.nrows() != n {
            return Err(ShapeError::GeneratorRows);
        }

        if gi.nrows() != n {
            return Err(ShapeError::IndependentRows);
        }

        if e.ncols() != g.ncols() {
            return Err(ShapeError::ExponentColumns);
        }

        if e.nrows() != id.len() {
            return Err(ShapeError::ExponentRows);
        }

        let mut sorted = id.clone();
        sorted.sort_unstable();
        if sorted.windows(2).any(|w| w[0] == w[1]) {
            return Err(ShapeError::DuplicateId);
        }

        Ok(Self { c, g, gi, e, id })
    }

    /// Exact conversion: every generator becomes a dependent factor.
    #[must_use]
    pub fn from_zonotope(z: &Zonotope) -> Self {
        let m = z.num_generators();
        Self {
            c: z.center().clone(),
            g: z.generators().clone(),
            gi: DMatrix::zeros(z.dim(), 0),
            e: DMatrix::identity(m, m),
            id: FactorId::fresh_n(m),
        }
    }

    /// Dimension of the space the set lives in.
    #[must_use]
    pub fn dim(&self) -> usize {
        self.c.len()
    }

    /// Center `c`.
    #[must_use]
    pub fn center(&self) -> &DVector<f64> {
        &self.c
    }

    /// Dependent generators `G`, one per column, matching the columns of [`exponents`](Self::exponents).
    #[must_use]
    pub fn dependent_generators(&self) -> &DMatrix<f64> {
        &self.g
    }

    /// Independent generators `GI`, one per column.
    #[must_use]
    pub fn independent_generators(&self) -> &DMatrix<f64> {
        &self.gi
    }

    /// Exponent matrix `E`: entry `(k, i)` is the power of the factor `ids()[k]` in monomial `i`.
    #[must_use]
    pub fn exponents(&self) -> &DMatrix<u32> {
        &self.e
    }

    /// Ids of the dependent factors, one per row of [`exponents`](Self::exponents).
    #[must_use]
    pub fn ids(&self) -> &[FactorId] {
        &self.id
    }

    /// Point of the set for the given factor values (`alpha` looked up by
    /// id, `beta` positional).
    ///
    /// # Panics
    ///
    /// Panics if `beta` does not have one entry per independent generator.
    #[must_use]
    pub fn evaluate_with(&self, alpha: impl Fn(FactorId) -> f64, beta: &[f64]) -> DVector<f64> {
        assert_eq!(
            beta.len(),
            self.gi.ncols(),
            "one β per independent generator"
        );

        let a: Vec<f64> = self.id.iter().map(|&k| alpha(k)).collect();

        self.evaluate_positional(&a, beta)
    }

    /// Point of the set for positional factor values: `a[k]` belongs to `ids()[k]`.
    ///
    /// Callers check that `a` has one entry per id and `beta` one entry per
    /// independent generator.
    fn evaluate_positional(&self, a: &[f64], beta: &[f64]) -> DVector<f64> {
        let mut p = &self.c + &self.gi * DVector::from_column_slice(beta);
        for i in 0..self.g.ncols() {
            p += self.g.column(i) * self.monomial_value(i, a);
        }

        p
    }

    /// Value of monomial `i`, `Π_k a[k]^E[k, i]`, for positional factor values `a`.
    fn monomial_value(&self, i: usize, a: &[f64]) -> f64 {
        a.iter()
            .zip(self.e.column(i).iter())
            .map(|(&x, &d)| powu(x, d))
            .product()
    }

    /// Positional variant of [`evaluate_with`](Self::evaluate_with): `alpha[k]` belongs to `ids()[k]`.
    ///
    /// # Panics
    ///
    /// Panics if `alpha` does not have one entry per id, or `beta` one entry
    /// per independent generator.
    #[must_use]
    pub fn evaluate(&self, alpha: &[f64], beta: &[f64]) -> DVector<f64> {
        assert_eq!(alpha.len(), self.id.len(), "one α per factor");
        assert_eq!(
            beta.len(),
            self.gi.ncols(),
            "one β per independent generator"
        );

        self.evaluate_positional(alpha, beta)
    }

    /// Exact: `{ M x | x ∈ PZ }`.
    ///
    /// # Panics
    ///
    /// Panics if `m` does not have one column per dimension.
    #[must_use]
    pub fn linear_map(&self, m: &DMatrix<f64>) -> Self {
        let mut errs = RowErrors::new(m.nrows());
        let c = round::mat_vec(m, &self.c, &mut errs);
        let g = round::mat_mul(m, &self.g, &mut errs);
        let gi = round::mat_mul(m, &self.gi, &mut errs);

        Self {
            c,
            g,
            gi: hcat(&gi, &errs.generators()),
            e: self.e.clone(),
            id: self.id.clone(),
        }
    }

    /// Enclosure of `{ M x | M ∈ m, x ∈ PZ }` for an interval matrix `m`:
    /// the exact map by the center matrix, plus independent generators for the
    /// radius, sized by the interval hull of the set. Dependencies on the
    /// factors survive through the center map.
    ///
    /// # Panics
    ///
    /// Panics if `m` does not have one column per dimension.
    #[must_use]
    pub fn interval_map(&self, m: &IntervalMatrix) -> Self {
        let (center, radius) = m.center_radius();
        let spread = uncertainty_generators(&radius, &self.interval_hull());
        let mapped = self.linear_map(&center);

        Self {
            gi: hcat(&mapped.gi, &spread),
            ..mapped
        }
    }

    /// Exact: `{ x + v | x ∈ PZ }`.
    ///
    /// # Panics
    ///
    /// Panics if `v` does not have the set's dimension.
    #[must_use]
    pub fn translate(&self, v: &DVector<f64>) -> Self {
        let mut errs = RowErrors::new(self.dim());
        let c = round::vec_add(&self.c, v, &mut errs);

        Self {
            c,
            g: self.g.clone(),
            gi: hcat(&self.gi, &errs.generators()),
            e: self.e.clone(),
            id: self.id.clone(),
        }
    }

    /// Same set, with all dependent factors renamed to fresh ids (decorrelates it from every other set).
    #[must_use]
    pub fn with_fresh_ids(&self) -> Self {
        Self {
            id: FactorId::fresh_n(self.id.len()),
            ..self.clone()
        }
    }

    /// Exact Minkowski sum `{ x + y | x ∈ self, y ∈ other }` (sets treated as independent).
    ///
    /// # Panics
    ///
    /// Panics if the two sets have different dimensions.
    #[must_use]
    pub fn minkowski_sum(&self, other: &Self) -> Self {
        self.exact_plus(&other.with_fresh_ids())
    }

    /// Exact addition respecting shared factors: `{ p₁(α) + p₂(α) }`.
    ///
    /// # Panics
    ///
    /// Panics if the two sets have different dimensions.
    #[must_use]
    pub fn exact_plus(&self, other: &Self) -> Self {
        let (id, e1, e2) = merge_ids(self, other);
        let mut errs = RowErrors::new(self.dim());
        let c = round::vec_add(&self.c, &other.c, &mut errs);
        Self {
            c,
            g: hcat(&self.g, &other.g),
            gi: hcat(&hcat(&self.gi, &other.gi), &errs.generators()),
            e: hcat(&e1, &e2),
            id,
        }
        .compact()
    }

    /// Exact Cartesian product, keeping shared factors correlated.
    ///
    /// The result is [`compact`](Self::compact)ed, like [`exact_plus`](Self::exact_plus).
    #[must_use]
    pub fn cartesian_product(&self, other: &Self) -> Self {
        let (id, e1, e2) = merge_ids(self, other);
        let (n1, n2) = (self.dim(), other.dim());
        let block = |a: &DMatrix<f64>, b: &DMatrix<f64>| {
            DMatrix::from_fn(n1 + n2, a.ncols() + b.ncols(), |i, j| {
                match (i < n1, j < a.ncols()) {
                    (true, true) => a[(i, j)],
                    (false, false) => b[(i - n1, j - a.ncols())],
                    _ => 0.0,
                }
            })
        };
        Self {
            c: DVector::from_iterator(n1 + n2, self.c.iter().chain(other.c.iter()).copied()),
            g: block(&self.g, &other.g),
            gi: block(&self.gi, &other.gi),
            e: hcat(&e1, &e2),
            id,
        }
        .compact()
    }

    /// Merges generators with identical exponent columns, moves constant
    /// monomials into the center, and drops zero dependent generators and
    /// unused factors.
    ///
    /// Independent generators are kept as they are, even zero ones, so the
    /// positions of the `β` values stay stable across [`exact_plus`](Self::exact_plus)
    /// and [`split`](Self::split). The price is that zero independent
    /// generators, e.g. from a singular [`linear_map`](Self::linear_map), are
    /// never reclaimed here; [`to_zonotope`](Self::to_zonotope) leaves them out.
    /// With the `sound` feature, bounds on the rounding error of the merged
    /// sums are appended after them.
    #[must_use]
    pub fn compact(&self) -> Self {
        let n = self.dim();
        let mut c = self.c.clone();
        let mut errs = RowErrors::new(n);
        let mut columns: Vec<(Vec<u32>, DVector<f64>)> = Vec::new();
        let mut index: BTreeMap<Vec<u32>, usize> = BTreeMap::new();
        for i in 0..self.g.ncols() {
            let exp: Vec<u32> = self.e.column(i).iter().copied().collect();
            let gv = self.g.column(i).into_owned();
            if exp.iter().all(|&x| x == 0) {
                round::add_into(&mut c, &gv, &mut errs);
            } else if let Some(&j) = index.get(&exp) {
                round::add_into(&mut columns[j].1, &gv, &mut errs);
            } else {
                index.insert(exp.clone(), columns.len());
                columns.push((exp, gv));
            }
        }

        columns.retain(|(_, g)| g.iter().any(|&x| x != 0.0));
        let used: Vec<usize> = (0..self.id.len())
            .filter(|&k| columns.iter().any(|(e, _)| e[k] != 0))
            .collect();
        Self {
            c,
            g: DMatrix::from_fn(n, columns.len(), |i, j| columns[j].1[i]),
            gi: hcat(&self.gi, &errs.generators()),
            e: DMatrix::from_fn(used.len(), columns.len(), |k, j| columns[j].0[used[k]]),
            id: used.iter().map(|&k| self.id[k]).collect(),
        }
    }

    /// How monomial `col` ranges over the factor domain, from the parity of its exponents.
    fn monomial_range(&self, col: usize) -> MonomialRange {
        let exps = self.e.column(col);
        if exps.iter().all(|&x| x == 0) {
            MonomialRange::Constant
        } else if exps.iter().all(|&x| x % 2 == 0) {
            MonomialRange::UnitRange
        } else {
            MonomialRange::Symmetric
        }
    }

    /// Interval enclosure (treats every monomial as independent, so it is
    /// sound but can be loose; tighten with [`split`](Self::split)). With the
    /// `sound` feature the bounds are rounded outward.
    #[must_use]
    pub fn interval_hull(&self) -> IntervalBox {
        let mut iv: Vec<Interval> = self.c.iter().map(|&x| Interval::point(x)).collect();
        for j in 0..self.g.ncols() {
            let range = self.monomial_range(j);
            for (i, &g) in self.g.column(j).iter().enumerate() {
                iv[i] = iv[i] + range.scaled_bounds(g);
            }
        }

        for (i, row) in self.gi.row_iter().enumerate() {
            let r = round::abs_sum_up(row.iter());
            iv[i] = iv[i] + Interval::new(-r, r);
        }

        IntervalBox(iv)
    }

    /// Zonotope enclosure: monomials with only even exponents range over
    /// `[0, 1]`, so they contribute `g/2 + (g/2)·β`.
    ///
    /// All-zero generators, dependent or independent, are left out, so
    /// [`Zonotope::order`] counts only generators that shape the set.
    #[must_use]
    pub fn to_zonotope(&self) -> Zonotope {
        let mut enclosed = self.enclose_monomials(|_| true);
        enclosed
            .generators
            .extend(self.gi.column_iter().map(nalgebra::Matrix::into_owned));
        enclosed.generators.retain(|g| g.iter().any(|&x| x != 0.0));
        let gens = from_column_list(self.dim(), &enclosed.generators);

        Zonotope::new(enclosed.center, hcat(&gens, &enclosed.errs.generators()))
    }

    /// Replaces the dependent monomials `pick` selects by their enclosure:
    /// a constant moves into the center, `[0, 1]` monomials contribute
    /// `g/2 + (g/2)·β`, the rest `g·β`, each with its own new `β`.
    fn enclose_monomials(&self, pick: impl Fn(usize) -> bool) -> Enclosed {
        let mut out = Enclosed {
            center: self.c.clone(),
            kept: Vec::new(),
            generators: Vec::new(),
            errs: RowErrors::new(self.dim()),
        };
        for j in 0..self.g.ncols() {
            if !pick(j) {
                out.kept.push(j);
                continue;
            }

            let g = self.g.column(j).into_owned();
            match self.monomial_range(j) {
                MonomialRange::Constant => round::add_into(&mut out.center, &g, &mut out.errs),
                MonomialRange::UnitRange => {
                    let half = round::halves(&g, &mut out.errs);
                    round::add_into(&mut out.center, &half, &mut out.errs);
                    out.generators.push(half);
                }
                MonomialRange::Symmetric => out.generators.push(g),
            }
        }

        out
    }

    /// Encloses every monomial that involves one of `factors`, turning it into
    /// an independent generator appended after the existing ones, and drops
    /// those factors. Sound, and exact for the monomials it leaves alone.
    fn enclose_factors(&self, factors: &[FactorId]) -> Self {
        let rows: Vec<usize> = (0..self.id.len())
            .filter(|&k| factors.contains(&self.id[k]))
            .collect();
        let enclosed = self.enclose_monomials(|j| rows.iter().any(|&k| self.e[(k, j)] != 0));
        let keep_ids: Vec<usize> = (0..self.id.len()).filter(|k| !rows.contains(k)).collect();
        let n = self.dim();
        let gi = hcat(&self.gi, &from_column_list(n, &enclosed.generators));

        Self {
            c: enclosed.center,
            g: DMatrix::from_fn(n, enclosed.kept.len(), |i, j| self.g[(i, enclosed.kept[j])]),
            gi: hcat(&gi, &enclosed.errs.generators()),
            e: DMatrix::from_fn(keep_ids.len(), enclosed.kept.len(), |k, j| {
                self.e[(keep_ids[k], enclosed.kept[j])]
            }),
            id: keep_ids.iter().map(|&k| self.id[k]).collect(),
        }
    }

    /// `{ (xᵀ Q₁ x, …, xᵀ Q_m x) | x ∈ PZ }`, one output dimension per matrix in `maps`.
    ///
    /// Exact when the set has no independent generators, as in Kochdumper &
    /// Althoff (2021). Otherwise every monomial that involves an independent factor
    /// is enclosed and becomes an independent generator of the result, so the
    /// result is a sound enclosure; the monomials in the dependent factors
    /// alone stay exact.
    ///
    /// # Panics
    ///
    /// Panics if a matrix in `maps` is not `dim × dim`, or if an exponent of
    /// the result overflows `u32`.
    #[must_use]
    pub fn quadratic_map(&self, maps: &[DMatrix<f64>]) -> Self {
        let dim = self.dim();
        assert!(
            maps.iter().all(|m| m.shape() == (dim, dim)),
            "every matrix of a quadratic map must be dim × dim"
        );

        let (temp, columns, exponents) = self.promoted();
        let mut errs = RowErrors::new(maps.len());
        let center = DVector::from_fn(maps.len(), |i, _| {
            round::bilinear(&self.c, &maps[i], &self.c, i, &mut errs)
        });
        let mut gens = Vec::new();
        let mut exps = Vec::new();
        for t in 0..columns.len() {
            // Linear terms: cᵀ Q hₜ + hₜᵀ Q c.
            gens.push(symmetric_products(maps, &self.c, &columns[t], &mut errs));
            exps.push(exponents[t].clone());
            for u in t..columns.len() {
                gens.push(if t == u {
                    DVector::from_fn(maps.len(), |i, _| {
                        round::bilinear(&columns[t], &maps[i], &columns[t], i, &mut errs)
                    })
                } else {
                    symmetric_products(maps, &columns[t], &columns[u], &mut errs)
                });
                exps.push(add_exponents(&exponents[t], &exponents[u]));
            }
        }

        let mut id = self.id.clone();
        id.extend_from_slice(&temp);
        Self {
            c: center,
            g: from_column_list(maps.len(), &gens),
            gi: errs.generators(),
            e: from_column_list(id.len(), &exps),
            id,
        }
        .compact()
        .enclose_factors(&temp)
    }

    /// `{ (Σ_a x_a xᵀ T_{1,a} x, …, Σ_a x_a xᵀ T_{m,a} x) | x ∈ PZ }`, one output
    /// dimension per entry of `maps`: entry `i` holds the `dim` slices
    /// `T_{i,a}` of a cubic form, `T_{i,a}[b, c]` the coefficient of
    /// `x_a x_b x_c`.
    ///
    /// Exact when the set has no independent generators, like
    /// [`quadratic_map`](Self::quadratic_map); otherwise every monomial that
    /// involves an independent factor is enclosed and becomes an independent
    /// generator of the result. The degree of the result is three times that
    /// of the set.
    ///
    /// # Panics
    ///
    /// Panics if an entry of `maps` does not hold `dim` matrices of size
    /// `dim × dim`, or if an exponent of the result overflows `u32`.
    #[must_use]
    pub fn cubic_map(&self, maps: &[Vec<DMatrix<f64>>]) -> Self {
        let dim = self.dim();
        assert!(
            maps.iter()
                .all(|t| t.len() == dim && t.iter().all(|m| m.shape() == (dim, dim))),
            "every cubic form must have dim slices of size dim × dim"
        );

        let (temp, mut columns, mut exponents) = self.promoted();
        // The center joins as column 0 with the zero exponent, so the
        // expansion of (c + Σ hₜ mₜ)³ is one loop over column triples.
        columns.insert(0, self.c.clone());
        exponents.insert(0, alloc::vec![0; self.id.len() + temp.len()]);

        let mut errs = RowErrors::new(maps.len());
        let mut center = DVector::zeros(maps.len());
        let mut gens = Vec::new();
        let mut exps = Vec::new();
        for t in 0..columns.len() {
            for u in t..columns.len() {
                for v in u..columns.len() {
                    let triple = [&columns[t], &columns[u], &columns[v]];
                    let coefficient = symmetric_triple_products(maps, triple, &mut errs);
                    if v == 0 {
                        center = coefficient;
                    } else {
                        gens.push(coefficient);
                        let pair = add_exponents(&exponents[t], &exponents[u]);
                        exps.push(add_exponents(&pair, &exponents[v]));
                    }
                }
            }
        }

        let mut id = self.id.clone();
        id.extend_from_slice(&temp);
        Self {
            c: center,
            g: from_column_list(maps.len(), &gens),
            gi: errs.generators(),
            e: from_column_list(id.len(), &exps),
            id,
        }
        .compact()
        .enclose_factors(&temp)
    }

    /// The generators as one polynomial: every `β` promoted to a temporary
    /// dependent factor of its own, so a polynomial map can multiply out all
    /// generators alike. Returns the temporary factors, the dependent then
    /// the independent generators, and the exponents of each over the
    /// factors of the set followed by the temporary ones.
    fn promoted(&self) -> (Vec<FactorId>, Vec<DVector<f64>>, Vec<Vec<u32>>) {
        let temp = FactorId::fresh_n(self.gi.ncols());
        let all = hcat(&self.g, &self.gi);
        let (ids, dep) = (self.id.len(), self.g.ncols());
        let promoted = DMatrix::from_fn(ids + temp.len(), all.ncols(), |k, t| {
            match (k < ids, t < dep) {
                (true, true) => self.e[(k, t)],
                (false, false) => u32::from(k - ids == t - dep),
                _ => 0,
            }
        });
        let columns = all
            .column_iter()
            .map(nalgebra::Matrix::into_owned)
            .collect();
        let exponents = promoted
            .column_iter()
            .map(|c| c.iter().copied().collect())
            .collect();

        (temp, columns, exponents)
    }

    /// Enclosure with at most `order · dim` generators, dependent and
    /// independent ones counted together.
    ///
    /// The generators with the smallest `‖g‖₁ − ‖g‖∞` are dropped: dependent
    /// ones are enclosed like in [`to_zonotope`](Self::to_zonotope), and
    /// together with the dropped independent ones they are replaced by a box,
    /// as `method` says. The kept dependent generators stay exact, so the
    /// result keeps its dependencies on the remaining factors. The kept
    /// independent generators come first, then the box. Returns the
    /// [`compact`](Self::compact)ed set if it already meets the order.
    ///
    /// With the `sound` feature and [`Reduction::Pca`], up to `dim` generators
    /// for rounding errors come on top.
    ///
    /// # Panics
    ///
    /// Panics if `order < 1`.
    #[must_use]
    pub fn reduce(&self, order: f64, method: Reduction) -> Self {
        // Compact first: the final compact() then has nothing left to merge, so
        // it adds no rounding-error generators beyond the order.
        self.compact().reduce_compacted(order, method)
    }

    /// [`reduce`](Self::reduce) for a set without constant, zero or duplicate monomials.
    fn reduce_compacted(&self, order: f64, method: Reduction) -> Self {
        let (h, n) = (self.g.ncols(), self.dim());
        let column = |j: usize| {
            if j < h {
                self.g.column(j)
            } else {
                self.gi.column(j - h)
            }
        };
        let count = h + self.gi.ncols();
        let Some((kept, dropped)) =
            reduce::select(count, n, order, |j| reduce::girard_metric(column(j).iter()))
        else {
            return self.clone();
        };

        let mut enclosed = self.enclose_monomials(|j| dropped.binary_search(&j).is_ok());
        let dropped_independent = dropped.iter().filter(|&&j| j >= h);
        enclosed
            .generators
            .extend(dropped_independent.map(|&j| column(j).into_owned()));
        let enclosure = reduce::enclose(
            &from_column_list(n, &enclosed.generators),
            method,
            &mut enclosed.errs,
        );
        let kept_independent: Vec<usize> =
            kept.iter().filter(|&&j| j >= h).map(|&j| j - h).collect();
        let gi = hcat(&self.gi.select_columns(&kept_independent), &enclosure);

        Self {
            c: enclosed.center,
            g: self.g.select_columns(&enclosed.kept),
            gi: hcat(&gi, &enclosed.errs.generators()),
            e: self.e.select_columns(&enclosed.kept),
            id: self.id.clone(),
        }
        .compact()
    }

    /// Splits the domain of `factor` into `[-1, 0]` and `[0, 1]`. Each half
    /// is exact and uses a fresh id for the rescaled factor
    /// (`α = (α' ∓ 1) / 2`). Returns `(lower, upper)`.
    ///
    /// # Panics
    ///
    /// Panics if `factor` is not one of [`ids`](Self::ids), or if it appears
    /// with an exponent above 56, where the binomial coefficients of the
    /// rescaling are no longer exact in `f64`.
    #[must_use]
    pub fn split(&self, factor: FactorId) -> (Self, Self) {
        let k = self
            .id
            .iter()
            .position(|&x| x == factor)
            .expect("factor not in this set");

        (self.half_domain(k, -1.0), self.half_domain(k, 1.0))
    }

    /// The half of the set where factor `k` lies between 0 and `sign`, with
    /// `α_k = (α' + sign) / 2` substituted for a fresh factor `α'`.
    fn half_domain(&self, k: usize, sign: f64) -> Self {
        let mut gens: Vec<DVector<f64>> = Vec::new();
        let mut exps: Vec<Vec<u32>> = Vec::new();
        let mut errs = RowErrors::new(self.dim());
        for i in 0..self.g.ncols() {
            let column = self.g.column(i).into_owned();
            for (exp, coef) in self.expand_rescaled(i, k, sign) {
                exps.push(exp);
                gens.push(round::scaled(&column, coef, &mut errs));
            }
        }

        let mut id = self.id.clone();
        id[k] = FactorId::fresh();
        let (n, p) = (self.dim(), id.len());

        Self {
            c: self.c.clone(),
            g: from_column_list(n, &gens),
            gi: hcat(&self.gi, &errs.generators()),
            e: from_column_list(p, &exps),
            id,
        }
        .compact()
    }

    /// Binomial expansion of monomial `i` after substituting
    /// `α_k = (α' + sign) / 2`: one `(exponents, coefficient)` pair per power
    /// `j` of `α'`, from
    /// `(α'/2 + sign/2)^d = Σ_j C(d, j) (1/2)^d α'^j sign^(d-j)`.
    fn expand_rescaled(&self, i: usize, k: usize, sign: f64) -> Vec<(Vec<u32>, f64)> {
        let d = self.e[(k, i)];
        assert!(
            d <= MAX_SPLIT_EXPONENT,
            "split needs exponents of at most {MAX_SPLIT_EXPONENT}, found {d}"
        );

        // Repeated squaring, not `powi`: powers of 1/2 and ±1 are exact that way.
        (0..=d)
            .map(|j| {
                let coef = binomial(d, j) * pow_by_squaring(0.5, d) * pow_by_squaring(sign, d - j);
                let mut exp: Vec<u32> = self.e.column(i).iter().copied().collect();
                exp[k] = j;
                (exp, coef)
            })
            .collect()
    }
}

/// The parts of a set after [`SparsePolyZonotope::enclose_monomials`].
struct Enclosed {
    /// Center, shifted by the enclosed constant and `[0, 1]` monomials.
    center: DVector<f64>,
    /// Indices of the dependent generators that were not enclosed, in order.
    kept: Vec<usize>,
    /// New generators, one per enclosed non-constant monomial, each with its own `β`.
    generators: Vec<DVector<f64>>,
    /// Rounding-error bounds of the shifts and halvings.
    errs: RowErrors,
}

/// `(aᵀ Qᵢ b + bᵀ Qᵢ a)ᵢ`, one entry per matrix, with rounding errors in `errs`.
fn symmetric_products(
    q: &[DMatrix<f64>],
    a: &DVector<f64>,
    b: &DVector<f64>,
    errs: &mut RowErrors,
) -> DVector<f64> {
    DVector::from_fn(q.len(), |i, _| {
        let a_b = round::bilinear(a, &q[i], b, i, errs);
        let b_a = round::bilinear(b, &q[i], a, i, errs);
        round::add(a_b, b_a, i, errs)
    })
}

/// The coefficient of the monomial `m_a m_b m_c` in each cubic form of
/// `maps` applied to `Σ hₜ mₜ`, for the columns `[h_a, h_b, h_c]` with
/// `a ≤ b ≤ c`: `T(p, q, r)` summed over every distinct ordering of the
/// three, with rounding errors in `errs`.
fn symmetric_triple_products(
    maps: &[Vec<DMatrix<f64>>],
    [a, b, c]: [&DVector<f64>; 3],
    errs: &mut RowErrors,
) -> DVector<f64> {
    let mut orderings = alloc::vec![[a, b, c]];
    for ordering in [[a, c, b], [b, a, c], [b, c, a], [c, a, b], [c, b, a]] {
        if !orderings.iter().any(|o| same_columns(o, &ordering)) {
            orderings.push(ordering);
        }
    }

    DVector::from_fn(maps.len(), |i, _| {
        orderings.iter().fold(0.0, |acc, [p, q, r]| {
            let term = round::trilinear(p, &maps[i], q, r, i, errs);
            round::add(acc, term, i, errs)
        })
    })
}

/// Whether two orderings name the same columns at every position.
fn same_columns(x: &[&DVector<f64>; 3], y: &[&DVector<f64>; 3]) -> bool {
    x.iter().zip(y).all(|(p, q)| core::ptr::eq(*p, *q))
}

/// Exponents of the product of two monomials.
///
/// # Panics
///
/// Panics if an exponent overflows `u32`.
fn add_exponents(a: &[u32], b: &[u32]) -> Vec<u32> {
    a.iter()
        .zip(b)
        .map(|(x, y)| x.checked_add(*y).expect("exponent overflows u32"))
        .collect()
}

/// `x^n`, via [`f64::powi`] with the `std` feature and repeated squaring without it.
///
/// Exponents beyond `i32::MAX` take the repeated-squaring path in both cases.
fn powu(x: f64, n: u32) -> f64 {
    #[cfg(feature = "std")]
    if let Ok(n) = i32::try_from(n) {
        return x.powi(n);
    }

    pow_by_squaring(x, n)
}

/// `x^n` by repeated squaring, in `O(log n)` multiplications; `x^0` is 1, also for `x = 0`.
fn pow_by_squaring(mut x: f64, mut n: u32) -> f64 {
    let mut acc = 1.0;
    while n > 0 {
        if n & 1 == 1 {
            acc *= x;
        }

        x *= x;
        n >>= 1;
    }

    acc
}

impl SparsePolyZonotope {
    /// Whether [`split`](Self::split) accepts `factor`: it is one of
    /// [`ids`](Self::ids), and none of its exponents is above the limit of
    /// `split`. Callers that pick factors to split can skip the others
    /// instead of panicking.
    #[must_use]
    pub fn can_split(&self, factor: FactorId) -> bool {
        self.id
            .iter()
            .position(|&x| x == factor)
            .is_some_and(|k| self.can_split_row(k))
    }

    /// [`can_split`](Self::can_split) for the factor in row `k`.
    pub(crate) fn can_split_row(&self, k: usize) -> bool {
        self.e.row(k).iter().all(|&d| d <= MAX_SPLIT_EXPONENT)
    }
}

/// Largest exponent [`SparsePolyZonotope::split`] accepts: every `C(d, j)` with
/// `d <= 56` stays below `2^53`, so [`binomial`] and the coefficients
/// `C(d, j) / 2^d` of the rescaling are exact.
const MAX_SPLIT_EXPONENT: u32 = 56;

/// Binomial coefficient `C(n, k)` for `k <= n`, exact for `n <=` [`MAX_SPLIT_EXPONENT`].
///
/// Integer arithmetic keeps every step exact: `C(n, i) (n - i)` is divisible by
/// `i + 1` and below `2^63` for those `n`.
#[expect(
    clippy::cast_precision_loss,
    reason = "C(n, k) < 2^53 for n <= MAX_SPLIT_EXPONENT, so the conversion is exact"
)]
fn binomial(n: u32, k: u32) -> f64 {
    (0..k).fold(1u64, |acc, i| acc * u64::from(n - i) / u64::from(i + 1)) as f64
}

/// Union of the two id lists, with both exponent matrices re-indexed to it.
fn merge_ids(
    a: &SparsePolyZonotope,
    b: &SparsePolyZonotope,
) -> (Vec<FactorId>, DMatrix<u32>, DMatrix<u32>) {
    let mut id = a.id.clone();
    let mut pos: BTreeMap<FactorId, usize> = id.iter().enumerate().map(|(i, &k)| (k, i)).collect();
    for &k in &b.id {
        pos.entry(k).or_insert_with(|| {
            id.push(k);
            id.len() - 1
        });
    }

    let p = id.len();
    let e1 = DMatrix::from_fn(p, a.e.ncols(), |r, c| {
        if r < a.e.nrows() { a.e[(r, c)] } else { 0 }
    });
    let mut e2 = DMatrix::zeros(p, b.e.ncols());
    for (r, k) in b.id.iter().enumerate() {
        for c in 0..b.e.ncols() {
            e2[(pos[k], c)] = b.e[(r, c)];
        }
    }

    (id, e1, e2)
}

/// Unit tests for the private power helpers, which the integration tests only
/// reach through the `std` path.
#[cfg(test)]
mod tests {
    use super::{pow_by_squaring, powu};

    /// `x^n` as `n` plain multiplications, the reference both helpers must match.
    fn naive_pow(x: f64, n: u32) -> f64 {
        (0..n).fold(1.0, |acc, _| acc * x)
    }

    /// Repeated squaring agrees with plain multiplication, including `x^0 = 1` for `x = 0`.
    #[test]
    fn pow_by_squaring_matches_repeated_multiplication() {
        for x in [0.0, 1.0, -1.0, 0.5, -1.5, 0.3] {
            for n in 0..=40 {
                let (got, want) = (pow_by_squaring(x, n), naive_pow(x, n));
                assert!(
                    (got - want).abs() <= 1e-12 * want.abs(),
                    "{x}^{n}: {got} vs {want}"
                );
            }
        }
    }

    /// Exponents beyond `i32::MAX` take the repeated-squaring path instead of panicking.
    #[test]
    fn powu_handles_exponents_beyond_i32_max() {
        assert!((powu(1.0, u32::MAX) - 1.0).abs() < f64::EPSILON);
        assert!((powu(-1.0, u32::MAX) + 1.0).abs() < f64::EPSILON);
        assert!(powu(0.5, u32::MAX).abs() < f64::EPSILON);
    }
}