rssn 0.2.9

A comprehensive scientific computing library for Rust, aiming for feature parity with NumPy and SymPy.
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
#![allow(clippy::match_same_arms)]

//! # Gröbner Bases
//!
//! This module provides functions for computing Gröbner bases of polynomial ideals.
//! It includes implementations for multivariate polynomial division, S-polynomial computation,
//! and Buchberger's algorithm for generating a Gröbner basis. Monomial orderings are also supported.
//!
//! ## Overview
//!
//! A Gröbner basis is a particular kind of generating set of an ideal in a polynomial ring.
//! Gröbner bases have many applications in computational algebra, including:
//! - Solving systems of polynomial equations
//! - Ideal membership testing
//! - Computing polynomial remainders
//! - Elimination theory
//!
//! ## Examples
//!
//! ### Computing a Gröbner Basis
//!
//! **Demo One**
//!
//! ```rust
//! use std::collections::BTreeMap;
//!
//! use rssn::symbolic::core::Expr;
//! use rssn::symbolic::core::Monomial;
//! use rssn::symbolic::core::SparsePolynomial;
//! use rssn::symbolic::grobner::MonomialOrder;
//! use rssn::symbolic::grobner::buchberger;
//!
//! // Create polynomials: x^2 - y and xy - 1
//! let mut poly1_terms = BTreeMap::new();
//!
//! let mut mono1 = BTreeMap::new();
//!
//! mono1.insert("x".to_string(), 2);
//!
//! poly1_terms.insert(Monomial(mono1), Expr::new_constant(1.0));
//!
//! let mut mono2 = BTreeMap::new();
//!
//! mono2.insert("y".to_string(), 1);
//!
//! poly1_terms.insert(Monomial(mono2), Expr::new_constant(-1.0));
//!
//! let poly1 = SparsePolynomial { terms: poly1_terms };
//!
//! // Compute Gröbner basis
//! let basis = vec![poly1];
//!
//! let grobner = buchberger(&basis, MonomialOrder::Lexicographical).unwrap();
//! ```
//!
//! **Demo Two**
//!
//! ```rust
//! // Grobner Basis Computation Example
//!
//! // This example demonstrates how to compute the Grobner basis for a system of
//! // polynomial equations using Buchberger's algorithm.
//!
//! // We will compute the Grobner basis for the intersection of two circles:
//! // Equation 1: x^2 + y^2 - 1 = 0
//! // Equation 2: (x-1)^2 + y^2 - 1 = 0  => x^2 - 2x + y^2 = 0
//!
//! use rssn::input::parser::parse_expr;
//! use rssn::symbolic::core::Expr;
//! use rssn::symbolic::core::SparsePolynomial;
//! use rssn::symbolic::grobner::MonomialOrder;
//! use rssn::symbolic::grobner::buchberger;
//! use rssn::symbolic::polynomial::expr_to_sparse_poly;
//! use rssn::symbolic::polynomial::sparse_poly_to_expr;
//!
//! println!("=== Grobner Basis Computation Example ===\n");
//!
//! // Define the polynomial equations as strings
//! let input1 = "x^2 + y^2 - 1";
//! let input2 = "x^2 - 2*x + y^2";
//!
//! // Parse the strings into expressions
//! let f1_expr = match parse_expr(input1) {
//!     | Ok(("", expr)) => expr,
//!     | Ok((rem, _)) => panic!("Unparsed input: '{}'", rem),
//!     | Err(e) => panic!("Failed to parse expression '{}': {:?}", input1, e),
//! };
//!
//! let f2_expr = match parse_expr(input2) {
//!     | Ok(("", expr)) => expr,
//!     | Ok((rem, _)) => panic!("Unparsed input: '{}'", rem),
//!     | Err(e) => panic!("Failed to parse expression '{}': {:?}", input2, e),
//! };
//!
//! println!("Polynomial 1 (f1): {}", f1_expr);
//! println!("Polynomial 2 (f2): {}\n", f2_expr);
//!
//! // Convert expressions to SparsePolynomial
//! let f1_sparse = expr_to_sparse_poly(&f1_expr, &["x", "y"]);
//! let f2_sparse = expr_to_sparse_poly(&f2_expr, &["x", "y"]);
//!
//! // Create the basis for Buchberger's algorithm
//! let basis = vec![f1_sparse, f2_sparse];
//!
//! println!("Computing Grobner basis using Lexicographical order...\n");
//!
//! // Compute the Grobner basis
//! match buchberger(&basis, MonomialOrder::Lexicographical) {
//!     | Ok(grobner_basis) => {
//!         println!("Grobner Basis:");
//!         for (i, poly) in grobner_basis.iter().enumerate() {
//!             println!("  g{}: {}", i + 1, sparse_poly_to_expr(poly));
//!         }
//!     },
//!     | Err(e) => {
//!         eprintln!("Error computing Grobner basis: {}", e);
//!     },
//! }
//!
//! println!("\n=== Example Complete ===");
//! ```
//!
//! **Demo Three**
//!
//! ```rust
//! // Grobner Basis Computation Example
//! //
//! // This example demonstrates how to compute the Grobner basis for a system of
//! // polynomial equations using Buchberger's algorithm.
//! //
//! // We will compute the Grobner basis for the intersection of two circles:
//! // Equation 1: x^2 + y^2 - 1 = 0
//! // Equation 2: (x-1)^2 + y^2 - 1 = 0  => x^2 - 2x + y^2 = 0
//!
//! use std::collections::BTreeMap;
//! use std::ops::Add;
//! use std::ops::Mul;
//! use std::ops::Sub;
//!
//! use rssn::symbolic::core::Expr;
//! use rssn::symbolic::core::Monomial;
//! use rssn::symbolic::core::SparsePolynomial;
//! use rssn::symbolic::grobner::MonomialOrder;
//! use rssn::symbolic::grobner::buchberger;
//! use rssn::symbolic::polynomial::sparse_poly_to_expr;
//!
//! // Helper function to create a SparsePolynomial from a single variable.
//! fn var_poly(name: &str) -> SparsePolynomial {
//!     let mut terms = BTreeMap::new();
//!     let mut mono = BTreeMap::new();
//!     mono.insert(name.to_string(), 1);
//!     terms.insert(Monomial(mono), Expr::Constant(1.0));
//!     SparsePolynomial { terms }
//! }
//!
//! // Helper function to create a SparsePolynomial from a constant.
//! fn const_poly(value: f64) -> SparsePolynomial {
//!     let mut terms = BTreeMap::new();
//!     terms.insert(Monomial(BTreeMap::new()), Expr::Constant(value));
//!     SparsePolynomial { terms }
//! }
//!
//!
//! println!("=== Grobner Basis Computation Example ===\n");
//!
//! // Define variables and constants as SparsePolynomials
//! let x = var_poly("x");
//! let y = var_poly("y");
//! let one = const_poly(1.0);
//! let two = const_poly(2.0);
//!
//! // Equation 1: x^2 + y^2 - 1 = 0
//! let f1_sparse = (x.clone() * x.clone())
//!     .add(y.clone() * y.clone())
//!     .sub(one.clone());
//! println!("Polynomial 1 (f1): {}", sparse_poly_to_expr(&f1_sparse));
//!
//! // Equation 2: x^2 - 2x + y^2 = 0
//! let f2_sparse = (x.clone() * x.clone())
//!     .sub(two.clone() * x.clone())
//!     .add(y.clone() * y.clone());
//! println!("Polynomial 2 (f2): {}\n", sparse_poly_to_expr(&f2_sparse));
//!
//! // Create the basis for Buchberger's algorithm
//! let basis = vec![f1_sparse, f2_sparse];
//!
//! println!("Computing Grobner basis using Lexicographical order...\n");
//!
//! // Compute the Grobner basis
//! match buchberger(&basis, MonomialOrder::Lexicographical) {
//!     | Ok(grobner_basis) => {
//!         println!("Grobner Basis:");
//!         for (i, poly) in grobner_basis.iter().enumerate() {
//!             println!("  g{}: {}", i + 1, sparse_poly_to_expr(poly));
//!         }
//!     },
//!     | Err(e) => {
//!         eprintln!("Error computing Grobner basis: {}", e);
//!     },
//! }
//!
//! println!("\n=== Example Complete ===");
//! ```
//!
//! **Demo Four**
//!
//! ```rust
//! // Grobner Basis Computation Example
//! //
//! // This example demonstrates how to compute the Grobner basis for a system of
//! // polynomial equations using Buchberger's algorithm.
//! //
//! // We will compute the Grobner basis for the intersection of two circles:
//! // Equation 1: x^2 + y^2 - 1 = 0
//! // Equation 2: (x-1)^2 + y^2 - 1 = 0  => x^2 - 2x + y^2 = 0
//!
//! use std::collections::BTreeMap;
//!
//! use rssn::symbolic::core::Expr;
//! use rssn::symbolic::core::Monomial;
//! use rssn::symbolic::core::SparsePolynomial;
//! use rssn::symbolic::grobner::MonomialOrder;
//! use rssn::symbolic::grobner::buchberger;
//! use rssn::symbolic::polynomial::expr_to_sparse_poly;
//! use rssn::symbolic::polynomial::sparse_poly_to_expr;
//!
//!
//! println!(
//!     "=== Grobner Basis \
//!          Computation Example ===\n"
//! );
//!
//! // Define the variables
//! let x = Expr::new_variable("x");
//!
//! let y = Expr::new_variable("y");
//!
//! let one = Expr::new_constant(1.0);
//!
//! let two = Expr::new_constant(2.0);
//!
//! // Equation 1: x^2 + y^2 - 1 = 0
//! let f1_expr = Expr::new_sub(
//!     Expr::new_add(
//!         Expr::new_pow(x.clone(), two.clone()),
//!         Expr::new_pow(y.clone(), two.clone()),
//!     ),
//!     one.clone(),
//! );
//!
//! println!("Polynomial 1 (f1): {}", f1_expr);
//!
//! // Equation 2: (x-1)^2 + y^2 - 1 = 0  => x^2 - 2x + y^2 = 0
//! let f2_expr = Expr::new_add(
//!     Expr::new_sub(
//!         Expr::new_pow(x.clone(), two.clone()),
//!         Expr::new_mul(two.clone(), x.clone()),
//!     ),
//!     Expr::new_pow(y.clone(), two.clone()),
//! );
//!
//! println!("Polynomial 2 (f2): {}\n", f2_expr);
//!
//! // Convert expressions to SparsePolynomial
//! let f1_sparse = expr_to_sparse_poly(&f1_expr, &["x", "y"]);
//!
//! let f2_sparse = expr_to_sparse_poly(&f2_expr, &["x", "y"]);
//!
//! // Create the basis for Buchberger's algorithm
//! let basis = vec![f1_sparse, f2_sparse];
//!
//! println!(
//!     "Computing Grobner basis \
//!          using Lexicographical \
//!          order...\n"
//! );
//!
//! // Compute the Grobner basis
//! match buchberger(&basis, MonomialOrder::Lexicographical) {
//!     | Ok(grobner_basis) => {
//!         println!("Grobner Basis:");
//!
//!         for (i, poly) in grobner_basis.iter().enumerate() {
//!             println!("  g{}: {}", i + 1, sparse_poly_to_expr(poly));
//!         }
//!     },
//!     | Err(e) => {
//!         eprintln!(
//!             "Error computing \
//!                  Grobner basis: {}",
//!             e
//!         );
//!     },
//! }
//!
//! println!("\n=== Example Complete ===");
//! ```

