refactor wip

This commit is contained in:
2026-04-27 22:40:55 +02:00
parent 723033f3aa
commit 627a2d88f4
7 changed files with 163 additions and 177 deletions

View File

@@ -1,12 +1,9 @@
use std::cell::RefCell; use circuit_cas::circuit::probabilistic::ProbCircuit;
use std::rc::Rc; use circuit_cas::circuit::dag::CircuitExt;
use circuit_cas::circuit::traits::Circuit;
use circuit_cas::circuit::dag::{ProbCircuit, CircuitExt};
use circuit_cas::var; use circuit_cas::var;
fn main() { fn main() {
let mut circuit = ProbCircuit::new(); let circuit = ProbCircuit::new();
// Build (x + y) * (x + z) // Build (x + y) * (x + z)
let x = circuit.leaf(var!("x")); let x = circuit.leaf(var!("x"));

View File

@@ -1,6 +1,3 @@
use std::cell::RefCell;
use std::rc::Rc;
use circuit_cas::circuit::quotient::Quotient; use circuit_cas::circuit::quotient::Quotient;
use circuit_cas::poly::var::StaticVar; use circuit_cas::poly::var::StaticVar;
use circuit_cas::var; use circuit_cas::var;
@@ -15,7 +12,7 @@ fn main() {
1 * ((&x ^ 1) * (&nx ^ 1)) - 1 * (&x ^ 1), 1 * ((&x ^ 1) * (&nx ^ 1)) - 1 * (&x ^ 1),
]; ];
let mut quotient: Quotient<StaticVar> = idem.into_iter().collect(); let quotient: Quotient<StaticVar> = idem.into_iter().collect();
println!("{quotient}"); println!("{quotient:?}");
} }

View File

