Compare commits

...

20 Commits

Author SHA1 Message Date
5caccbaf50 improve var creation for SumProdCircuit 2026-04-28 17:29:11 +02:00
0c4bddf3b0 building quotient from ideal to make it more explicit 2026-04-27 23:29:03 +02:00
3fbd7e3773 improve api and simplify SumProdCircuit creation 2026-04-27 23:15:06 +02:00
627a2d88f4 refactor wip 2026-04-27 22:40:55 +02:00
723033f3aa wip refactor 2026-04-27 22:05:46 +02:00
3a83340c8f rename Mono fields for better understanding 2026-04-24 10:14:00 +02:00
0d5fc8225d add README.md 2026-04-22 23:58:39 +02:00
fe163b74b4 update quotient to ensure ideal defined with a grobner basis 2026-04-22 23:53:21 +02:00
fb12ec3819 check reduced grobner basis 2026-04-22 23:45:43 +02:00
e22a45926a add buchberger algorithm 2026-04-22 22:33:30 +02:00
1730ac2fac add S-polynomials 2026-04-22 22:14:49 +02:00
79bf205762 add polynomial division 2026-04-22 19:35:39 +02:00
5bc6124222 cargo fmt 2026-04-22 18:58:19 +02:00
fc7db3c989 add scale node 2026-04-22 18:16:26 +02:00
42d1dd30dc add quotient circuit structure and improve fmt for polynomials 2026-04-22 17:17:14 +02:00
dee53e6339 move tests on circuits (dag) 2026-04-22 16:27:18 +02:00
8c646fd920 refactor poly 2026-04-22 16:12:56 +02:00
fd05f6b024 move tests and implement dag 2026-04-22 15:59:19 +02:00
891546069c add tests 2026-04-22 12:13:49 +02:00
99fee298c7 add iterator in children nodes 2026-04-22 11:59:40 +02:00
20 changed files with 1562 additions and 366 deletions

134
README.md Normal file
View File

@@ -0,0 +1,134 @@
# circuit-cas
A computer algebra system in Rust for algebraic circuit verification over polynomial rings with integer coefficients.
## Overview
`circuit-cas` provides two main layers:
- **`poly`** — multivariate polynomials over , Gröbner bases, and ideals
- **`circuit`** — arithmetic circuits (DAGs of add/mul nodes) quotiented by an ideal
The intended use case is verifying arithmetic circuits modulo an ideal: two circuits computing the same polynomial in the quotient ring are equivalent.
## Modules
### `poly`
#### Variables — `poly::var`
Variables are any type implementing the `Var` trait. The built-in `StaticVar` carries a static string name and optional integer indices, with a `var!` macro for construction:
```rust
use circuit_cas::var;
let x = var!("x"); // x
let x0 = var!("x", 0); // x₀
let x01 = var!("x", 0, 1); // x₀,₁
```
#### Polynomials — `poly::flat`
`Poly<V>` is a multivariate polynomial over backed by a `HashMap<Mono<V>, i32>`. Arithmetic operators (`+`, `-`, `*`) and scalar multiplication are provided. Monomial ordering uses pure lexicographic order (lex) with variable names sorted alphabetically.
```rust
// x² - 2xy (using array-of-pairs syntax)
let f: Poly<StaticVar> = [
(1i32, Mono::from([("x", 2u32)])),
(-2i32, Mono::from([("x", 1u32), ("y", 1u32)])),
].into_iter().collect();
```
Key operations:
| Method | Description |
|--------|-------------|
| `Poly::is_zero` | whether the polynomial is the zero polynomial |
| `Poly::leading_term_lex` | leading `(monomial, coefficient)` under lex |
| `Poly::s_poly(&other)` | S-polynomial of two polynomials |
| `Poly::div_rem(divisor)` | pseudo-division: returns `(d, q, r)` with `lc(g)^d·f = q·g + r` |
#### Ideals — `poly::ideal`
`Ideal<V, S>` uses the typestate pattern to track at the type level whether its generators form a Gröbner basis:
```rust
use circuit_cas::poly::ideal::{Ideal, Generators, GroebnerBasis};
// Arbitrary generators
let ideal: Ideal<StaticVar, Generators> = Ideal::new(vec![f1, f2]);
// Compute the reduced Gröbner basis — consumes the original ideal
let gb: Ideal<StaticVar, GroebnerBasis> = ideal.groebner_basis();
// Ideal membership test (only available on GroebnerBasis state)
assert!(gb.contains(&some_poly));
```
`Ideal` implements `Display` as `<g1, g2, ...>` and `FromIterator<Poly<V>>` for construction from an iterator.
#### Buchberger's algorithm — `poly::buchberger`
```rust
use circuit_cas::poly::buchberger::{groebner_basis, is_groebner_basis};
let basis = groebner_basis(vec![f1, f2]);
assert!(is_groebner_basis(&basis));
```
`groebner_basis` returns the **reduced** Gröbner basis: after running Buchberger's algorithm it minimizes (removes redundant generators) and interreduces (fully reduces each generator modulo the others).
### `circuit`
#### DAG — `circuit::dag`
`Circuit<V>` is a DAG of `Node<V>` values, with structural sharing via interning. Nodes are `Leaf(V)`, `Scale(id, i32)`, `Sum(id, id)`, or `Prod(id, id)`.
#### Quotient ring — `circuit::quotient`
`Quotient<V>` pairs an arithmetic circuit with a `Ideal<V, GroebnerBasis>`, representing a circuit in the quotient ring `[vars] / I`.
```rust
use circuit_cas::circuit::quotient::Quotient;
// Build from a list of generators — Gröbner basis is computed automatically
let quotient: Quotient<StaticVar> = vec![f1, f2, f3].into_iter().collect();
// Or from a pre-computed Gröbner basis
let quotient = Quotient::from(gb);
println!("{quotient}"); // C/<g1, g2>
```
## Example
```rust
use circuit_cas::{var, circuit::quotient::Quotient, poly::var::StaticVar};
fn main() {
let x = var!("x");
let xb = var!("x\u{0304}"); // x̄
// Idempotency relations: x² = x, x̄² = x̄, x·x̄ = x
let idem = vec![
1 * (&x ^ 2) - 1 * (&x ^ 1),
1 * (&xb ^ 2) - 1 * (&xb ^ 1),
1 * ((&x ^ 1) * (&xb ^ 1)) - 1 * (&x ^ 1),
];
let quotient: Quotient<StaticVar> = idem.into_iter().collect();
println!("{quotient}");
}
```
Run with:
```
cargo run --example quotient
```
## Development
```
cargo test # run all tests
```

View File

@@ -1,26 +1,25 @@
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use circuit_cas::circuit::probabilistic::ProbCircuit;
use circuit_cas::circuit::dag::{Circuit, CircuitExt}; use circuit_cas::circuit::dag::CircuitExt;
use circuit_cas::var;
fn main() { fn main() {
let circuit = Rc::new(RefCell::new(Circuit::new())); let circuit: Rc<RefCell<ProbCircuit>> = ProbCircuit::new();
// Build (x + y) * (x + z) // vars accept anything that implements Into<StaticVar>: &'static str, (&str, u32), (&str, u32, u32)
let x = circuit.leaf(var!("x")); let x = circuit.var("x");
let y = circuit.leaf(var!("y")); let y = circuit.var(("y", 1)); // indexed variable y_1
let z = circuit.leaf(var!("z")); let z = circuit.var(("z", 0, 1)); // doubly-indexed variable z_{0,1}
let x_plus_y = circuit.leaf(var!("x")) + y; let x_plus_y = circuit.var("x") + y;
let x_plus_z = circuit.leaf(var!("x")) + z; let x_plus_z = circuit.var("x") + z;
let expr = x_plus_y * x_plus_z; let expr = x_plus_y * x_plus_z;
// Deduplication: both x leaves share the same NodeId // Deduplication: both x leaves share the same NodeId
let x2 = circuit.leaf(var!("x")); let x2 = circuit.var("x");
assert_eq!(x.id, x2.id); assert_eq!(x.id, x2.id);
println!("(x + y) * (x + z) root node id: {:?}", expr.id); println!("(x + y_1) * (x + z_{{0,1}}) root node id: {:?}", expr.id);
println!("x node id: {:?}", x.id); println!("x node id: {:?}", x.id);
println!("x deduplicated node id: {:?}", x2.id); println!("x deduplicated node id: {:?}", x2.id);
} }

View File

