alkahest-cas 2.0.3

High-performance computer algebra kernel: symbolic expressions, polynomials, Gröbner bases, JIT, and Arb ball arithmetic.
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
//! V2-5 — Hermite and Smith normal forms for dense integer matrices (`IntegerMatrix`)
//! and polynomial matrices over ℚ (`PolyMatrixQ` / `RatUniPoly`).
//!
//! Integer Hermite form uses FLINT `fmpz_mat_hnf_transform` (Storjohann-class implementations
//! inside FLINT). Integer Smith form follows SymPy `smith_normal_decomp` (`U * M * V = S`).
//! Polynomial Hermite / Smith use the same column-elimination pattern over the Euclidean
//! domain `ℚ[x]`.

#![allow(
    clippy::needless_range_loop,
    clippy::cmp_owned,
    clippy::unnecessary_min_or_max
)]

use super::smith;
use super::smith_poly;

use crate::errors::AlkahestError;
use crate::flint::integer::FlintInteger;
use crate::flint::mat::FlintMat;
use rug::{Integer, Rational};
use std::fmt;
use std::ops::Mul;

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Errors from constructing or combining normal-form matrices.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NormalFormError {
    /// A row in a nested initializer had the wrong length.
    DimensionMismatch {
        row: usize,
        expected_cols: usize,
        got: usize,
    },
    /// `A * B` was requested but `A.cols != B.rows`.
    IncompatibleMultiply { left_cols: usize, right_rows: usize },
}

impl fmt::Display for NormalFormError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NormalFormError::DimensionMismatch {
                row,
                expected_cols,
                got,
            } => write!(f, "row {row} has {got} columns, expected {expected_cols}",),
            NormalFormError::IncompatibleMultiply {
                left_cols,
                right_rows,
            } => write!(
                f,
                "cannot multiply {left_cols}-wide matrix by matrix with {right_rows} rows",
            ),
        }
    }
}

impl std::error::Error for NormalFormError {}

