use crate::multiplicity::MultiplicityLike;
const SUM_OVERFLOW: &str = "AC multiset multiplicity overflowed its configured width";
type Pair<G, M> = (G, M);
#[inline]
fn debug_assert_canonical<G: Copy + Ord, M: MultiplicityLike>(m: &[Pair<G, M>]) {
debug_assert!(
m.windows(2).all(|w| w[0].0 < w[1].0),
"AC multiset not strictly sorted / duplicate-free by class id"
);
debug_assert!(
m.iter().all(|(_, mult)| *mult >= M::ONE),
"AC multiset has a zero (or absent) multiplicity entry"
);
}
pub fn multiset_disjoint<G: Copy + Ord, M: MultiplicityLike>(
a: &[Pair<G, M>],
b: &[Pair<G, M>],
) -> bool {
debug_assert_canonical(a);
debug_assert_canonical(b);
let (mut i, mut j) = (0, 0);
while i < a.len() && j < b.len() {
match a[i].0.cmp(&b[j].0) {
std::cmp::Ordering::Less => i += 1,
std::cmp::Ordering::Greater => j += 1,
std::cmp::Ordering::Equal => return false,
}
}
true
}
pub fn multiset_subset<G: Copy + Ord, M: MultiplicityLike>(
a: &[Pair<G, M>],
b: &[Pair<G, M>],
) -> bool {
debug_assert_canonical(a);
debug_assert_canonical(b);
let mut j = 0;
for &(ag, am) in a {
while j < b.len() && b[j].0 < ag {
j += 1;
}
if j >= b.len() || b[j].0 != ag || b[j].1 < am {
return false;
}
j += 1;
}
true
}
pub fn multiset_subtract_into<G: Copy + Ord, M: MultiplicityLike>(
out: &mut Vec<Pair<G, M>>,
a: &[Pair<G, M>],
b: &[Pair<G, M>],
) {
debug_assert_canonical(a);
debug_assert_canonical(b);
out.clear();
let (mut i, mut j) = (0, 0);
while i < a.len() {
if j < b.len() && b[j].0 < a[i].0 {
j += 1;
continue;
}
if j < b.len() && b[j].0 == a[i].0 {
let rem = a[i].0; let mult = a[i].1.saturating_sub(b[j].1);
if mult > M::ZERO {
out.push((rem, mult));
}
i += 1;
j += 1;
} else {
out.push(a[i]);
i += 1;
}
}
}
pub fn multiset_subtract<G: Copy + Ord, M: MultiplicityLike>(
a: &[Pair<G, M>],
b: &[Pair<G, M>],
) -> Vec<Pair<G, M>> {
let mut out = Vec::with_capacity(a.len());
multiset_subtract_into(&mut out, a, b);
out
}
pub fn multiset_union_into<G: Copy + Ord, M: MultiplicityLike>(
out: &mut Vec<Pair<G, M>>,
a: &[Pair<G, M>],
b: &[Pair<G, M>],
) {
debug_assert_canonical(a);
debug_assert_canonical(b);
out.clear();
let (mut i, mut j) = (0, 0);
while i < a.len() && j < b.len() {
match a[i].0.cmp(&b[j].0) {
std::cmp::Ordering::Less => {
out.push(a[i]);
i += 1;
}
std::cmp::Ordering::Greater => {
out.push(b[j]);
j += 1;
}
std::cmp::Ordering::Equal => {
out.push((a[i].0, a[i].1.checked_add(b[j].1).expect(SUM_OVERFLOW)));
i += 1;
j += 1;
}
}
}
out.extend_from_slice(&a[i..]);
out.extend_from_slice(&b[j..]);
}
pub fn multiset_union<G: Copy + Ord, M: MultiplicityLike>(
a: &[Pair<G, M>],
b: &[Pair<G, M>],
) -> Vec<Pair<G, M>> {
let mut out = Vec::with_capacity(a.len() + b.len());
multiset_union_into(&mut out, a, b);
out
}
pub fn multiset_lcm_into<G: Copy + Ord, M: MultiplicityLike>(
out: &mut Vec<Pair<G, M>>,
a: &[Pair<G, M>],
b: &[Pair<G, M>],
) {
debug_assert_canonical(a);
debug_assert_canonical(b);
out.clear();
let (mut i, mut j) = (0, 0);
while i < a.len() && j < b.len() {
match a[i].0.cmp(&b[j].0) {
std::cmp::Ordering::Less => {
out.push(a[i]);
i += 1;
}
std::cmp::Ordering::Greater => {
out.push(b[j]);
j += 1;
}
std::cmp::Ordering::Equal => {
out.push((a[i].0, a[i].1.max(b[j].1)));
i += 1;
j += 1;
}
}
}
out.extend_from_slice(&a[i..]);
out.extend_from_slice(&b[j..]);
}
pub fn multiset_lcm<G: Copy + Ord, M: MultiplicityLike>(
a: &[Pair<G, M>],
b: &[Pair<G, M>],
) -> Vec<Pair<G, M>> {
let mut out = Vec::with_capacity(a.len() + b.len());
multiset_lcm_into(&mut out, a, b);
out
}
pub fn multiset_intersect_into<G: Copy + Ord, M: MultiplicityLike>(
out: &mut Vec<Pair<G, M>>,
a: &[Pair<G, M>],
b: &[Pair<G, M>],
) {
debug_assert_canonical(a);
debug_assert_canonical(b);
out.clear();
let (mut i, mut j) = (0, 0);
while i < a.len() && j < b.len() {
match a[i].0.cmp(&b[j].0) {
std::cmp::Ordering::Less => i += 1,
std::cmp::Ordering::Greater => j += 1,
std::cmp::Ordering::Equal => {
out.push((a[i].0, a[i].1.min(b[j].1)));
i += 1;
j += 1;
}
}
}
}
pub fn multiset_intersect<G: Copy + Ord, M: MultiplicityLike>(
a: &[Pair<G, M>],
b: &[Pair<G, M>],
) -> Vec<Pair<G, M>> {
let mut out = Vec::new();
multiset_intersect_into(&mut out, a, b);
out
}
pub fn multiset_size<G: Copy, M: MultiplicityLike>(m: &[Pair<G, M>]) -> u64 {
m.iter()
.try_fold(0u64, |acc, (_, mult)| acc.checked_add(mult.to_u64()))
.expect(SUM_OVERFLOW)
}
pub fn monomial_cmp<G: Copy + Ord, M: MultiplicityLike>(
a: &[Pair<G, M>],
b: &[Pair<G, M>],
) -> std::cmp::Ordering {
multiset_size(a)
.cmp(&multiset_size(b))
.then_with(|| a.iter().rev().cmp(b.iter().rev()))
}
pub struct NfRule<G, M> {
pub lhs: Vec<Pair<G, M>>,
pub rhs: Vec<Pair<G, M>>,
}
#[derive(Clone, Copy)]
pub struct NfRuleRef<'a, G, M> {
pub lhs: &'a [Pair<G, M>],
pub rhs: &'a [Pair<G, M>],
}
impl<'a, G, M> From<&'a NfRule<G, M>> for NfRuleRef<'a, G, M> {
fn from(r: &'a NfRule<G, M>) -> Self {
Self {
lhs: &r.lhs,
rhs: &r.rhs,
}
}
}
#[derive(Clone, Copy)]
pub struct NfRules<'r, 'i, G, M> {
rules: &'i [NfRuleRef<'r, G, M>],
index: Option<&'i NfIndex<G>>,
}
impl<'r, 'i, G: Copy + Ord, M: MultiplicityLike> NfRules<'r, 'i, G, M> {
pub fn linear(rules: &'i [NfRuleRef<'r, G, M>]) -> Self {
Self { rules, index: None }
}
pub fn indexed(rules: &'i [NfRuleRef<'r, G, M>], index: &'i NfIndex<G>) -> Self {
debug_assert_eq!(
index.n_rules,
rules.len(),
"NfIndex was built from a different rule slice"
);
Self {
rules,
index: Some(index),
}
}
#[inline]
fn find_applicable(
&self,
out: &[Pair<G, M>],
cands: &mut CandVec,
) -> Option<NfRuleRef<'r, G, M>> {
match self.index {
None => self
.rules
.iter()
.copied()
.find(|r| rule_applies_linear(r, out)),
Some(ix) => {
ix.candidates(out, cands);
cands.iter().find_map(|&i| {
let r = self.rules[i as usize];
multiset_subset(r.lhs, out).then_some(r)
})
}
}
}
}
#[inline]
fn rule_applies_linear<G: Copy + Ord, M: MultiplicityLike>(
r: &NfRuleRef<'_, G, M>,
out: &[Pair<G, M>],
) -> bool {
if r.lhs.is_empty() {
return false;
}
debug_assert!(monomial_cmp(r.lhs, r.rhs) == std::cmp::Ordering::Greater);
multiset_subset(r.lhs, out)
}
type CandVec = smallvec::SmallVec<[u32; 32]>;
pub struct NfIndex<G> {
keys: Vec<G>,
starts: Vec<u32>,
order: Vec<u32>,
n_rules: usize,
}
impl<G: Copy + Ord> NfIndex<G> {
pub fn build<M: MultiplicityLike>(rules: &[NfRuleRef<'_, G, M>]) -> Self {
let mut ix = Self {
keys: Vec::new(),
starts: Vec::new(),
order: Vec::new(),
n_rules: 0,
};
ix.rebuild(rules);
ix
}
pub fn rebuild<M: MultiplicityLike>(&mut self, rules: &[NfRuleRef<'_, G, M>]) {
self.keys.clear();
self.starts.clear();
self.order.clear();
self.n_rules = rules.len();
u32::try_from(rules.len()).expect(
"NfIndex holds rule positions as u32; a table of 2^32 or more rules needs a \
wider position word",
);
let mut pairs: Vec<(G, u32)> = rules
.iter()
.enumerate()
.filter(|(_, r)| {
if r.lhs.is_empty() {
return false;
}
debug_assert!(monomial_cmp(r.lhs, r.rhs) == std::cmp::Ordering::Greater);
true
})
.map(|(i, r)| {
debug_assert_canonical(r.lhs);
(r.lhs[0].0, i as u32)
})
.collect();
pairs.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
self.starts.push(0);
for (k, i) in pairs {
if self.keys.last() != Some(&k) {
self.keys.push(k);
self.starts.push(self.order.len() as u32);
}
self.order.push(i);
*self.starts.last_mut().unwrap() = self.order.len() as u32;
}
}
#[inline]
fn candidates<M: MultiplicityLike>(&self, out: &[Pair<G, M>], buf: &mut CandVec) {
buf.clear();
for p in out {
if let Ok(k) = self.keys.binary_search(&p.0) {
let (s, e) = (self.starts[k] as usize, self.starts[k + 1] as usize);
buf.extend_from_slice(&self.order[s..e]);
}
}
buf.sort_unstable();
}
}
const GUARD_MAX_REWRITES: usize = 1_000_000;
pub fn normalize_ms_into<G: Copy + Ord, M: MultiplicityLike>(
out: &mut Vec<Pair<G, M>>,
scratch: &mut Vec<Pair<G, M>>,
ms: &[Pair<G, M>],
rules: NfRules<'_, '_, G, M>,
) {
normalize_ms_into_with_limit(out, scratch, ms, rules, GUARD_MAX_REWRITES);
}
fn normalize_ms_into_with_limit<G: Copy + Ord, M: MultiplicityLike>(
out: &mut Vec<Pair<G, M>>,
scratch: &mut Vec<Pair<G, M>>,
ms: &[Pair<G, M>],
rules: NfRules<'_, '_, G, M>,
max_rewrites: usize,
) {
out.clear();
out.extend_from_slice(ms);
let mut cands = CandVec::new();
let mut rewrites = 0usize;
while let Some(rule) = rules.find_applicable(out, &mut cands) {
assert!(
rewrites < max_rewrites,
"normalize_ms_into exceeded its rewrite guard before reaching a normal form"
);
#[cfg(debug_assertions)]
let before = out.clone();
multiset_subtract_into(scratch, out, rule.lhs);
multiset_union_into(out, scratch, rule.rhs);
#[cfg(debug_assertions)]
debug_assert!(
monomial_cmp(out, &before) == std::cmp::Ordering::Less,
"rewrite step failed to lower the host monomial (order not admissible?)"
);
rewrites += 1;
}
}
pub fn normalize_ms<G: Copy + Ord, M: MultiplicityLike>(
ms: &[Pair<G, M>],
rules: &[NfRule<G, M>],
) -> Vec<Pair<G, M>> {
let refs: Vec<NfRuleRef<'_, G, M>> = rules.iter().map(NfRuleRef::from).collect();
let mut out = Vec::new();
let mut scratch = Vec::new();
normalize_ms_into(&mut out, &mut scratch, ms, NfRules::linear(&refs));
out
}
pub fn clamp_idempotent<G: Copy, M: MultiplicityLike>(ms: &mut [Pair<G, M>]) {
for p in ms.iter_mut() {
p.1 = M::ONE;
}
}
pub fn normalize_set_into<G: Copy + Ord, M: MultiplicityLike>(
out: &mut Vec<Pair<G, M>>,
scratch: &mut Vec<Pair<G, M>>,
ms: &[Pair<G, M>],
rules: NfRules<'_, '_, G, M>,
) {
normalize_set_into_with_limit(out, scratch, ms, rules, GUARD_MAX_REWRITES);
}
fn normalize_set_into_with_limit<G: Copy + Ord, M: MultiplicityLike>(
out: &mut Vec<Pair<G, M>>,
scratch: &mut Vec<Pair<G, M>>,
ms: &[Pair<G, M>],
rules: NfRules<'_, '_, G, M>,
max_rewrites: usize,
) {
out.clear();
out.extend_from_slice(ms);
clamp_idempotent(out);
let mut cands = CandVec::new();
let mut rewrites = 0usize;
while let Some(rule) = rules.find_applicable(out, &mut cands) {
assert!(
rewrites < max_rewrites,
"normalize_set_into exceeded its rewrite guard before reaching a normal form"
);
#[cfg(debug_assertions)]
let before = out.clone();
multiset_subtract_into(scratch, out, rule.lhs);
multiset_union_into(out, scratch, rule.rhs);
clamp_idempotent(out);
#[cfg(debug_assertions)]
debug_assert!(
monomial_cmp(out, &before) == std::cmp::Ordering::Less,
"idempotent rewrite step failed to lower the host monomial"
);
rewrites += 1;
}
}
pub fn normalize_set<G: Copy + Ord, M: MultiplicityLike>(
ms: &[Pair<G, M>],
rules: &[NfRule<G, M>],
) -> Vec<Pair<G, M>> {
let refs: Vec<NfRuleRef<'_, G, M>> = rules.iter().map(NfRuleRef::from).collect();
let mut out = Vec::new();
let mut scratch = Vec::new();
normalize_set_into(&mut out, &mut scratch, ms, NfRules::linear(&refs));
out
}
pub fn clamp_nilpotent<G: Copy, M: MultiplicityLike>(ms: &mut Vec<Pair<G, M>>, order: u8) {
for p in ms.iter_mut() {
p.1 = p.1.rem_order(order);
}
ms.retain(|p| p.1 != M::ZERO);
}
pub fn normalize_nilpotent_into<G: Copy + Ord, M: MultiplicityLike>(
out: &mut Vec<Pair<G, M>>,
scratch: &mut Vec<Pair<G, M>>,
ms: &[Pair<G, M>],
rules: NfRules<'_, '_, G, M>,
order: u8,
) {
normalize_nilpotent_into_with_limit(out, scratch, ms, rules, order, GUARD_MAX_REWRITES);
}
fn normalize_nilpotent_into_with_limit<G: Copy + Ord, M: MultiplicityLike>(
out: &mut Vec<Pair<G, M>>,
scratch: &mut Vec<Pair<G, M>>,
ms: &[Pair<G, M>],
rules: NfRules<'_, '_, G, M>,
order: u8,
max_rewrites: usize,
) {
out.clear();
out.extend_from_slice(ms);
clamp_nilpotent(out, order);
let mut cands = CandVec::new();
let mut rewrites = 0usize;
while let Some(rule) = rules.find_applicable(out, &mut cands) {
assert!(
rewrites < max_rewrites,
"normalize_nilpotent_into exceeded its rewrite guard before reaching a normal form"
);
#[cfg(debug_assertions)]
let before = out.clone();
multiset_subtract_into(scratch, out, rule.lhs);
multiset_union_into(out, scratch, rule.rhs);
clamp_nilpotent(out, order);
#[cfg(debug_assertions)]
debug_assert!(
monomial_cmp(out, &before) == std::cmp::Ordering::Less,
"nilpotent rewrite step failed to lower the host monomial"
);
rewrites += 1;
}
}
pub fn normalize_nilpotent<G: Copy + Ord, M: MultiplicityLike>(
ms: &[Pair<G, M>],
rules: &[NfRule<G, M>],
order: u8,
) -> Vec<Pair<G, M>> {
let refs: Vec<NfRuleRef<'_, G, M>> = rules.iter().map(NfRuleRef::from).collect();
let mut out = Vec::new();
let mut scratch = Vec::new();
normalize_nilpotent_into(&mut out, &mut scratch, ms, NfRules::linear(&refs), order);
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::id::ENodeId;
use crate::multiplicity::Multiplicity;
fn id(n: u32) -> ENodeId {
ENodeId::new(n)
}
fn ms(pairs: &[(u32, u32)]) -> Vec<Pair<ENodeId, Multiplicity>> {
let mut v: Vec<Pair<ENodeId, Multiplicity>> = pairs
.iter()
.map(|&(g, m)| (id(g), Multiplicity(m)))
.collect();
v.sort_by_key(|p| p.0);
v
}
#[test]
fn disjoint_basic() {
assert!(multiset_disjoint(
&ms(&[(1, 1), (2, 1)]),
&ms(&[(3, 1), (4, 1)])
));
assert!(!multiset_disjoint(
&ms(&[(1, 1), (2, 1)]),
&ms(&[(2, 1), (5, 1)])
));
assert!(multiset_disjoint::<ENodeId, Multiplicity>(
&[],
&ms(&[(1, 1)])
));
assert!(multiset_disjoint::<ENodeId, Multiplicity>(&[], &[]));
}
#[test]
fn disjoint_ignores_multiplicity() {
assert!(!multiset_disjoint(&ms(&[(2, 5)]), &ms(&[(2, 1)])));
}
#[test]
fn subset_basic() {
assert!(multiset_subset(
&ms(&[(1, 1), (2, 1)]),
&ms(&[(1, 1), (2, 1), (4, 1)])
));
assert!(!multiset_subset(
&ms(&[(1, 1), (2, 1), (4, 1)]),
&ms(&[(1, 1), (2, 1)])
));
assert!(!multiset_subset(
&ms(&[(1, 1), (2, 1)]),
&ms(&[(2, 1), (4, 1)])
));
assert!(multiset_subset::<ENodeId, Multiplicity>(
&[],
&ms(&[(1, 1)])
));
}
#[test]
fn subset_respects_multiplicity() {
assert!(multiset_subset(&ms(&[(1, 2)]), &ms(&[(1, 3)])));
assert!(!multiset_subset(&ms(&[(1, 3)]), &ms(&[(1, 2)])));
assert!(multiset_subset(&ms(&[(1, 2)]), &ms(&[(1, 2)])));
}
#[test]
fn subtract_basic() {
assert_eq!(
multiset_subtract(&ms(&[(1, 1), (2, 1), (4, 1)]), &ms(&[(1, 1), (2, 1)])),
ms(&[(4, 1)])
);
assert_eq!(
multiset_subtract(&ms(&[(1, 1)]), &ms(&[(9, 1)])),
ms(&[(1, 1)])
);
}
#[test]
fn subtract_multiplicity_clamps_and_drops_zeros() {
assert_eq!(
multiset_subtract(&ms(&[(1, 3), (2, 1)]), &ms(&[(1, 1)])),
ms(&[(1, 2), (2, 1)])
);
assert_eq!(
multiset_subtract(&ms(&[(1, 2), (2, 1)]), &ms(&[(1, 2)])),
ms(&[(2, 1)])
);
let empty: Vec<Pair<ENodeId, Multiplicity>> = Vec::new();
assert_eq!(multiset_subtract(&ms(&[(1, 1)]), &ms(&[(1, 5)])), empty);
}
#[test]
fn union_sums_multiplicities() {
assert_eq!(
multiset_union(&ms(&[(1, 1), (2, 1)]), &ms(&[(2, 1), (4, 1)])),
ms(&[(1, 1), (2, 2), (4, 1)])
);
assert_eq!(
multiset_union(&ms(&[(4, 1)]), &ms(&[(3, 1)])),
ms(&[(3, 1), (4, 1)])
);
assert_eq!(
multiset_union(&ms(&[(3, 1), (4, 1)]), &ms(&[(3, 1)])),
ms(&[(3, 2), (4, 1)])
);
}
#[test]
fn lcm_takes_max_multiplicity() {
assert_eq!(
multiset_lcm(&ms(&[(1, 1), (2, 1)]), &ms(&[(2, 1), (4, 1)])),
ms(&[(1, 1), (2, 1), (4, 1)])
);
assert_eq!(multiset_lcm(&ms(&[(1, 3)]), &ms(&[(1, 1)])), ms(&[(1, 3)]));
assert_eq!(
multiset_lcm(&ms(&[(1, 2)]), &ms(&[(5, 1)])),
ms(&[(1, 2), (5, 1)])
);
}
#[test]
fn lcm_contains_both_operands() {
let a = ms(&[(1, 2), (2, 1)]);
let b = ms(&[(2, 3), (4, 1)]);
let ab = multiset_lcm(&a, &b);
assert!(multiset_subset(&a, &ab));
assert!(multiset_subset(&b, &ab));
}
#[test]
fn subtract_then_union_round_trips_lcm() {
let a = ms(&[(1, 1), (2, 2)]);
let b = ms(&[(2, 1), (4, 1)]);
let ab = multiset_lcm(&a, &b);
let residual = multiset_subtract(&ab, &a);
assert_eq!(multiset_union(&residual, &a), ab);
}
#[test]
fn into_variants_match_allocating_and_reuse_buffer() {
let a = ms(&[(1, 1), (2, 2), (4, 1)]);
let b = ms(&[(2, 1), (4, 1), (5, 1)]);
let mut buf = ms(&[(99, 7)]);
multiset_subtract_into(&mut buf, &a, &b);
assert_eq!(buf, multiset_subtract(&a, &b));
multiset_union_into(&mut buf, &a, &b);
assert_eq!(buf, multiset_union(&a, &b));
multiset_lcm_into(&mut buf, &a, &b);
assert_eq!(buf, multiset_lcm(&a, &b));
}
#[test]
fn normalize_ms_into_matches_and_reuses() {
let rules = vec![
NfRule {
lhs: ms(&[(1, 1), (2, 1)]),
rhs: ms(&[(3, 1)]),
},
NfRule {
lhs: ms(&[(3, 1), (4, 1)]),
rhs: ms(&[(5, 1)]),
},
];
let input = ms(&[(1, 1), (2, 1), (4, 1)]);
let refs: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
rules.iter().map(NfRuleRef::from).collect();
let mut out = ms(&[(99, 3)]); let mut scratch = ms(&[(88, 2)]); normalize_ms_into(&mut out, &mut scratch, &input, NfRules::linear(&refs));
assert_eq!(out, ms(&[(5, 1)]));
assert_eq!(out, normalize_ms(&input, &rules));
}
#[test]
#[should_panic(
expected = "normalize_ms_into exceeded its rewrite guard before reaching a normal form"
)]
fn rewrite_guard_never_returns_a_partial_normal_form() {
let rules = [NfRule {
lhs: ms(&[(1, 1)]),
rhs: Vec::new(),
}];
let refs: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
rules.iter().map(NfRuleRef::from).collect();
let mut out = Vec::new();
let mut scratch = Vec::new();
normalize_ms_into_with_limit(
&mut out,
&mut scratch,
&ms(&[(1, 2)]),
NfRules::linear(&refs),
1,
);
}
#[test]
fn indexed_picks_the_same_rule_as_the_linear_scan() {
let rules = [
NfRule {
lhs: ms(&[(3, 1), (4, 1)]),
rhs: ms(&[(6, 1)]),
},
NfRule {
lhs: ms(&[(1, 1), (2, 1)]),
rhs: ms(&[(7, 1)]),
},
];
let refs: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
rules.iter().map(NfRuleRef::from).collect();
let index = NfIndex::build(&refs);
let input = ms(&[(1, 1), (2, 1), (3, 1), (4, 1)]);
let mut lin = Vec::new();
let mut ixd = Vec::new();
let mut scratch = Vec::new();
normalize_ms_into(&mut lin, &mut scratch, &input, NfRules::linear(&refs));
normalize_ms_into(
&mut ixd,
&mut scratch,
&input,
NfRules::indexed(&refs, &index),
);
assert_eq!(lin, ixd, "indexed and linear normal forms diverged");
assert_eq!(lin, ms(&[(6, 1), (7, 1)]));
}
#[test]
fn indexed_matches_linear_for_every_host_over_six_classes() {
let rules = vec![
NfRule {
lhs: ms(&[(2, 1), (3, 1)]),
rhs: ms(&[(1, 1)]),
},
NfRule {
lhs: ms(&[(1, 1), (4, 1)]),
rhs: ms(&[(2, 1)]),
},
NfRule {
lhs: ms(&[(1, 2)]),
rhs: ms(&[(3, 1)]),
},
NfRule {
lhs: ms(&[(4, 1), (5, 1)]),
rhs: ms(&[(1, 1)]),
},
NfRule {
lhs: ms(&[(1, 1), (2, 1), (3, 1)]),
rhs: ms(&[(5, 1)]),
},
];
for r in &rules {
assert_eq!(
monomial_cmp(&r.lhs, &r.rhs),
std::cmp::Ordering::Greater,
"test rule table is mis-oriented"
);
}
let refs: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
rules.iter().map(NfRuleRef::from).collect();
let index = NfIndex::build(&refs);
let mut checked = 0;
for code in 0..3usize.pow(6) {
let mut host: Vec<Pair<ENodeId, Multiplicity>> = Vec::new();
let mut c = code;
for cls in 1..=6u32 {
let mult = (c % 3) as u32;
c /= 3;
if mult > 0 {
host.push((id(cls), Multiplicity(mult)));
}
}
let (mut lin, mut ixd, mut scratch) = (Vec::new(), Vec::new(), Vec::new());
normalize_ms_into(&mut lin, &mut scratch, &host, NfRules::linear(&refs));
normalize_ms_into(
&mut ixd,
&mut scratch,
&host,
NfRules::indexed(&refs, &index),
);
assert_eq!(lin, ixd, "normalize_ms_into diverged on host {host:?}");
normalize_set_into(&mut lin, &mut scratch, &host, NfRules::linear(&refs));
normalize_set_into(
&mut ixd,
&mut scratch,
&host,
NfRules::indexed(&refs, &index),
);
assert_eq!(lin, ixd, "normalize_set_into diverged on host {host:?}");
for order in [2u8, 3] {
normalize_nilpotent_into(
&mut lin,
&mut scratch,
&host,
NfRules::linear(&refs),
order,
);
normalize_nilpotent_into(
&mut ixd,
&mut scratch,
&host,
NfRules::indexed(&refs, &index),
order,
);
assert_eq!(
lin, ixd,
"normalize_nilpotent_into (order {order}) diverged on host {host:?}"
);
}
checked += 1;
}
assert_eq!(checked, 729);
}
#[test]
fn nf_index_rebuild_matches_fresh_build() {
let first = [NfRule {
lhs: ms(&[(5, 1), (6, 1)]),
rhs: ms(&[(2, 1)]),
}];
let second = [
NfRule {
lhs: ms(&[(1, 1), (9, 1)]),
rhs: ms(&[(4, 1)]),
},
NfRule {
lhs: ms(&[(1, 3)]),
rhs: ms(&[(2, 1)]),
},
];
let r1: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
first.iter().map(NfRuleRef::from).collect();
let r2: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
second.iter().map(NfRuleRef::from).collect();
let mut reused = NfIndex::build(&r1);
reused.rebuild(&r2);
let fresh = NfIndex::build(&r2);
assert_eq!(reused.keys, fresh.keys);
assert_eq!(reused.starts, fresh.starts);
assert_eq!(reused.order, fresh.order);
assert_eq!(reused.n_rules, fresh.n_rules);
}
#[test]
fn empty_lhs_rule_is_skipped_by_both_paths() {
let rules = [
NfRule {
lhs: Vec::new(),
rhs: Vec::new(),
},
NfRule {
lhs: ms(&[(1, 1), (2, 1)]),
rhs: ms(&[(3, 1)]),
},
];
let refs: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
rules.iter().map(NfRuleRef::from).collect();
let index = NfIndex::build(&refs);
assert_eq!(index.order, vec![1]);
let input = ms(&[(1, 1), (2, 1)]);
let (mut lin, mut ixd, mut scratch) = (Vec::new(), Vec::new(), Vec::new());
normalize_ms_into(&mut lin, &mut scratch, &input, NfRules::linear(&refs));
normalize_ms_into(
&mut ixd,
&mut scratch,
&input,
NfRules::indexed(&refs, &index),
);
assert_eq!(lin, ms(&[(3, 1)]));
assert_eq!(lin, ixd);
}
#[test]
fn clamp_nilpotent_reduces_mod_order_and_drops_zeros() {
let mut m = ms(&[(1, 2), (2, 3), (3, 4)]);
clamp_nilpotent(&mut m, 2);
assert_eq!(m, ms(&[(2, 1)]));
let mut m3 = ms(&[(1, 3), (2, 4), (3, 5)]);
clamp_nilpotent(&mut m3, 3);
assert_eq!(m3, ms(&[(2, 1), (3, 2)]));
let mut even = ms(&[(1, 2), (2, 4)]);
clamp_nilpotent(&mut even, 2);
assert!(even.is_empty());
}
#[test]
fn normalize_nilpotent_symmetric_difference_join() {
let rules = vec![NfRule {
lhs: ms(&[(1, 1), (2, 1)]),
rhs: vec![], }];
assert_eq!(
normalize_nilpotent(&ms(&[(1, 1), (2, 1), (3, 1)]), &rules, 2),
ms(&[(3, 1)])
);
assert!(normalize_nilpotent(&ms(&[(1, 2)]), &[], 2).is_empty());
let input = ms(&[(1, 1), (2, 1), (3, 1)]);
let refs: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
rules.iter().map(NfRuleRef::from).collect();
let mut out = ms(&[(99, 3)]);
let mut scratch = ms(&[(88, 2)]);
normalize_nilpotent_into(&mut out, &mut scratch, &input, NfRules::linear(&refs), 2);
assert_eq!(out, normalize_nilpotent(&input, &rules, 2));
}
fn lcg(rng: &mut u64, m: u32) -> u32 {
*rng = rng
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
((*rng >> 33) as u32) % m
}
fn rand_ms(rng: &mut u64) -> Vec<Pair<ENodeId, Multiplicity>> {
let mut v = Vec::new();
for g in 1..=6u32 {
let c = lcg(rng, 4);
if c > 0 {
v.push((id(g), Multiplicity(c)));
}
}
v
}
#[test]
fn monomial_cmp_kapur_deglex_counterexample() {
let bb = ms(&[(2, 2)]);
let ac = ms(&[(1, 1), (3, 1)]);
assert_eq!(monomial_cmp(&ac, &bb), std::cmp::Ordering::Greater);
let ac_a = multiset_union(&ac, &ms(&[(1, 1)])); let bb_a = multiset_union(&bb, &ms(&[(1, 1)])); assert_eq!(monomial_cmp(&ac_a, &bb_a), std::cmp::Ordering::Greater);
}
#[test]
fn monomial_cmp_compatibility_randomized() {
let mut rng: u64 = 42;
let mut checked = 0usize;
for _ in 0..2000 {
let a = rand_ms(&mut rng);
let b = rand_ms(&mut rng);
let x = rand_ms(&mut rng);
let ord = monomial_cmp(&a, &b);
if ord == std::cmp::Ordering::Equal {
assert_eq!(a, b, "Equal must mean identical multisets");
continue;
}
assert_eq!(
monomial_cmp(&multiset_union(&a, &x), &multiset_union(&b, &x)),
ord,
"compatibility violated: a={a:?} b={b:?} x={x:?}"
);
checked += 1;
}
assert!(checked > 1000);
}
#[test]
fn monomial_cmp_subterm_property_randomized() {
let mut rng: u64 = 7;
for _ in 0..1000 {
let b = rand_ms(&mut rng);
let mut ext = rand_ms(&mut rng);
if ext.is_empty() {
ext = ms(&[(1, 1)]);
}
let a = multiset_union(&b, &ext);
assert_eq!(monomial_cmp(&a, &b), std::cmp::Ordering::Greater);
}
}
#[test]
fn former_cycle_rules_terminate_at_irreducible_normal_form() {
let r1 = NfRule {
lhs: ms(&[(1, 1), (3, 1)]),
rhs: ms(&[(2, 2)]),
}; let r2 = NfRule {
lhs: ms(&[(1, 2), (3, 1)]),
rhs: ms(&[(1, 1), (2, 2)]),
}; assert_eq!(monomial_cmp(&r1.lhs, &r1.rhs), std::cmp::Ordering::Greater);
assert_eq!(monomial_cmp(&r2.lhs, &r2.rhs), std::cmp::Ordering::Greater);
let rules = [r1, r2];
for host in [
ms(&[(1, 1), (2, 2)]),
ms(&[(1, 2), (3, 1)]),
ms(&[(1, 2), (3, 2)]),
] {
let out = normalize_ms(&host, &rules);
for r in &rules {
assert!(
!multiset_subset(&r.lhs, &out),
"normalize_ms({host:?}) returned a reducible result {out:?}"
);
}
}
}
}