Compare commits

...

8 Commits

14 changed files with 428 additions and 207 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::rc::Rc;
use circuit_cas::circuit::dag::{Circuit, CircuitExt};
use circuit_cas::var;
use circuit_cas::circuit::probabilistic::ProbCircuit;
use circuit_cas::circuit::dag::CircuitExt;
fn main() {
let circuit = Rc::new(RefCell::new(Circuit::new()));
let circuit: Rc<RefCell<ProbCircuit>> = ProbCircuit::new();
// Build (x + y) * (x + z)
let x = circuit.leaf(var!("x"));
let y = circuit.leaf(var!("y"));
let z = circuit.leaf(var!("z"));
// vars accept anything that implements Into<StaticVar>: &'static str, (&str, u32), (&str, u32, u32)
let x = circuit.var("x");
let y = circuit.var(("y", 1)); // indexed variable y_1
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_z = circuit.leaf(var!("x")) + z;
let x_plus_y = circuit.var("x") + y;
let x_plus_z = circuit.var("x") + z;
let expr = x_plus_y * x_plus_z;
// 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);
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 deduplicated node id: {:?}", x2.id);
}

View File

@@ -1,21 +1,31 @@
use std::cell::RefCell;
use std::rc::Rc;
use circuit_cas::circuit::quotient::Quotient;
use circuit_cas::poly::var::StaticVar;
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 = vec![
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 mut quotient: Quotient<StaticVar> = idem.into_iter().collect();
let quotient: Rc<RefCell<QuotientCircuit>> = idem.into();
println!("{quotient}");
// 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,57 +1,29 @@
use slotmap::{SlotMap, new_key_type};
use std::cell::RefCell;
use std::collections::HashMap;
use std::ops::{Add, Mul};
use std::rc::Rc;
use crate::poly::var::Var;
use super::traits::{Circuit, Node};
new_key_type! { pub struct NodeId; }
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Node<V: Var> {
Leaf(V),
Scale(NodeId, i32),
Sum(NodeId, NodeId),
Prod(NodeId, NodeId),
}
impl<V: Var> Node<V> {
pub fn children(&self) -> impl Iterator<Item = NodeId> {
match self {
Node::Leaf(_) => [None, None],
Node::Scale(n, _) => [Some(*n), None],
Node::Sum(l, r) | Node::Prod(l, r) => [Some(*l), Some(*r)],
}
.into_iter()
.flatten()
}
}
#[derive(Clone, Debug)]
pub struct Circuit<V: Var> {
nodes: SlotMap<NodeId, Node<V>>,
intern: HashMap<Node<V>, NodeId>,
pub struct Dag<N: Node> {
nodes: SlotMap<NodeId, N>,
intern: HashMap<N, NodeId>,
}
impl<V: Var> Default for Circuit<V> {
impl<N: Node> Default for Dag<N> {
fn default() -> Self {
Circuit {
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) {
return id;
}
@@ -60,90 +32,33 @@ impl<V: Var> Circuit<V> {
id
}
pub fn get(&self, id: NodeId) -> Option<&Node<V>> {
pub(super) fn get(&self, id: NodeId) -> Option<&N> {
self.nodes.get(id)
}
pub fn add(&mut self, left: NodeId, right: NodeId) -> NodeId {
let (l, r) = if left <= right {
(left, right)
} else {
(right, left)
};
self.node(Node::Sum(l, r))
}
pub fn mul(&mut self, left: NodeId, right: NodeId) -> NodeId {
let (l, r) = if left <= right {
(left, right)
} else {
(right, left)
};
self.node(Node::Prod(l, r))
}
pub fn len(&self) -> usize {
pub(super) fn len(&self) -> usize {
self.nodes.len()
}
pub fn children(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
pub(super) fn children(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
self.nodes.get(id).into_iter().flat_map(Node::children)
}
pub fn remove(&mut self, id: NodeId) {
pub(super) fn remove(&mut self, id: NodeId) {
if let Some(node) = self.nodes.remove(id) {
self.intern.remove(&node);
}
}
}
pub struct CircuitNode<V: Var> {
pub struct RefNode<C: Circuit> {
pub id: NodeId,
circuit: Rc<RefCell<Circuit<V>>>,
}
pub trait CircuitExt<V: Var> {
fn leaf(&self, v: V) -> CircuitNode<V>;
fn get_node(&self, id: NodeId) -> Option<CircuitNode<V>>;
pub(super) circuit: Rc<RefCell<C>>,
}
impl<V: Var> CircuitExt<V> for Rc<RefCell<Circuit<V>>> {
fn leaf(&self, v: V) -> CircuitNode<V> {
let id = self.borrow_mut().node(Node::Leaf(v));
CircuitNode {
id,
circuit: self.clone(),
}
}
fn get_node(&self, id: NodeId) -> Option<CircuitNode<V>> {
self.borrow().get(id)?;
Some(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().add(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().mul(self.id, rhs.id);
CircuitNode {
id,
circuit: self.circuit,
}
}
pub trait CircuitExt {
type C: Circuit;
type Var;
fn var<T: Into<Self::Var>>(&self, v: T) -> RefNode<Self::C>;
}

View File

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

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 }
}

View File

@@ -1,44 +1,73 @@
use super::dag::{Circuit, Node, NodeId};
use crate::poly::{flat::Poly, var::Var};
use std::cell::RefCell;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use itertools::Itertools;
use crate::poly::var::{StaticVar, Var};
use crate::poly::ideal::{Generators, GroebnerBasis, Ideal};
use super::dag::{Dag, NodeId};
use super::traits::{Node, SumProdCircuit};
use std::fmt::{self, Display};
#[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 Quotient<V: Var> {
basis: Vec<Poly<V>>,
circuit: Circuit<V>,
pub struct QuotientCircuit<V: Var = StaticVar> {
basis: Ideal<V, GroebnerBasis>,
dag: Dag<QNode<V>>,
}
impl<V: Var> FromIterator<Poly<V>> for Quotient<V> {
fn from_iter<T: IntoIterator<Item = Poly<V>>>(iter: T) -> Self {
Quotient {
basis: iter.into_iter().collect(),
circuit: Default::default(),
}
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> Display for Quotient<V> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(
fmt,
"C/<{}>",
self.basis.iter().map(|p| format!("{p}")).join(",")
)
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> Quotient<V> {
pub fn node(&mut self, n: Node<V>) -> NodeId {
self.circuit.node(n)
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))
}
pub fn add(&mut self, left: NodeId, right: NodeId) -> NodeId {
self.circuit.add(left, right)
}
pub fn mul(&mut self, left: NodeId, right: NodeId) -> NodeId {
self.circuit.mul(left, right)
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))
}
}

View File

@@ -1,50 +1,48 @@
use std::cell::RefCell;
use std::rc::Rc;
use super::dag::{Circuit, CircuitExt};
use crate::poly::var::StaticVar;
use super::probabilistic::ProbCircuit;
use super::dag::CircuitExt;
#[test]
fn test_deduplication() {
let circuit = Rc::new(RefCell::new(Circuit::new()));
let circuit: Rc<RefCell<ProbCircuit>> = ProbCircuit::new();
// Same leaf constructed twice returns the same NodeId
let x1 = circuit.leaf(StaticVar::from("x"));
let x2 = circuit.leaf(StaticVar::from("x"));
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.leaf(StaticVar::from("y"));
let sum1 = circuit.leaf(StaticVar::from("x")) + circuit.leaf(StaticVar::from("y"));
let sum2 = circuit.leaf(StaticVar::from("x")) + circuit.leaf(StaticVar::from("y"));
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.leaf(StaticVar::from("x")) + circuit.leaf(StaticVar::from("y"));
let xy2 = circuit.leaf(StaticVar::from("x")) + circuit.leaf(StaticVar::from("y"));
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.leaf(StaticVar::from("x")) + circuit.leaf(StaticVar::from("y"));
let yx = circuit.leaf(StaticVar::from("y")) + circuit.leaf(StaticVar::from("x"));
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.leaf(StaticVar::from("z"));
let xy_z = (circuit.leaf(StaticVar::from("x")) + circuit.leaf(StaticVar::from("y")))
+ circuit.leaf(StaticVar::from("z"));
let x_yz = circuit.leaf(StaticVar::from("x"))
+ (circuit.leaf(StaticVar::from("y")) + circuit.leaf(StaticVar::from("z")));
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.leaf(StaticVar::from("x")) + circuit.leaf(StaticVar::from("y")))
* circuit.leaf(StaticVar::from("z"));
let xyz2 = (circuit.leaf(StaticVar::from("x")) + circuit.leaf(StaticVar::from("y")))
* circuit.leaf(StaticVar::from("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

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

@@ -4,8 +4,8 @@ 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.term.iter().peekable();
let mut b_it = b.term.iter().peekable();
let mut a_it = a.vars.iter().peekable();
let mut b_it = b.vars.iter().peekable();
loop {
match (a_it.peek(), b_it.peek()) {
@@ -95,20 +95,20 @@ impl<V: Var, U: Into<Mono<V>>> FromIterator<(i32, U)> for Poly<V> {
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Mono<V: Var> {
pub term: Vec<(V, u32)>,
pub vars: Vec<(V, u32)>,
}
impl<V: Var> Mono<V> {
pub fn contains(&self, other: &Mono<V>) -> bool {
let mut self_it = self.term.iter().peekable();
let mut other_it = other.term.iter().peekable();
let mut self_it = self.vars.iter().peekable();
let mut other_it = other.vars.iter().peekable();
while let Some((o_term, o_exp)) = other_it.peek() {
if let Some((s_term, s_exp)) = self_it.peek() {
if s_term < o_term {
while let Some((o_var, o_exp)) = other_it.peek() {
if let Some((s_var, s_exp)) = self_it.peek() {
if s_var < o_var {
self_it.next();
continue;
} else if s_term > o_term {
} else if s_var > o_var {
return false;
} else if o_exp <= s_exp {
self_it.next();
@@ -126,8 +126,8 @@ impl<V: Var> Mono<V> {
/// 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.term.iter().peekable();
let mut other_it = other.term.iter().peekable();
let mut self_it = self.vars.iter().peekable();
let mut other_it = other.vars.iter().peekable();
let mut result: Vec<(V, u32)> = vec![];
loop {
@@ -149,13 +149,13 @@ impl<V: Var> Mono<V> {
}
}
Mono { term: result }
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.term.into_iter().peekable();
let mut other_it = other.term.iter().peekable();
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 {
@@ -179,7 +179,7 @@ impl<V: Var> Mono<V> {
}
}
Mono { term: result }
Mono { vars: result }
}
}
@@ -194,19 +194,19 @@ where
impl<V: Var, U: Into<V>> FromIterator<(U, u32)> for Mono<V> {
fn from_iter<T: IntoIterator<Item = (U, u32)>>(iter: T) -> Self {
let mut term = iter
let mut vars = iter
.into_iter()
.map(|(t, pow)| (t.into(), pow))
.collect::<Vec<(V, u32)>>();
term.sort();
vars.sort();
// Check duplicate variables
assert!(
(term[..])
(vars[..])
.windows(2)
.all(|window| window[0].0 != window[1].0)
);
Mono { term }
Mono { vars }
}
}

View File

@@ -64,7 +64,7 @@ impl<V: Var> Display for Mono<V> {
write!(
fmt,
"{}",
self.term
self.vars
.iter()
.map(|(t, p)| match p {
1 => format!("{t}"),

View File

@@ -5,11 +5,14 @@ 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>,

View File

@@ -24,31 +24,31 @@ 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 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_term.peek(), b_term.peek()) {
match (a_vars.peek(), b_vars.peek()) {
(Some((a_var, _)), Some((b_var, _))) => {
if a_var < b_var {
result.push(a_term.next().unwrap());
result.push(a_vars.next().unwrap());
} else if a_var > b_var {
result.push(b_term.next().unwrap());
result.push(b_vars.next().unwrap());
} else {
let (var, a_exp) = a_term.next().unwrap();
let (_, b_exp) = b_term.next().unwrap();
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_term.next();
a_vars.next();
}
(None, Some(b)) => {
result.push(b.clone());
b_term.next();
b_vars.next();
}
(None, None) => {
break;
@@ -56,7 +56,7 @@ impl<V: Var> Mul for Mono<V> {
}
}
Mono { term: result }
Mono { vars: result }
}
}

View File

@@ -57,7 +57,7 @@ fn test_mono_mul() {
// Multiply by constant monomial (empty term vec = 1)
let a: Mono<StaticVar> = [("x", 4)].into();
let one: Mono<StaticVar> = Mono { term: vec![] };
let one: Mono<StaticVar> = Mono { vars: vec![] };
assert_eq!(a.clone() * one, a);
}
@@ -110,7 +110,7 @@ fn test_lex_cmp() {
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 { term: vec![] };
let one: Mono<StaticVar> = Mono { vars: vec![] };
// x² > xy (x exponent 2 vs 1)
assert_eq!(lex_cmp(&x2, &xy), Ordering::Greater);
@@ -144,7 +144,7 @@ fn test_mono_div() {
// x / x = 1
let a: Mono<StaticVar> = [("x", 1)].into();
let b: Mono<StaticVar> = [("x", 1)].into();
assert_eq!(a.div(&b), Mono { term: vec![] });
assert_eq!(a.div(&b), Mono { vars: vec![] });
}
#[test]
@@ -210,7 +210,7 @@ fn test_s_poly() {
fn make_const_poly(c: i32) -> Poly<StaticVar> {
Poly {
mono: [(Mono { term: vec![] }, c)].into_iter().collect(),
mono: [(Mono { vars: vec![] }, c)].into_iter().collect(),
}
}