add buchberger algorithm

This commit is contained in:
2026-04-22 22:33:30 +02:00
parent 1730ac2fac
commit e22a45926a
5 changed files with 190 additions and 13 deletions

74
src/poly/buchberger.rs Normal file
View File

@@ -0,0 +1,74 @@
use super::flat::Poly;
use super::var::Var;
/// Computes a Gröbner basis for the ideal generated by `generators` using
/// Buchberger's algorithm under lex order.
///
/// The returned basis spans the same ideal as the input and satisfies
/// Buchberger's criterion: every S-polynomial of a pair in the basis
/// reduces to zero modulo the basis.
pub fn groebner_basis<V: Var>(generators: Vec<Poly<V>>) -> Vec<Poly<V>> {
let mut g: Vec<Poly<V>> = generators.into_iter().filter(|p| !p.is_zero()).collect();
let mut i = 0;
while i < g.len() {
let mut j = i + 1;
while j < g.len() {
let s = g[i].s_poly(&g[j]);
let r = reduce(&s, &g);
if !r.is_zero() {
g.push(r);
}
j += 1;
}
i += 1;
}
g
}
/// Checks whether `basis` satisfies Buchberger's criterion under lex order:
/// the S-polynomial of every pair reduces to zero modulo the basis.
///
/// Returns `true` iff `basis` is a Gröbner basis for the ideal it generates.
pub fn is_groebner_basis<V: Var>(basis: &[Poly<V>]) -> bool {
for i in 0..basis.len() {
for j in (i + 1)..basis.len() {
let s = basis[i].s_poly(&basis[j]);
if !reduce(&s, basis).is_zero() {
return false;
}
}
}
true
}
/// Reduces `f` modulo `basis` until no leading term of `f` is divisible
/// by the leading monomial of any element in `basis`.
///
/// Uses the pseudo-division remainder and repeats until stable.
fn reduce<V: Var>(f: &Poly<V>, basis: &[Poly<V>]) -> Poly<V> {
let mut p = f.clone();
'outer: loop {
let Some((lm_p, _)) = p.leading_term_lex() else {
break;
};
for g in basis {
let Some((lm_g, _)) = g.leading_term_lex() else {
continue;
};
if lm_p.contains(&lm_g) {
let (_, _, r) = p.clone().div_rem(g);
p = r;
continue 'outer;
}
}
break;
}
p
}