impl AlkahestError for NormalFormError {
    fn code(&self) -> &'static str {
        match self {
            NormalFormError::DimensionMismatch { .. } => "E-NFM-001",
            NormalFormError::IncompatibleMultiply { .. } => "E-NFM-002",
        }
    }

    fn remediation(&self) -> Option<&'static str> {
        match self {
            NormalFormError::DimensionMismatch { .. } => {
                Some("every row in `IntegerMatrix::from_nested` must have equal width")
            }
            NormalFormError::IncompatibleMultiply { .. } => {
                Some("for `A * B`, use matrices where `A.cols == B.rows`")
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Integer matrices
// ---------------------------------------------------------------------------

/// Dense `m × n` matrix over ℤ (row-major).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IntegerMatrix {
    pub rows: usize,
    pub cols: usize,
    data: Vec<Integer>,
}

impl IntegerMatrix {
    /// Build from nested rows of `i64` (must be rectangular).
    pub fn from_nested(rows: Vec<Vec<i64>>) -> Result<Self, NormalFormError> {
        if rows.is_empty() {
            return Ok(Self {
                rows: 0,
                cols: 0,
                data: vec![],
            });
        }
        let cols = rows[0].len();
        let mut data = Vec::with_capacity(rows.len() * cols);
        for (ri, r) in rows.iter().enumerate() {
            if r.len() != cols {
                return Err(NormalFormError::DimensionMismatch {
                    row: ri,
                    expected_cols: cols,
                    got: r.len(),
                });
            }
            for &x in r {
                data.push(Integer::from(x));
            }
        }
        Ok(Self {
            rows: rows.len(),
            cols,
            data,
        })
    }

    fn from_rug_rows(rows: Vec<Vec<Integer>>) -> Result<Self, NormalFormError> {
        if rows.is_empty() {
            return Ok(Self {
                rows: 0,
                cols: 0,
                data: vec![],
            });
        }
        let cols = rows[0].len();
        let mut data = Vec::with_capacity(rows.len() * cols);
        for (ri, r) in rows.iter().enumerate() {
            if r.len() != cols {
                return Err(NormalFormError::DimensionMismatch {
                    row: ri,
                    expected_cols: cols,
                    got: r.len(),
                });
            }
            for x in r {
                data.push(x.clone());
            }
        }
        Ok(Self {
            rows: rows.len(),
            cols,
            data,
        })
    }

    #[inline]
    pub fn get(&self, r: usize, c: usize) -> &Integer {
        &self.data[r * self.cols + c]
    }

    /// Matrix product `self * other`.
    pub fn mul(&self, other: &IntegerMatrix) -> Result<Self, NormalFormError> {
        if self.cols != other.rows {
            return Err(NormalFormError::IncompatibleMultiply {
                left_cols: self.cols,
                right_rows: other.rows,
            });
        }
        let m = self.rows;
        let n = other.cols;
        let k = self.cols;
        let mut out = vec![Integer::from(0); m * n];
        for i in 0..m {
            for j in 0..n {
                let mut acc = Integer::from(0);
                for t in 0..k {
                    acc += self.get(i, t) * other.get(t, j);
                }
                out[i * n + j] = acc;
            }
        }
        Ok(IntegerMatrix {
            rows: m,
            cols: n,
            data: out,
        })
    }

    fn to_flint(&self) -> FlintMat {
        let mut a = FlintMat::new(self.rows, self.cols);
        for i in 0..self.rows {
            for j in 0..self.cols {
                let fi = FlintInteger::from_rug(self.get(i, j));
                a.set_entry(i, j, &fi);
            }
        }
        a
    }

    fn from_flint(m: &FlintMat) -> Self {
        let rows = m.rows();
        let cols = m.cols();
        let mut data = Vec::with_capacity(rows * cols);
        for i in 0..rows {
            for j in 0..cols {
                data.push(m.get_flint(i, j).to_rug());
            }
        }
        Self { rows, cols, data }
    }

    fn to_nested_integer(&self) -> Vec<Vec<Integer>> {
        (0..self.rows)
            .map(|i| (0..self.cols).map(|j| self.get(i, j).clone()).collect())
            .collect()
    }
}

/// Hermite normal form: returns `(H, U)` with `U * M = H`, where `U` is unimodular.
/// Uses FLINT `fmpz_mat_hnf_transform`.
pub fn hermite_form(m: &IntegerMatrix) -> (IntegerMatrix, IntegerMatrix) {
    if m.rows == 0 || m.cols == 0 {
        return (
            IntegerMatrix {
                rows: m.rows,
                cols: m.cols,
                data: vec![],
            },
            IntegerMatrix::identity(m.rows),
        );
    }
    let a = m.to_flint();
    let mut h = FlintMat::new(m.rows, m.cols);
    let mut u = FlintMat::new(m.rows, m.rows);
    a.hnf_transform(&mut h, &mut u);
    (IntegerMatrix::from_flint(&h), IntegerMatrix::from_flint(&u))
}

impl IntegerMatrix {
    fn identity(n: usize) -> Self {
        let mut data = vec![Integer::from(0); n * n];
        for i in 0..n {
            data[i * n + i] = Integer::from(1);
        }
        Self {
            rows: n,
            cols: n,
            data,
        }
    }
}

/// Smith normal form: `(S, U, V)` with `S == U * M * V`, `S` rectangular-diagonal, invariant
/// factors dividing along the diagonal.
pub fn smith_form(
    m: &IntegerMatrix,
) -> Result<(IntegerMatrix, IntegerMatrix, IntegerMatrix), NormalFormError> {
    if m.rows == 0 || m.cols == 0 {
        return Ok((
            IntegerMatrix {
                rows: m.rows,
                cols: m.cols,
                data: vec![],
            },
            IntegerMatrix::identity(m.rows),
            IntegerMatrix::identity(m.cols),
        ));
    }
    let (s, u, v) = smith::smith_normal_decomp(m.to_nested_integer());
    Ok((
        IntegerMatrix::from_rug_rows(s)?,
        IntegerMatrix::from_rug_rows(u)?,
        IntegerMatrix::from_rug_rows(v)?,
    ))
}

// ---------------------------------------------------------------------------
// ℚ[x] polynomials (dense, ascending degree)
// ---------------------------------------------------------------------------

/// Univariate polynomial over ℚ, `∑ cᵢ xⁱ`.
#[derive(Clone, Debug)]
pub struct RatUniPoly {
    /// Ascending coefficients; trailing zeros are stripped.
    pub coeffs: Vec<Rational>,
}

impl PartialEq for RatUniPoly {
    fn eq(&self, other: &Self) -> bool {
        self.coeffs == other.coeffs
    }
}

impl Eq for RatUniPoly {}

impl RatUniPoly {
    pub fn zero() -> Self {
        Self { coeffs: vec![] }
    }

    pub fn one() -> Self {
        Self {
            coeffs: vec![Rational::from(1)],
        }
    }

    pub fn constant(c: Rational) -> Self {
        if c == Rational::from(0) {
            Self::zero()
        } else {
            Self { coeffs: vec![c] }
        }
    }

    /// The polynomial `x`.
    pub fn x() -> Self {
        Self {
            coeffs: vec![Rational::from(0), Rational::from(1)],
        }
    }

    pub(crate) fn trim(mut self) -> Self {
        while self.coeffs.last() == Some(&Rational::from(0)) {
            self.coeffs.pop();
        }
        self
    }

    pub fn degree(&self) -> i32 {
        self.coeffs.len() as i32 - 1
    }

    pub fn is_zero(&self) -> bool {
        self.coeffs.is_empty()
    }

    pub(crate) fn leading_coeff(&self) -> Rational {
        self.coeffs
            .last()
            .cloned()
            .unwrap_or_else(|| Rational::from(0))
    }

    /// Euclidean division: `a = q * b + r`, `deg r < deg b` (or `r = 0`).
    pub fn div_rem(a: &Self, b: &Self) -> (Self, Self) {
        assert!(!b.is_zero());
        let mut a = a.clone();
        let mut a_c = std::mem::take(&mut a.coeffs);
        let b = b.clone().trim();
        let b_c = &b.coeffs;
        let db = b_c.len() as i32 - 1;
        let lb = b_c[b_c.len() - 1].clone();

        let mut q = vec![Rational::from(0); (a_c.len().saturating_sub(b_c.len()) + 1).max(0)];

        while a_c.len() as i32 > db && a_c.last().map(|v| v != &Rational::from(0)).unwrap_or(false)
        {
            let da = a_c.len() as i32 - 1;
            let la = a_c.last().unwrap().clone();
            let shift = (da - db) as usize;
            if shift >= q.len() {
                q.resize(shift + 1, Rational::from(0));
            }
            let t = la / &lb;
            q[shift] += &t;
            for j in 0..b_c.len() {
                let i = shift + j;
                let prod = t.clone() * b_c[j].clone();
                a_c[i] -= &prod;
            }
            while a_c.last() == Some(&Rational::from(0)) {
                a_c.pop();
            }
        }

        let q_poly = RatUniPoly { coeffs: q }.trim();
        let r_poly = RatUniPoly { coeffs: a_c }.trim();
        (q_poly, r_poly)
    }

    pub fn gcd(&self, other: &Self) -> Self {
        let mut a = self.clone();
        let mut b = other.clone();
        if a.degree() < b.degree() {
            std::mem::swap(&mut a, &mut b);
        }
        while !b.is_zero() {
            let (_, r) = RatUniPoly::div_rem(&a, &b);
            a = b;
            b = r;
        }
        if a.is_zero() {
            RatUniPoly::zero()
        } else {
            let mut g = a.trim();
            let lc = g.leading_coeff();
            for c in &mut g.coeffs {
                *c /= lc.clone();
            }
            g.trim()
        }
    }

    pub fn gcdex(a: &Self, b: &Self) -> (Self, Self, Self) {
        if b.is_zero() {
            if a.is_zero() {
                return (Self::zero(), Self::one(), Self::zero());
            }
            let mut an = a.clone().trim();
            let lc = an.leading_coeff();
            let inv = Rational::from(1) / lc.clone();
            for c in &mut an.coeffs {
                *c *= inv.clone();
            }
            let an = an.trim();
            return (Self::constant(inv), Self::zero(), an);
        }
        let (q, r) = Self::div_rem(a, b);
        let (s1, t1, g) = Self::gcdex(b, &r);
        let qt = &q * &t1;
        let tt = &s1 - &qt;
        (t1, tt.trim(), g)
    }

    pub(super) fn exquo(&self, g: &Self) -> Self {
        let (q, r) = RatUniPoly::div_rem(self, g);
        if !r.is_zero() {
            panic!("RatUniPoly::exquo: not divisible");
        }
        q
    }
}

impl std::ops::Add for &RatUniPoly {
    type Output = RatUniPoly;
    fn add(self, rhs: &RatUniPoly) -> RatUniPoly {
        let n = self.coeffs.len().max(rhs.coeffs.len());
        let mut c = vec![Rational::from(0); n];
        for i in 0..n {
            if i < self.coeffs.len() {
                c[i] += self.coeffs[i].clone();
            }
            if i < rhs.coeffs.len() {
                c[i] += rhs.coeffs[i].clone();
            }
        }
        RatUniPoly { coeffs: c }.trim()
    }
}

impl std::ops::Sub for &RatUniPoly {
    type Output = RatUniPoly;
    fn sub(self, rhs: &RatUniPoly) -> RatUniPoly {
        let n = self.coeffs.len().max(rhs.coeffs.len());
        let mut c = vec![Rational::from(0); n];
        for i in 0..n {
            if i < self.coeffs.len() {
                c[i] += self.coeffs[i].clone();
            }
            if i < rhs.coeffs.len() {
                c[i] -= rhs.coeffs[i].clone();
            }
        }
        RatUniPoly { coeffs: c }.trim()
    }
}

impl Mul for RatUniPoly {
    type Output = Self;
    fn mul(self, rhs: Self) -> Self {
        (&self).mul(&rhs)
    }
}

impl std::ops::Mul for &RatUniPoly {
    type Output = RatUniPoly;
    fn mul(self, rhs: &RatUniPoly) -> RatUniPoly {
        if self.is_zero() || rhs.is_zero() {
            return RatUniPoly::zero();
        }
        let mut c = vec![Rational::from(0); self.coeffs.len() + rhs.coeffs.len() - 1];
        for (i, a) in self.coeffs.iter().enumerate() {
            for (j, b) in rhs.coeffs.iter().enumerate() {
                c[i + j] += a.clone() * b;
            }
        }
        RatUniPoly { coeffs: c }.trim()
    }
}

impl std::ops::Neg for &RatUniPoly {
    type Output = RatUniPoly;
    fn neg(self) -> RatUniPoly {
        let coeffs = self.coeffs.iter().map(|c| -c.clone()).collect();
        RatUniPoly { coeffs }.trim()
    }
}

// ---------------------------------------------------------------------------
// Polynomial matrices over ℚ[x]
// ---------------------------------------------------------------------------

/// Rectangular matrix whose entries are univariate polynomials over ℚ.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PolyMatrixQ {
    pub rows: usize,
    pub cols: usize,
    data: Vec<RatUniPoly>,
}

