|
| 1 | +use std::{ |
| 2 | + collections::BTreeMap, |
| 3 | + fmt::Display, |
| 4 | + ops::{Add, Mul, MulAssign, Neg, Sub}, |
| 5 | +}; |
| 6 | + |
| 7 | +use itertools::Itertools; |
| 8 | +use powdr_number::FieldElement; |
| 9 | + |
| 10 | +use crate::witgen::range_constraints::RangeConstraint; |
| 11 | + |
| 12 | +use super::symbolic_expression::SymbolicExpression; |
| 13 | + |
| 14 | +/// A symbolic expression in unknown variables of type `V` and (symbolically) |
| 15 | +/// known terms, representing a sum of (super-)quadratic, linear and constant parts. |
| 16 | +/// The quadratic terms are of the form `X * Y`, where `X` and `Y` are |
| 17 | +/// `QuadraticSymbolicExpression`s that have at least one unknown. |
| 18 | +/// The linear terms are of the form `a * X`, where `a` is a (symbolically) known |
| 19 | +/// value and `X` is an unknown variable. |
| 20 | +/// The constant term is a (symbolically) known value. |
| 21 | +/// |
| 22 | +/// It also provides ways to quickly update the expression when the value of |
| 23 | +/// an unknown variable gets known and provides functions to solve |
| 24 | +/// (some kinds of) equations. |
| 25 | +#[derive(Debug, Clone)] |
| 26 | +pub struct QuadraticSymbolicExpression<T: FieldElement, V> { |
| 27 | + /// Quadratic terms of the form `a * X * Y`, where `a` is a (symbolically) |
| 28 | + /// known value and `X` and `Y` are quadratic symbolic expressions that |
| 29 | + /// have at least one unknown. |
| 30 | + quadratic: Vec<(Self, Self)>, |
| 31 | + /// Linear terms of the form `a * X`, where `a` is a (symbolically) known |
| 32 | + /// value and `X` is an unknown variable. |
| 33 | + linear: BTreeMap<V, SymbolicExpression<T, V>>, |
| 34 | + /// Constant term, a (symbolically) known value. |
| 35 | + constant: SymbolicExpression<T, V>, |
| 36 | +} |
| 37 | +// TODO We need occurrence lists for all variables, both in their unknon |
| 38 | +// version and in their known version (in the symbolic expressions), |
| 39 | +// because range constraints therein can also change. |
| 40 | +// they could also change to simpler expressions if one sub-expression turns to one or zero. |
| 41 | +// So we also need update functions for the symbolic expressions. |
| 42 | + |
| 43 | +impl<T: FieldElement, V> From<SymbolicExpression<T, V>> for QuadraticSymbolicExpression<T, V> { |
| 44 | + fn from(k: SymbolicExpression<T, V>) -> Self { |
| 45 | + Self { |
| 46 | + quadratic: Default::default(), |
| 47 | + linear: Default::default(), |
| 48 | + constant: k, |
| 49 | + } |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +impl<T: FieldElement, V> From<T> for QuadraticSymbolicExpression<T, V> { |
| 54 | + fn from(k: T) -> Self { |
| 55 | + SymbolicExpression::from(k).into() |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +impl<T: FieldElement, V: Ord + Clone> QuadraticSymbolicExpression<T, V> { |
| 60 | + pub fn from_known_symbol(symbol: V, rc: RangeConstraint<T>) -> Self { |
| 61 | + SymbolicExpression::from_symbol(symbol, rc).into() |
| 62 | + } |
| 63 | + pub fn from_unknown_variable(var: V) -> Self { |
| 64 | + Self { |
| 65 | + quadratic: Default::default(), |
| 66 | + linear: [(var.clone(), T::from(1).into())].into_iter().collect(), |
| 67 | + constant: T::from(0).into(), |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + /// If this expression does not contain unknown variables, returns the symbolic expression. |
| 72 | + pub fn try_to_known(&self) -> Option<&SymbolicExpression<T, V>> { |
| 73 | + if self.quadratic.is_empty() && self.linear.is_empty() { |
| 74 | + Some(&self.constant) |
| 75 | + } else { |
| 76 | + None |
| 77 | + } |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +impl<T: FieldElement, V: Clone + Ord> Add for QuadraticSymbolicExpression<T, V> { |
| 82 | + type Output = QuadraticSymbolicExpression<T, V>; |
| 83 | + |
| 84 | + fn add(mut self, rhs: Self) -> Self { |
| 85 | + self.quadratic.extend(rhs.quadratic); |
| 86 | + for (var, coeff) in rhs.linear { |
| 87 | + self.linear |
| 88 | + .entry(var) |
| 89 | + .and_modify(|f| *f += coeff.clone()) |
| 90 | + .or_insert_with(|| coeff); |
| 91 | + } |
| 92 | + self.linear.retain(|_, f| !f.is_known_zero()); |
| 93 | + self.constant += rhs.constant; |
| 94 | + self |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +impl<T: FieldElement, V: Clone + Ord> Add for &QuadraticSymbolicExpression<T, V> { |
| 99 | + type Output = QuadraticSymbolicExpression<T, V>; |
| 100 | + |
| 101 | + fn add(self, rhs: Self) -> Self::Output { |
| 102 | + self.clone() + rhs.clone() |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +impl<T: FieldElement, V: Clone + Ord> Sub for &QuadraticSymbolicExpression<T, V> { |
| 107 | + type Output = QuadraticSymbolicExpression<T, V>; |
| 108 | + |
| 109 | + fn sub(self, rhs: Self) -> Self::Output { |
| 110 | + self + &-rhs |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +impl<T: FieldElement, V: Clone + Ord> Sub for QuadraticSymbolicExpression<T, V> { |
| 115 | + type Output = QuadraticSymbolicExpression<T, V>; |
| 116 | + |
| 117 | + fn sub(self, rhs: Self) -> Self::Output { |
| 118 | + &self - &rhs |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +impl<T: FieldElement, V: Clone + Ord> QuadraticSymbolicExpression<T, V> { |
| 123 | + fn negate(&mut self) { |
| 124 | + for (first, _) in &mut self.quadratic { |
| 125 | + first.negate() |
| 126 | + } |
| 127 | + for coeff in self.linear.values_mut() { |
| 128 | + *coeff = -coeff.clone(); |
| 129 | + } |
| 130 | + self.constant = -self.constant.clone(); |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +impl<T: FieldElement, V: Clone + Ord> Neg for QuadraticSymbolicExpression<T, V> { |
| 135 | + type Output = QuadraticSymbolicExpression<T, V>; |
| 136 | + |
| 137 | + fn neg(mut self) -> Self { |
| 138 | + self.negate(); |
| 139 | + self |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +impl<T: FieldElement, V: Clone + Ord> Neg for &QuadraticSymbolicExpression<T, V> { |
| 144 | + type Output = QuadraticSymbolicExpression<T, V>; |
| 145 | + |
| 146 | + fn neg(self) -> Self::Output { |
| 147 | + -((*self).clone()) |
| 148 | + } |
| 149 | +} |
| 150 | + |
| 151 | +/// Multiply by known symbolic expression. |
| 152 | +impl<T: FieldElement, V: Clone + Ord> Mul<&SymbolicExpression<T, V>> |
| 153 | + for QuadraticSymbolicExpression<T, V> |
| 154 | +{ |
| 155 | + type Output = QuadraticSymbolicExpression<T, V>; |
| 156 | + |
| 157 | + fn mul(mut self, rhs: &SymbolicExpression<T, V>) -> Self { |
| 158 | + self *= rhs; |
| 159 | + self |
| 160 | + } |
| 161 | +} |
| 162 | + |
| 163 | +impl<T: FieldElement, V: Clone + Ord> Mul<SymbolicExpression<T, V>> |
| 164 | + for QuadraticSymbolicExpression<T, V> |
| 165 | +{ |
| 166 | + type Output = QuadraticSymbolicExpression<T, V>; |
| 167 | + |
| 168 | + fn mul(self, rhs: SymbolicExpression<T, V>) -> Self { |
| 169 | + self * &rhs |
| 170 | + } |
| 171 | +} |
| 172 | + |
| 173 | +impl<T: FieldElement, V: Clone + Ord> MulAssign<&SymbolicExpression<T, V>> |
| 174 | + for QuadraticSymbolicExpression<T, V> |
| 175 | +{ |
| 176 | + fn mul_assign(&mut self, rhs: &SymbolicExpression<T, V>) { |
| 177 | + if rhs.is_known_zero() { |
| 178 | + *self = T::zero().into(); |
| 179 | + } else { |
| 180 | + for (first, _) in &mut self.quadratic { |
| 181 | + *first *= rhs; |
| 182 | + } |
| 183 | + for coeff in self.linear.values_mut() { |
| 184 | + *coeff *= rhs.clone(); |
| 185 | + } |
| 186 | + self.constant *= rhs.clone(); |
| 187 | + } |
| 188 | + } |
| 189 | +} |
| 190 | + |
| 191 | +impl<T: FieldElement, V: Clone + Ord> Mul for QuadraticSymbolicExpression<T, V> { |
| 192 | + type Output = QuadraticSymbolicExpression<T, V>; |
| 193 | + |
| 194 | + fn mul(self, rhs: QuadraticSymbolicExpression<T, V>) -> Self { |
| 195 | + if let Some(k) = rhs.try_to_known() { |
| 196 | + self * k |
| 197 | + } else if let Some(k) = self.try_to_known() { |
| 198 | + rhs * k |
| 199 | + } else { |
| 200 | + Self { |
| 201 | + quadratic: vec![(self, rhs)], |
| 202 | + linear: Default::default(), |
| 203 | + constant: T::from(0).into(), |
| 204 | + } |
| 205 | + } |
| 206 | + } |
| 207 | +} |
| 208 | + |
| 209 | +impl<T: FieldElement, V: Clone + Ord + Display> Display for QuadraticSymbolicExpression<T, V> { |
| 210 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 211 | + write!( |
| 212 | + f, |
| 213 | + "{}", |
| 214 | + self.quadratic |
| 215 | + .iter() |
| 216 | + .map(|(a, b)| format!("({a}) * ({b})")) |
| 217 | + .chain( |
| 218 | + self.linear |
| 219 | + .iter() |
| 220 | + .map(|(var, coeff)| match coeff.try_to_number() { |
| 221 | + Some(k) if k == 1.into() => format!("{var}"), |
| 222 | + Some(k) if k == (-1).into() => format!("-{var}"), |
| 223 | + _ => format!("{coeff} * {var}"), |
| 224 | + }) |
| 225 | + ) |
| 226 | + .chain(match self.constant.try_to_number() { |
| 227 | + Some(k) if k == T::zero() => None, |
| 228 | + _ => Some(format!("{}", self.constant)), |
| 229 | + }) |
| 230 | + .format(" + ") |
| 231 | + ) |
| 232 | + } |
| 233 | +} |
| 234 | + |
| 235 | +#[cfg(test)] |
| 236 | +mod tests { |
| 237 | + use super::*; |
| 238 | + use crate::witgen::range_constraints::RangeConstraint; |
| 239 | + use powdr_number::GoldilocksField; |
| 240 | + |
| 241 | + use pretty_assertions::assert_eq; |
| 242 | + |
| 243 | + #[test] |
| 244 | + fn test_mul_zero() { |
| 245 | + type Qse = QuadraticSymbolicExpression<GoldilocksField, String>; |
| 246 | + let x = Qse::from_unknown_variable("X".to_string()); |
| 247 | + let y = Qse::from_unknown_variable("Y".to_string()); |
| 248 | + let a = Qse::from_known_symbol("A".to_string(), RangeConstraint::default()); |
| 249 | + let t = x * y + a; |
| 250 | + assert_eq!(t.to_string(), "(X) * (Y) + A"); |
| 251 | + } |
| 252 | +} |
0 commit comments