Skip to main content

polyzonotope/
sparse.rs

1//! Sparse polynomial zonotopes (Kochdumper & Althoff, IEEE TAC 2021).
2
3use 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/// Global identifier of a dependent factor `α_k`.
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
20pub struct FactorId(u64);
21
22/// Next unused [`FactorId`] value; shared process-wide so ids never collide.
23///
24/// `portable_atomic` rather than `core`, so targets without native 64-bit
25/// atomics (Cortex-M, 32-bit RISC-V) still get a shared counter.
26static NEXT_FACTOR: AtomicU64 = AtomicU64::new(0);
27
28impl FactorId {
29    /// A new id, distinct from every id handed out before in this process.
30    #[must_use]
31    pub fn fresh() -> Self {
32        Self(NEXT_FACTOR.fetch_add(1, Ordering::Relaxed))
33    }
34
35    /// `n` new ids, distinct from each other and from every earlier id.
36    #[must_use]
37    pub fn fresh_n(n: usize) -> Vec<Self> {
38        (0..n).map(|_| Self::fresh()).collect()
39    }
40}
41
42/// Why the parts passed to [`SparsePolyZonotope::new`] do not fit together.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum ShapeError {
45    /// The dependent generator matrix `G` does not have one row per dimension.
46    GeneratorRows,
47    /// The independent generator matrix `GI` does not have one row per dimension.
48    IndependentRows,
49    /// The exponent matrix `E` does not have one column per dependent generator.
50    ExponentColumns,
51    /// The exponent matrix `E` does not have one row per factor id.
52    ExponentRows,
53    /// The same [`FactorId`] appears more than once.
54    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/// Sparse polynomial zonotope `⟨c, G, GI, E, id⟩`.
72#[derive(Clone, Debug, PartialEq)]
73///
74/// Invariants (checked by [`new`](Self::new)): `g` and `gi` have one row per
75/// entry of `c`, `e` has one column per column of `g` and one row per id, and
76/// the ids are distinct.
77pub struct SparsePolyZonotope {
78    /// Center `c`; its length is the dimension of the set.
79    c: DVector<f64>,
80    /// Dependent generators `G`, one per column; column `i` is scaled by monomial `i`.
81    g: DMatrix<f64>,
82    /// Independent generators `GI`, one per column, each scaled by its own `β_j`.
83    gi: DMatrix<f64>,
84    /// Exponents `E`: entry `(k, i)` is the power of `α_k` in monomial `i`.
85    e: DMatrix<u32>,
86    /// Global ids of the dependent factors; row `k` of `e` belongs to `id[k]`.
87    id: Vec<FactorId>,
88}
89
90/// How a dependent monomial ranges over `α ∈ [-1, 1]^p`.
91enum MonomialRange {
92    /// All exponents are zero: the monomial is exactly 1.
93    Constant,
94    /// All exponents are even: the monomial ranges over `[0, 1]`.
95    UnitRange,
96    /// Some exponent is odd: the monomial ranges over `[-1, 1]`.
97    Symmetric,
98}
99
100impl MonomialRange {
101    /// The range of `g · m` as the monomial `m` ranges over this range.
102    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    /// The set `⟨c, g, gi, e, id⟩`, after checking that the shapes fit together.
113    ///
114    /// # Errors
115    ///
116    /// - [`ShapeError::GeneratorRows`] if `g` does not have `c.len()` rows.
117    /// - [`ShapeError::IndependentRows`] if `gi` does not have `c.len()` rows.
118    /// - [`ShapeError::ExponentColumns`] if `e` and `g` differ in column count.
119    /// - [`ShapeError::ExponentRows`] if `e` does not have one row per id.
120    /// - [`ShapeError::DuplicateId`] if an id appears twice.
121    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    /// Exact conversion: every generator becomes a dependent factor.
155    #[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    /// Dimension of the space the set lives in.
168    #[must_use]
169    pub fn dim(&self) -> usize {
170        self.c.len()
171    }
172
173    /// Center `c`.
174    #[must_use]
175    pub fn center(&self) -> &DVector<f64> {
176        &self.c
177    }
178
179    /// Dependent generators `G`, one per column, matching the columns of [`exponents`](Self::exponents).
180    #[must_use]
181    pub fn dependent_generators(&self) -> &DMatrix<f64> {
182        &self.g
183    }
184
185    /// Independent generators `GI`, one per column.
186    #[must_use]
187    pub fn independent_generators(&self) -> &DMatrix<f64> {
188        &self.gi
189    }
190
191    /// Exponent matrix `E`: entry `(k, i)` is the power of the factor `ids()[k]` in monomial `i`.
192    #[must_use]
193    pub fn exponents(&self) -> &DMatrix<u32> {
194        &self.e
195    }
196
197    /// Ids of the dependent factors, one per row of [`exponents`](Self::exponents).
198    #[must_use]
199    pub fn ids(&self) -> &[FactorId] {
200        &self.id
201    }
202
203    /// Point of the set for the given factor values (`alpha` looked up by
204    /// id, `beta` positional).
205    ///
206    /// # Panics
207    ///
208    /// Panics if `beta` does not have one entry per independent generator.
209    #[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    /// Point of the set for positional factor values: `a[k]` belongs to `ids()[k]`.
223    ///
224    /// Callers check that `a` has one entry per id and `beta` one entry per
225    /// independent generator.
226    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    /// Value of monomial `i`, `Π_k a[k]^E[k, i]`, for positional factor values `a`.
236    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    /// Positional variant of [`evaluate_with`](Self::evaluate_with): `alpha[k]` belongs to `ids()[k]`.
244    ///
245    /// # Panics
246    ///
247    /// Panics if `alpha` does not have one entry per id, or `beta` one entry
248    /// per independent generator.
249    #[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    /// Exact: `{ M x | x ∈ PZ }`.
262    ///
263    /// # Panics
264    ///
265    /// Panics if `m` does not have one column per dimension.
266    #[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    /// Enclosure of `{ M x | M ∈ m, x ∈ PZ }` for an interval matrix `m`:
283    /// the exact map by the center matrix, plus independent generators for the
284    /// radius, sized by the interval hull of the set. Dependencies on the
285    /// factors survive through the center map.
286    ///
287    /// # Panics
288    ///
289    /// Panics if `m` does not have one column per dimension.
290    #[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(&center);
295
296        Self {
297            gi: hcat(&mapped.gi, &spread),
298            ..mapped
299        }
300    }
301
302    /// Exact: `{ x + v | x ∈ PZ }`.
303    ///
304    /// # Panics
305    ///
306    /// Panics if `v` does not have the set's dimension.
307    #[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    /// Same set, with all dependent factors renamed to fresh ids (decorrelates it from every other set).
322    #[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    /// Exact Minkowski sum `{ x + y | x ∈ self, y ∈ other }` (sets treated as independent).
331    ///
332    /// # Panics
333    ///
334    /// Panics if the two sets have different dimensions.
335    #[must_use]
336    pub fn minkowski_sum(&self, other: &Self) -> Self {
337        self.exact_plus(&other.with_fresh_ids())
338    }
339
340    /// Exact addition respecting shared factors: `{ p₁(α) + p₂(α) }`.
341    ///
342    /// # Panics
343    ///
344    /// Panics if the two sets have different dimensions.
345    #[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    /// Exact Cartesian product, keeping shared factors correlated.
361    ///
362    /// The result is [`compact`](Self::compact)ed, like [`exact_plus`](Self::exact_plus).
363    #[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    /// Merges generators with identical exponent columns, moves constant
387    /// monomials into the center, and drops zero dependent generators and
388    /// unused factors.
389    ///
390    /// Independent generators are kept as they are, even zero ones, so the
391    /// positions of the `β` values stay stable across [`exact_plus`](Self::exact_plus)
392    /// and [`split`](Self::split). The price is that zero independent
393    /// generators, e.g. from a singular [`linear_map`](Self::linear_map), are
394    /// never reclaimed here; [`to_zonotope`](Self::to_zonotope) leaves them out.
395    /// With the `sound` feature, bounds on the rounding error of the merged
396    /// sums are appended after them.
397    #[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    /// How monomial `col` ranges over the factor domain, from the parity of its exponents.
431    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    /// Interval enclosure (treats every monomial as independent, so it is
443    /// sound but can be loose; tighten with [`split`](Self::split)). With the
444    /// `sound` feature the bounds are rounded outward.
445    #[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    /// Zonotope enclosure: monomials with only even exponents range over
464    /// `[0, 1]`, so they contribute `g/2 + (g/2)·β`.
465    ///
466    /// All-zero generators, dependent or independent, are left out, so
467    /// [`Zonotope::order`] counts only generators that shape the set.
468    #[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    /// Replaces the dependent monomials `pick` selects by their enclosure:
481    /// a constant moves into the center, `[0, 1]` monomials contribute
482    /// `g/2 + (g/2)·β`, the rest `g·β`, each with its own new `β`.
483    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    /// Encloses every monomial that involves one of `factors`, turning it into
512    /// an independent generator appended after the existing ones, and drops
513    /// those factors. Sound, and exact for the monomials it leaves alone.
514    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    /// `{ (xᵀ Q₁ x, …, xᵀ Q_m x) | x ∈ PZ }`, one output dimension per matrix in `maps`.
535    ///
536    /// Exact when the set has no independent generators, as in Kochdumper &
537    /// Althoff (2021). Otherwise every monomial that involves an independent factor
538    /// is enclosed and becomes an independent generator of the result, so the
539    /// result is a sound enclosure; the monomials in the dependent factors
540    /// alone stay exact.
541    ///
542    /// # Panics
543    ///
544    /// Panics if a matrix in `maps` is not `dim × dim`, or if an exponent of
545    /// the result overflows `u32`.
546    #[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            // Linear terms: cᵀ Q hₜ + hₜᵀ Q c.
563            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    /// `{ (Σ_a x_a xᵀ T_{1,a} x, …, Σ_a x_a xᵀ T_{m,a} x) | x ∈ PZ }`, one output
591    /// dimension per entry of `maps`: entry `i` holds the `dim` slices
592    /// `T_{i,a}` of a cubic form, `T_{i,a}[b, c]` the coefficient of
593    /// `x_a x_b x_c`.
594    ///
595    /// Exact when the set has no independent generators, like
596    /// [`quadratic_map`](Self::quadratic_map); otherwise every monomial that
597    /// involves an independent factor is enclosed and becomes an independent
598    /// generator of the result. The degree of the result is three times that
599    /// of the set.
600    ///
601    /// # Panics
602    ///
603    /// Panics if an entry of `maps` does not hold `dim` matrices of size
604    /// `dim × dim`, or if an exponent of the result overflows `u32`.
605    #[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        // The center joins as column 0 with the zero exponent, so the
616        // expansion of (c + Σ hₜ mₜ)³ is one loop over column triples.
617        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    /// The generators as one polynomial: every `β` promoted to a temporary
654    /// dependent factor of its own, so a polynomial map can multiply out all
655    /// generators alike. Returns the temporary factors, the dependent then
656    /// the independent generators, and the exponents of each over the
657    /// factors of the set followed by the temporary ones.
658    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    /// Enclosure with at most `order · dim` generators, dependent and
682    /// independent ones counted together.
683    ///
684    /// The generators with the smallest `‖g‖₁ − ‖g‖∞` are dropped: dependent
685    /// ones are enclosed like in [`to_zonotope`](Self::to_zonotope), and
686    /// together with the dropped independent ones they are replaced by a box,
687    /// as `method` says. The kept dependent generators stay exact, so the
688    /// result keeps its dependencies on the remaining factors. The kept
689    /// independent generators come first, then the box. Returns the
690    /// [`compact`](Self::compact)ed set if it already meets the order.
691    ///
692    /// With the `sound` feature and [`Reduction::Pca`], up to `dim` generators
693    /// for rounding errors come on top.
694    ///
695    /// # Panics
696    ///
697    /// Panics if `order < 1`.
698    #[must_use]
699    pub fn reduce(&self, order: f64, method: Reduction) -> Self {
700        // Compact first: the final compact() then has nothing left to merge, so
701        // it adds no rounding-error generators beyond the order.
702        self.compact().reduce_compacted(order, method)
703    }
704
705    /// [`reduce`](Self::reduce) for a set without constant, zero or duplicate monomials.
706    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    /// Splits the domain of `factor` into `[-1, 0]` and `[0, 1]`. Each half
747    /// is exact and uses a fresh id for the rescaled factor
748    /// (`α = (α' ∓ 1) / 2`). Returns `(lower, upper)`.
749    ///
750    /// # Panics
751    ///
752    /// Panics if `factor` is not one of [`ids`](Self::ids), or if it appears
753    /// with an exponent above 56, where the binomial coefficients of the
754    /// rescaling are no longer exact in `f64`.
755    #[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    /// The half of the set where factor `k` lies between 0 and `sign`, with
767    /// `α_k = (α' + sign) / 2` substituted for a fresh factor `α'`.
768    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    /// Binomial expansion of monomial `i` after substituting
795    /// `α_k = (α' + sign) / 2`: one `(exponents, coefficient)` pair per power
796    /// `j` of `α'`, from
797    /// `(α'/2 + sign/2)^d = Σ_j C(d, j) (1/2)^d α'^j sign^(d-j)`.
798    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        // Repeated squaring, not `powi`: powers of 1/2 and ±1 are exact that way.
806        (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
817/// The parts of a set after [`SparsePolyZonotope::enclose_monomials`].
818struct Enclosed {
819    /// Center, shifted by the enclosed constant and `[0, 1]` monomials.
820    center: DVector<f64>,
821    /// Indices of the dependent generators that were not enclosed, in order.
822    kept: Vec<usize>,
823    /// New generators, one per enclosed non-constant monomial, each with its own `β`.
824    generators: Vec<DVector<f64>>,
825    /// Rounding-error bounds of the shifts and halvings.
826    errs: RowErrors,
827}
828
829/// `(aᵀ Qᵢ b + bᵀ Qᵢ a)ᵢ`, one entry per matrix, with rounding errors in `errs`.
830fn 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
843/// The coefficient of the monomial `m_a m_b m_c` in each cubic form of
844/// `maps` applied to `Σ hₜ mₜ`, for the columns `[h_a, h_b, h_c]` with
845/// `a ≤ b ≤ c`: `T(p, q, r)` summed over every distinct ordering of the
846/// three, with rounding errors in `errs`.
847fn 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
867/// Whether two orderings name the same columns at every position.
868fn 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
872/// Exponents of the product of two monomials.
873///
874/// # Panics
875///
876/// Panics if an exponent overflows `u32`.
877fn 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
884/// `x^n`, via [`f64::powi`] with the `std` feature and repeated squaring without it.
885///
886/// Exponents beyond `i32::MAX` take the repeated-squaring path in both cases.
887fn 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
896/// `x^n` by repeated squaring, in `O(log n)` multiplications; `x^0` is 1, also for `x = 0`.
897fn 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    /// Whether [`split`](Self::split) accepts `factor`: it is one of
913    /// [`ids`](Self::ids), and none of its exponents is above the limit of
914    /// `split`. Callers that pick factors to split can skip the others
915    /// instead of panicking.
916    #[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    /// [`can_split`](Self::can_split) for the factor in row `k`.
925    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
930/// Largest exponent [`SparsePolyZonotope::split`] accepts: every `C(d, j)` with
931/// `d <= 56` stays below `2^53`, so [`binomial`] and the coefficients
932/// `C(d, j) / 2^d` of the rescaling are exact.
933const MAX_SPLIT_EXPONENT: u32 = 56;
934
935/// Binomial coefficient `C(n, k)` for `k <= n`, exact for `n <=` [`MAX_SPLIT_EXPONENT`].
936///
937/// Integer arithmetic keeps every step exact: `C(n, i) (n - i)` is divisible by
938/// `i + 1` and below `2^63` for those `n`.
939#[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
947/// Union of the two id lists, with both exponent matrices re-indexed to it.
948fn 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/// Unit tests for the private power helpers, which the integration tests only
976/// reach through the `std` path.
977#[cfg(test)]
978mod tests {
979    use super::{pow_by_squaring, powu};
980
981    /// `x^n` as `n` plain multiplications, the reference both helpers must match.
982    fn naive_pow(x: f64, n: u32) -> f64 {
983        (0..n).fold(1.0, |acc, _| acc * x)
984    }
985
986    /// Repeated squaring agrees with plain multiplication, including `x^0 = 1` for `x = 0`.
987    #[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    /// Exponents beyond `i32::MAX` take the repeated-squaring path instead of panicking.
1001    #[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}