use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::collections::BTreeSet;

use crate::symbolic::core::Expr;
use crate::symbolic::core::Monomial;
use crate::symbolic::core::SparsePolynomial;
use crate::symbolic::polynomial::add_poly;
use crate::symbolic::polynomial::mul_poly;
use crate::symbolic::simplify::is_zero;
use crate::symbolic::simplify_dag::simplify;

/// Defines the monomial ordering to be used in polynomial division.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
#[repr(C)]
pub enum MonomialOrder {
    /// Dictionary order: compares exponents of variables in a fixed sequence.
    Lexicographical,
    /// Compares total degree first, then uses lexicographical order to break ties.
    GradedLexicographical,
    /// Compares total degree first, then uses reverse lexicographical order to break ties.
    GradedReverseLexicographical,
}

/// Compares two monomials based on a given ordering.
pub(crate) fn compare_monomials(
    m1: &Monomial,
    m2: &Monomial,
    order: MonomialOrder,
) -> Ordering {
    match order {
        | MonomialOrder::Lexicographical => compare_lex(m1, m2),
        | MonomialOrder::GradedLexicographical => {
            let deg1: u32 = m1.0.values().sum();
            let deg2: u32 = m2.0.values().sum();
            match deg1.cmp(&deg2) {
                | Ordering::Equal => compare_lex(m1, m2),
                | other => other,
            }
        },
        | MonomialOrder::GradedReverseLexicographical => {
            let deg1: u32 = m1.0.values().sum();
            let deg2: u32 = m2.0.values().sum();
            match deg1.cmp(&deg2) {
                | Ordering::Equal => compare_revlex(m1, m2),
                | other => other,
            }
        },
    }
}