@@ -1,5 +1,7 @@
use slotmap::{SlotMap, new_key_type}; use slotmap::{SlotMap, new_key_type};
use std::cell::RefCell;
use std::collections::HashMap; use std::collections::HashMap;
use std::rc::Rc;
use super::traits::{Circuit, Node}; use super::traits::{Circuit, Node};
@@ -21,7 +23,7 @@ impl<N: Node> Default for Dag<N> {
} }
impl<N: Node> Dag<N> { impl<N: Node> Dag<N> {
fn node(&mut self, n: N) -> NodeId { 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;
} }
@@ -30,44 +32,40 @@ impl<N:Node> Dag<N>{
id id
} }
fn get(&self, id: NodeId) -> Option<&N> { pub(super) fn get(&self, id: NodeId) -> Option<&N> {
self.nodes.get(id) self.nodes.get(id)
} }
fn len(&self) -> usize { pub(super) fn len(&self) -> usize {
self.nodes.len() self.nodes.len()
} }
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) self.nodes.get(id).into_iter().flat_map(Node::children)
} }
fn remove(&mut self, id: NodeId) { 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 RefNode<T:DerefMut<Target=Dag>>{ pub struct RefNode<C: Circuit> {
pub id: NodeId, pub id: NodeId,
circuit: Rc<RefCell<T>> pub(super) circuit: Rc<RefCell<C>>,
} }
impl<C: Circuit> RefNode<C> { impl<C: Circuit> RefNode<C> {
fn leaf(&mut self, variable: C::Var)->Self{ pub fn get_node(&self, id: NodeId) -> Option<Self> {
let mut c = self.circuit.borrow_mut();
let id = c.leaf(variable);
RefNode {
id,
circuit: self.circuit.clone(),
}
}
fn get_node(&self, id:NodeId)->Option<Self>{
self.circuit.borrow().get(id)?; self.circuit.borrow().get(id)?;
Some(RefNode { Some(RefNode { id, circuit: self.circuit.clone() })
id,
circuit: self.circuit.clone(),
})
} }
} }
pub trait CircuitExt {
type C: Circuit;
type Var;
fn leaf(&self, var: Self::Var) -> RefNode<Self::C>;
fn len(&self) -> usize;
}

View File

@@ -1,9 +1,10 @@
use std::ops::{Deref, DerefMut}; use std::cell::RefCell;
use std::ops::{Add, Deref, DerefMut, Mul};
use std::rc::Rc; use std::rc::Rc;
use crate::poly::var::Var; use crate::poly::var::Var;
use super::dag::{Dag,NodeId}; use super::dag::{CircuitExt, Dag, NodeId, RefNode};
use super::traits::{Circuit,Node,RefNode}; use super::traits::Node;
#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Debug, PartialEq, Eq, Hash)]
@@ -13,7 +14,6 @@ pub enum PNode<V: Var> {
Prod(NodeId, NodeId), Prod(NodeId, NodeId),
} }
impl<V: Var> Node for PNode<V> { impl<V: Var> Node for PNode<V> {
fn children(&self) -> impl Iterator<Item = NodeId> { fn children(&self) -> impl Iterator<Item = NodeId> {
match self { match self {
@@ -25,55 +25,68 @@ impl<V:Var> Node for PNode<V>{
} }
} }
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug)]
pub struct ProbCircuit<V: Var> { pub struct ProbCircuit<V: Var> {
dag: Dag<PNode<V>>, 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()))
}
pub fn leaf(&mut self, v: V) -> NodeId { self.node(PNode::Leaf(v)) }
pub 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))
}
pub 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> { impl<V: Var> Deref for ProbCircuit<V> {
type Target = Dag<PNode<V>>; type Target = Dag<PNode<V>>;
fn deref(&self)->&Self::Target{ fn deref(&self) -> &Self::Target { &self.dag }
&self.dag
}
} }
impl<V: Var> DerefMut for ProbCircuit<V> { impl<V: Var> DerefMut for ProbCircuit<V> {
fn deref_mut(&mut self)->&mut Self::Target{ fn deref_mut(&mut self) -> &mut Self::Target { &mut self.dag }
&mut self.dag
}
} }
impl<V: Var> CircuitExt for Rc<RefCell<ProbCircuit<V>>> {
impl<V: Var> Rc<ProbCircuit<V>> { type C = ProbCircuit<V>;
pub fn var<T:Into<V>>(variable:T)->RefNode<Self>{
todo!()
}
}
impl<V:Var> Circuit for ProbCircuit<V>{
type Node=PNode<V>;
type Var = V; type Var = V;
fn leaf(&mut self, variable:V)->NodeId{ fn leaf(&self, var: V) -> RefNode<ProbCircuit<V>> {
self.node(Self::Node::Leaf(variable)) let id = self.borrow_mut().leaf(var);
RefNode { id, circuit: self.clone() }
} }
fn add(&mut self, left: NodeId, right: NodeId) -> NodeId { fn len(&self) -> usize { self.borrow().len() }
let (l, r) = if left <= right {
(left, right)
} else {
(right, left)
};
self.node(Self::Node::Sum(l, r))
} }
fn mul(&mut self, left: NodeId, right: NodeId) -> NodeId { impl<V: Var> Add for RefNode<ProbCircuit<V>> {
let (l, r) = if left <= right { type Output = Self;
(left, right)
} else { fn add(self, rhs: Self) -> Self {
(right, left) let id = self.circuit.borrow_mut().add(self.id, rhs.id);
}; RefNode { id, circuit: self.circuit }
self.node(Self::Node::Prod(l, r))
} }
} }
impl<V: Var> Mul for RefNode<ProbCircuit<V>> {
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 }
}
}

View File