@@ -1,9 +1,7 @@
use circuit_cas::poly::flat;
use circuit_cas::var; use circuit_cas::var;
fn main() { fn main() {
let poly = (2 let poly = (2 * ((var!("x", 1, 5) ^ 5) * (var!("x", 1, 2) ^ 5) * (var!("x", 2, 5) ^ 1)))
* ((var!("x", 1, 5) ^ 5) * (var!("x", 1, 2) ^ 5) * (var!("x", 2, 5) ^ 1)))
+ (3 * ((var!("x", 1, 9) ^ 5) * (var!("x", 1, 2) ^ 5) * (var!("x", 2, 5) ^ 1))); + (3 * ((var!("x", 1, 9) ^ 5) * (var!("x", 1, 2) ^ 5) * (var!("x", 2, 5) ^ 1)));
let x = var!("x"); let x = var!("x");
@@ -11,13 +9,13 @@ fn main() {
let z = var!("z"); let z = var!("z");
let other = -3 * ((&x ^ 2) * (&y ^ 4)); let other = -3 * ((&x ^ 2) * (&y ^ 4));
let mono = (&x^2)*(&y^4); let mono = (&x ^ 2) * (&y ^ 4);
let inside = (&x^2)*(&y^2)*(&z^1); let inside = (&x ^ 2) * (&y ^ 2) * (&z ^ 1);
if mono.contains(&inside){ if mono.contains(&inside) {
println!("{inside}\u{2286}{mono}"); println!("{inside}\u{2286}{mono}");
}else{ } else {
println!("{inside}\u{2284}{mono}"); println!("{inside}\u{2284}{mono}");
} }

31
examples/quotient.rs Normal file
View File

@@ -0,0 +1,31 @@
use std::cell::RefCell;
use std::rc::Rc;
use circuit_cas::circuit::dag::CircuitExt;
use circuit_cas::circuit::quotient::QuotientCircuit;
use circuit_cas::circuit::traits::Circuit;
use circuit_cas::poly::ideal::{Generators, Ideal};
use circuit_cas::var;
fn main() {
let x = var!("x");
let nx = var!("x\u{0304}");
let idem: Ideal<_, Generators> = vec![
1 * (&x ^ 2) - 1 * (&x ^ 1),
1 * (&nx ^ 2) - 1 * (&nx ^ 1),
1 * ((&x ^ 1) * (&nx ^ 1)) - 1 * (&x ^ 1),
].into();
let quotient: Rc<RefCell<QuotientCircuit>> = idem.into();
// Build x * x̄ + x in the DAG
// var accepts anything that implements Into<StaticVar>: &'static str, (&str, u32), (&str, u32, u32)
let xn = quotient.var("x");
let nxn = quotient.var("x\u{0304}");
let prod = xn * nxn;
let xn2 = quotient.var("x");
let expr = prod + xn2;
println!("dag size: {}", quotient.borrow().len());
println!("expr node id: {:?}", expr.id);
}

View File

@@ -1,34 +1,29 @@
use slotmap::{new_key_type, SlotMap}; use slotmap::{SlotMap, new_key_type};
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::HashMap; use std::collections::HashMap;
use std::ops::{Add, Mul};
use std::rc::Rc; use std::rc::Rc;
use crate::poly::var::Var; use super::traits::{Circuit, Node};
new_key_type! { pub struct NodeId; } new_key_type! { pub struct NodeId; }
#[derive(Clone, PartialEq, Eq, Hash)] #[derive(Clone, Debug)]
pub enum Node<V: Var> { pub struct Dag<N: Node> {
Leaf(V), nodes: SlotMap<NodeId, N>,
Sum(NodeId, NodeId), intern: HashMap<N, NodeId>,
Prod(NodeId, NodeId),
} }
pub struct Circuit<V: Var> { impl<N: Node> Default for Dag<N> {
nodes: SlotMap<NodeId, Node<V>>, fn default() -> Self {
intern: HashMap<Node<V>, NodeId>, Dag {
} nodes: Default::default(),
intern: Default::default(),
impl<V: Var> Circuit<V> {
pub fn new() -> Self {
Circuit {
nodes: SlotMap::with_key(),
intern: HashMap::new(),
} }
} }
}
pub fn node(&mut self, n: Node<V>) -> NodeId { impl<N: Node> Dag<N> {
pub(super) fn node(&mut self, n: N) -> NodeId {
if let Some(&id) = self.intern.get(&n) { if let Some(&id) = self.intern.get(&n) {
return id; return id;
} }
@@ -37,47 +32,33 @@ impl<V: Var> Circuit<V> {
id id
} }
pub fn get(&self, id: NodeId) -> Option<&Node<V>> { pub(super) fn get(&self, id: NodeId) -> Option<&N> {
self.nodes.get(id) self.nodes.get(id)
} }
pub fn remove(&mut self, id: NodeId) { pub(super) fn len(&self) -> usize {
self.nodes.len()
}
pub(super) fn children(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
self.nodes.get(id).into_iter().flat_map(Node::children)
}
pub(super) fn remove(&mut self, id: NodeId) {
if let Some(node) = self.nodes.remove(id) { if let Some(node) = self.nodes.remove(id) {
self.intern.remove(&node); self.intern.remove(&node);
} }
} }
} }
pub struct CircuitNode<V: Var> { pub struct RefNode<C: Circuit> {
pub id: NodeId, pub id: NodeId,
circuit: Rc<RefCell<Circuit<V>>>, pub(super) circuit: Rc<RefCell<C>>,
} }
pub trait CircuitExt<V: Var> {
fn leaf(&self, v: V) -> CircuitNode<V>; pub trait CircuitExt {
} type C: Circuit;
type Var;
impl<V: Var> CircuitExt<V> for Rc<RefCell<Circuit<V>>> { fn var<T: Into<Self::Var>>(&self, v: T) -> RefNode<Self::C>;
fn leaf(&self, v: V) -> CircuitNode<V> {
let id = self.borrow_mut().node(Node::Leaf(v));
CircuitNode { id, circuit: self.clone() }
}
}
impl<V: Var> Add for CircuitNode<V> {
type Output = Self;
fn add(self, rhs: Self) -> Self {
let id = self.circuit.borrow_mut().node(Node::Sum(self.id, rhs.id));
CircuitNode { id, circuit: self.circuit }
}
}
impl<V: Var> Mul for CircuitNode<V> {
type Output = Self;
fn mul(self, rhs: Self) -> Self {
let id = self.circuit.borrow_mut().node(Node::Prod(self.id, rhs.id));
CircuitNode { id, circuit: self.circuit }
}
} }

View File

@@ -1 +1,7 @@
pub mod traits;
pub mod dag; pub mod dag;
pub mod probabilistic;
pub mod quotient;
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,68 @@
use std::cell::RefCell;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use crate::poly::var::{StaticVar, Var};
use super::dag::{Dag, NodeId};
use super::traits::{Node, SumProdCircuit};
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum PNode<V: Var> {
Var(V),
Sum(NodeId, NodeId),
Prod(NodeId, NodeId),
}
impl<V: Var> Node for PNode<V> {
fn children(&self) -> impl Iterator<Item = NodeId> {
match self {
Self::Var(_) => [None, None],
Self::Sum(l, r) | Self::Prod(l, r) => [Some(*l), Some(*r)],
}
.into_iter()
.flatten()
}
}
#[derive(Clone, Debug)]
pub struct ProbCircuit<V: Var = StaticVar> {
dag: Dag<PNode<V>>,
}
impl<V: Var> Default for ProbCircuit<V> {
fn default() -> Self { ProbCircuit { dag: Dag::default() } }
}
impl<V: Var> ProbCircuit<V> {
pub fn new() -> Rc<RefCell<Self>> {
Rc::new(RefCell::new(Self::default()))
}
}
impl<V: Var> SumProdCircuit for ProbCircuit<V> {
type Var = V;
fn var<T: Into<V>>(&mut self, v: T) -> NodeId { self.node(PNode::Var(v.into())) }
fn add(&mut self, l: NodeId, r: NodeId) -> NodeId {
let (l, r) = if l <= r { (l, r) } else { (r, l) };
self.node(PNode::Sum(l, r))
}
fn mul(&mut self, l: NodeId, r: NodeId) -> NodeId {
let (l, r) = if l <= r { (l, r) } else { (r, l) };
self.node(PNode::Prod(l, r))
}
}
impl<V: Var> Deref for ProbCircuit<V> {
type Target = Dag<PNode<V>>;
fn deref(&self) -> &Self::Target { &self.dag }
}
impl<V: Var> DerefMut for ProbCircuit<V> {
fn deref_mut(&mut self) -> &mut Self::Target { &mut self.dag }
}

73
src/circuit/quotient.rs Normal file
View File

@@ -0,0 +1,73 @@
use std::cell::RefCell;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use crate::poly::var::{StaticVar, Var};
use crate::poly::ideal::{Generators, GroebnerBasis, Ideal};
use super::dag::{Dag, NodeId};
use super::traits::{Node, SumProdCircuit};
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum QNode<V: Var> {
Var(V),
Sum(NodeId, NodeId),
Prod(NodeId, NodeId),
DivStep(NodeId, NodeId),
}
impl<V: Var> Node for QNode<V> {
fn children(&self) -> impl Iterator<Item = NodeId> {
match self {
Self::Var(_) => [None, None],
Self::Sum(l, r) | Self::Prod(l, r) | Self::DivStep(l, r) => [Some(*l), Some(*r)],
}
.into_iter()
.flatten()
}
}
#[derive(Clone, Debug)]
pub struct QuotientCircuit<V: Var = StaticVar> {
basis: Ideal<V, GroebnerBasis>,
dag: Dag<QNode<V>>,
}
impl<V: Var> From<Ideal<V, Generators>> for Rc<RefCell<QuotientCircuit<V>>> {
fn from(ideal: Ideal<V, Generators>) -> Self {
ideal.groebner_basis().into()
}
}
impl<V: Var> From<Ideal<V, GroebnerBasis>> for Rc<RefCell<QuotientCircuit<V>>> {
fn from(basis: Ideal<V, GroebnerBasis>) -> Self {
Rc::new(RefCell::new(QuotientCircuit { basis, dag: Default::default() }))
}
}
impl<V: Var> Deref for QuotientCircuit<V> {
type Target = Dag<QNode<V>>;
fn deref(&self) -> &Self::Target { &self.dag }
}
impl<V: Var> DerefMut for QuotientCircuit<V> {
fn deref_mut(&mut self) -> &mut Self::Target { &mut self.dag }
}
impl<V: Var> SumProdCircuit for QuotientCircuit<V> {
type Var = V;
fn var<T: Into<V>>(&mut self, v: T) -> NodeId { self.node(QNode::Var(v.into())) }
fn add(&mut self, l: NodeId, r: NodeId) -> NodeId {
let (l, r) = if l <= r { (l, r) } else { (r, l) };
self.node(QNode::Sum(l, r))
}
fn mul(&mut self, l: NodeId, r: NodeId) -> NodeId {
let (l, r) = if l <= r { (l, r) } else { (r, l) };
self.node(QNode::Prod(l, r))
}
}

50
src/circuit/tests.rs Normal file
View File

@@ -0,0 +1,50 @@
use std::cell::RefCell;
use std::rc::Rc;
use super::probabilistic::ProbCircuit;
use super::dag::CircuitExt;
#[test]
fn test_deduplication() {
let circuit: Rc<RefCell<ProbCircuit>> = ProbCircuit::new();
// Same leaf constructed twice returns the same NodeId
let x1 = circuit.var("x");
let x2 = circuit.var("x");
assert_eq!(x1.id, x2.id);
assert_eq!(circuit.borrow().len(), 1);
// Same sum constructed twice returns the same NodeId
let _y = circuit.var("y");
let sum1 = circuit.var("x") + circuit.var("y");
let sum2 = circuit.var("x") + circuit.var("y");
assert_eq!(sum1.id, sum2.id);
assert_eq!(circuit.borrow().len(), 3); // x, y, x+y
// Shared subexpression: (x + y) * (x + y) reuses the x+y node
let xy = circuit.var("x") + circuit.var("y");
let xy2 = circuit.var("x") + circuit.var("y");
let _sq = xy * xy2;
assert_eq!(circuit.borrow().len(), 4); // x, y, x+y, (x+y)*(x+y)
// Commutativity: x+y and y+x are the same node
let xy = circuit.var("x") + circuit.var("y");
let yx = circuit.var("y") + circuit.var("x");
assert_eq!(xy.id, yx.id);
// Associativity: (x+y)+z and x+(y+z) are distinct nodes
let _z = circuit.var("z");
let xy_z = (circuit.var("x") + circuit.var("y"))
+ circuit.var("z");
let x_yz = circuit.var("x")
+ (circuit.var("y") + circuit.var("z"));
assert_ne!(xy_z.id, x_yz.id);
// Deep shared structure: (x+y)*z appears twice in ((x+y)*z) + ((x+y)*z)
let xyz1 = (circuit.var("x") + circuit.var("y"))
* circuit.var("z");
let xyz2 = (circuit.var("x") + circuit.var("y"))
* circuit.var("z");
assert_eq!(xyz1.id, xyz2.id);
let _sum = xyz1 + xyz2;
// x, y, z, x+y(==y+x), (x+y)*z, (x+y)+z, y+z, x+(y+z), (x+y)*z+(x+y)*z, sq
assert_eq!(circuit.borrow().len(), 10);
}

63
src/circuit/traits.rs Normal file
View File

@@ -0,0 +1,63 @@
use std::cell::RefCell;
use std::hash::Hash;
use std::ops::{Add, DerefMut, Mul};
use std::rc::Rc;
use super::dag::{CircuitExt, Dag, NodeId, RefNode};
pub trait Node: Clone + PartialEq + Eq + Hash {
fn children(&self) -> impl Iterator<Item = NodeId>;
}
pub trait Circuit: Clone + DerefMut<Target = Dag<Self::Node>> {
type Node: Node;
fn node(&mut self, n: Self::Node) -> NodeId { (**self).node(n) }
fn remove(&mut self, id: NodeId) { (**self).remove(id) }
fn get(&self, id: NodeId) -> Option<&Self::Node> { (**self).get(id) }
fn len(&self) -> usize { (**self).len() }
fn children(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ { (**self).children(id) }
}
impl<T, N> Circuit for T
where
T: Clone + DerefMut<Target = Dag<N>>,
N: Node,
{
type Node = N;
}
pub trait SumProdCircuit: Circuit {
type Var;
fn var<T: Into<Self::Var>>(&mut self, v: T) -> NodeId;
fn add(&mut self, l: NodeId, r: NodeId) -> NodeId;
fn mul(&mut self, l: NodeId, r: NodeId) -> NodeId;
}
impl<C: SumProdCircuit> Add for RefNode<C> {
type Output = Self;
fn add(self, rhs: Self) -> Self {
let id = self.circuit.borrow_mut().add(self.id, rhs.id);
RefNode { id, circuit: self.circuit }
}
}
impl<C: SumProdCircuit> Mul for RefNode<C> {
type Output = Self;
fn mul(self, rhs: Self) -> Self {
let id = self.circuit.borrow_mut().mul(self.id, rhs.id);
RefNode { id, circuit: self.circuit }
}
}
impl<C: SumProdCircuit> CircuitExt for Rc<RefCell<C>> {
type C = C;
type Var = C::Var;
fn var<T: Into<C::Var>>(&self, v: T) -> RefNode<C> {
let id = self.borrow_mut().var(v);
RefNode { id, circuit: self.clone() }
}
}

View File

@@ -1,34 +1,35 @@
pub fn num_to_subscript(s: String) -> String {
pub fn num_to_subscript(s:String)->String{ s.chars()
s.chars().map(|c| match c{ .map(|c| match c {
'0'=>'\u{2080}', '0' => '\u{2080}',
'1'=>'\u{2081}', '1' => '\u{2081}',
'2'=>'\u{2082}', '2' => '\u{2082}',
'3'=>'\u{2083}', '3' => '\u{2083}',
'4'=>'\u{2084}', '4' => '\u{2084}',
'5'=>'\u{2085}', '5' => '\u{2085}',
'6'=>'\u{2086}', '6' => '\u{2086}',
'7'=>'\u{2087}', '7' => '\u{2087}',
'8'=>'\u{2088}', '8' => '\u{2088}',
'9'=>'\u{2089}', '9' => '\u{2089}',
_=>c _ => c,
}).collect() })
.collect()
} }
pub fn num_to_superscript(s:String)->String{ pub fn num_to_superscript(s: String) -> String {
s.chars().map(|c| match c{ s.chars()
'0'=>'\u{2070}', .map(|c| match c {
'1'=>'\u{20B9}', '0' => '\u{2070}',
'2'=>'\u{00B2}', '1' => '\u{20B9}',
'3'=>'\u{00B3}', '2' => '\u{00B2}',
'4'=>'\u{2074}', '3' => '\u{00B3}',
'5'=>'\u{2075}', '4' => '\u{2074}',
'6'=>'\u{2076}', '5' => '\u{2075}',
'7'=>'\u{2077}', '6' => '\u{2076}',
'8'=>'\u{2078}', '7' => '\u{2077}',
'9'=>'\u{2079}', '8' => '\u{2078}',
_=>c '9' => '\u{2079}',
}).collect() _ => c,
})
.collect()
} }

View File

@@ -1,3 +1,3 @@
pub mod poly;
pub mod circuit; pub mod circuit;
pub mod fmt; pub mod fmt;
pub mod poly;

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

@@ -0,0 +1,98 @@
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;
}
// Minimize: remove any g whose LM is divisible by LM(h) for some other h.
let mut i = 0;
while i < g.len() {
let lm_i = g[i].leading_term_lex().unwrap().0.clone();
let redundant =
(0..g.len()).any(|j| j != i && lm_i.contains(&g[j].leading_term_lex().unwrap().0));
if redundant {
g.remove(i);
} else {
i += 1;
}
}
// Interreduce: replace each generator with its normal form modulo the others.
for i in 0..g.len() {
let others: Vec<Poly<V>> = g
.iter()
.enumerate()
.filter(|(j, _)| *j != i)
.map(|(_, p)| p.clone())
.collect();
g[i] = reduce(&g[i], &others);
}
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.
pub(crate) 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
}

View File

@@ -1,15 +1,57 @@
use itertools::Itertools; use std::cmp::Ordering;
use std::fmt::{self, Display};
use std::ops::{Add, BitXor, Mul, Sub};
use super::var::{StaticVar, Var};
use crate::fmt::num_to_superscript;
use std::collections::HashMap; use std::collections::HashMap;
use super::var::Var;
pub fn lex_cmp<V: Var>(a: &Mono<V>, b: &Mono<V>) -> Ordering {
let mut a_it = a.vars.iter().peekable();
let mut b_it = b.vars.iter().peekable();
loop {
match (a_it.peek(), b_it.peek()) {
(None, None) => return Ordering::Equal,
(Some((_, a_exp)), None) => {
return if *a_exp > 0 {
Ordering::Greater
} else {
Ordering::Equal
};
}
(None, Some((_, b_exp))) => {
return if *b_exp > 0 {
Ordering::Less
} else {
Ordering::Equal
};
}
(Some((a_var, a_exp)), Some((b_var, b_exp))) => {
if a_var < b_var {
if *a_exp > 0 {
return Ordering::Greater;
}
a_it.next();
} else if a_var > b_var {
if *b_exp > 0 {
return Ordering::Less;
}
b_it.next();
} else {
match a_exp.cmp(b_exp) {
Ordering::Equal => {
a_it.next();
b_it.next();
}
ord => return ord,
}
}
}
}
}
}
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct Poly<V: Var> { pub struct Poly<V: Var> {
mono: HashMap<Mono<V>, i32>, pub(crate) mono: HashMap<Mono<V>, i32>,
} }
impl<V: Var> Default for Poly<V> { impl<V: Var> Default for Poly<V> {
@@ -20,19 +62,17 @@ impl<V: Var> Default for Poly<V> {
} }
} }
impl<V: Var> Display for Poly<V> { impl<V: Var> Poly<V> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { pub fn is_zero(&self) -> bool {
match self.mono.is_empty() { self.mono.is_empty()
true => write!(fmt, ""), }
false => write!(
fmt, /// Returns (leading monomial, leading coefficient) under lex order, or None if zero.
"{}", pub fn leading_term_lex(&self) -> Option<(Mono<V>, i32)> {
self.mono self.mono
.iter() .iter()
.map(|(m, c)| format!("{}{}", c, m)) .max_by(|(m1, _), (m2, _)| lex_cmp(m1, m2))
.join(" + ") .map(|(m, &c)| (m.clone(), c))
),
}
} }
} }
@@ -53,22 +93,22 @@ impl<V: Var, U: Into<Mono<V>>> FromIterator<(i32, U)> for Poly<V> {
} }
} }
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Mono<V: Var> { pub struct Mono<V: Var> {
pub term: Vec<(V, u32)>, pub vars: Vec<(V, u32)>,
} }
impl<V: Var> Mono<V> { impl<V: Var> Mono<V> {
pub fn contains(&self, other: &Mono<V>) -> bool { pub fn contains(&self, other: &Mono<V>) -> bool {
let mut self_it = self.term.iter().peekable(); let mut self_it = self.vars.iter().peekable();
let mut other_it = other.term.iter().peekable(); let mut other_it = other.vars.iter().peekable();
while let Some((o_term, o_exp)) = other_it.peek() { while let Some((o_var, o_exp)) = other_it.peek() {
if let Some((s_term, s_exp)) = self_it.peek() { if let Some((s_var, s_exp)) = self_it.peek() {
if s_term < o_term { if s_var < o_var {
self_it.next(); self_it.next();
continue; continue;
} else if s_term > o_term { } else if s_var > o_var {
return false; return false;
} else if o_exp <= s_exp { } else if o_exp <= s_exp {
self_it.next(); self_it.next();
@@ -83,6 +123,64 @@ impl<V: Var> Mono<V> {
true true
} }
/// Returns the lcm of self and other (element-wise max of exponents).
pub fn lcm(&self, other: &Mono<V>) -> Mono<V> {
let mut self_it = self.vars.iter().peekable();
let mut other_it = other.vars.iter().peekable();
let mut result: Vec<(V, u32)> = vec![];
loop {
match (self_it.peek(), other_it.peek()) {
(None, None) => break,
(Some(_), None) => result.push(self_it.next().unwrap().clone()),
(None, Some(_)) => result.push(other_it.next().unwrap().clone()),
(Some((s_var, _)), Some((o_var, _))) => {
if s_var < o_var {
result.push(self_it.next().unwrap().clone());
} else if s_var > o_var {
result.push(other_it.next().unwrap().clone());
} else {
let (var, s_exp) = self_it.next().unwrap();
let (_, o_exp) = other_it.next().unwrap();
result.push((var.clone(), (*s_exp).max(*o_exp)));
}
}
}
}
Mono { vars: result }
}
/// Divides self by other. Assumes `self.contains(other)`.
pub fn div(self, other: &Mono<V>) -> Mono<V> {
let mut self_it = self.vars.into_iter().peekable();
let mut other_it = other.vars.iter().peekable();
let mut result: Vec<(V, u32)> = vec![];
loop {
match (self_it.peek(), other_it.peek()) {
(None, None) => break,
(Some(_), None) => result.push(self_it.next().unwrap()),
(None, Some(_)) => unreachable!("divisor not contained in dividend"),
(Some((s_var, _)), Some((o_var, _))) => {
if s_var < o_var {
result.push(self_it.next().unwrap());
} else if s_var > o_var {
unreachable!("divisor not contained in dividend");
} else {
let (var, s_exp) = self_it.next().unwrap();
let (_, o_exp) = other_it.next().unwrap();
if s_exp > *o_exp {
result.push((var, s_exp - o_exp));
}
}
}
}
}
Mono { vars: result }
}
} }
impl<V: Var, T: IntoIterator> From<T> for Mono<V> impl<V: Var, T: IntoIterator> From<T> for Mono<V>
@@ -96,231 +194,19 @@ where
impl<V: Var, U: Into<V>> FromIterator<(U, u32)> for Mono<V> { impl<V: Var, U: Into<V>> FromIterator<(U, u32)> for Mono<V> {
fn from_iter<T: IntoIterator<Item = (U, u32)>>(iter: T) -> Self { fn from_iter<T: IntoIterator<Item = (U, u32)>>(iter: T) -> Self {
let mut term = iter let mut vars = iter
.into_iter() .into_iter()
.map(|(t, pow)| (t.into(), pow)) .map(|(t, pow)| (t.into(), pow))
.collect::<Vec<(V, u32)>>(); .collect::<Vec<(V, u32)>>();
term.sort(); vars.sort();
// Check duplicate variables // Check duplicate variables
assert!((term[..]) assert!(
.windows(2) (vars[..])
.all(|window| window[0].0 != window[1].0)); .windows(2)
.all(|window| window[0].0 != window[1].0)
);
Mono { term } Mono { vars }
}
}
impl<V: Var> Display for Mono<V> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(
fmt,
"{}",
self.term
.iter()
.map(|(t, p)| match p {
1 => format!("{t}"),
_ => format!("{t}{}", num_to_superscript(p.to_string())),
})
.join("")
)
}
}
impl BitXor<u32> for StaticVar {
type Output = Mono<StaticVar>;
fn bitxor(self, exp: u32) -> Self::Output {
[(self, exp)].into()
}
}
impl<'a> BitXor<u32> for &'a StaticVar {
type Output = Mono<StaticVar>;
fn bitxor(self, exp: u32) -> Self::Output {
[(self.clone(), exp)].into()
}
}
impl<V: Var> Mul for Mono<V> {
type Output = Self;
fn mul(self, other: Mono<V>) -> Self::Output {
let mut a_term = self.term.into_iter().peekable();
let mut b_term = other.term.into_iter().peekable();
let mut result: Vec<(V, u32)> = Default::default();
loop {
match (a_term.peek(), b_term.peek()) {
(Some((a_var, _)), Some((b_var, _))) => {
if a_var < b_var {
result.push(a_term.next().unwrap());
} else if a_var > b_var {
result.push(b_term.next().unwrap());
} else {
let (var, a_exp) = a_term.next().unwrap();
let (_, b_exp) = b_term.next().unwrap();
result.push((var, a_exp + b_exp));
}
}
(Some(a), None) => {
result.push(a.clone());
a_term.next();
}
(None, Some(b)) => {
result.push(b.clone());
b_term.next();
}
(None, None) => {
break;
}
}
}
Mono { term: result }
}
}
impl<V: Var> Mul<Mono<V>> for i32 {
type Output = Poly<V>;
fn mul(self, mono: Mono<V>) -> Self::Output {
let mut poly: HashMap<Mono<V>, i32> = Default::default();
poly.insert(mono, self);
Poly { mono: poly }
}
}
impl<V: Var> Add for Poly<V> {
type Output = Poly<V>;
fn add(mut self, other: Poly<V>) -> Self::Output {
for (mono, coeff) in other.mono {
let entry = self.mono.entry(mono).or_insert(0);
*entry += coeff;
}
self.mono.retain(|_, &mut coeff| coeff != 0);
self
}
}
impl<V: Var> Sub for Poly<V> {
type Output = Poly<V>;
fn sub(mut self, other: Poly<V>) -> Self::Output {
for (mono, coeff) in other.mono {
let entry = self.mono.entry(mono).or_insert(0);
*entry -= coeff;
}
self.mono.retain(|_, &mut coeff| coeff != 0);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mono_contains() {
let a: Mono<StaticVar> = [("x", 2), ("y", 1)].into();
// Lower exponent of same variable is contained
assert!(a.contains(&Mono::from([("x", 1)])));
// Higher exponent of same variable is not contained
assert!(!a.contains(&Mono::from([("x", 3)])));
// Identical monomial is contained
assert!(a.contains(&Mono::from([("x", 2), ("y", 1)])));
// Variable absent from self is not contained
assert!(!a.contains(&Mono::from([("x", 2), ("z", 1)])));
// Subset of variables with lower exponents is contained
assert!(a.contains(&Mono::from([("x", 1), ("y", 1)])));
// Single variable with exact exponent is contained
assert!(a.contains(&Mono::from([("x", 2)])));
// Insufficient exponent in self means not contained
assert!(!Mono::<StaticVar>::from([("x", 1)]).contains(&Mono::from([("x", 2)])));
// Missing variable in self means not contained
assert!(!Mono::<StaticVar>::from([("x", 1), ("y", 1)]).contains(&Mono::from([("x", 2)])));
assert!(!Mono::<StaticVar>::from([("x", 1)]).contains(&Mono::from([("x", 1), ("y", 1)])));
}
#[test]
fn test_mono_mul() {
// Same variable: exponents add
let a: Mono<StaticVar> = [("x", 2)].into();
let b: Mono<StaticVar> = [("x", 3)].into();
assert_eq!(a * b, Mono::from([("x", 5)]));
// Disjoint variables: both appear in result
let a: Mono<StaticVar> = [("x", 2)].into();
let b: Mono<StaticVar> = [("y", 3)].into();
assert_eq!(a * b, Mono::from([("x", 2), ("y", 3)]));
// Mixed: shared and disjoint variables
let a: Mono<StaticVar> = [("x", 1), ("y", 2)].into();
let b: Mono<StaticVar> = [("y", 1), ("z", 3)].into();
assert_eq!(a * b, Mono::from([("x", 1), ("y", 3), ("z", 3)]));
// Commutativity
let a: Mono<StaticVar> = [("x", 2), ("z", 1)].into();
let b: Mono<StaticVar> = [("y", 3)].into();
assert_eq!(a.clone() * b.clone(), b * a);
// Multiply by constant monomial (empty term vec = 1)
let a: Mono<StaticVar> = [("x", 4)].into();
let one: Mono<StaticVar> = Mono { term: vec![] };
assert_eq!(a.clone() * one, a);
}
#[test]
fn test_poly_add() {
// Distinct monomials are collected as separate terms
let a: Poly<StaticVar> = [(1, [("x", 2)]), (2, [("y", 1)])].into();
let b: Poly<StaticVar> = [(3, [("z", 1)])].into();
let expected: Poly<StaticVar> = [(1, [("x", 2)]), (2, [("y", 1)]), (3, [("z", 1)])].into();
assert_eq!(a + b, expected);
// Coefficients of matching monomials are summed
let a: Poly<StaticVar> = [(2, [("x", 1)])].into();
let b: Poly<StaticVar> = [(3, [("x", 1)])].into();
let expected: Poly<StaticVar> = [(5, [("x", 1)])].into();
assert_eq!(a + b, expected);
// Terms that cancel sum to zero are dropped
let a: Poly<StaticVar> = [(1, [("x", 1)])].into();
let b: Poly<StaticVar> = [(-1, [("x", 1)])].into();
let expected: Poly<StaticVar> = Poly::default();
assert_eq!(a + b, expected);
}
#[test]
fn test_poly_sub() {
// Distinct monomials are collected as separate terms with negated rhs coefficients
let a: Poly<StaticVar> = [(3, [("x", 2)])].into();
let b: Poly<StaticVar> = [(1, [("y", 1)])].into();
let expected: Poly<StaticVar> = [(3, [("x", 2)]), (-1, [("y", 1)])].into();
assert_eq!(a - b, expected);
// Coefficients of matching monomials are subtracted
let a: Poly<StaticVar> = [(5, [("x", 1)])].into();
let b: Poly<StaticVar> = [(3, [("x", 1)])].into();
let expected: Poly<StaticVar> = [(2, [("x", 1)])].into();
assert_eq!(a - b, expected);
// Subtracting equal polynomials yields zero
let a: Poly<StaticVar> = [(4, [("x", 2)]), (1, [("y", 1)])].into();
let b: Poly<StaticVar> = [(4, [("x", 2)]), (1, [("y", 1)])].into();
assert_eq!(a - b, Poly::default());
} }
} }

76
src/poly/fmt.rs Normal file
View File

@@ -0,0 +1,76 @@
use std::fmt::{self, Display, Formatter};
use itertools::Itertools;
use crate::fmt::{num_to_subscript, num_to_superscript};
use crate::poly::flat::{Mono, Poly};
use crate::poly::ideal::Ideal;
use crate::poly::var::{StaticVar, Var};
impl Display for StaticVar {
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> {
let num_indices = self.indices.len();
match num_indices {
0 => write!(fmt, "{}", self.name),
_ => write!(
fmt,
"{}{}",
self.name,
self.indices
.iter()
.map(|x: &u32| num_to_subscript(x.to_string()))
.join(",")
),
}
}
}
impl<V: Var> Display for Poly<V> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self.mono.is_empty() {
true => write!(fmt, ""),
false => write!(
fmt,
"{}",
self.mono
.iter()
.map(|(m, c)| match c {
1 => format!("{}", m),
-1 => format!("-{}", m),
_ => format!("{}{}", c, m),
})
.join(" + ")
),
}
}
}
impl<V: Var, S> Display for Ideal<V, S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "<")?;
let mut iter = self.generators().iter();
if let Some(first) = iter.next() {
write!(f, "{first}")?;
for p in iter {
write!(f, ", {p}")?;
}
}
write!(f, ">")
}
}
impl<V: Var> Display for Mono<V> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(
fmt,
"{}",
self.vars
.iter()
.map(|(t, p)| match p {
1 => format!("{t}"),
_ => format!("{t}{}", num_to_superscript(p.to_string())),
})
.join("")
)
}
}