pub(crate) fn compare_lex(
    m1: &Monomial,
    m2: &Monomial,
) -> Ordering {
    let all_vars: BTreeSet<&String> = m1.0.keys().chain(m2.0.keys()).collect();

    for var in all_vars {
        let e1 = m1.0.get(var).unwrap_or(&0);

        let e2 = m2.0.get(var).unwrap_or(&0);

        match e1.cmp(e2) {
            | Ordering::Equal => {
                continue;
            },
            | other => return other,
        }
    }

    Ordering::Equal
}

pub(crate) fn compare_revlex(
    m1: &Monomial,
    m2: &Monomial,
) -> Ordering {
    let mut all_vars: Vec<&String> = m1.0.keys().chain(m2.0.keys()).collect();

    all_vars.sort();

    all_vars.dedup();

    for var in all_vars.iter().rev() {
        let e1 = m1.0.get(*var).unwrap_or(&0);

        let e2 = m2.0.get(*var).unwrap_or(&0);

        match e1.cmp(e2) {
            | Ordering::Equal => continue,
            | Ordering::Greater => return Ordering::Less,
            | Ordering::Less => return Ordering::Greater,
        }
    }

    Ordering::Equal
}

/// Performs division of a multivariate polynomial `f` by a set of divisors `F`.
///
/// This function implements the multivariate division algorithm, which is a generalization
/// of polynomial long division. It repeatedly subtracts multiples of the divisors from `f`
/// until a remainder is obtained that cannot be further reduced.
///
/// # Arguments
/// * `f` - The dividend polynomial.
/// * `divisors` - A slice of `SparsePolynomial`s representing the divisors.
/// * `order` - The `MonomialOrder` to use for division.
///
/// # Returns
/// A tuple `(quotients, remainder)` where `quotients` is a `Vec<SparsePolynomial>`
/// (one for each divisor) and `remainder` is a `SparsePolynomial`.
///
/// # Errors
///
/// This function will return an error if there is a logic error during term processing,
/// such as a leading term not being found in the polynomial or divisor terms.
pub fn poly_division_multivariate(
    f: &SparsePolynomial,
    divisors: &[SparsePolynomial],
    order: MonomialOrder,
) -> Result<(Vec<SparsePolynomial>, SparsePolynomial), String> {
    let mut quotients = vec![
        SparsePolynomial {
            terms: BTreeMap::new()
        };
        divisors.len()
    ];

    let mut remainder = SparsePolynomial {
        terms: BTreeMap::new(),
    };

    let mut p = f.clone();

    while !p.terms.is_empty() {
        let mut division_occurred = false;

        let lead_term_p = match p.terms.keys().max_by(|a, b| compare_monomials(a, b, order)) {
            | Some(lt) => lt.clone(),
            | None => continue,
        };

        for (i, divisor) in divisors.iter().enumerate() {
            if divisor.terms.is_empty() {
                continue;
            }

            let lead_term_g = match divisor
                .terms
                .keys()
                .max_by(|a, b| compare_monomials(a, b, order))
            {
                | Some(lt) => lt.clone(),
                | None => unreachable!(),
            };

            if is_divisible(&lead_term_p, &lead_term_g) {
                let coeff_p = match p.terms.get(&lead_term_p) {
                    | Some(c) => c,
                    | None => {
                        return Err("Logic error: lead term not in polynomial terms".to_string());
                    },
                };

                let coeff_g = match divisor.terms.get(&lead_term_g) {
                    | Some(c) => c,
                    | None => {
                        return Err("Logic error: lead term not found in divisor terms".to_string());
                    },
                };

                let coeff_ratio = simplify(&Expr::new_div(coeff_p.clone(), coeff_g.clone()));

                let mono_ratio = subtract_monomials(&lead_term_p, &lead_term_g);

                let mut t_terms = BTreeMap::new();

                t_terms.insert(mono_ratio, coeff_ratio);

                let t = SparsePolynomial { terms: t_terms };

                quotients[i] = add_poly(&quotients[i], &t);

                let t_g = mul_poly(&t, divisor);

                p = subtract_poly(&p, &t_g);

                division_occurred = true;

                break;
            }
        }

        if !division_occurred {
            let coeff = match p.terms.remove(&lead_term_p) {
                | Some(c) => c,
                | None => {
                    return Err("Logic error: lead term not found for removal".to_string());
                },
            };

            remainder.terms.insert(lead_term_p, coeff);
        }
    }

    Ok((quotients, remainder))
}

