95 lines
2.2 KiB
Rust
95 lines
2.2 KiB
Rust
use std::ops::{Deref, DerefMut};
|
|
|
|
use crate::poly::var::Var;
|
|
use crate::poly::flat::Poly;
|
|
use crate::poly::ideal::{Generators, GroebnerBasis, Ideal};
|
|
use super::dag::{Dag,NodeId};
|
|
use super::traits::{Circuit,Node};
|
|
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
|
pub enum QNode<V: Var> {
|
|
Leaf(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::Leaf(_) => [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> {
|
|
basis: Ideal<V, GroebnerBasis>,
|
|
dag: Dag<QNode<V>>,
|
|
}
|
|
|
|
impl<V: Var> From<Ideal<V, GroebnerBasis>> for QuotientCircuit<V> {
|
|
fn from(basis: Ideal<V, GroebnerBasis>) -> Self {
|
|
Self {
|
|
basis,
|
|
dag: Default::default(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<V: Var> FromIterator<Poly<V>> for QuotientCircuit<V> {
|
|
fn from_iter<T: IntoIterator<Item = Poly<V>>>(iter: T) -> Self {
|
|
let ideal: Ideal<V, Generators> = iter.into_iter().collect();
|
|
Self {
|
|
basis: ideal.groebner_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> Circuit for QuotientCircuit<V>{
|
|
type Node=QNode<V>;
|
|
type Var=V;
|
|
|
|
fn leaf(&mut self, variable:V)->NodeId{
|
|
self.node(Self::Node::Leaf(variable))
|
|
}
|
|
|
|
fn add(&mut self, left: NodeId, right: NodeId) -> NodeId {
|
|
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 {
|
|
let (l, r) = if left <= right {
|
|
(left, right)
|
|
} else {
|
|
(right, left)
|
|
};
|
|
self.node(Self::Node::Prod(l, r))
|
|
}
|
|
}
|
|
|