69
src/poly/ideal.rs Normal file
View File

@@ -0,0 +1,69 @@
use std::marker::PhantomData;
use super::buchberger;
use super::flat::Poly;
use super::var::Var;
/// Marker: the ideal's generators are arbitrary polynomials.
#[derive(Clone, Debug)]
pub struct Generators;
/// Marker: the ideal's generators form a Gröbner basis.
#[derive(Clone, Debug)]
pub struct GroebnerBasis;
#[derive(Clone, Debug)]
pub struct Ideal<V: Var, S> {
generators: Vec<Poly<V>>,
_state: PhantomData<S>,
}
impl<V: Var> Ideal<V, Generators> {
pub fn new(generators: Vec<Poly<V>>) -> Self {
Ideal {
generators,
_state: PhantomData,
}
}
/// Computes a Gröbner basis for this ideal using Buchberger's algorithm.
pub fn groebner_basis(self) -> Ideal<V, GroebnerBasis> {
Ideal {
generators: buchberger::groebner_basis(self.generators),
_state: PhantomData,
}
}
}
impl<V: Var> Into<Ideal<V, GroebnerBasis>> for Ideal<V, Generators> {
fn into(self) -> Ideal<V, GroebnerBasis> {
self.groebner_basis()
}
}
impl<V: Var> FromIterator<Poly<V>> for Ideal<V, Generators> {
fn from_iter<T: IntoIterator<Item = Poly<V>>>(iter: T) -> Self {
Ideal::new(iter.into_iter().collect())
}
}
impl<V: Var, T: IntoIterator<Item = Poly<V>>> From<T> for Ideal<V, Generators> {
fn from(iter: T) -> Self {
iter.into_iter().collect()
}
}
impl<V: Var, S> Ideal<V, S> {
pub fn generators(&self) -> &[Poly<V>] {
&self.generators
}
}
impl<V: Var> Ideal<V, GroebnerBasis> {
/// Returns `true` if `p` belongs to this ideal.
///
/// Reduces `p` modulo the Gröbner basis; membership holds iff the remainder is zero.
pub fn contains(&self, p: &Poly<V>) -> bool {
buchberger::reduce(p, &self.generators).is_zero()
}
}