pub(crate) fn is_divisible(
    m1: &Monomial,
    m2: &Monomial,
) -> bool {
    m2.0.iter()
        .all(|(var, exp2)| m1.0.get(var).is_some_and(|exp1| exp1 >= exp2))
}

pub(crate) fn subtract_monomials(
    m1: &Monomial,
    m2: &Monomial,
) -> Monomial {
    let mut result = m1.0.clone();

    for (var, exp2) in &m2.0 {
        let exp1 = result.entry(var.clone()).or_insert(0);

        *exp1 -= exp2;
    }

    Monomial(result.into_iter().filter(|(_, exp)| *exp > 0).collect())
}

/// Subtracts one polynomial from another.
///
/// # Arguments
/// * `p1` - The first polynomial.
/// * `p2` - The second polynomial.
///
/// # Returns
/// A `SparsePolynomial` representing `p1 - p2`.
#[must_use]
pub fn subtract_poly(
    p1: &SparsePolynomial,
    p2: &SparsePolynomial,
) -> SparsePolynomial {
    let mut result_terms = p1.terms.clone();

    for (mono, coeff) in &p2.terms {
        let entry = result_terms
            .entry(mono.clone())
            .or_insert_with(|| Expr::Constant(0.0));

        *entry = simplify(&Expr::new_sub(entry.clone(), coeff.clone()));
    }

    result_terms.retain(|_, v| !is_zero(v));

    SparsePolynomial { terms: result_terms }
}

