Skip to main content

qualia_core_db/specialized_libs/
symbolic_assumptions.rs

1//! **Simplification under assumptions** (Gap analysis §3.3) — CAS simplifications that are
2//! only *valid* when the simplifier knows a variable's sign / nonzero-ness.
3//!
4//! Plain [`simplify`] must stay sound for *all* real
5//! inputs, so it cannot turn `√(x²)` into `x` (that is `|x|`), or `ln(a·b)` into
6//! `ln a + ln b` (the log laws need positivity). This module takes an explicit
7//! [`Assumptions`] set (`x > 0`, `n ≠ 0`, …) and applies exactly those rewrites the
8//! assumptions license — and **no others**. Every rewrite is gated on a *proof* of the
9//! needed sign from the assumptions (see [`Assumptions::is_positive`] etc.); when the sign
10//! cannot be established the node is left untouched (fail-closed: never an unsound rewrite).
11
12use super::symbolic_algebra::{add, c, ln, mul, neg, pow, simplify, sqrt, Expr};
13use std::collections::HashMap;
14
15/// A sign / domain assumption about a single variable.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Sign {
18    /// `x > 0`.
19    Positive,
20    /// `x ≥ 0`.
21    NonNegative,
22    /// `x < 0`.
23    Negative,
24    /// `x ≤ 0`.
25    NonPositive,
26    /// `x ≠ 0` (sign unknown).
27    Nonzero,
28}
29
30/// A set of per-variable sign assumptions used to license otherwise-unsound rewrites.
31#[derive(Debug, Clone, Default)]
32pub struct Assumptions {
33    signs: HashMap<String, Sign>,
34}
35
36impl Assumptions {
37    /// Creates a default `Assumptions`.
38    pub fn new() -> Self {
39        Self {
40            signs: HashMap::new(),
41        }
42    }
43
44    /// Assert a sign for `var`. Builder-style (chainable).
45    pub fn assume(mut self, var: &str, sign: Sign) -> Self {
46        self.signs.insert(var.to_string(), sign);
47        self
48    }
49
50    fn var_sign(&self, name: &str) -> Option<Sign> {
51        self.signs.get(name).copied()
52    }
53
54    /// Provable `expr ≥ 0` under these assumptions (a *sufficient* test — `None`-of-proof
55    /// means "unknown", never "negative").
56    pub fn is_nonnegative(&self, e: &Expr) -> bool {
57        match e {
58            Expr::Const(k) => *k >= 0.0,
59            Expr::Var(name) => matches!(
60                self.var_sign(name),
61                Some(Sign::Positive) | Some(Sign::NonNegative)
62            ),
63            // Even integer powers are ≥ 0 for any real base; odd powers inherit the base.
64            Expr::Pow(a, n) => *n % 2 == 0 || self.is_nonnegative(a),
65            Expr::Sqrt(_) | Expr::Exp(_) => true, // real sqrt ≥ 0, exp > 0
66            Expr::Mul(a, b) => {
67                (self.is_nonnegative(a) && self.is_nonnegative(b))
68                    || (self.is_nonpositive(a) && self.is_nonpositive(b))
69            }
70            Expr::Add(a, b) => self.is_nonnegative(a) && self.is_nonnegative(b),
71            Expr::Neg(a) => self.is_nonpositive(a),
72            _ => false,
73        }
74    }
75
76    /// Provable `expr > 0` under these assumptions.
77    pub fn is_positive(&self, e: &Expr) -> bool {
78        match e {
79            Expr::Const(k) => *k > 0.0,
80            Expr::Var(name) => matches!(self.var_sign(name), Some(Sign::Positive)),
81            Expr::Exp(_) => true,
82            Expr::Sqrt(a) => self.is_positive(a),
83            Expr::Pow(a, n) => *n % 2 == 0 && self.is_nonzero(a) || self.is_positive(a),
84            Expr::Mul(a, b) => {
85                (self.is_positive(a) && self.is_positive(b))
86                    || (self.is_negative(a) && self.is_negative(b))
87            }
88            Expr::Add(a, b) => {
89                self.is_positive(a) && self.is_nonnegative(b)
90                    || self.is_nonnegative(a) && self.is_positive(b)
91            }
92            Expr::Neg(a) => self.is_negative(a),
93            _ => false,
94        }
95    }
96
97    /// Provable `expr ≤ 0`.
98    pub fn is_nonpositive(&self, e: &Expr) -> bool {
99        match e {
100            Expr::Const(k) => *k <= 0.0,
101            Expr::Var(name) => matches!(
102                self.var_sign(name),
103                Some(Sign::Negative) | Some(Sign::NonPositive)
104            ),
105            Expr::Neg(a) => self.is_nonnegative(a),
106            _ => false,
107        }
108    }
109
110    /// Provable `expr < 0`.
111    pub fn is_negative(&self, e: &Expr) -> bool {
112        match e {
113            Expr::Const(k) => *k < 0.0,
114            Expr::Var(name) => matches!(self.var_sign(name), Some(Sign::Negative)),
115            Expr::Neg(a) => self.is_positive(a),
116            _ => false,
117        }
118    }
119
120    /// Provable `expr ≠ 0`.
121    pub fn is_nonzero(&self, e: &Expr) -> bool {
122        match e {
123            Expr::Const(k) => *k != 0.0,
124            Expr::Var(name) => matches!(
125                self.var_sign(name),
126                Some(Sign::Positive) | Some(Sign::Negative) | Some(Sign::Nonzero)
127            ),
128            Expr::Exp(_) => true,
129            Expr::Pow(a, _) => self.is_nonzero(a),
130            Expr::Sqrt(a) => self.is_positive(a),
131            Expr::Mul(a, b) => self.is_nonzero(a) && self.is_nonzero(b),
132            Expr::Neg(a) => self.is_nonzero(a),
133            _ => false,
134        }
135    }
136}
137
138/// Simplify `expr` using assumption-gated rewrites on top of the plain (always-sound)
139/// [`simplify`]. Applied to a bounded fixpoint. Rewrites performed (each only when the
140/// assumptions *prove* the side condition):
141///
142/// - `√(x²) → x`           when `x ≥ 0`  (and `→ −x` when `x ≤ 0`)
143/// - `(√x)² → x`           when `x ≥ 0`
144/// - `ln(a·b) → ln a + ln b`   when `a, b > 0`
145/// - `ln(aⁿ) → n·ln a`         when `a > 0`
146pub fn simplify_with_assumptions(expr: &Expr, asm: &Assumptions) -> Expr {
147    let mut cur = simplify(expr);
148    for _ in 0..16 {
149        let next = simplify(&rewrite(&cur, asm));
150        if next == cur {
151            break;
152        }
153        cur = next;
154    }
155    cur
156}
157
158fn rewrite(e: &Expr, asm: &Assumptions) -> Expr {
159    // Rewrite children first (bottom-up).
160    let e = match e {
161        Expr::Add(a, b) => add(rewrite(a, asm), rewrite(b, asm)),
162        Expr::Sub(a, b) => Expr::Sub(Box::new(rewrite(a, asm)), Box::new(rewrite(b, asm))),
163        Expr::Mul(a, b) => mul(rewrite(a, asm), rewrite(b, asm)),
164        Expr::Div(a, b) => Expr::Div(Box::new(rewrite(a, asm)), Box::new(rewrite(b, asm))),
165        Expr::Pow(a, n) => pow(rewrite(a, asm), *n),
166        Expr::Neg(a) => neg(rewrite(a, asm)),
167        Expr::Sqrt(a) => sqrt(rewrite(a, asm)),
168        Expr::Exp(a) => Expr::Exp(Box::new(rewrite(a, asm))),
169        Expr::Ln(a) => ln(rewrite(a, asm)),
170        Expr::Sin(a) => Expr::Sin(Box::new(rewrite(a, asm))),
171        Expr::Cos(a) => Expr::Cos(Box::new(rewrite(a, asm))),
172        Expr::Tan(a) => Expr::Tan(Box::new(rewrite(a, asm))),
173        Expr::Const(_) | Expr::Var(_) => e.clone(),
174    };
175
176    match &e {
177        // √(x²) → x (x≥0) / −x (x≤0).
178        Expr::Sqrt(inner) => {
179            if let Expr::Pow(base, 2) = &**inner {
180                if asm.is_nonnegative(base) {
181                    return (**base).clone();
182                }
183                if asm.is_nonpositive(base) {
184                    return neg((**base).clone());
185                }
186            }
187            e
188        }
189        // (√x)² → x  when x ≥ 0.
190        Expr::Pow(base, 2) => {
191            if let Expr::Sqrt(under) = &**base {
192                if asm.is_nonnegative(under) {
193                    return (**under).clone();
194                }
195            }
196            e
197        }
198        // ln laws under positivity.
199        Expr::Ln(arg) => match &**arg {
200            Expr::Mul(a, b) if asm.is_positive(a) && asm.is_positive(b) => {
201                add(ln((**a).clone()), ln((**b).clone()))
202            }
203            Expr::Pow(a, n) if asm.is_positive(a) => mul(c(*n as f64), ln((**a).clone())),
204            _ => e,
205        },
206        _ => e,
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::super::symbolic_algebra::{c, exp, mul, pow, sqrt, var};
213    use super::*;
214
215    #[test]
216    fn sqrt_of_square_uses_sign() {
217        // √(x²) → x when x ≥ 0.
218        let pos = Assumptions::new().assume("x", Sign::Positive);
219        assert_eq!(
220            simplify_with_assumptions(&sqrt(pow(var("x"), 2)), &pos),
221            var("x")
222        );
223        // → −x when x ≤ 0.
224        let neg_x = Assumptions::new().assume("x", Sign::Negative);
225        assert_eq!(
226            simplify_with_assumptions(&sqrt(pow(var("x"), 2)), &neg_x),
227            neg(var("x"))
228        );
229        // Unknown sign → left as √(x²) (no unsound rewrite).
230        let unknown = Assumptions::new();
231        let s = simplify_with_assumptions(&sqrt(pow(var("x"), 2)), &unknown);
232        assert_eq!(s, sqrt(pow(var("x"), 2)));
233    }
234
235    #[test]
236    fn sqrt_square_inverse() {
237        // (√x)² → x when x ≥ 0.
238        let asm = Assumptions::new().assume("x", Sign::NonNegative);
239        assert_eq!(
240            simplify_with_assumptions(&pow(sqrt(var("x")), 2), &asm),
241            var("x")
242        );
243    }
244
245    #[test]
246    fn log_laws_need_positivity() {
247        let asm = Assumptions::new()
248            .assume("a", Sign::Positive)
249            .assume("b", Sign::Positive);
250        // ln(a·b) → ln a + ln b ; numerically equal at a sample point.
251        let got = simplify_with_assumptions(&ln(mul(var("a"), var("b"))), &asm);
252        let mut env = HashMap::new();
253        env.insert("a".to_string(), 3.0);
254        env.insert("b".to_string(), 5.0);
255        assert!((got.eval(&env).unwrap() - (15.0_f64).ln()).abs() < 1e-9);
256        assert_eq!(got, add(ln(var("a")), ln(var("b"))));
257        // ln(a³) → 3·ln a.
258        let got2 = simplify_with_assumptions(&ln(pow(var("a"), 3)), &asm);
259        assert_eq!(got2, mul(c(3.0), ln(var("a"))));
260        // Without the positivity assumption, no rewrite.
261        let none = Assumptions::new();
262        assert_eq!(
263            simplify_with_assumptions(&ln(mul(var("a"), var("b"))), &none),
264            ln(mul(var("a"), var("b")))
265        );
266    }
267
268    #[test]
269    fn sign_inference_basics() {
270        let asm = Assumptions::new().assume("x", Sign::Positive);
271        assert!(asm.is_positive(&exp(var("x"))));
272        assert!(asm.is_nonnegative(&pow(var("y"), 2))); // even power, any base
273        assert!(asm.is_nonzero(&var("x")));
274        assert!(!asm.is_positive(&var("y"))); // unknown
275    }
276}