impl PolyMatrixQ {
    pub(super) fn shell(rows: usize, cols: usize) -> Self {
        Self {
            rows,
            cols,
            data: vec![],
        }
    }

    pub fn from_nested(rows: Vec<Vec<RatUniPoly>>) -> Result<Self, NormalFormError> {
        if rows.is_empty() {
            return Ok(Self {
                rows: 0,
                cols: 0,
                data: vec![],
            });
        }
        let cols = rows[0].len();
        let mut data = Vec::with_capacity(rows.len() * cols);
        for (ri, r) in rows.iter().enumerate() {
            if r.len() != cols {
                return Err(NormalFormError::DimensionMismatch {
                    row: ri,
                    expected_cols: cols,
                    got: r.len(),
                });
            }
            for p in r {
                data.push(p.clone());
            }
        }
        Ok(Self {
            rows: rows.len(),
            cols,
            data,
        })
    }

    #[inline]
    pub fn get(&self, r: usize, c: usize) -> &RatUniPoly {
        &self.data[r * self.cols + c]
    }

    pub fn mul(&self, other: &PolyMatrixQ) -> Result<Self, NormalFormError> {
        if self.cols != other.rows {
            return Err(NormalFormError::IncompatibleMultiply {
                left_cols: self.cols,
                right_rows: other.rows,
            });
        }
        let m = self.rows;
        let n = other.cols;
        let k = self.cols;
        let mut out = Vec::with_capacity(m * n);
        for i in 0..m {
            for j in 0..n {
                let mut acc = RatUniPoly::zero();
                for t in 0..k {
                    let prod = self.get(i, t).clone() * other.get(t, j).clone();
                    acc = (&acc + &prod).trim();
                }
                out.push(acc);
            }
        }
        Ok(PolyMatrixQ {
            rows: m,
            cols: n,
            data: out,
        })
    }