/// Computes the leading term (monomial, coefficient) of a polynomial.
pub(crate) fn leading_term(
    p: &SparsePolynomial,
    order: MonomialOrder,
) -> Option<(Monomial, Expr)> {
    p.terms
        .iter()
        .max_by(|(m1, _), (m2, _)| compare_monomials(m1, m2, order))
        .map(|(m, c)| (m.clone(), c.clone()))
}

/// Computes the least common multiple (LCM) of two monomials.
pub(crate) fn lcm_monomial(
    m1: &Monomial,
    m2: &Monomial,
) -> Monomial {
    let mut lcm_map = m1.0.clone();

    for (var, &exp2) in &m2.0 {
        let exp1 = lcm_map.entry(var.clone()).or_insert(0);

        *exp1 = std::cmp::max(*exp1, exp2);
    }

    Monomial(lcm_map)
}

/// Computes the S-polynomial of two polynomials.
/// S(f, g) = (lcm(LM(f), LM(g)) / LT(f)) * f - (lcm(LM(f), LM(g)) / LT(g)) * g
pub(crate) fn s_polynomial(
    p1: &SparsePolynomial,
    p2: &SparsePolynomial,
    order: MonomialOrder,
) -> Option<SparsePolynomial> {
    let (lm1, lc1) = leading_term(p1, order)?;

    let (lm2, lc2) = leading_term(p2, order)?;

    let lcm = lcm_monomial(&lm1, &lm2);

    let t1_mono = subtract_monomials(&lcm, &lm1);

    let t1_coeff = simplify(&Expr::new_div(Expr::Constant(1.0), lc1));

    let mut t1_terms = BTreeMap::new();

    t1_terms.insert(t1_mono, t1_coeff);

    let t1 = SparsePolynomial { terms: t1_terms };

    let t2_mono = subtract_monomials(&lcm, &lm2);

    let t2_coeff = simplify(&Expr::new_div(Expr::Constant(1.0), lc2));

    let mut t2_terms = BTreeMap::new();

    t2_terms.insert(t2_mono, t2_coeff);

    let t2 = SparsePolynomial { terms: t2_terms };

    let term1 = mul_poly(&t1, p1);

    let term2 = mul_poly(&t2, p2);

    Some(subtract_poly(&term1, &term2))
}