View File

@@ -1,2 +1,9 @@
pub mod buchberger;
pub mod flat; pub mod flat;
pub mod fmt;
pub mod ideal;
pub mod ops;
pub mod var; pub mod var;
#[cfg(test)]
mod tests;

205
src/poly/ops.rs Normal file
View File

@@ -0,0 +1,205 @@
use std::collections::HashMap;
use std::ops::{Add, BitXor, Mul, Sub};
use crate::poly::flat::{Mono, Poly};
use crate::poly::var::{StaticVar, Var};
impl BitXor<u32> for StaticVar {
type Output = Mono<StaticVar>;
fn bitxor(self, exp: u32) -> Self::Output {
[(self, exp)].into()
}
}
impl<'a> BitXor<u32> for &'a StaticVar {
type Output = Mono<StaticVar>;
fn bitxor(self, exp: u32) -> Self::Output {
[(self.clone(), exp)].into()
}
}
impl<V: Var> Mul for Mono<V> {
type Output = Self;
fn mul(self, other: Mono<V>) -> Self::Output {
let mut a_vars = self.vars.into_iter().peekable();
let mut b_vars = other.vars.into_iter().peekable();
let mut result: Vec<(V, u32)> = Default::default();
loop {
match (a_vars.peek(), b_vars.peek()) {
(Some((a_var, _)), Some((b_var, _))) => {
if a_var < b_var {
result.push(a_vars.next().unwrap());
} else if a_var > b_var {
result.push(b_vars.next().unwrap());
} else {
let (var, a_exp) = a_vars.next().unwrap();
let (_, b_exp) = b_vars.next().unwrap();
result.push((var, a_exp + b_exp));
}
}
(Some(a), None) => {
result.push(a.clone());
a_vars.next();
}
(None, Some(b)) => {
result.push(b.clone());
b_vars.next();
}
(None, None) => {
break;
}
}
}
Mono { vars: result }
}
}
impl<V: Var> Mul<Mono<V>> for i32 {
type Output = Poly<V>;
fn mul(self, mono: Mono<V>) -> Self::Output {
let mut poly: HashMap<Mono<V>, i32> = Default::default();
poly.insert(mono, self);
Poly { mono: poly }
}
}
impl<V: Var> Mul<Poly<V>> for i32 {
type Output = Poly<V>;
fn mul(self, mut poly: Poly<V>) -> Self::Output {
if self == 0 {
return Poly::default();
}
for coeff in poly.mono.values_mut() {
*coeff *= self;
}
poly
}
}
impl<V: Var> Mul for Poly<V> {
type Output = Poly<V>;
fn mul(self, other: Poly<V>) -> Self::Output {
let mut result = Poly::default();
for (m1, c1) in &self.mono {
for (m2, c2) in &other.mono {
let entry = result.mono.entry(m1.clone() * m2.clone()).or_insert(0i32);
*entry += c1 * c2;
}
}
result.mono.retain(|_, &mut c| c != 0);
result
}
}
impl<V: Var> Add for Poly<V> {
type Output = Poly<V>;
fn add(mut self, other: Poly<V>) -> Self::Output {
for (mono, coeff) in other.mono {
let entry = self.mono.entry(mono).or_insert(0);
*entry += coeff;
}
self.mono.retain(|_, &mut coeff| coeff != 0);
self
}
}
impl<V: Var> Sub for Poly<V> {
type Output = Poly<V>;
fn sub(mut self, other: Poly<V>) -> Self::Output {
for (mono, coeff) in other.mono {
let entry = self.mono.entry(mono).or_insert(0);
*entry -= coeff;
}
self.mono.retain(|_, &mut coeff| coeff != 0);
self
}
}
fn gcd(a: i32, b: i32) -> i32 {
let (mut a, mut b) = (a.abs(), b.abs());
while b != 0 {
let t = b;
b = a % b;
a = t;
}
a
}
impl<V: Var> Poly<V> {
/// S-polynomial of `self` and `other` under lex order.
///
/// Let `L = lcm(LM(f), LM(g))` and `d = gcd(lc(f), lc(g))`. Returns:
/// `(lc(g)/d) * (L/LM(f)) * f - (lc(f)/d) * (L/LM(g)) * g`
///
/// The leading terms cancel by construction. Panics if either polynomial is zero.
pub fn s_poly(&self, other: &Poly<V>) -> Poly<V> {
let (lm_f, lc_f) = self.leading_term_lex().expect("f must be nonzero");
let (lm_g, lc_g) = other.leading_term_lex().expect("g must be nonzero");
let l = lm_f.lcm(&lm_g);
let t_f: Poly<V> = 1 * l.clone().div(&lm_f);
let t_g: Poly<V> = 1 * l.div(&lm_g);
let d = gcd(lc_f, lc_g);
let left = (lc_g / d) * (t_f * self.clone());
let right = (lc_f / d) * (t_g * other.clone());
left - right
}
}
impl<V: Var> Poly<V> {
/// Pseudo-division with remainder.
///
/// Returns `(d, q, r)` satisfying `lc(divisor)^d * self = q * divisor + r`,
/// where no term of `r` has its monomial divisible by `LM(divisor)` under lex order.
///
/// Panics if `divisor` is zero.
pub fn div_rem(self, divisor: &Poly<V>) -> (u32, Poly<V>, Poly<V>) {
let (lt_g_mono, lt_g_coeff) = divisor.leading_term_lex().expect("divisor must be nonzero");
let mut p = self;
let mut q = Poly::default();
let mut r = Poly::default();
let mut d = 0u32;
while !p.is_zero() {
let (lt_p_mono, lt_p_coeff) = p.leading_term_lex().unwrap();
if lt_p_mono.contains(&lt_g_mono) {
let t_mono = lt_p_mono.div(&lt_g_mono);
if lt_p_coeff % lt_g_coeff == 0 {
// Exact division: no need to multiply through by lc(g)
let t_poly: Poly<V> = (lt_p_coeff / lt_g_coeff) * t_mono;
p = p - t_poly.clone() * divisor.clone();
q = q + t_poly;
} else {
// Pseudo-division: multiply through by lc(g) to stay in
let t_poly: Poly<V> = lt_p_coeff * t_mono;
p = lt_g_coeff * p - t_poly.clone() * divisor.clone();
q = lt_g_coeff * q + t_poly;
r = lt_g_coeff * r;
d += 1;
}
} else {
let lt_poly: Poly<V> = lt_p_coeff * lt_p_mono;
p = p - lt_poly.clone();
r = r + lt_poly;
}
}
(d, q, r)
}
}