    fn transpose(&self) -> PolyMatrixQ {
        let mut data = Vec::with_capacity(self.rows * self.cols);
        for j in 0..self.cols {
            for i in 0..self.rows {
                data.push(self.get(i, j).clone());
            }
        }
        PolyMatrixQ {
            rows: self.cols,
            cols: self.rows,
            data,
        }
    }
}

/// Hermite column-form on `Mᵀ`, then transpose — yields `(H, U)` with `U * M = H`
/// for the row-style convention used by integer matrices.
pub fn hermite_form_poly(m: &PolyMatrixQ) -> (PolyMatrixQ, PolyMatrixQ) {
    let mt = m.transpose();
    let (ht, v) = smith_poly::hermite_column_poly(&mt);
    (ht.transpose(), v.transpose())
}

/// Smith normal form over `ℚ[x]`: `(S, U, V)` with `S == U * M * V`.
pub fn smith_form_poly(m: &PolyMatrixQ) -> (PolyMatrixQ, PolyMatrixQ, PolyMatrixQ) {
    smith_poly::smith_normal_poly(m)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use rug::Complete;

    #[test]
    fn hnf_transform_matches_flint_and_um_equals_h() {
        let m = IntegerMatrix::from_nested(vec![vec![12, 6, 4], vec![3, 9, 6], vec![2, 16, 14]])
            .unwrap();
        let (h, u) = hermite_form(&m);
        let um = u.mul(&m).unwrap();
        assert_eq!(um, h);
        let fh = h.to_flint();
        assert!(fh.is_in_hnf());
    }

    #[test]
    fn snf_sympy_example_3x3() {
        let m = IntegerMatrix::from_nested(vec![vec![12, 6, 4], vec![3, 9, 6], vec![2, 16, 14]])
            .unwrap();
        let (s, u, v) = smith_form(&m).unwrap();
        let umv = u.mul(&m).unwrap().mul(&v).unwrap();
        assert_eq!(umv, s);
        assert!(s.to_flint().is_in_snf());
        // invariant divisibility on diagonal
        let d = m.rows.min(m.cols);
        for i in 0..d.saturating_sub(1) {
            let a = s.get(i, i).clone();
            let b = s.get(i + 1, i + 1).clone();
            if a != Integer::from(0) && b != Integer::from(0) {
                let (_, r) = b.div_rem_floor_ref(&a).complete();
                assert_eq!(r, Integer::from(0));
            }
        }
    }

    #[test]
    fn snf_random_small_matches_flint_diagonal() {
        use rug::rand::RandState;
        let mut rand = RandState::new();
        for _ in 0..30 {
            let mut rows = vec![];
            for _ in 0..4 {
                let mut r = vec![];
                for _ in 0..4 {
                    let x: u32 = rand.bits(6);
                    r.push(x as i64);
                }
                rows.push(r);
            }
            let m = IntegerMatrix::from_nested(rows).unwrap();
            let (s, u, v) = smith_form(&m).unwrap();
            let umv = u.mul(&m).unwrap().mul(&v).unwrap();
            assert_eq!(umv, s);
            let fa = m.to_flint();
            let mut fs = FlintMat::new(m.rows, m.cols);
            fa.snf_diagonal(&mut fs);
            assert!(s.to_flint().equals(&fs));
        }
    }

    #[test]
    fn poly_hermite_and_smith_diag_x() {
        let x = RatUniPoly::x();
        let z = RatUniPoly::zero();
        let m =
            PolyMatrixQ::from_nested(vec![vec![x.clone(), z.clone()], vec![z.clone(), x.clone()]])
                .unwrap();
        let (h, u) = hermite_form_poly(&m);
        let um = u.mul(&m).unwrap();
        assert_eq!(um, h);

        let (s, us, vs) = smith_form_poly(&m);
        let prod = us.mul(&m).unwrap().mul(&vs).unwrap();
        assert_eq!(prod, s);
    }
}