/// Computes a Gröbner basis for a polynomial ideal using Buchberger's algorithm.
///
/// Buchberger's algorithm takes a set of generators for a polynomial ideal and
/// produces a Gröbner basis for that ideal. A Gröbner basis has many desirable
/// properties, such as simplifying polynomial division and solving systems of
/// polynomial equations.
///
/// # Arguments
/// * `basis` - A slice of `SparsePolynomial`s representing the initial generators of the ideal.
/// * `order` - The `MonomialOrder` to use for computations.
///
/// # Returns
/// A `Vec<SparsePolynomial>` representing the Gröbner basis.
///
/// # Errors
///
/// This function will return an error if `poly_division_multivariate` encounters
/// an error during the reduction of S-polynomials.
pub fn buchberger(
    basis: &[SparsePolynomial],
    order: MonomialOrder,
) -> Result<Vec<SparsePolynomial>, String> {
    if basis.is_empty() {
        return Ok(vec![]);
    }

    let mut g = basis.to_vec();

    let mut pairs: Vec<(usize, usize)> = (0..g.len())
        .flat_map(|i| (i + 1..g.len()).map(move |j| (i, j)))
        .collect();

    while let Some((i, j)) = pairs.pop() {
        if let Some(s_poly) = s_polynomial(&g[i], &g[j], order) {
            let (_, remainder) = poly_division_multivariate(&s_poly, &g, order)?;

            if !remainder.terms.is_empty() {
                let new_poly_idx = g.len();

                for k in 0..new_poly_idx {
                    pairs.push((k, new_poly_idx));
                }

                g.push(remainder);
            }
        }
    }

    Ok(reduced_basis(g, order))
}

/// Reduces a Gröbner basis to its reduced form.
///
/// A reduced Gröbner basis is a unique (for a given order) basis where:
/// 1. The leading coefficient of each polynomial is 1.
/// 2. For each polynomial p in the basis, no monomial in p is divisible by any LT(g) for g in G \ {p}.
pub fn reduced_basis(
    basis: Vec<SparsePolynomial>,
    order: MonomialOrder,
) -> Vec<SparsePolynomial> {
    if basis.is_empty() {
        return vec![];
    }

    // 1. Get a minimal basis
    let mut minimal = Vec::new();

    let mut sorted_basis = basis;

    sorted_basis.retain(|p| !p.terms.is_empty());

    for i in 0..sorted_basis.len() {
        let lt_i = match leading_term(&sorted_basis[i], order) {
            | Some((m, _)) => m,
            | None => continue,
        };

        let mut redundant = false;

        for (j, other_poly) in sorted_basis.iter().enumerate() {
            if i == j {
                continue;
            }

            let lt_j = match leading_term(other_poly, order) {
                | Some((m, _)) => m,
                | None => continue,
            };

            if is_divisible(&lt_i, &lt_j) {
                // If LT_j divides LT_i, then LT_i is redundant.
                if lt_i != lt_j || i > j {
                    redundant = true;

                    break;
                }
            }
        }

        if !redundant {
            minimal.push(sorted_basis[i].clone());
        }
    }

    // 2. Reduce each polynomial by the others
    let mut reduced = Vec::new();

    for i in 0..minimal.len() {
        let mut others = minimal.clone();

        others.remove(i);

        let (_, rem) = poly_division_multivariate(&minimal[i], &others, order)
            .unwrap_or_else(|_| (vec![], minimal[i].clone()));

        // 3. Make monic
        if let Some((_, lc)) = leading_term(&rem, order) {
            let mut monic_terms = BTreeMap::new();

            for (m, c) in rem.terms {
                let monic_c = simplify(&Expr::new_div(c, lc.clone()));

                if !is_zero(&monic_c) {
                    monic_terms.insert(m, monic_c);
                }
            }

            reduced.push(SparsePolynomial { terms: monic_terms });
        }
    }

    reduced.sort_by(|p1, p2| {
        let lt1 = leading_term(p1, order).map(|(m, _)| m);

        let lt2 = leading_term(p2, order).map(|(m, _)| m);

        match (lt1, lt2) {
            | (Some(m1), Some(m2)) => compare_monomials(&m1, &m2, order),
            | (Some(_), None) => Ordering::Greater,
            | (None, Some(_)) => Ordering::Less,
            | (None, None) => Ordering::Equal,
        }
    });

    reduced
}