diff --git a/Cargo.lock b/Cargo.lock index 30fdb2568..d907095d9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2333,6 +2333,15 @@ dependencies = [ "ppvm-traits", ] +[[package]] +name = "ppvm-sym-2" +version = "0.4.1" +dependencies = [ + "fxhash", + "num", + "ppvm-traits-2", +] + [[package]] name = "ppvm-tableau" version = "0.4.1" diff --git a/Cargo.toml b/Cargo.toml index 5fb910c24..ad216df51 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,7 @@ members = [ "crates/ppvm-cli", "crates/ppvm-traits-2", "crates/ppvm-pauli-word-2", + "crates/ppvm-sym-2", # Runnable copies of the Rust code blocks in skills/ppvm-usage/SKILL.md. # Built by `cargo build --workspace --all-targets` in CI so the skill # can't silently drift away from the public API. diff --git a/crates/ppvm-sym-2/Cargo.toml b/crates/ppvm-sym-2/Cargo.toml new file mode 100644 index 000000000..1d46201fb --- /dev/null +++ b/crates/ppvm-sym-2/Cargo.toml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: 2026 The PPVM Authors +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "ppvm-sym-2" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +publish = false +description = "Symbolic (sin/cos polynomial) coefficient ring over ppvm-traits-2." + +[dependencies] +# Seed-free hasher for the monomial table, so `Display` output is stable +# across runs. +fxhash = "0.2.1" +num = "0.4" +ppvm-traits-2 = { path = "../ppvm-traits-2" } diff --git a/crates/ppvm-sym-2/src/add.rs b/crates/ppvm-sym-2/src/add.rs new file mode 100644 index 000000000..d72b2162d --- /dev/null +++ b/crates/ppvm-sym-2/src/add.rs @@ -0,0 +1,233 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Addition and subtraction on [`Term`], truncating with the left operand's +//! settings. A [`Sum`] carries no settings, so it is only changed through +//! [`Sum::add_term`]/[`Sum::mul_term`], which take them explicitly. + +use crate::sum::Sum; +use crate::term::{Inner, Term}; + +impl Sum { + /// Add a non-`Sum` representation, with the truncation of [`Sum::add_term`]. + #[inline] + fn add_small(&mut self, rhs: Inner, max: usize, min_eps: f64) { + match rhs { + Inner::One(p, c) => self.add_term(p, c, max, min_eps), + Inner::Const(c) => self.c0 += c, + Inner::Sum(_) => unreachable!(), + } + } +} + +/// A `Sum` operand's table is reused (moved in), whichever side it is on; a +/// right-hand table is pruned to `self`'s settings when its own are looser. +impl std::ops::AddAssign for Term { + #[inline] + fn add_assign(&mut self, rhs: Term) { + let (max, eps) = (self.max_sin, self.min_eps); + let looser = self.is_looser(&rhs); + self.inner = match (std::mem::take(&mut self.inner), rhs.inner) { + (Inner::Const(a), Inner::Const(b)) => Inner::Const(a + b), + (Inner::Sum(mut s1), Inner::Sum(s2)) => { + for (p, c) in s2.maps.into_iter().flat_map(|m| m.terms) { + s1.add_term(p, c, max, eps); + } + s1.c0 += s2.c0; + Inner::Sum(s1) + } + (Inner::Sum(mut s), small) => { + s.add_small(small, max, eps); + Inner::Sum(s) + } + (small, Inner::Sum(mut s)) => { + if looser { + s.prune(max, eps); + } + s.add_small(small, max, eps); + Inner::Sum(s) + } + (a, b) => { + let mut s = Sum::new(); + s.add_small(a, max, eps); + s.add_small(b, max, eps); + Inner::Sum(s) + } + }; + } +} + +impl Term { + /// `self += sign · rhs` without cloning a `Sum` right operand's table. + fn add_scaled_ref(&mut self, rhs: &Term, sign: f64) { + if let (Inner::Sum(lhs), Inner::Sum(rhs)) = (&mut self.inner, &rhs.inner) { + for (p, c) in rhs.iter() { + lhs.add_term(p.clone(), sign * c, self.max_sin, self.min_eps); + } + lhs.c0 += sign * rhs.c0; + return; + } + let mut rhs = rhs.clone(); + if sign < 0.0 { + rhs.negate(); + } + *self += rhs; + } +} + +impl std::ops::AddAssign<&Term> for Term { + #[inline] + fn add_assign(&mut self, rhs: &Term) { + self.add_scaled_ref(rhs, 1.0); + } +} + +impl std::ops::SubAssign<&Term> for Term { + #[inline] + fn sub_assign(&mut self, rhs: &Term) { + self.add_scaled_ref(rhs, -1.0); + } +} + +impl std::ops::SubAssign for Term { + #[inline] + #[allow(clippy::suspicious_op_assign_impl)] // subtraction adds the negation + fn sub_assign(&mut self, mut rhs: Term) { + rhs.negate(); + *self += rhs; + } +} + +impl std::ops::AddAssign for Term { + #[inline] + fn add_assign(&mut self, rhs: f64) { + *self += Term::from_f64(rhs); + } +} + +impl std::ops::SubAssign for Term { + #[inline] + fn sub_assign(&mut self, rhs: f64) { + *self += Term::from_f64(-rhs); + } +} + +binary_ops!(Add::add from AddAssign::add_assign for Term, &Term, f64); +binary_ops!(Sub::sub from SubAssign::sub_assign for Term, &Term, f64); + +impl std::ops::Add for f64 { + type Output = Term; + + #[inline] + fn add(self, rhs: Term) -> Term { + rhs + self + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::prod::Prod; + use crate::term::Var; + use ppvm_traits_2::ImaginaryUnit; + + #[test] + fn term_operators_truncate_with_the_left_settings() { + let mut sum = Sum::new(); + // The identity folds into c₀, which no threshold truncates. + sum.add_term(Prod::new(), 1.0, 0, 1e-3); + sum.add_term(Prod::new(), 1e-9, 0, 1e-3); + assert_eq!((sum.len(), sum.c0()), (0, 1.0 + 1e-9)); + + let mut t = Term::from(1.0) + Var(1).cos(); + t.set_max_sin(0); + t.set_min_eps(1e-3); + t += Var(0).sin(); // above `max_sin`: dropped + t += Var(1).cos() * 1e-6; // below `min_eps`: dropped + t += 1e-9; // a constant: kept + assert_eq!(t.inner(), (Term::from(1.0 + 1e-9) + Var(1).cos()).inner()); + } + + #[test] + fn cancellation_removes_the_monomial() { + let mut t = Var(0).sin(); + t += Var(0).sin() * -1.0; + assert_eq!(t.n_monomials(), 0); + assert_eq!(t.to_string(), "[]"); + // A merge that lands below `min_eps` (not exactly 0) is removed too. + let mut t = Var(0).sin() + Var(1).cos(); + t.set_min_eps(1e-3); + t += Var(0).sin() * -0.9995; + assert_eq!(t.n_monomials(), 1); + } + + #[test] + fn scaling_down_prunes_but_a_sign_flip_does_not_walk_twice() { + let mut t = Var(0).sin() + Var(1).cos() * 1e-3; + t.set_min_eps(1e-6); + t *= -1.0; + assert_eq!(t.n_monomials(), 2); + t *= 1e-4; + assert_eq!(t.n_monomials(), 1, "1e-7 fell below min_eps"); + t *= 0.0; + assert_eq!(t.n_monomials(), 0); + } + + #[test] + fn truncation_parameters_come_from_the_left() { + // The left operand's `max_sin` wins. + let mut a = Term::from_f64(1.0) + Var(1).cos(); + a.set_max_sin(0); + let b = Var(0).sin(); // max_sin = usize::MAX + let ab = a.clone() * b.clone(); + let ba = b * a; + assert_eq!(ab.n_monomials(), 0, "LHS max_sin = 0 truncated everything"); + assert!(ba.n_monomials() > 0, "LHS max_sin = MAX kept the monomials"); + } + + #[test] + fn identity_monomial_folds_into_c0_through_term_ops() { + // `Term` addition folds `i⁰ · 1` into `c₀`; only `Sum += Prod` does not. + let mut t = Term::from(1.0) + Var(0).sin(); + t += Term::imaginary_unit() * Term::imaginary_unit(); + assert_eq!(t.n_monomials(), 1); + assert!(matches!(t.inner(), Inner::Sum(s) if s.c0() == 0.0)); + } + + #[test] + fn adding_a_constant_to_a_single_monomial_keeps_both() { + let mut t = Var(0).sin(); + t += 2.0; + assert_eq!(t.eval(&[1.1]).unwrap(), 2.0 + 1.1f64.sin()); + } + + #[test] + fn subtraction_matches_adding_the_negation() { + let a = Term::from(1.0) + Var(0).sin() * 2.0; + let b = Var(0).sin() + Var(1).cos(); + let want = a.clone() + -b.clone(); + assert_eq!(a.clone() - b.clone(), want); + assert_eq!(a.clone() - &b, want); + let mut c = a.clone(); + c -= &b; + assert_eq!(c, want); + assert_eq!(a.clone() - 1.5, a + -1.5); + } + + #[test] + fn adding_a_term_ignores_the_right_operands_thresholds() { + let mut big = Term::from(0.0) + Var(0).sin(); + big.set_min_eps(0.5); + let mut small = Term::from(1.0) + Var(1).sin() * 1e-6; + small.set_min_eps(1e-12); + let mut l = small.clone(); + l += big.clone(); + assert_eq!(l.n_monomials(), 2, "left `min_eps` = 1e-12 keeps both"); + big += small; + assert_eq!( + big.n_monomials(), + 1, + "left `min_eps` = 0.5 drops the 1e-6 monomial" + ); + } +} diff --git a/crates/ppvm-sym-2/src/coeff.rs b/crates/ppvm-sym-2/src/coeff.rs new file mode 100644 index 000000000..fd507270b --- /dev/null +++ b/crates/ppvm-sym-2/src/coeff.rs @@ -0,0 +1,498 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! [`Term`] as a `ppvm-traits-2` coefficient: [`Coefficient`], [`Angle`], +//! [`ImaginaryUnit`], [`Conjugate`] and `Halvable`. + +use ppvm_traits_2::{Angle, Coefficient, Conjugate, ImaginaryUnit}; + +use crate::prod::{ONE, Prod}; +use crate::sum::Sum; +use crate::term::{Inner, Term, Var}; + +impl Coefficient for Term { + /// Flips the stored signs in place (or does nothing for `+1`); never a + /// `Term` product. Panics on a bare variable. + #[inline] + fn mul_sign(&self, sign: i8) -> Self { + let mut ret = self.clone(); + ret.mul_sign_assign(sign); + ret + } + + #[inline] + fn mul_sign_assign(&mut self, sign: i8) { + if sign < 0 { + self.negate(); + } + } + + /// `|c|` for a constant (including a `Sum` with no monomials), `+∞` otherwise. + /// + /// So a `CoefficientThreshold` policy never drops a symbolic coefficient; + /// symbolic terms truncate through `max_sin`/`min_eps` instead. This breaks the + /// law `N(x) == 0 iff x == 0`, but no absolute value exists on this ring, and an + /// `ℓ¹` norm (a usable substitute) would start dropping symbolic coefficients. + fn magnitude(&self) -> f64 { + self.as_const().map_or(f64::INFINITY, f64::abs) + } +} + +/// `x_u ↦ (sin x_u, cos x_u)`. The ring is the free polynomial ring, so +/// `sin² + cos² = 1` holds only after evaluation. +impl Angle for Var { + #[inline] + fn sin_cos(&self) -> (Term, Term) { + (self.sin(), self.cos()) + } +} + +/// An `f64` angle on a symbolic sum, folded to two constants. +impl Angle for f64 { + #[inline] + fn sin_cos(&self) -> (Term, Term) { + let (s, c) = f64::sin_cos(*self); + (Term::from_f64(s), Term::from_f64(c)) + } +} + +impl Term { + /// Multiply by `i^phase`: `eval_complex(x.mul_phase(k)) == iᵏ · eval_complex(x)`. + /// Even phases scale in place; odd ones flip every key's `i` bit and rebuild. + #[inline] + pub fn mul_phase(&self, phase: u8) -> Self { + match (&self.inner, phase & 3) { + (_, 0) => self.clone(), + (_, 2) => -self.clone(), + (_, k) => self.rotate_phase(k), + } + } + + /// [`Term::mul_phase`] for odd `k`. + fn rotate_phase(&self, k: u8) -> Self { + let relabel = |p: &Prod, c: f64| { + let mut q = p.clone(); + let sign = q.mul_phase(k); + (q, c * sign) + }; + match self.inner { + Inner::Sum(ref s) => { + let mut ret = Sum::new(); + for (p, c) in s.iter().chain([(&ONE, s.c0)]) { + let (q, c) = relabel(p, c); + ret.add_term(q, c, self.max_sin, self.min_eps); + } + self.with_inner(Inner::Sum(ret)) + } + Inner::Const(c) => { + let (q, c) = relabel(&ONE, c); + self.with_inner(Inner::truncated(q, c, self.max_sin, self.min_eps)) + } + Inner::One(ref p, c) => { + let (q, c) = relabel(p, c); + self.with_inner(Inner::truncated(q, c, self.max_sin, self.min_eps)) + } + } + } +} + +/// `i` is `One(i, 1.0)`; `i·i` normalises back to `Const(−1.0)`. +impl ImaginaryUnit for Term { + fn imaginary_unit() -> Self { + Term::from_f64(1.0).mul_phase(1) + } + + /// Folds `i` into the monomials rather than running a `Term` product. + fn mul_i(&self) -> Self { + self.mul_phase(1) + } + + /// Folds `iᵏ` into the monomials. + fn mul_i_pow(&self, k: u8) -> Self { + self.mul_phase(k & 3) + } +} + +/// `i ↦ −i`: negates every imaginary monomial in place, since no key changes. +impl Conjugate for Term { + fn conj(&self) -> Self { + let mut ret = self.clone(); + match ret.inner { + Inner::Sum(ref mut s) => { + if let Some(maps) = &mut s.maps { + for (_, c) in maps.terms.iter_mut().filter(|(p, _)| p.imag) { + *c = -*c; + } + } + } + Inner::One(ref p, ref mut c) if p.imag => *c = -*c, + Inner::One(..) | Inner::Const(_) => {} + } + ret + } +} + +/// Folds from the first summand, so its truncation settings apply, as for `a + b +/// + …`; an empty iterator gives `Const(0.0)` with the default settings. +impl std::iter::Sum for Term { + #[inline] + fn sum>(mut iter: I) -> Self { + let mut total = iter.next().unwrap_or_else(|| Term::from_f64(0.0)); + for t in iter { + total += t; + } + total + } +} + +/// Exact in `f64`: scales the coefficients by `0.5` without pruning, so +/// `x.half() + x.half() == x`. +impl ppvm_traits_2::Halvable for Term { + #[inline] + fn half(&self) -> Self { + let mut ret = self.clone(); + match ret.inner { + Inner::Sum(ref mut s) => s.scale(0.5), + Inner::One(_, ref mut c) | Inner::Const(ref mut c) => *c *= 0.5, + } + ret + } +} + +impl std::ops::Neg for Term { + type Output = Term; + + #[inline] + fn neg(mut self) -> Self::Output { + self.negate(); + self + } +} + +macro_rules! from_number { + ($($t:ty),*) => {$( + impl From<$t> for Term { + #[inline] + fn from(value: $t) -> Self { + Term::from_f64(value as f64) + } + } + )*}; +} +from_number!(f32, f64, i32, i64); + +/// `is_zero()` holds for a constant (`Const`, or a `Sum` with no monomials) with `|c| <= min_eps`. +impl num::Zero for Term { + fn zero() -> Self { + Term::from_f64(0.0) + } + + fn is_zero(&self) -> bool { + self.as_const().is_some_and(|c| c.abs() <= self.min_eps) + } +} + +/// `one()` is `Const(1.0)`. +impl num::One for Term { + fn one() -> Self { + Term::from_f64(1.0) + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::term::Var; + use num::{Complex, Zero}; + + /// Constants in any form are zero at or below `min_eps` and have `|c|` as their + /// magnitude; symbolic forms never are zero and never get dropped by a threshold. + #[test] + fn constants_in_any_form_are_zero_and_have_a_magnitude() { + assert!(Term::from_f64(0.0).is_zero()); + assert_eq!(Term::from_f64(-1e-30).magnitude(), 1e-30); + let mut t = Var(0).sin(); + t += Var(0).sin() * -1.0; + assert!(matches!(t.inner(), Inner::Sum(_))); + assert!(t.is_zero(), "a cancelled `Sum` is zero"); + assert_eq!(t.magnitude(), 0.0); + t += -2.5; + assert!(!t.is_zero()); + assert_eq!(t.magnitude(), 2.5); + let mut tiny = Var(0).sin(); + tiny.set_min_eps(0.0); + tiny *= 1e-30; + assert!(!tiny.is_zero()); + assert_eq!(tiny.magnitude(), f64::INFINITY); + // With the default `min_eps` the product truncates to an exact zero. + assert!((Var(0).sin() * 1e-30).is_zero()); + } + + #[test] + fn equality_looks_through_the_representation() { + let with = |inner| Term { + inner, + max_sin: usize::MAX, + min_eps: f64::EPSILON, + }; + let mut c0_only = Sum::new(); + c0_only.c0 = 1.0; + assert_eq!(with(Inner::Sum(c0_only.clone())), Term::from(1.0)); + assert_eq!(Term::from(1.0), with(Inner::Sum(c0_only))); + assert_eq!(with(Inner::Sum(Sum::new())), Term::from(0.0)); + + let x = Var(0).sin() * 2.0; + let mut one_entry = Term::from(0.0) + x.clone(); + assert!(matches!(one_entry.inner(), Inner::Sum(_))); + assert_eq!(one_entry, x); + assert_eq!(x, one_entry); + assert_ne!(one_entry, x.mul_phase(1), "the `i` bit is part of the key"); + one_entry += 1.0; + assert_ne!(one_entry, x, "an extra c₀ differs"); + assert_ne!(Var(0).sin() * 3.0, x, "coefficients differ"); + assert_ne!(Var(1).sin() * 2.0, x, "keys differ"); + + // `x − x` is the zero constant in every form. + let mut t = Var(0).sin() + Var(1).cos(); + t += (Var(0).sin() + Var(1).cos()) * -1.0; + assert_eq!(t, Term::from(0.0)); + assert_eq!( + Term::imaginary_unit() * Term::imaginary_unit(), + -Term::from(1.0) + ); + + assert_ne!( + Term::from(1.0), + Term::from(1.0) + x.clone(), + "extra monomials differ" + ); + assert_ne!(Term::from(1.0) + x.clone(), Term::from(1.0)); + let mut tight = Term::from(1.0); + tight.set_max_sin(2); + assert_ne!(tight, Term::from(1.0), "truncation settings are compared"); + } + + #[test] + fn half_is_exact_and_sum_keeps_the_first_settings() { + use ppvm_traits_2::Halvable; + for a in forms() { + assert_eq!(a.half() + a.half(), a, "{a}"); + } + let mut first = Term::from(1.0) + Var(0).sin(); + first.set_max_sin(1); + let total: Term = [first, Var(1).sin(), Var(0).sin() * Var(1).sin()] + .into_iter() + .sum(); + assert_eq!((total.max_sin(), total.n_monomials()), (1, 2)); + } + + #[test] + fn conversions_and_neg() { + for t in [Term::from(2i32), Term::from(2i64), Term::from(2.0f32)] { + assert_eq!(t, Term::from(2.0f64)); + } + assert_eq!(-Term::from(2.0), Term::from(-2.0)); + } + + /// One of every representation and phase: `Const`, `One`, map-backed sums + /// with real, imaginary and negative parts, and a variable past the eval cache. + pub(crate) fn forms() -> Vec { + let x = Var(0).sin(); + let s = Term::from(0.5) + Var(1).cos(); + let mut c0_only = Term::from(0.0) + Var(1).cos(); + c0_only *= 0.0; + c0_only += 0.75; + vec![ + Term::from(2.0), + Term::from(0.0), + x.clone(), + x.clone() * x.clone(), + s.clone(), + s.clone() + x.clone(), + Term::imaginary_unit(), + x.mul_phase(1), + x.mul_phase(3), + s.mul_phase(3), + s.mul_phase(2), // c₀ = −0.5 + (s.clone() + x.clone()).mul_phase(1) + x.clone(), + c0_only, + Var(40).cos() + Var(0).cos() * 2.0, + ] + } + + pub(crate) const PT: [f64; 41] = { + let mut v = [0.0; 41]; + v[0] = 0.3; + v[1] = 1.1; + v[40] = -0.7; + v + }; + + pub(crate) fn ev(t: &Term) -> Complex { + t.eval_complex(&PT).unwrap() + } + + pub(crate) fn close(a: Complex, b: Complex) -> bool { + (a - b).norm() < 1e-12 * (1.0 + a.norm().max(b.norm())) + } + + /// `eval_complex` is a ring homomorphism to `ℂ` commuting with `conj`, + /// `mul_phase` and `mul_sign`; `eval` is its real part, and borrowed ops + /// match owned ones. + #[test] + fn evaluation_is_a_ring_homomorphism() { + let i = Term::imaginary_unit(); + let forms = forms(); + for a in &forms { + let ea = ev(a); + assert!((a.eval(&PT).unwrap() - ea.re).abs() < 1e-12, "eval of {a}"); + assert!(close(ev(&a.conj()), ea.conj()), "conj of {a}"); + assert!(close(ev(&(a.clone() + 1.5)), ea + 1.5), "{a} + 1.5"); + assert!(close(ev(&(1.5 + a.clone())), ea + 1.5), "1.5 + {a}"); + assert!(close(ev(&(a.clone() - 1.5)), ea - 1.5), "{a} - 1.5"); + assert!(close(ev(&(a.clone() * -3.0)), ea * -3.0), "{a} · -3"); + assert!(close(ev(&(-3.0 * a.clone())), ea * -3.0), "-3 · {a}"); + assert!(close(ev(&-a.clone()), -ea), "-{a}"); + assert_eq!(a.mul_sign(-1), -a.clone(), "{a}"); + assert_eq!(a.mul_sign(1), *a, "{a}"); + let mut b = a.clone(); + b.mul_sign_assign(-1); + assert_eq!(b, a.mul_sign(-1)); + for k in 0..4u8 { + assert!(close(ev(&a.mul_phase(k)), ea * Complex::i().powu(k as u32))); + } + assert_eq!(a.clone() * i.clone(), a.mul_phase(1), "{a} · i"); + for b in &forms { + let eb = ev(b); + assert!(close(ev(&(a.clone() + b.clone())), ea + eb), "{a} + {b}"); + assert!(close(ev(&(a.clone() - b.clone())), ea - eb), "{a} - {b}"); + assert!(close(ev(&(a.clone() * b.clone())), ea * eb), "{a} · {b}"); + + let mut by_ref = a.clone(); + by_ref += b; + assert_eq!(by_ref, a.clone() + b.clone(), "{a} += &{b}"); + let mut by_ref = a.clone(); + by_ref -= b; + assert_eq!(by_ref, a.clone() - b.clone(), "{a} -= &{b}"); + let mut by_ref = a.clone(); + by_ref *= b; + assert_eq!(by_ref, a.clone() * b.clone(), "{a} *= &{b}"); + } + } + assert_eq!(i.conj(), -i); + } + + /// Associativity and distributivity hold in value for every triple of forms. + #[test] + fn ring_axioms_hold_after_evaluation() { + let forms = forms(); + for a in &forms { + for b in &forms { + for c in &forms { + let (a, b, c) = (a.clone(), b.clone(), c.clone()); + let abc = ev(&((a.clone() * b.clone()) * c.clone())); + assert!(close(abc, ev(&(a.clone() * (b.clone() * c.clone()))))); + let lhs = ev(&(a.clone() * (b.clone() + c.clone()))); + assert!(close( + lhs, + ev(&(a.clone() * b.clone() + a.clone() * c.clone())) + )); + let lhs = ev(&((a.clone() + b.clone()) + c.clone())); + assert!(close(lhs, ev(&(a + (b + c))))); + } + } + } + } + + #[test] + fn conj_is_an_involution_and_fixes_real_forms() { + for a in forms() { + assert_eq!(a.conj().conj(), a, "{a}"); + } + let x = Var(0).sin() + Var(1).cos().mul_phase(1); + assert_eq!(x.conj().conj(), x); + let real = Term::from(0.5) + Var(1).cos(); + assert_eq!(real.conj(), real); + assert_eq!(Term::from(2.0).conj(), Term::from(2.0)); + } + + #[test] + fn mul_phase_reduces_any_exponent_mod_4() { + for a in [Var(0).sin(), Var(0).sin().mul_phase(1), Term::from(2.0)] { + for k in 0..=u8::MAX { + assert_eq!(a.mul_phase(k), a.mul_phase(k % 4), "{a}, k = {k}"); + assert_eq!(a.mul_i_pow(k), a.mul_phase(k % 4), "{a}, k = {k}"); + } + } + let mut p = Prod::sin(0); + assert_eq!(p.mul_phase(1), 1.0); + assert_eq!(p.mul_phase(255), 1.0); // i · i³ = 1 + assert!(!p.is_imag()); + } + + #[test] + fn four_factors_of_i_are_the_identity() { + let x = Var(0).sin() + Var(1).cos(); + let i = Term::imaginary_unit(); + let mut y = x.clone(); + for _ in 0..4 { + y *= &i; + } + assert_eq!(y, x); + assert_eq!(x.mul_phase(2).mul_phase(2), x); + } + + #[test] + fn iter_sum_matches_folded_addition() { + let forms = forms(); + let total: Term = forms.iter().cloned().sum(); + let expected: Complex = forms.iter().map(ev).sum(); + assert!(close(ev(&total), expected)); + let empty: Term = std::iter::empty().sum(); + assert_eq!(empty, Term::from(0.0)); + } + + /// The identity monomial never appears as a key or inside `One`. + #[test] + fn identity_monomial_is_always_normalised() { + let i = Term::imaginary_unit(); + assert!(matches!(i.inner(), Inner::One(p, c) if p.is_imag() && *c == 1.0)); + assert_eq!(i.clone() * i.clone(), -Term::from(1.0)); + assert_eq!(i.mul_phase(3), Term::from(1.0)); + assert_eq!(Term::from(2.0).mul_i_pow(0), Term::from(2.0)); + assert_eq!(Term::from(2.0).mul_i_pow(2), Term::from(-2.0)); + let no_identity_key = |t: &Term| match t.inner() { + Inner::Sum(s) => s.iter().all(|(p, _)| !p.is_identity()), + Inner::One(p, _) => !p.is_identity(), + _ => true, + }; + for a in forms() { + for b in forms() { + let ab = a.clone() * b.clone(); + assert!(no_identity_key(&ab), "{a} · {b}"); + assert!(no_identity_key(&(a.clone() + b.clone())), "{a} + {b}"); + assert!(no_identity_key(&ab.mul_phase(1)), "i · {a} · {b}"); + } + } + } + + #[test] + fn opposite_phases_share_a_key_and_cancel() { + let x = Var(0).sin(); + let t = x.mul_phase(1) + x.mul_phase(3); // i·x − i·x + assert_eq!(t.n_monomials(), 0); + assert_eq!(t.eval_complex(&[0.4]).unwrap(), Complex::new(0.0, 0.0)); + // i² is a sign on the real key, not a separate key. + assert_eq!(x.mul_phase(2), -x); + } + + #[test] + fn sin_cos_is_the_angle_domain() { + let (s, c) = Angle::::sin_cos(&Var(0)); + assert_eq!(s, Var(0).sin()); + assert_eq!(c, Var(0).cos()); + let (s, c) = Angle::::sin_cos(&0.3f64); + assert_eq!(s, Term::from_f64(0.3f64.sin())); + assert_eq!(c, Term::from_f64(0.3f64.cos())); + } +} diff --git a/crates/ppvm-sym-2/src/display.rs b/crates/ppvm-sym-2/src/display.rs new file mode 100644 index 000000000..754a0beec --- /dev/null +++ b/crates/ppvm-sym-2/src/display.rs @@ -0,0 +1,145 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! `Display` for the symbolic types. A `Sum` prints its monomials in a total +//! order (sine degree, cosine degree, real before imaginary, then the factors), +//! so the output never depends on the table. An imaginary monomial prints a +//! leading `i`. + +use std::fmt::Display; + +use crate::prod::Prod; +use crate::sum::Sum; +use crate::term::{Inner, Term}; + +impl Display for Prod { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let sin_len = self.factors.iter().filter(|x| x.sin > 0).count(); + let cos_len = self.factors.iter().filter(|x| x.cos > 0).count(); + if self.imag { + write!(f, "i")?; + if sin_len + cos_len > 0 { + write!(f, " ")?; + } + } + + for (i, fac) in self.factors.iter().filter(|x| x.sin > 0).enumerate() { + let (u, m) = (fac.var, fac.sin); + write!(f, "sin^{m}(%{u})")?; + if i + 1 < sin_len || cos_len > 0 { + write!(f, " ")?; + } + } + for (i, fac) in self.factors.iter().filter(|x| x.cos > 0).enumerate() { + let (u, m) = (fac.var, fac.cos); + write!(f, "cos^{m}(%{u})")?; + if i + 1 < cos_len { + write!(f, " ")?; + } + } + Ok(()) + } +} + +impl Display for Sum { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "[")?; + if self.c0 != 0.0 { + write!(f, "{:.3}", self.c0)?; + if !self.is_empty() { + write!(f, " + ")?; + } + } + + let mut sorted = self.iter().collect::>(); + sorted.sort_by_cached_key(|(p, _)| (p.sin_pow(), p.cos_pow(), p.imag, p.factors.clone())); + + for (i, (p, c)) in sorted.iter().enumerate() { + write!(f, "{c:.3} * {p}")?; + if i + 1 < sorted.len() { + write!(f, " + ")?; + } + } + write!(f, "]") + } +} + +impl Display for Term { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.inner { + Inner::Sum(ref s) => s.fmt(f), + Inner::One(ref p, c) => write!(f, "{c:.3} * {p}"), + Inner::Const(c) => write!(f, "{c}"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::term::Var; + + #[test] + fn test_display_prod() { + let mut p = Prod::new(); + p.mul_sin(1); + p.mul_sin(1); + p.mul_cos(2); + assert_eq!(p.to_string(), "sin^2(%1) cos^1(%2)"); + } + + #[test] + fn test_display_term() { + let mut s = Term::from_f64(3.0); + s += Var(1).sin(); + s += Var(2).cos(); + assert_eq!( + s.to_string(), + "[3.000 + 1.000 * cos^1(%2) + 1.000 * sin^1(%1)]" + ); + + s.set_max_sin(2); + s *= Var(2).sin(); + s *= Var(1).sin(); + assert_eq!( + s.to_string(), + "[3.000 * sin^1(%1) sin^1(%2) + 1.000 * sin^1(%1) sin^1(%2) cos^1(%2)]" + ); + } + + #[test] + fn display_of_the_small_forms() { + // `Const` prints with NO precision spec, unlike every other form. + assert_eq!(Term::from_f64(1.5).to_string(), "1.5"); + assert_eq!(Var(0).sin().to_string(), "1.000 * sin^1(%0)"); + } + + #[test] + fn empty_sum_prints_as_brackets() { + // The `mul_term` zero shortcut leaves an empty + // `Sum`, which prints as `[]` — not `0`. + let mut t = Term::from_f64(1.0) + Var(1).cos(); + t.set_max_sin(1); + t *= Var(0).sin() * Var(1).sin(); + assert_eq!(t.to_string(), "[]"); + // A sum that never allocated its table renders the same way. + assert_eq!(Sum::new().to_string(), "[]"); + // A constant-only sum closes its bracket. + let mut s = Sum::new(); + s.c0 = 3.0; + assert_eq!(s.to_string(), "[3.000]"); + } + + #[test] + fn phase_and_sign_rendering() { + let x = Var(0).sin(); + assert_eq!(x.mul_phase(1).to_string(), "1.000 * i sin^1(%0)"); + assert_eq!(x.mul_phase(3).to_string(), "-1.000 * i sin^1(%0)"); + assert_eq!(Term::from(2.0).mul_phase(1).to_string(), "2.000 * i"); + assert_eq!((x.clone() * -2.5).to_string(), "-2.500 * sin^1(%0)"); + let mut p = Prod::cos(0); + p.mul_sin(0); + assert_eq!(p.to_string(), "sin^1(%0) cos^1(%0)"); + assert_eq!(Prod::new().to_string(), ""); + } +} diff --git a/crates/ppvm-sym-2/src/eval.rs b/crates/ppvm-sym-2/src/eval.rs new file mode 100644 index 000000000..181717989 --- /dev/null +++ b/crates/ppvm-sym-2/src/eval.rs @@ -0,0 +1,247 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Evaluation at concrete angles. Within a monomial the fold multiplies the +//! `sin` factors, then the `cos` factors, each in ascending variable order; +//! that order fixes the floating-point result and is part of the contract. + +use std::mem::MaybeUninit; + +use num::Complex; + +use crate::prod::Prod; +use crate::sum::Sum; +use crate::term::{Inner, Term}; + +/// Evaluation needed a variable `vals` has no value for: `vals.len() <= k`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MissingVariable(pub u32); + +impl std::fmt::Display for MissingVariable { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "variable %{} not found", self.0) + } +} + +impl std::error::Error for MissingVariable {} + +/// Variables [`AngleCache`] memoizes; higher ids are recomputed per access. +const INLINE_VARS: usize = 32; + +/// Per-call memo of `sin`/`cos` of each variable, so a [`Sum`] with many +/// monomials computes each transcendental once. Bit-identical to the uncached +/// fold, and bounds-checked per access so the same [`MissingVariable`] is +/// reported first. Slots stay uninitialized until their validity bit is set. +struct AngleCache<'a> { + vals: &'a [f64], + /// Bit `i` set <=> the corresponding slot is initialized. + sin_valid: u32, + cos_valid: u32, + sin: [MaybeUninit; INLINE_VARS], + cos: [MaybeUninit; INLINE_VARS], +} + +impl<'a> AngleCache<'a> { + #[inline] + fn new(vals: &'a [f64]) -> Self { + Self { + vals, + sin_valid: 0, + cos_valid: 0, + sin: [MaybeUninit::uninit(); INLINE_VARS], + cos: [MaybeUninit::uninit(); INLINE_VARS], + } + } + + /// `sin` or `cos` of `vals[k]`, memoized for `k < INLINE_VARS`. + #[inline] + fn get(&mut self, k: u32, trig: Trig) -> Result { + let i = k as usize; + let v = *self.vals.get(i).ok_or(MissingVariable(k))?; + let f = match trig { + Trig::Sin => f64::sin, + Trig::Cos => f64::cos, + }; + if i >= INLINE_VARS { + return Ok(f(v)); + } + let (valid, slots) = match trig { + Trig::Sin => (&mut self.sin_valid, &mut self.sin), + Trig::Cos => (&mut self.cos_valid, &mut self.cos), + }; + if *valid & (1 << i) == 0 { + slots[i].write(f(v)); + *valid |= 1 << i; + } + // SAFETY: the validity bit is set only after this slot is initialized. + Ok(unsafe { slots[i].assume_init() }) + } +} + +/// Which trigonometric function a fold step needs. +#[derive(Clone, Copy)] +enum Trig { + Sin, + Cos, +} + +impl Prod { + /// The real part of [`Prod::eval_complex`] at `vals` (`vals[i]` binds + /// variable `i`): `0.0` for an imaginary monomial, `1.0` for the empty one. + #[cfg(test)] + #[inline] + pub(crate) fn eval(&self, vals: &[f64]) -> Result { + Ok(self.eval_complex(vals)?.re) + } + + /// The fold in contract order; every evaluation path goes through it. + #[inline] + fn fold( + &self, + mut trig_of: impl FnMut(u32, Trig) -> Result, + ) -> Result { + let mut res = 1.0; + for f in self.factors.iter().filter(|f| f.sin > 0) { + res *= trig_of(f.var, Trig::Sin)?.powi(f.sin as i32); + } + for f in self.factors.iter().filter(|f| f.cos > 0) { + res *= trig_of(f.var, Trig::Cos)?.powi(f.cos as i32); + } + Ok(res) + } + + /// The value at `vals`, including the phase. + pub(crate) fn eval_complex(&self, vals: &[f64]) -> Result, MissingVariable> { + Ok(self.with_phase(self.fold_uncached(vals)?)) + } + + /// [`Prod::fold`] reading `vals` directly, for a one-off monomial. + #[inline] + fn fold_uncached(&self, vals: &[f64]) -> Result { + self.fold(|k, trig| { + let v = vals.get(k as usize).ok_or(MissingVariable(k))?; + Ok(match trig { + Trig::Sin => v.sin(), + Trig::Cos => v.cos(), + }) + }) + } + + /// `v`, or `i·v` for an imaginary monomial. + #[inline] + fn with_phase(&self, v: f64) -> Complex { + if self.imag { + Complex::new(0.0, v) + } else { + Complex::new(v, 0.0) + } + } +} + +impl Sum { + /// Phase-aware evaluation; see [`Prod::eval_complex`]. + pub(crate) fn eval_complex(&self, vals: &[f64]) -> Result, MissingVariable> { + let mut cache = AngleCache::new(vals); + let mut res = Complex::new(self.c0, 0.0); + for (p, c) in self.iter() { + res += p.with_phase(p.fold(|k, trig| cache.get(k, trig))?) * c; + } + Ok(res) + } +} + +impl Term { + /// The real part of [`Term::eval_complex`]. + #[inline] + pub fn eval(&self, vals: &[f64]) -> Result { + Ok(self.eval_complex(vals)?.re) + } + + /// The value at `vals` (`vals[i]` binds variable `i`), including the phase. + pub fn eval_complex(&self, vals: &[f64]) -> Result, MissingVariable> { + match self.inner { + Inner::Const(c) => Ok(Complex::new(c, 0.0)), + Inner::One(ref p, c) => Ok(p.eval_complex(vals)? * c), + Inner::Sum(ref s) => s.eval_complex(vals), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::term::Var; + use crate::term::{DEFAULT_MAX_SIN, DEFAULT_MIN_EPS}; + + #[test] + fn missing_variable_is_a_typed_error() { + let err = Var(5).sin().eval(&[0.1]).unwrap_err(); + assert_eq!(err, MissingVariable(5)); + assert_eq!(err.to_string(), "variable %5 not found"); + + // The cached `Sum` path reports the first missing variable the + // sin-then-cos walk reaches (`%7`), not the lowest missing id (`%5`). + let mut p = Prod::sin(7); + p.mul_cos(5); + let mut s = Sum::new(); + s.add_term(p, 1.0, DEFAULT_MAX_SIN, DEFAULT_MIN_EPS); + assert_eq!( + s.eval_complex(&[0.1, 0.2, 0.3, 0.4]).map(|z| z.re), + Err(MissingVariable(7)) + ); + } + + #[test] + fn fold_order_is_sin_ascending_then_cos_ascending() { + // Bit-identical to a hand-written fold in contract order. + let mut p = Prod::sin(0); + p.mul_sin(0); + p.mul_sin(0); + p.mul_sin(1); + p.mul_sin(1); + p.mul_cos(0); + let vals = [1.1, 2.1]; + let expected = 1.0f64 * 1.1f64.sin().powi(3) * 2.1f64.sin().powi(2) * 1.1f64.cos().powi(1); + assert_eq!(p.eval(&vals).unwrap().to_bits(), expected.to_bits()); + } + + /// table order, across the inline window and with repeated variables. + #[test] + fn cached_sum_eval_is_bit_identical_to_uncached() { + let n = INLINE_VARS as u32 + 4; + let vals: Vec = (0..n).map(|i| 0.37 * i as f64 - 3.0).collect(); + let mut s = Sum::new(); + s.c0 = 0.125; + for i in 0..n { + let mut p = Prod::sin(i); + p.mul_cos((i * 7) % n); + p.mul_sin((i * 3) % n); + if i % 3 == 0 { + p.mul_phase(1); + } + s.add_term(p, 1.0 + i as f64, DEFAULT_MAX_SIN, DEFAULT_MIN_EPS); + } + let mut re = s.c0; + let mut z = Complex::new(s.c0, 0.0); + for (p, c) in s.iter() { + re += p.eval(&vals).unwrap() * c; + z += p.eval_complex(&vals).unwrap() * c; + } + assert_eq!(s.eval_complex(&vals).unwrap().re.to_bits(), re.to_bits()); + let got = s.eval_complex(&vals).unwrap(); + assert_eq!( + (got.re.to_bits(), got.im.to_bits()), + (z.re.to_bits(), z.im.to_bits()) + ); + } + + #[test] + fn small_forms_and_the_real_part() { + assert_eq!(Prod::new().eval(&[]), Ok(1.0)); + assert_eq!(Sum::new().eval_complex(&[]), Ok(Complex::new(0.0, 0.0))); + let mut p = Prod::cos(0); + p.mul_phase(1); + assert_eq!(p.eval(&[0.0]), Ok(0.0)); + assert_eq!(p.eval_complex(&[0.0]), Ok(Complex::new(0.0, 1.0))); + } +} diff --git a/crates/ppvm-sym-2/src/lib.rs b/crates/ppvm-sym-2/src/lib.rs new file mode 100644 index 000000000..8e29fcdc3 --- /dev/null +++ b/crates/ppvm-sym-2/src/lib.rs @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Symbolic coefficients for `ppvm-traits-2`: polynomials in `sin`/`cos` of +//! circuit parameters, evaluated once angle values are known. + +#[macro_use] +mod macros; + +mod add; +mod coeff; +mod display; +mod eval; +mod mul; +mod prod; +mod sum; +mod term; + +pub use eval::MissingVariable; +pub use term::{DEFAULT_MAX_SIN, DEFAULT_MIN_EPS, Term, Var}; diff --git a/crates/ppvm-sym-2/src/macros.rs b/crates/ppvm-sym-2/src/macros.rs new file mode 100644 index 000000000..f6ce0e762 --- /dev/null +++ b/crates/ppvm-sym-2/src/macros.rs @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Operator boilerplate shared by the arithmetic modules. + +/// `impl Op for Term` in terms of `OpAssign`, for each listed `R`. +macro_rules! binary_ops { + ($op:ident::$f:ident from $assign:ident::$af:ident for $($rhs:ty),*) => {$( + impl std::ops::$op<$rhs> for crate::Term { + type Output = crate::Term; + + #[inline] + fn $f(mut self, rhs: $rhs) -> crate::Term { + std::ops::$assign::$af(&mut self, rhs); + self + } + } + )*}; +} diff --git a/crates/ppvm-sym-2/src/mul.rs b/crates/ppvm-sym-2/src/mul.rs new file mode 100644 index 000000000..484cca64e --- /dev/null +++ b/crates/ppvm-sym-2/src/mul.rs @@ -0,0 +1,526 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The ring product on [`Prod`], [`Sum`] and [`Term`]. Operators take their +//! right operand by value so a `Sum` operand can be moved in instead of copied. + +use crate::prod::{Factor, Prod, merge_factors}; +use crate::sum::Sum; +use crate::term::{Inner, Term}; + +impl Prod { + /// Multiply this product by an additional `sin(x_u)`. + #[inline(always)] + pub(crate) fn mul_sin(&mut self, u: u32) { + self.merge_factor(Factor::new(u, 1, 0)); + self.sin_pow += 1; + self.debug_check(); + } + + /// Multiply this product by an additional `cos(x_u)`. + #[inline(always)] + pub(crate) fn mul_cos(&mut self, u: u32) { + self.merge_factor(Factor::new(u, 0, 1)); + self.debug_check(); + } +} + +impl Sum { + /// Multiply in place by `coeff · p`, with the truncation of [`Sum::add_term`]. + /// + /// If `p.sin_pow() > max` every product exceeds `max`, so the table is + /// cleared without walking it (leaving an empty `Sum`, not `Const(0.0)`). + #[inline] + pub(crate) fn mul_term(&mut self, p: &Prod, coeff: f64, max: usize, min_eps: f64) { + if p.sin_pow() > max { + if let Some(maps) = &mut self.maps { + maps.terms.clear(); + } + self.c0 = 0.0; + return; + } + + // `i` is not a scalar even though it has no factors. + if p.is_identity() { + self.scale(coeff); + self.prune(max, min_eps); + return; + } + + // Ping-pong: `aux` is empty on entry, so after the swap `terms` holds + // `aux`'s retained capacity and `aux` holds the table to rebuild from. + let mut maps = self.maps.take().unwrap_or_default(); + debug_assert!(maps.aux.is_empty()); + std::mem::swap(&mut maps.terms, &mut maps.aux); + let mut old_terms = std::mem::take(&mut maps.aux); + maps.terms.reserve(old_terms.len()); + self.maps = Some(maps); + + // Reset `c₀` *before* the rebuild: `i · i` lands back on the identity + // monomial and folds into `c₀`, which a reset afterwards would wipe. + let c0 = std::mem::take(&mut self.c0) * coeff; + if c0.abs() > min_eps { + self.add_term(p.clone(), c0, max, min_eps); + } + for (mut k, v) in old_terms.drain() { + let sign = k.mul_prod(p); + self.add_term(k, v * coeff * sign, max, min_eps); + } + // Hand the (now empty, still-allocated) buffer back for the next multiply. + self.maps.as_mut().unwrap().aux = old_terms; + } + + /// Multiply every coefficient, `c₀` included, by `r`, without truncating. + #[inline] + pub(crate) fn scale(&mut self, r: f64) { + self.c0 *= r; + for v in self.maps.iter_mut().flat_map(|m| m.terms.values_mut()) { + *v *= r; + } + } +} + +impl Prod { + /// Multiply in place by `rhs`, returning the sign (`±1.0`) the coefficient + /// picks up: `−1` when both factors carry an `i`. + #[inline] + pub(crate) fn mul_prod(&mut self, rhs: &Prod) -> f64 { + self.sin_pow += rhs.sin_pow; + match (self.factors.len(), rhs.factors.as_slice()) { + (_, []) => {} + (0, _) => self.factors = rhs.factors.clone(), + // The common case on the propagation hot path: the right operand is + // a single `sin(x_u)` or `cos(x_u)` atom. + (_, &[f]) => self.merge_factor(f), + (_, fs) => self.factors = merge_factors(&self.factors, fs), + } + self.debug_check(); + self.compose_imag(rhs) + } + + /// `self · rhs` as a new monomial plus the coefficient sign; see + /// [`Prod::mul_prod`]. Allocates exactly one factor vector. + #[inline] + pub(crate) fn times(&self, rhs: &Prod) -> (Prod, f64) { + let mut out = Prod { + factors: merge_factors(&self.factors, &rhs.factors), + sin_pow: self.sin_pow + rhs.sin_pow, + imag: self.imag, + }; + out.debug_check(); + let sign = out.compose_imag(rhs); + (out, sign) + } + + #[inline] + fn compose_imag(&mut self, rhs: &Prod) -> f64 { + self.set_phase_exponent(self.imag as u8 + rhs.imag as u8) + } +} + +impl Term { + /// Flip the sign of every coefficient in place (exact; never truncates). + #[inline] + pub(crate) fn negate(&mut self) { + match self.inner { + Inner::Sum(ref mut s) => s.scale(-1.0), + Inner::One(_, ref mut c) | Inner::Const(ref mut c) => *c = -*c, + } + } + + /// Whether `rhs` truncates less than `self`, so a representation taken over + /// from it must be truncated again. + #[inline] + pub(crate) fn is_looser(&self, rhs: &Term) -> bool { + rhs.max_sin > self.max_sin || rhs.min_eps < self.min_eps + } + + /// Apply `self`'s settings to its current representation. + pub(crate) fn retruncate(&mut self) { + let (max, eps) = (self.max_sin, self.min_eps); + match &mut self.inner { + Inner::Sum(s) => s.prune(max, eps), + Inner::One(..) => { + let Inner::One(p, c) = std::mem::take(&mut self.inner) else { + unreachable!() + }; + self.inner = Inner::truncated(p, c, max, eps); + } + Inner::Const(_) => {} + } + } +} + +/// Scales every coefficient; shrinking (`|rhs| < 1`) prunes monomials at or below +/// `min_eps`, so a sign flip stays a single pass. +impl std::ops::MulAssign for Term { + #[inline] + fn mul_assign(&mut self, rhs: f64) { + match self.inner { + Inner::Sum(ref mut s) => { + s.scale(rhs); + if rhs.abs() < 1.0 { + s.prune(self.max_sin, self.min_eps); + } + } + Inner::One(_, ref mut c) => { + *c *= rhs; + if c.abs() <= self.min_eps { + self.inner = Inner::Const(0.0); + } + } + Inner::Const(ref mut c) => *c *= rhs, + } + } +} + +/// Uses `self`'s truncation settings; `rhs`'s are ignored. Only an owned `Sum` +/// operand is moved in; everything else goes through the borrowed product. +impl std::ops::MulAssign for Term { + #[inline] + fn mul_assign(&mut self, rhs: Term) { + let (max, eps) = (self.max_sin, self.min_eps); + let looser = self.is_looser(&rhs); + let rhs_settings = (rhs.max_sin, rhs.min_eps); + match (&mut self.inner, rhs.inner) { + (Inner::Const(c), Inner::Sum(s)) => { + let c = *c; + self.inner = Inner::Sum(s); + if looser { + self.retruncate(); + } + *self *= c; + } + (Inner::One(p, c), Inner::Sum(mut s)) => { + s.mul_term(p, *c, max, eps); + self.inner = Inner::Sum(s); + } + (_, inner) => { + let mut rhs = Term::default_with(inner); + (rhs.max_sin, rhs.min_eps) = rhs_settings; + *self *= &rhs; + } + } + } +} + +/// Never clones `rhs` unless the result must own its table (`Const`/`One` × `Sum`). +impl std::ops::MulAssign<&Term> for Term { + #[inline] + fn mul_assign(&mut self, rhs: &Term) { + let (max, eps) = (self.max_sin, self.min_eps); + let looser = self.is_looser(rhs); + let inner = match (&mut self.inner, &rhs.inner) { + (_, Inner::Const(c)) => return *self *= *c, + (Inner::Const(c), rhs) => { + let c = *c; + self.inner = rhs.clone(); + if looser { + self.retruncate(); + } + return *self *= c; + } + (Inner::Sum(s), Inner::One(p, c)) => return s.mul_term(p, *c, max, eps), + (Inner::One(p, c), Inner::Sum(s)) => { + let mut s = s.clone(); + s.mul_term(p, *c, max, eps); + Inner::Sum(s) + } + (Inner::One(p, c), Inner::One(p2, c2)) => { + let (p, sign) = p.times(p2); + Inner::truncated(p, *c * c2 * sign, max, eps) + } + // `c₀` takes part as the identity monomial, which `add_term` folds back. + (Inner::Sum(s1), Inner::Sum(s2)) => { + let mut out = Sum::new(); + let rhs: Vec<_> = s2.parts().collect(); + for (p1, c1) in s1.parts() { + for &(p2, c2) in &rhs { + let (p, sign) = p1.times(p2); + out.add_term(p, c1 * c2 * sign, max, eps); + } + } + Inner::Sum(out) + } + }; + self.inner = inner; + } +} + +binary_ops!(Mul::mul from MulAssign::mul_assign for Term, &Term, f64); + +impl std::ops::Mul for f64 { + type Output = Term; + + #[inline] + fn mul(self, rhs: Term) -> Term { + rhs * self + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::term::Var; + use crate::term::{DEFAULT_MAX_SIN, DEFAULT_MIN_EPS}; + + #[test] + fn monomial_canonical_under_multiplication_order() { + // Same monomial built by different multiplication orders must be the + // SAME key (canonicality is what stops the term count exploding). + let mut a = Prod::sin(3); + a.mul_prod(&Prod::cos(1)); + a.mul_prod(&Prod::sin(1)); + + let mut b = Prod::sin(1); + b.mul_prod(&Prod::sin(3)); + b.mul_prod(&Prod::cos(1)); + assert_eq!(a, b.times(&Prod::new()).0); + + assert_eq!(a, b); + assert_eq!(hash_of(&a), hash_of(&b)); + assert_eq!(a.sin_pow(), 2); + assert_eq!(a.cos_pow(), 1); + } + + fn hash_of(p: &Prod) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = fxhash::FxHasher64::default(); + p.hash(&mut h); + h.finish() + } + + #[test] + fn i_times_i_is_a_sign_on_the_real_key() { + let mut a = Prod::sin(0); + assert_eq!(a.mul_phase(1), 1.0); + let mut b = Prod::cos(0); + assert_eq!(b.mul_phase(3), -1.0); // i³ = −i: key `i`, sign −1 + let (c, sign) = a.times(&b); // the keys multiply as i · i = −1 + assert!(!c.is_imag()); + assert_eq!(sign, -1.0); + } + + #[test] + fn mul_term_zero_shortcut_leaves_empty_sum() { + // The shortcut leaves an EMPTY `Sum`, not `Const(0.0)`. + let mut s = Sum::new(); + s.add_term(Prod::cos(0), 1.0, DEFAULT_MAX_SIN, DEFAULT_MIN_EPS); + let mut p = Prod::sin(0); + p.mul_sin(1); + s.mul_term(&p, 1.0, 1, f64::EPSILON); + assert!(s.is_empty()); + assert_eq!(s.c0(), 0.0); + } + + #[test] + fn mul_term_reuses_the_aux_allocation() { + // After a rebuild both buffers are still allocated. + let mut s = Sum::new(); + for i in 0..16u32 { + s.add_term(Prod::cos(i), 1.0, DEFAULT_MAX_SIN, DEFAULT_MIN_EPS); + } + s.mul_term(&Prod::sin(0), 1.0, DEFAULT_MAX_SIN, DEFAULT_MIN_EPS); + let maps = s.maps.as_ref().expect("first monomial creates the map box"); + assert!(maps.aux.is_empty()); + assert!(maps.aux.capacity() > 0, "aux allocation was freed"); + assert_eq!(s.len(), 16); + } + + /// `One × Sum` keeps the product (owned and borrowed), and a negative `c₀` + /// takes part in `Sum × Sum`. + #[test] + fn products_with_sums_keep_every_cross_term() { + let x = [1.1f64, 2.2]; + let (s0, s1, c1) = (x[0].sin(), x[1].sin(), x[1].cos()); + let a = Term::from_f64(-1.0) + Var(0).sin(); + let b = Var(1).sin() + Var(1).cos(); + let close = |t: Term, want: f64| (t.eval(&x).unwrap() - want).abs() < 1e-12; + assert!(close(Var(0).sin() * b.clone(), s0 * (s1 + c1))); + assert!(close(Var(0).sin() * &b, s0 * (s1 + c1))); + assert!(close(a * b, (s0 - 1.0) * (s1 + c1))); + } + + #[test] + fn products_of_small_forms_stay_out_of_the_map() { + let mut capped = Var(0).sin(); + capped.set_max_sin(1); + assert_eq!((capped * Var(1).sin()).inner(), &Inner::Const(0.0)); + let t = Var(0).sin() * Var(1).cos(); + assert!(matches!(t.inner(), Inner::One(..))); + let t = Term::from_f64(2.0) * Var(0).sin(); + assert!(matches!(t.inner(), Inner::One(_, c) if *c == 2.0)); + } + + use crate::coeff::tests::forms; + use ppvm_traits_2::{Conjugate, ImaginaryUnit}; + use std::collections::HashMap; + + fn sum_term(max_sin: usize) -> Term { + Term { + inner: Inner::Sum(Sum::new()), + max_sin, + min_eps: f64::EPSILON, + } + } + + /// The nonzero monomials of a term, `c₀` under the identity key. + fn table(t: &Term) -> HashMap { + let mut s = sum_term(usize::MAX); + s += t.clone(); + let Inner::Sum(s) = s.inner else { + unreachable!() + }; + s.parts() + .filter(|(_, c)| *c != 0.0) + .map(|(p, c)| (p.clone(), c)) + .collect() + } + + type BinOp = fn(Term, &Term) -> Term; + + /// With `max_sin = k` on the left operand, in any representation, a product, + /// sum or difference is exactly the untruncated result with every monomial of + /// sine degree `> k` removed; every other operation's result obeys `k` too. + #[test] + fn max_sin_truncation_is_exact_in_every_form() { + let forms = forms(); + let obeys = |t: &Term, k| table(t).keys().all(|p| p.sin_pow() <= k); + for k in 0..=4 { + for a in &forms { + let mut lhs = a.clone(); + lhs.set_max_sin(k); + assert!(obeys(&lhs, k), "k = {k}: {a}"); + for t in [ + lhs.mul_phase(1), + lhs.conj(), + lhs.clone() * 0.5, + -lhs.clone(), + ] { + assert!(obeys(&t, k), "k = {k}: {a} → {t}"); + } + for b in &forms { + let ops: [(BinOp, &str); 5] = [ + (|x, y| x * y.clone(), "*"), + (|x, y| x * y, "*&"), + (|x, y| x + y.clone(), "+"), + (|x, y| x + y, "+&"), + (|x, y| x - y, "-&"), + ]; + for (op, name) in ops { + let full = table(&op(a.clone(), b)); + let got = table(&op(lhs.clone(), b)); + let want: HashMap<_, _> = + full.into_iter().filter(|(p, _)| p.sin_pow() <= k).collect(); + assert_eq!(got.len(), want.len(), "k = {k}: {a} {name} {b}"); + for (p, c) in &want { + assert!((got[p] - c).abs() < 1e-12, "k = {k}: {a} {name} {b} at {p}"); + } + } + } + } + } + } + + /// `min_eps` applies to monomials in every form; the constant is never dropped. + #[test] + fn min_eps_applies_to_monomials_only() { + let mut one = Var(0).sin(); + one.set_min_eps(1e-3); + assert_eq!((one.clone() * 1e-4).inner(), &Inner::Const(0.0)); + assert_eq!( + (one.clone() * (Var(1).cos() * 1e-4)).inner(), + &Inner::Const(0.0) + ); + let mut c = Term::from(1.0); + c.set_min_eps(1e-3); + assert_eq!((c.clone() * 1e-9).as_const(), Some(1e-9)); + // A table adopted from a looser right operand is pruned to the left's settings. + let loose = Term::from(1.0) + Var(0).sin() * 1e-6; + assert_eq!((c.clone() * loose.clone()).n_monomials(), 0); + assert_eq!((c.clone() * &loose).n_monomials(), 0); + assert_eq!((c + loose).n_monomials(), 0); + } + + /// `min_eps` drops `|c| <= min_eps`, so `min_eps = 0` drops exactly the zeros. + #[test] + fn min_eps_drops_coefficients_at_the_threshold() { + let eps = 1e-3; + let mut s = Sum::new(); + s.add_term(Prod::sin(0), eps * 4.0, usize::MAX, eps); + s.add_term(Prod::sin(1), eps, usize::MAX, eps); + assert_eq!(s.len(), 1); + s.mul_term(&Prod::cos(0), 0.5, usize::MAX, eps); + assert_eq!(s.len(), 1, "the product stays above `min_eps`"); + s.mul_term(&Prod::cos(0), 0.5, usize::MAX, eps); + assert!(s.is_empty(), "the product reached `min_eps`"); + + let x = Var(0).sin() + Var(1).sin(); + let mut t = x.clone(); + t.set_min_eps(0.0); + assert_eq!( + (t.clone() - &x).n_monomials(), + 0, + "cancellation removes the entry" + ); + assert_eq!((t.clone() * 0.0).n_monomials(), 0); + assert!(num::Zero::is_zero(&(t * 0.0))); + } + + #[test] + fn mul_term_on_an_unallocated_sum_moves_c0_into_the_table() { + let mut s = Sum::new(); + s.c0 = 2.0; + s.mul_term(&Prod::sin(3), 0.5, DEFAULT_MAX_SIN, DEFAULT_MIN_EPS); + assert_eq!(s.c0(), 0.0); + assert_eq!(s.iter().collect::>(), vec![(&Prod::sin(3), 1.0)]); + } + + #[test] + fn product_of_constant_only_sums_stays_constant() { + let mut a = sum_term(usize::MAX); + a += 2.0; + let mut b = sum_term(usize::MAX); + b += -3.0; + let ab = a * b; + assert!(matches!(ab.inner(), Inner::Sum(s) if s.c0() == -6.0 && s.is_empty())); + } + + /// A long chain of in-place multiplies, cloning along the way, tracks the + /// running product in `ℂ`: the `aux` ping-pong never leaks stale monomials. + #[test] + fn long_multiply_chains_track_the_running_product() { + let mut vals = vec![0.0; 41]; + vals[0] = 0.4; + vals[1] = -1.3; + vals[40] = 2.2; + let ev = |t: &Term| t.eval_complex(&vals).unwrap(); + let factors = [ + Var(0).sin(), + Term::from(0.5) + Var(1).cos(), + Term::imaginary_unit(), + Var(40).cos() * 1.5, + Var(0).cos().mul_phase(3) + Var(1).sin(), + Term::from(-2.0), + ]; + let mut t = Term::from(0.25) + Var(1).sin(); + let mut want = ev(&t); + for step in 0..60 { + let f = &factors[step % factors.len()]; + want *= ev(f); + t *= f; + if step % 7 == 0 { + t = t.clone(); + } + let got = ev(&t); + assert!( + (got - want).norm() <= 1e-9 * want.norm().max(1.0), + "step {step}" + ); + if let Inner::Sum(s) = t.inner() { + assert!(s.maps.as_ref().is_none_or(|m| m.aux.is_empty())); + } + } + assert!(want.norm() > 0.0); + } +} diff --git a/crates/ppvm-sym-2/src/prod.rs b/crates/ppvm-sym-2/src/prod.rs new file mode 100644 index 000000000..3ea2baa57 --- /dev/null +++ b/crates/ppvm-sym-2/src/prod.rs @@ -0,0 +1,201 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The monomial [`Prod`] and its per-variable [`Factor`]. + +use std::cmp::Ordering; + +/// One variable's contribution to a monomial: `sin(x_var)^sin · cos(x_var)^cos`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub(crate) struct Factor { + /// The variable id. + pub(crate) var: u32, + /// The exponent of `sin(x_var)` (may be `0` if only `cos` is present). + pub(crate) sin: u32, + /// The exponent of `cos(x_var)` (may be `0` if only `sin` is present). + pub(crate) cos: u32, +} + +/// `[i] sin^m cos^n`: a monomial over symbolic variables. +/// +/// Canonical, so the derived `Hash`/`Eq` identify the monomial: factors sorted +/// by variable, one per variable, none all-zero. A phase `iᵏ` keeps only its +/// `i` bit here; the sign `(−1)^⌊k/2⌋` goes into the coefficient, which is why +/// every phase operation returns a `±1.0`. +#[derive(Debug, Clone, Default)] +pub(crate) struct Prod { + /// Ascending by `var`, one entry per variable, no all-zero entry. + pub(crate) factors: Vec, + /// Total sine degree, cached for the `max_sin` check on every insert. + pub(crate) sin_pow: usize, + /// Whether the monomial carries a factor `i`. + pub(crate) imag: bool, +} + +/// `sin_pow` is derived from `factors`, so identity is `(factors, imag)`. +impl PartialEq for Prod { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.imag == other.imag && self.factors == other.factors + } +} + +impl Eq for Prod {} + +impl std::hash::Hash for Prod { + #[inline] + fn hash(&self, h: &mut H) { + self.factors.hash(h); + self.imag.hash(h); + } +} + +/// The real identity monomial `1`. +pub(crate) static ONE: Prod = Prod::new(); + +impl Factor { + #[inline] + pub(crate) const fn new(var: u32, sin: u32, cos: u32) -> Self { + Self { var, sin, cos } + } +} + +impl Prod { + /// Construct the empty product (the multiplicative identity, value `1`). + pub(crate) const fn new() -> Self { + Self { + factors: Vec::new(), + sin_pow: 0, + imag: false, + } + } + + /// Multiply by `iᵏ`, returning the sign (`±1.0`) the coefficient must be + /// multiplied by to keep the phase canonical. + #[inline] + pub(crate) fn mul_phase(&mut self, k: u8) -> f64 { + self.set_phase_exponent(self.imag as u8 + (k & 3)) + } + + /// Whether the monomial carries a factor `i`. + #[cfg(test)] + #[inline] + pub(crate) fn is_imag(&self) -> bool { + self.imag + } + + /// Whether this is the real identity monomial `1`, which is never a table key. + #[inline] + pub(crate) fn is_identity(&self) -> bool { + self.factors.is_empty() && !self.imag + } + + /// Set the phase to `iᵉ`: keep `e`'s odd part in the `imag` bit and return + /// its sign, `(−1)^⌊e/2⌋` (mod 4). + #[inline] + pub(crate) fn set_phase_exponent(&mut self, e: u8) -> f64 { + self.imag = e & 1 == 1; + if e & 2 == 0 { 1.0 } else { -1.0 } + } + + /// Build the singleton product `sin(x_id)`. + pub(crate) fn sin(id: u32) -> Self { + let mut p = Self::new(); + p.mul_sin(id); + p + } + + /// Build the singleton product `cos(x_id)`. + pub(crate) fn cos(id: u32) -> Self { + let mut p = Self::new(); + p.mul_cos(id); + p + } + + /// Total power of the sine factors (cached; `O(1)`). + #[inline] + pub(crate) fn sin_pow(&self) -> usize { + self.sin_pow + } + + /// Total power of the cosine factors (`O(factors)`; only `Display` needs it). + #[inline] + pub(crate) fn cos_pow(&self) -> usize { + self.factors.iter().map(|f| f.cos as usize).sum() + } + + /// Merge `f` into the sorted factor vector (exponents add). + #[inline] + pub(crate) fn merge_factor(&mut self, f: Factor) { + match self.factors.binary_search_by_key(&f.var, |g| g.var) { + Ok(i) => { + self.factors[i].sin += f.sin; + self.factors[i].cos += f.cos; + } + Err(i) => self.factors.insert(i, f), + } + } + + /// Debug-only check of canonicality and the cached sine degree. + #[cfg(debug_assertions)] + pub(crate) fn debug_check(&self) { + for (i, f) in self.factors.iter().enumerate() { + assert!(f.sin > 0 || f.cos > 0, "all-zero factor in Prod"); + if i > 0 { + assert!(self.factors[i - 1].var < f.var, "Prod factors not sorted"); + } + } + let s: usize = self.factors.iter().map(|f| f.sin as usize).sum(); + assert_eq!(s, self.sin_pow, "sin_pow drifted"); + } + + #[cfg(not(debug_assertions))] + #[inline] + pub(crate) fn debug_check(&self) {} +} + +/// Merge two sorted factor vectors (exponents add), preserving canonicality. +pub(crate) fn merge_factors(lhs: &[Factor], rhs: &[Factor]) -> Vec { + let mut out = Vec::with_capacity(lhs.len() + rhs.len()); + let (mut i, mut j) = (0usize, 0usize); + while i < lhs.len() && j < rhs.len() { + let (a, b) = (lhs[i], rhs[j]); + match a.var.cmp(&b.var) { + Ordering::Less => { + out.push(a); + i += 1; + } + Ordering::Greater => { + out.push(b); + j += 1; + } + Ordering::Equal => { + out.push(Factor::new(a.var, a.sin + b.sin, a.cos + b.cos)); + i += 1; + j += 1; + } + } + } + out.extend_from_slice(&lhs[i..]); + out.extend_from_slice(&rhs[j..]); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn merge_factors_is_a_sorted_union_adding_exponents() { + let f = Factor::new; + let a = [f(0, 1, 0), f(2, 0, 1), f(5, 2, 0)]; + let b = [f(1, 1, 0), f(2, 1, 1), f(9, 0, 3)]; + let m = merge_factors(&a, &b); + assert_eq!( + m, + vec![f(0, 1, 0), f(1, 1, 0), f(2, 1, 2), f(5, 2, 0), f(9, 0, 3)] + ); + assert_eq!(merge_factors(&a, &[]), a.to_vec()); + assert_eq!(merge_factors(&[], &b), b.to_vec()); + } +} diff --git a/crates/ppvm-sym-2/src/sum.rs b/crates/ppvm-sym-2/src/sum.rs new file mode 100644 index 000000000..f910b2dde --- /dev/null +++ b/crates/ppvm-sym-2/src/sum.rs @@ -0,0 +1,162 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The monomial table [`Sum`]. + +use std::collections::hash_map::Entry; + +use fxhash::FxHashMap; + +use crate::prod::{ONE, Prod}; + +/// `c₀ + Σᵢ cᵢ · pᵢ` over distinct monomials `pᵢ`. +/// +/// The table is allocated on first insert. `aux` is a second, empty-between-uses +/// table that [`Sum::mul_term`] rebuilds into, so neither allocation is freed. +#[derive(Debug, Default)] +pub(crate) struct Sum { + pub(crate) c0: f64, + pub(crate) maps: Option>, +} + +#[derive(Debug, Default)] +pub(crate) struct SumMaps { + pub(crate) terms: FxHashMap, + /// Persistent rebuild buffer for [`Sum::mul_term`], empty between operations. + pub(crate) aux: FxHashMap, +} + +impl Clone for Sum { + /// Clone the value only. `aux` is workspace, empty between operations, so a + /// clone starts it fresh rather than copying a buffer. + #[inline] + fn clone(&self) -> Self { + Self { + c0: self.c0, + maps: self.maps.as_ref().map(|maps| { + Box::new(SumMaps { + terms: maps.terms.clone(), + aux: FxHashMap::default(), + }) + }), + } + } +} + +/// Representational equality: exact `c0` and table contents. `aux` is not compared. +impl PartialEq for Sum { + fn eq(&self, other: &Self) -> bool { + self.c0 == other.c0 + && match (&self.maps, &other.maps) { + (Some(lhs), Some(rhs)) => lhs.terms == rhs.terms, + (Some(maps), None) | (None, Some(maps)) => maps.terms.is_empty(), + (None, None) => true, + } + } +} + +impl Sum { + /// Construct an empty sum (value `0`). + #[inline] + pub(crate) fn new() -> Self { + Self::default() + } + + /// The monomials, then a nonzero `c₀` as the identity monomial. + pub(crate) fn parts(&self) -> impl Iterator + '_ { + let c0 = (self.c0 != 0.0).then_some((&ONE, self.c0)); + self.iter().chain(c0) + } + + /// The constant part `c₀`. + #[cfg(test)] + #[inline] + pub(crate) fn c0(&self) -> f64 { + self.c0 + } + + /// The number of monomials in the table (excluding `c₀`). + #[inline] + pub(crate) fn len(&self) -> usize { + self.maps.as_ref().map_or(0, |maps| maps.terms.len()) + } + + /// Whether the monomial table is empty (`c₀` is not considered). + #[inline] + pub(crate) fn is_empty(&self) -> bool { + self.maps.as_ref().is_none_or(|maps| maps.terms.is_empty()) + } + + /// Iterate the monomial table in the backend's (deterministic, seed-free) + /// order. + pub(crate) fn iter(&self) -> impl Iterator + '_ { + self.maps + .iter() + .flat_map(|maps| maps.terms.iter()) + .map(|(p, c)| (p, *c)) + } + + /// Add `coeff · p`, dropping it if `p.sin_pow() > max` or `|coeff| <= min_eps`, + /// and removing the monomial if the merged coefficient reaches `min_eps`. + /// + /// The identity monomial folds into `c₀`, which is never truncated. Dropping at + /// insert is exact for `max` but not for `min_eps`: two sub-threshold + /// contributions to one monomial are both dropped, where a post-pass would + /// keep their sum. + #[inline] + pub(crate) fn add_term(&mut self, p: Prod, coeff: f64, max: usize, min_eps: f64) { + if p.is_identity() { + self.c0 += coeff; + return; + } + if p.sin_pow() > max || coeff.abs() <= min_eps { + return; + } + let maps = self.maps.get_or_insert_with(Default::default); + match maps.terms.entry(p) { + Entry::Occupied(mut e) => { + *e.get_mut() += coeff; + if e.get().abs() <= min_eps { + e.remove(); + } + } + Entry::Vacant(e) => { + e.insert(coeff); + } + } + } + + /// Remove every monomial with sine degree above `max` or `|c| <= min_eps`. + pub(crate) fn prune(&mut self, max: usize, min_eps: f64) { + if let Some(maps) = &mut self.maps { + maps.terms + .retain(|p, c| p.sin_pow <= max && c.abs() > min_eps); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::term::{DEFAULT_MAX_SIN, DEFAULT_MIN_EPS}; + + #[test] + fn empty_and_unallocated_sums_compare_equal() { + let mut s = Sum::new(); + s.add_term(Prod::sin(0), 1.0, DEFAULT_MAX_SIN, DEFAULT_MIN_EPS); + s.maps.as_mut().unwrap().terms.clear(); + assert_eq!(s, Sum::new()); + assert_eq!(Sum::new(), s); + } + + #[test] + fn identity_monomial_folds_into_c0_but_i_does_not() { + let mut s = Sum::new(); + s.add_term(Prod::new(), 2.0, DEFAULT_MAX_SIN, DEFAULT_MIN_EPS); + assert_eq!((s.c0(), s.len()), (2.0, 0)); + let mut i = Prod::new(); + i.mul_phase(1); + s.add_term(i, 3.0, DEFAULT_MAX_SIN, DEFAULT_MIN_EPS); + assert_eq!((s.c0(), s.len()), (2.0, 1)); + } +} diff --git a/crates/ppvm-sym-2/src/term.rs b/crates/ppvm-sym-2/src/term.rs new file mode 100644 index 000000000..3a80c5dbc --- /dev/null +++ b/crates/ppvm-sym-2/src/term.rs @@ -0,0 +1,231 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The user-facing [`Term`], its representation [`Inner`] and the angle [`Var`]. + +use crate::prod::Prod; +use crate::sum::Sum; + +/// The `max_sin` of a new [`Term`]: no sine-degree truncation. +pub const DEFAULT_MAX_SIN: usize = usize::MAX; +/// The `min_eps` of a new [`Term`]. +pub const DEFAULT_MIN_EPS: f64 = f64::EPSILON; + +/// The representation of a [`Term`]. `Sum` alone could hold every value; `One` +/// and `Const` exist only for performance, keeping the common single-monomial +/// and scalar cases out of a hash map. `One` never holds the identity monomial. +/// +/// `PartialEq` compares `c₀` and the monomials, not the variant, so `Const(c)` +/// equals a `Sum` holding only `c₀ = c`, and `One(p, c)` a `Sum` holding only `c · p`. +#[derive(Debug, Clone)] +pub(crate) enum Inner { + /// A general sum of products. + Sum(Sum), + /// A single weighted product. + One(Prod, f64), + /// A numeric constant. + Const(f64), +} + +/// `Const(0.0)`, the placeholder while an operator rebuilds the representation. +impl Default for Inner { + fn default() -> Self { + Inner::Const(0.0) + } +} + +impl PartialEq for Inner { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Inner::Sum(a), Inner::Sum(b)) => a == b, + // At most one side is a `Sum`; put it on the right, so the left + // has at most one monomial to look up. + _ => { + let (a, b) = match self { + Inner::Sum(_) => (other, self), + _ => (self, other), + }; + a.c0() == b.c0() + && a.n_monomials() == b.n_monomials() + && match a { + Inner::One(p, c) => b.coeff_of(p) == Some(*c), + _ => true, + } + } + } + } +} + +impl Inner { + fn c0(&self) -> f64 { + match self { + Inner::Const(c) => *c, + Inner::Sum(s) => s.c0, + Inner::One(..) => 0.0, + } + } + + fn n_monomials(&self) -> usize { + match self { + Inner::Sum(s) => s.len(), + Inner::One(..) => 1, + Inner::Const(_) => 0, + } + } + + fn coeff_of(&self, p: &Prod) -> Option { + match self { + Inner::Sum(s) => s.maps.as_ref()?.terms.get(p).copied(), + Inner::One(q, c) => (q == p).then_some(*c), + Inner::Const(_) => None, + } + } + + /// `c · p` with the truncation of [`Sum::add_term`]: `Const(c)` for the + /// identity, `Const(0.0)` when `p` fails a threshold, otherwise `One`. + #[inline] + pub(crate) fn truncated(p: Prod, c: f64, max: usize, min_eps: f64) -> Self { + if p.is_identity() { + Inner::Const(c) + } else if p.sin_pow() > max || c.abs() <= min_eps { + Inner::Const(0.0) + } else { + Inner::One(p, c) + } + } +} + +/// A symbolic polynomial in `sin(x_i)` and `cos(x_i)`. +/// +/// Carries its truncation settings, `max_sin` (maximum sine degree) and +/// `min_eps` (largest dropped coefficient magnitude), which every operation applies to its +/// result with the left operand's settings. +/// +/// # Examples +/// +/// ``` +/// use ppvm_sym_2::Var; +/// +/// // sin²(x0) at x0 = π/2 equals 1. +/// let expr = Var(0).sin() * Var(0).sin(); +/// let v = expr.eval(&[std::f64::consts::FRAC_PI_2]).unwrap(); +/// assert!((v - 1.0).abs() < 1e-12); +/// ``` +#[derive(Debug, Clone, PartialEq)] +pub struct Term { + pub(crate) inner: Inner, + pub(crate) max_sin: usize, // max sin power + pub(crate) min_eps: f64, // coefficients with |c| <= min_eps are dropped +} + +impl Term { + /// Set the maximum sine power, dropping the monomials above it. + #[inline] + pub fn set_max_sin(&mut self, max: usize) { + self.max_sin = max; + self.retruncate(); + } + + /// Set the coefficient cutoff, dropping the monomials with `|c| <= eps`. + #[inline] + pub fn set_min_eps(&mut self, eps: f64) { + self.min_eps = eps; + self.retruncate(); + } + + /// The maximum sine power retained during arithmetic ([`DEFAULT_MAX_SIN`] by default). + #[inline] + pub fn max_sin(&self) -> usize { + self.max_sin + } + + /// The coefficient cutoff used during arithmetic ([`DEFAULT_MIN_EPS`] by default). + #[inline] + pub fn min_eps(&self) -> f64 { + self.min_eps + } + + /// The value as an `f64` if it has no monomials (`Const`, or a `Sum` with only `c₀`). + #[inline] + pub fn as_const(&self) -> Option { + match &self.inner { + Inner::Const(c) => Some(*c), + Inner::Sum(s) if s.is_empty() => Some(s.c0), + _ => None, + } + } + + /// The internal representation, read-only, for tests and diagnostics. + #[cfg(test)] + #[inline] + pub(crate) fn inner(&self) -> &Inner { + &self.inner + } + + /// The angle variable `x_u`; shorthand for [`Var`]`(u)`. + pub fn var(u: u32) -> Var { + Var(u) + } + + /// Build a constant term from `c`, with the default truncation settings. + pub fn from_f64(c: f64) -> Self { + Self::default_with(Inner::Const(c)) + } + + pub(crate) fn default_with(inner: Inner) -> Self { + Self { + inner, + max_sin: DEFAULT_MAX_SIN, + min_eps: DEFAULT_MIN_EPS, + } + } + + /// Monomials in this term: `0` for a constant, `1` for a single product, + /// otherwise the table size. + pub fn n_monomials(&self) -> usize { + self.inner.n_monomials() + } + + /// A term with this term's truncation parameters and a new representation. + #[inline] + pub(crate) fn with_inner(&self, inner: Inner) -> Self { + Term { + inner, + max_sin: self.max_sin, + min_eps: self.min_eps, + } + } +} + +/// A symbolic angle `x_u`: the argument of `sin`/`cos`, never a [`Term`] itself. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Var(pub u32); + +impl Var { + /// `sin(x_u)`, with the default truncation settings. + pub fn sin(self) -> Term { + Term::default_with(Inner::One(Prod::sin(self.0), 1.0)) + } + + /// `cos(x_u)`, with the default truncation settings. + pub fn cos(self) -> Term { + Term::default_with(Inner::One(Prod::cos(self.0), 1.0)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn setting_thresholds_prunes_but_keeps_the_constant() { + let mut t = Term::from_f64(1e-9) + Var(0).sin() * Var(1).sin() + Var(1).cos() * 1e-6; + t.set_max_sin(0); + assert_eq!(t.n_monomials(), 1); + t.set_min_eps(1e-3); + assert_eq!((t.n_monomials(), t.as_const()), (0, Some(1e-9))); + let mut one = Var(0).sin(); + one.set_max_sin(0); + assert_eq!(one.inner(), &Inner::Const(0.0)); + } +}