464
src/poly/tests.rs Normal file
View File

@@ -0,0 +1,464 @@
use super::buchberger::{groebner_basis, is_groebner_basis};
use super::flat::{Mono, Poly, lex_cmp};
use super::ideal::{Generators, GroebnerBasis, Ideal};
use super::var::StaticVar;
#[test]
fn test_mono_contains() {
let a: Mono<StaticVar> = [("x", 2), ("y", 1)].into();
// Lower exponent of same variable is contained
assert!(a.contains(&Mono::from([("x", 1)])));
// Higher exponent of same variable is not contained
assert!(!a.contains(&Mono::from([("x", 3)])));
// Identical monomial is contained
assert!(a.contains(&Mono::from([("x", 2), ("y", 1)])));
// Variable absent from self is not contained
assert!(!a.contains(&Mono::from([("x", 2), ("z", 1)])));
// Subset of variables with lower exponents is contained
assert!(a.contains(&Mono::from([("x", 1), ("y", 1)])));
// Single variable with exact exponent is contained
assert!(a.contains(&Mono::from([("x", 2)])));
// Insufficient exponent in self means not contained
assert!(!Mono::<StaticVar>::from([("x", 1)]).contains(&Mono::from([("x", 2)])));
// Missing variable in self means not contained
assert!(!Mono::<StaticVar>::from([("x", 1), ("y", 1)]).contains(&Mono::from([("x", 2)])));
assert!(!Mono::<StaticVar>::from([("x", 1)]).contains(&Mono::from([("x", 1), ("y", 1)])));
}
#[test]
fn test_mono_mul() {
// Same variable: exponents add
let a: Mono<StaticVar> = [("x", 2)].into();
let b: Mono<StaticVar> = [("x", 3)].into();
assert_eq!(a * b, Mono::from([("x", 5)]));
// Disjoint variables: both appear in result
let a: Mono<StaticVar> = [("x", 2)].into();
let b: Mono<StaticVar> = [("y", 3)].into();
assert_eq!(a * b, Mono::from([("x", 2), ("y", 3)]));
// Mixed: shared and disjoint variables
let a: Mono<StaticVar> = [("x", 1), ("y", 2)].into();
let b: Mono<StaticVar> = [("y", 1), ("z", 3)].into();
assert_eq!(a * b, Mono::from([("x", 1), ("y", 3), ("z", 3)]));
// Commutativity
let a: Mono<StaticVar> = [("x", 2), ("z", 1)].into();
let b: Mono<StaticVar> = [("y", 3)].into();
assert_eq!(a.clone() * b.clone(), b * a);
// Multiply by constant monomial (empty term vec = 1)
let a: Mono<StaticVar> = [("x", 4)].into();
let one: Mono<StaticVar> = Mono { vars: vec![] };
assert_eq!(a.clone() * one, a);
}
#[test]
fn test_poly_add() {
// Distinct monomials are collected as separate terms
let a: Poly<StaticVar> = [(1, [("x", 2)]), (2, [("y", 1)])].into();
let b: Poly<StaticVar> = [(3, [("z", 1)])].into();
let expected: Poly<StaticVar> = [(1, [("x", 2)]), (2, [("y", 1)]), (3, [("z", 1)])].into();
assert_eq!(a + b, expected);
// Coefficients of matching monomials are summed
let a: Poly<StaticVar> = [(2, [("x", 1)])].into();
let b: Poly<StaticVar> = [(3, [("x", 1)])].into();
let expected: Poly<StaticVar> = [(5, [("x", 1)])].into();
assert_eq!(a + b, expected);
// Terms that cancel sum to zero are dropped
let a: Poly<StaticVar> = [(1, [("x", 1)])].into();
let b: Poly<StaticVar> = [(-1, [("x", 1)])].into();
let expected: Poly<StaticVar> = Poly::default();
assert_eq!(a + b, expected);
}
#[test]
fn test_poly_sub() {
// Distinct monomials are collected as separate terms with negated rhs coefficients
let a: Poly<StaticVar> = [(3, [("x", 2)])].into();
let b: Poly<StaticVar> = [(1, [("y", 1)])].into();
let expected: Poly<StaticVar> = [(3, [("x", 2)]), (-1, [("y", 1)])].into();
assert_eq!(a - b, expected);
// Coefficients of matching monomials are subtracted
let a: Poly<StaticVar> = [(5, [("x", 1)])].into();
let b: Poly<StaticVar> = [(3, [("x", 1)])].into();
let expected: Poly<StaticVar> = [(2, [("x", 1)])].into();
assert_eq!(a - b, expected);
// Subtracting equal polynomials yields zero
let a: Poly<StaticVar> = [(4, [("x", 2)]), (1, [("y", 1)])].into();
let b: Poly<StaticVar> = [(4, [("x", 2)]), (1, [("y", 1)])].into();
assert_eq!(a - b, Poly::default());
}
#[test]
fn test_lex_cmp() {
use std::cmp::Ordering;
let x2: Mono<StaticVar> = [("x", 2)].into();
let xy: Mono<StaticVar> = [("x", 1), ("y", 1)].into();
let y2: Mono<StaticVar> = [("y", 2)].into();
let x: Mono<StaticVar> = [("x", 1)].into();
let one: Mono<StaticVar> = Mono { vars: vec![] };
// x² > xy (x exponent 2 vs 1)
assert_eq!(lex_cmp(&x2, &xy), Ordering::Greater);
// x > y² (x has higher priority)
assert_eq!(lex_cmp(&x, &y2), Ordering::Greater);
// xy > y² (x present in xy but not y²)
assert_eq!(lex_cmp(&xy, &y2), Ordering::Greater);
// 1 < x
assert_eq!(lex_cmp(&one, &x), Ordering::Less);
// reflexive
assert_eq!(lex_cmp(&x2, &x2), Ordering::Equal);
}
#[test]
fn test_mono_div() {
// x² / x = x
let a: Mono<StaticVar> = [("x", 2)].into();
let b: Mono<StaticVar> = [("x", 1)].into();
assert_eq!(a.div(&b), Mono::from([("x", 1)]));
// x²y / xy = x
let a: Mono<StaticVar> = [("x", 2), ("y", 1)].into();
let b: Mono<StaticVar> = [("x", 1), ("y", 1)].into();
assert_eq!(a.div(&b), Mono::from([("x", 1)]));
// x²y / y = x²
let a: Mono<StaticVar> = [("x", 2), ("y", 1)].into();
let b: Mono<StaticVar> = [("y", 1)].into();
assert_eq!(a.div(&b), Mono::from([("x", 2)]));
// x / x = 1
let a: Mono<StaticVar> = [("x", 1)].into();
let b: Mono<StaticVar> = [("x", 1)].into();
assert_eq!(a.div(&b), Mono { vars: vec![] });
}
#[test]
fn test_mono_lcm() {
// lcm(x², xy) = x²y
let a: Mono<StaticVar> = [("x", 2)].into();
let b: Mono<StaticVar> = [("x", 1), ("y", 1)].into();
assert_eq!(a.lcm(&b), Mono::from([("x", 2), ("y", 1)]));
// lcm(x, y) = xy (disjoint)
let a: Mono<StaticVar> = [("x", 1)].into();
let b: Mono<StaticVar> = [("y", 1)].into();
assert_eq!(a.lcm(&b), Mono::from([("x", 1), ("y", 1)]));
// lcm(x², x²) = x² (identical)
let a: Mono<StaticVar> = [("x", 2)].into();
assert_eq!(a.lcm(&a.clone()), a);
}
#[test]
fn test_s_poly() {
// S(x², xy) = 0: S-poly of two monomials always vanishes
let f: Poly<StaticVar> = [(1, [("x", 2)])].into();
let g: Poly<StaticVar> = [(1, [("x", 1), ("y", 1)])].into();
assert!(f.s_poly(&g).is_zero());
// f = x² + y, g = xy + z (lex: LM(f)=x², LM(g)=xy)
// L = x²y, t_f = y, t_g = x, d = gcd(1,1) = 1
// S = y*(x²+y) - x*(xy+z) = x²y + y² - x²y - xz = y² - xz
let f: Poly<StaticVar> = [
(1i32, Mono::from([("x", 2u32)])),
(1i32, Mono::from([("y", 1u32)])),
]
.into_iter()
.collect();
let g: Poly<StaticVar> = [
(1i32, Mono::from([("x", 1u32), ("y", 1u32)])),
(1i32, Mono::from([("z", 1u32)])),
]
.into_iter()
.collect();
let expected: Poly<StaticVar> = [
(1i32, Mono::from([("y", 2u32)])),
(-1i32, Mono::from([("x", 1u32), ("z", 1u32)])),
]
.into_iter()
.collect();
assert_eq!(f.s_poly(&g), expected);
// f = 2x + y, g = 3x + z (same LM=x, d=gcd(2,3)=1)
// S = (3/1)*f - (2/1)*g = 3(2x+y) - 2(3x+z) = 3y - 2z
let f: Poly<StaticVar> = [(2, [("x", 1)]), (1, [("y", 1)])].into();
let g: Poly<StaticVar> = [(3, [("x", 1)]), (1, [("z", 1)])].into();
let expected: Poly<StaticVar> = [(3, [("y", 1)]), (-2, [("z", 1)])].into();
assert_eq!(f.s_poly(&g), expected);
// f = 4x, g = 6x (d = gcd(4,6) = 2)
// S = (6/2)*x*4x - (4/2)*x*6x = 3*4x - 2*6x = 12x - 12x = 0
let f: Poly<StaticVar> = [(4, [("x", 1)])].into();
let g: Poly<StaticVar> = [(6, [("x", 1)])].into();
assert!(f.s_poly(&g).is_zero());
}
fn make_const_poly(c: i32) -> Poly<StaticVar> {
Poly {
mono: [(Mono { vars: vec![] }, c)].into_iter().collect(),
}
}
fn verify_div_rem(
f: Poly<StaticVar>,
g: &Poly<StaticVar>,
d: u32,
q: Poly<StaticVar>,
r: Poly<StaticVar>,
) {
// lc(g)^d * f == q * g + r
let (_, lc_g) = g.leading_term_lex().unwrap();
let lhs = lc_g.pow(d) * f;
let rhs = q * g.clone() + r;
assert_eq!(lhs, rhs);
}
#[test]
fn test_div_rem() {
// x³ / x² = x, r=0, d=0
let f: Poly<StaticVar> = [(1, [("x", 3)])].into();
let g: Poly<StaticVar> = [(1, [("x", 2)])].into();
let expected_q: Poly<StaticVar> = [(1, [("x", 1)])].into();
let (d, q, r) = f.clone().div_rem(&g);
assert_eq!(q, expected_q);
assert!(r.is_zero());
verify_div_rem(f, &g, d, q, r);
// (x³ + x²y) / x² = x + y, r=0
// f = x²(x + y), g = x²
let f: Poly<StaticVar> = [
(1i32, Mono::from([("x", 3u32)])),
(1i32, Mono::from([("x", 2u32), ("y", 1u32)])),
]
.into_iter()
.collect();
let g: Poly<StaticVar> = [(1, [("x", 2)])].into();
let expected_q: Poly<StaticVar> = [(1, [("x", 1)]), (1, [("y", 1)])].into();
let (d, q, r) = f.clone().div_rem(&g);
assert_eq!(q, expected_q);
assert!(r.is_zero());
verify_div_rem(f, &g, d, q, r);
// (x³ + y) / x² = x, r=y
// LT(x³) divisible by x², LT(y) is not
let f: Poly<StaticVar> = [(1, [("x", 3)]), (1, [("y", 1)])].into();
let g: Poly<StaticVar> = [(1, [("x", 2)])].into();
let expected_q: Poly<StaticVar> = [(1, [("x", 1)])].into();
let expected_r: Poly<StaticVar> = [(1, [("y", 1)])].into();
let (d, q, r) = f.clone().div_rem(&g);
assert_eq!(q, expected_q);
assert_eq!(r, expected_r);
verify_div_rem(f, &g, d, q, r);
// 3x² / (2x): 2 ∤ 3, needs pseudo-division
// 2¹ · 3x² = 3x · 2x => d=1, q=3x, r=0
let f: Poly<StaticVar> = [(3, [("x", 2)])].into();
let g: Poly<StaticVar> = [(2, [("x", 1)])].into();
let expected_q: Poly<StaticVar> = [(3, [("x", 1)])].into();
let (d, q, r) = f.clone().div_rem(&g);
assert_eq!(d, 1);
assert_eq!(q, expected_q);
assert!(r.is_zero());
verify_div_rem(f, &g, d, q, r);
// 6xy / 2 = 3xy, r=0, d=0
let f: Poly<StaticVar> = [(6, [("x", 1), ("y", 1)])].into();
let g = make_const_poly(2);
let expected_q: Poly<StaticVar> = [(3, [("x", 1), ("y", 1)])].into();
let (d, q, r) = f.clone().div_rem(&g);
assert_eq!(d, 0);
assert_eq!(q, expected_q);
assert!(r.is_zero());
verify_div_rem(f, &g, d, q, r);
// (x² + xy) / (x + y) = x, r=0
// f = x(x + y), g = x + y
let f: Poly<StaticVar> = [
(1i32, Mono::from([("x", 2u32)])),
(1i32, Mono::from([("x", 1u32), ("y", 1u32)])),
]
.into_iter()
.collect();
let g: Poly<StaticVar> = [(1, [("x", 1)]), (1, [("y", 1)])].into();
let expected_q: Poly<StaticVar> = [(1, [("x", 1)])].into();
let (d, q, r) = f.clone().div_rem(&g);
assert_eq!(q, expected_q);
assert!(r.is_zero());
verify_div_rem(f, &g, d, q, r);
}
#[test]
fn test_groebner() {
// Ideal (x²) — already a Gröbner basis
let f: Poly<StaticVar> = [(1, [("x", 2)])].into();
let _basis = groebner_basis(vec![f]);
// Ideal (x³ - x², x² - x): gcd is x² - x
let f: Poly<StaticVar> = [
(1i32, Mono::from([("x", 3u32)])),
(-1i32, Mono::from([("x", 2u32)])),
]
.into_iter()
.collect();
let g: Poly<StaticVar> = [
(1i32, Mono::from([("x", 2u32)])),
(-1i32, Mono::from([("x", 1u32)])),
]
.into_iter()
.collect();
let basis = groebner_basis(vec![f, g]);
assert!(is_groebner_basis(&basis));
// Classic example: I = (x²y - x, xy² - y)
let f: Poly<StaticVar> = [
(1i32, Mono::from([("x", 2u32), ("y", 1u32)])),
(-1i32, Mono::from([("x", 1u32)])),
]
.into_iter()
.collect();
let g: Poly<StaticVar> = [
(1i32, Mono::from([("x", 1u32), ("y", 2u32)])),
(-1i32, Mono::from([("y", 1u32)])),
]
.into_iter()
.collect();
let basis = groebner_basis(vec![f, g]);
assert!(is_groebner_basis(&basis));
}
#[test]
fn test_is_groebner_basis() {
// {x} is a GB: only one element, no pairs to check.
let f: Poly<StaticVar> = [(1, [("x", 1)])].into();
assert!(is_groebner_basis(&[f]));
// {x, y} is a GB: S(x, y) = y*x - x*y = 0.
let x: Poly<StaticVar> = [(1, [("x", 1)])].into();
let y: Poly<StaticVar> = [(1, [("y", 1)])].into();
assert!(is_groebner_basis(&[x, y]));
// {x² + y, xy} is NOT a GB:
// S(x²+y, xy) = y*(x²+y) - x*(xy) = y² ≠ 0 mod the set.
let f: Poly<StaticVar> = [
(1i32, Mono::from([("x", 2u32)])),
(1i32, Mono::from([("y", 1u32)])),
]
.into_iter()
.collect();
let g: Poly<StaticVar> = [(1i32, Mono::from([("x", 1u32), ("y", 1u32)]))]
.into_iter()
.collect();
assert!(!is_groebner_basis(&[f, g]));
// After running groebner_basis, the result must always pass.
let f: Poly<StaticVar> = [
(1i32, Mono::from([("x", 2u32)])),
(1i32, Mono::from([("y", 1u32)])),
]
.into_iter()
.collect();
let g: Poly<StaticVar> = [(1i32, Mono::from([("x", 1u32), ("y", 1u32)]))]
.into_iter()
.collect();
let basis = groebner_basis(vec![f, g]);
assert!(is_groebner_basis(&basis));
}
#[test]
fn test_ideal() {
// Construction from Vec and iterator
let f: Poly<StaticVar> = [(1, [("x", 2)])].into();
let g: Poly<StaticVar> = [(1, [("y", 1)])].into();
let ideal = Ideal::new(vec![f.clone(), g.clone()]);
assert_eq!(ideal.generators().len(), 2);
let ideal: Ideal<StaticVar, Generators> = [f.clone(), g.clone()].into_iter().collect();
assert_eq!(ideal.generators().len(), 2);
// Construction via From / .into()
let ideal: Ideal<StaticVar, Generators> = vec![f.clone(), g.clone()].into();
assert_eq!(ideal.generators().len(), 2);
// Display: <x², y>
let ideal = Ideal::new(vec![f, g]);
assert_eq!(ideal.to_string(), "<x\u{00B2}, y>");
// groebner_basis transitions state and result satisfies the criterion
let f: Poly<StaticVar> = [
(1i32, Mono::from([("x", 2u32), ("y", 1u32)])),
(-1i32, Mono::from([("x", 1u32)])),
]
.into_iter()
.collect();
let g: Poly<StaticVar> = [
(1i32, Mono::from([("x", 1u32), ("y", 2u32)])),
(-1i32, Mono::from([("y", 1u32)])),
]
.into_iter()
.collect();
let ideal: Ideal<StaticVar, Generators> = [f, g].into_iter().collect();
let gb: Ideal<StaticVar, GroebnerBasis> = ideal.groebner_basis();
assert!(is_groebner_basis(gb.generators()));
}
#[test]
fn test_groebner_sagemath() {
// I = (x³ - 2xy, x²y - 2y² + x) ⊆ k[x, y]
// grobner basis: {4y³, x - 2y²}
// f1 = x³ - 2xy
let f1: Poly<StaticVar> = [
(1i32, Mono::from([("x", 3u32)])),
(-2i32, Mono::from([("x", 1u32), ("y", 1u32)])),
]
.into_iter()
.collect();
// f2 = x²y - 2y² + x
let f2: Poly<StaticVar> = [
(1i32, Mono::from([("x", 2u32), ("y", 1u32)])),
(-2i32, Mono::from([("y", 2u32)])),
(1i32, Mono::from([("x", 1u32)])),
]
.into_iter()
.collect();
let gb = Ideal::new(vec![f1.clone(), f2.clone()]).groebner_basis();
assert!(is_groebner_basis(gb.generators()));
assert_eq!(gb.generators().len(), 2);
// -x + 2y²
let neg_x_plus_2y2: Poly<StaticVar> = [
(-1i32, Mono::from([("x", 1u32)])),
(2i32, Mono::from([("y", 2u32)])),
]
.into_iter()
.collect();
// -4y³
let neg_4y3: Poly<StaticVar> = [(-4i32, Mono::from([("y", 3u32)]))].into_iter().collect();
let expected = [neg_x_plus_2y2, neg_4y3];
for e in &expected {
assert!(
gb.generators()
.iter()
.any(|a| *a == *e || *a == -1i32 * e.clone())
);
}
}

View File

@@ -1,27 +1,14 @@
use itertools::Itertools; use std::fmt::{Debug, Display};
use std::fmt::{self, Debug, Display, Formatter};
use std::hash::Hash; use std::hash::Hash;
use crate::fmt::num_to_subscript;
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct StaticVar { pub struct StaticVar {
name: &'static str, pub(crate) name: &'static str,
indices: Vec<u32>, pub(crate) indices: Vec<u32>,
} }
pub trait Var: PartialEq + Eq + PartialOrd + Ord + Clone + Hash + Debug + Display {} pub trait Var: PartialEq + Eq + PartialOrd + Ord + Clone + Hash + Debug + Display {}
impl Display for StaticVar {
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> {
let num_indices = self.indices.len();
match num_indices {
0 => write!(fmt, "{}", self.name),
_ => write!(fmt, "{}{}", self.name, self.indices.iter().map(|x| num_to_subscript(x.to_string())).join(",")),
}
}
}
impl Var for StaticVar {} impl Var for StaticVar {}
impl From<&'static str> for StaticVar { impl From<&'static str> for StaticVar {