1use super::symbolic_algebra::{add, c, ln, mul, neg, pow, simplify, sqrt, Expr};
13use std::collections::HashMap;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Sign {
18 Positive,
20 NonNegative,
22 Negative,
24 NonPositive,
26 Nonzero,
28}
29
30#[derive(Debug, Clone, Default)]
32pub struct Assumptions {
33 signs: HashMap<String, Sign>,
34}
35
36impl Assumptions {
37 pub fn new() -> Self {
39 Self {
40 signs: HashMap::new(),
41 }
42 }
43
44 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 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 Expr::Pow(a, n) => *n % 2 == 0 || self.is_nonnegative(a),
65 Expr::Sqrt(_) | Expr::Exp(_) => true, 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 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 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 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 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
138pub 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 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 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 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 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 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 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 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 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 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 let got2 = simplify_with_assumptions(&ln(pow(var("a"), 3)), &asm);
259 assert_eq!(got2, mul(c(3.0), ln(var("a"))));
260 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))); assert!(asm.is_nonzero(&var("x")));
274 assert!(!asm.is_positive(&var("y"))); }
276}