@@ -1,10 +1,12 @@
use std::ops::{Deref, DerefMut}; use std::cell::RefCell;
use std::ops::{Add, Deref, DerefMut, Mul};
use std::rc::Rc;
use crate::poly::var::Var; use crate::poly::var::Var;
use crate::poly::flat::Poly; use crate::poly::flat::Poly;
use crate::poly::ideal::{Generators, GroebnerBasis, Ideal}; use crate::poly::ideal::{Generators, GroebnerBasis, Ideal};
use super::dag::{Dag,NodeId}; use super::dag::{CircuitExt, Dag, NodeId, RefNode};
use super::traits::{Circuit,Node}; use super::traits::Node;
#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Debug, PartialEq, Eq, Hash)]
@@ -12,10 +14,9 @@ pub enum QNode<V: Var> {
Leaf(V), Leaf(V),
Sum(NodeId, NodeId), Sum(NodeId, NodeId),
Prod(NodeId, NodeId), Prod(NodeId, NodeId),
DivStep(NodeId, NodeId) DivStep(NodeId, NodeId),
} }
impl<V: Var> Node for QNode<V> { impl<V: Var> Node for QNode<V> {
fn children(&self) -> impl Iterator<Item = NodeId> { fn children(&self) -> impl Iterator<Item = NodeId> {
match self { match self {
@@ -35,60 +36,68 @@ pub struct QuotientCircuit<V: Var> {
impl<V: Var> From<Ideal<V, GroebnerBasis>> for QuotientCircuit<V> { impl<V: Var> From<Ideal<V, GroebnerBasis>> for QuotientCircuit<V> {
fn from(basis: Ideal<V, GroebnerBasis>) -> Self { fn from(basis: Ideal<V, GroebnerBasis>) -> Self {
Self { Self { basis, dag: Default::default() }
basis,
dag: Default::default(),
}
} }
} }
impl<V: Var> FromIterator<Poly<V>> for QuotientCircuit<V> { impl<V: Var> FromIterator<Poly<V>> for QuotientCircuit<V> {
fn from_iter<T: IntoIterator<Item = Poly<V>>>(iter: T) -> Self { fn from_iter<T: IntoIterator<Item = Poly<V>>>(iter: T) -> Self {
let ideal: Ideal<V, Generators> = iter.into_iter().collect(); let ideal: Ideal<V, Generators> = iter.into_iter().collect();
Self { Self { basis: ideal.groebner_basis(), dag: Default::default() }
basis: ideal.groebner_basis(),
dag: Default::default(),
}
} }
} }
pub type Quotient<V> = QuotientCircuit<V>;
impl<V: Var> Deref for QuotientCircuit<V> { impl<V: Var> Deref for QuotientCircuit<V> {
type Target = Dag<QNode<V>>; type Target = Dag<QNode<V>>;
fn deref(&self)->&Self::Target{ fn deref(&self) -> &Self::Target { &self.dag }
&self.dag
}
} }
impl<V: Var> DerefMut for QuotientCircuit<V> { impl<V: Var> DerefMut for QuotientCircuit<V> {
fn deref_mut(&mut self)->&mut Self::Target{ fn deref_mut(&mut self) -> &mut Self::Target { &mut self.dag }
&mut self.dag }
impl<V: Var> QuotientCircuit<V> {
pub fn leaf(&mut self, v: V) -> NodeId { self.node(QNode::Leaf(v)) }
pub 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 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))
} }
} }
impl<V:Var> Circuit for QuotientCircuit<V>{ impl<V: Var> CircuitExt for Rc<RefCell<QuotientCircuit<V>>> {
type Node=QNode<V>; type C = QuotientCircuit<V>;
type Var = V; type Var = V;
fn leaf(&mut self, variable:V)->NodeId{ fn leaf(&self, var: V) -> RefNode<QuotientCircuit<V>> {
self.node(Self::Node::Leaf(variable)) let id = self.borrow_mut().leaf(var);
RefNode { id, circuit: self.clone() }
} }
fn add(&mut self, left: NodeId, right: NodeId) -> NodeId { fn len(&self) -> usize { self.borrow().len() }
let (l, r) = if left <= right {
(left, right)
} else {
(right, left)
};
self.node(Self::Node::Sum(l, r))
} }
fn mul(&mut self, left: NodeId, right: NodeId) -> NodeId { impl<V: Var> Add for RefNode<QuotientCircuit<V>> {
let (l, r) = if left <= right { type Output = Self;
(left, right)
} else { fn add(self, rhs: Self) -> Self {
(right, left) let id = self.circuit.borrow_mut().add(self.id, rhs.id);
}; RefNode { id, circuit: self.circuit }
self.node(Self::Node::Prod(l, r))
} }
} }
impl<V: Var> Mul for RefNode<QuotientCircuit<V>> {
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 }
}
}

View File

@@ -1,32 +1,29 @@
use std::cell::RefCell; use super::probabilistic::ProbCircuit;
use std::rc::Rc; use super::dag::CircuitExt;
use super::dag::{ProbCircuit, CircuitExt};
use super::traits::Circuit;
use crate::poly::var::StaticVar; use crate::poly::var::StaticVar;
#[test] #[test]
fn test_deduplication() { fn test_deduplication() {
let mut circuit = ProbCircuit::new(); let circuit = ProbCircuit::new();
// Same leaf constructed twice returns the same NodeId // Same leaf constructed twice returns the same NodeId
let x1 = circuit.leaf(StaticVar::from("x")); let x1 = circuit.leaf(StaticVar::from("x"));
let x2 = circuit.leaf(StaticVar::from("x")); let x2 = circuit.leaf(StaticVar::from("x"));
assert_eq!(x1.id, x2.id); assert_eq!(x1.id, x2.id);
assert_eq!(circuit.borrow().len(), 1); assert_eq!(circuit.len(), 1);
// Same sum constructed twice returns the same NodeId // Same sum constructed twice returns the same NodeId
let _y = circuit.leaf(StaticVar::from("y")); let _y = circuit.leaf(StaticVar::from("y"));
let sum1 = circuit.leaf(StaticVar::from("x")) + 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 sum2 = circuit.leaf(StaticVar::from("x")) + circuit.leaf(StaticVar::from("y"));
assert_eq!(sum1.id, sum2.id); assert_eq!(sum1.id, sum2.id);
assert_eq!(circuit.borrow().len(), 3); // x, y, x+y assert_eq!(circuit.len(), 3); // x, y, x+y
// Shared subexpression: (x + y) * (x + y) reuses the x+y node // Shared subexpression: (x + y) * (x + y) reuses the x+y node
let xy = circuit.leaf(StaticVar::from("x")) + circuit.leaf(StaticVar::from("y")); 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 xy2 = circuit.leaf(StaticVar::from("x")) + circuit.leaf(StaticVar::from("y"));
let _sq = xy * xy2; let _sq = xy * xy2;
assert_eq!(circuit.borrow().len(), 4); // x, y, x+y, (x+y)*(x+y) assert_eq!(circuit.len(), 4); // x, y, x+y, (x+y)*(x+y)
// Commutativity: x+y and y+x are the same node // Commutativity: x+y and y+x are the same node
let xy = circuit.leaf(StaticVar::from("x")) + circuit.leaf(StaticVar::from("y")); let xy = circuit.leaf(StaticVar::from("x")) + circuit.leaf(StaticVar::from("y"));

View File

@@ -1,51 +1,26 @@
use std::hash::Hash; use std::hash::Hash;
use std::ops::{Add,Mul}; use std::ops::DerefMut;
use std::{rc::Rc,cell::RefCell};
use super::dag::NodeId; use super::dag::{Dag, NodeId};
pub trait Node: Clone + PartialEq + Eq + Hash { pub trait Node: Clone + PartialEq + Eq + Hash {
fn children(&self) -> impl Iterator<Item = NodeId>; fn children(&self) -> impl Iterator<Item = NodeId>;
} }
pub trait Circuit:Clone{ pub trait Circuit: Clone + DerefMut<Target = Dag<Self::Node>> {
type Var; type Node: Node;
type Node;
fn node(&mut self, n:Self::Node)->NodeId; fn node(&mut self, n: Self::Node) -> NodeId { (**self).node(n) }
fn remove(&mut self, id:NodeId); fn remove(&mut self, id: NodeId) { (**self).remove(id) }
fn get(&self, id:NodeId)->Option<&Self::Node>; fn get(&self, id: NodeId) -> Option<&Self::Node> { (**self).get(id) }
fn len(&self) -> usize { (**self).len() }
fn leaf(&mut self, var: Self::Var)->NodeId; fn children(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ { (**self).children(id) }
fn add(&mut self, left: NodeId, right: NodeId)->NodeId;
fn mul(&mut self, left: NodeId, right: NodeId)->NodeId;
fn len(&self)->usize;
fn children(&self, id:NodeId)->impl Iterator<Item=NodeId>+'_;
} }
impl<T, N> Circuit for T
impl<C:Circuit> Add for RefNode<C> { where
type Output = Self; T: Clone + DerefMut<Target = Dag<N>>,
N: Node,
fn add(self, rhs: Self) -> Self { {
let id = self.circuit.borrow_mut().add(self.id, rhs.id); type Node = N;
RefNode {
id,
circuit: self.circuit,
} }
}
}
impl<C:Circuit> 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,
}
}
}