1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
//! Pattern-matched simplification rules.
use std::collections::HashMap;
use super::graph::ExprGraph;
use super::node::{ExprId, Node};
impl ExprGraph {
/// Simplify an expression by applying rewrite rules to fixpoint.
///
/// Bottom-up: simplify children first, then match parent. Iterates
/// until no more changes occur.
pub fn simplify(&mut self, expr: ExprId) -> ExprId {
let mut memo = HashMap::new();
self.simplify_inner(expr, &mut memo)
}
fn simplify_inner(&mut self, expr: ExprId, memo: &mut HashMap<ExprId, ExprId>) -> ExprId {
if let Some(&cached) = memo.get(&expr) {
return cached;
}
// First, simplify children
let simplified_children = match self.node(expr) {
Node::Var(_) | Node::Lit(_) => expr,
Node::Add(a, b) => {
let sa = self.simplify_inner(a, memo);
let sb = self.simplify_inner(b, memo);
self.add(sa, sb)
}
Node::Mul(a, b) => {
let sa = self.simplify_inner(a, memo);
let sb = self.simplify_inner(b, memo);
self.mul(sa, sb)
}
Node::Neg(a) => {
let sa = self.simplify_inner(a, memo);
self.neg(sa)
}
Node::Recip(a) => {
let sa = self.simplify_inner(a, memo);
self.recip(sa)
}
Node::Sqrt(a) => {
let sa = self.simplify_inner(a, memo);
self.sqrt(sa)
}
Node::Sin(a) => {
let sa = self.simplify_inner(a, memo);
self.sin(sa)
}
Node::Atan2(y, x) => {
let sy = self.simplify_inner(y, memo);
let sx = self.simplify_inner(x, memo);
self.atan2(sy, sx)
}
Node::Exp2(a) => {
let sa = self.simplify_inner(a, memo);
self.exp2(sa)
}
Node::Log2(a) => {
let sa = self.simplify_inner(a, memo);
self.log2(sa)
}
Node::Select(c, a, b) => {
let sc = self.simplify_inner(c, memo);
let sa = self.simplify_inner(a, memo);
let sb = self.simplify_inner(b, memo);
self.select(sc, sa, sb)
}
};
// Now apply rewrite rules on the node with simplified children
let result = self.rewrite(simplified_children);
// If rewrite changed something, simplify again (fixpoint)
let final_result = if result != simplified_children {
self.simplify_inner(result, memo)
} else {
result
};
memo.insert(expr, final_result);
final_result
}
/// Apply one round of rewrite rules.
fn rewrite(&mut self, expr: ExprId) -> ExprId {
match self.node(expr) {
// --- Identity / Annihilation ---
// Add(x, ZERO) → x
Node::Add(a, b) if b == ExprId::ZERO => a,
// Add(ZERO, x) → x
Node::Add(a, b) if a == ExprId::ZERO => b,
// Mul(x, ONE) → x
Node::Mul(a, b) if b == ExprId::ONE => a,
// Mul(ONE, x) → x
Node::Mul(a, b) if a == ExprId::ONE => b,
// Mul(x, ZERO) → ZERO
Node::Mul(_, b) if b == ExprId::ZERO => ExprId::ZERO,
// Mul(ZERO, x) → ZERO
Node::Mul(a, _) if a == ExprId::ZERO => ExprId::ZERO,
// Neg(Neg(x)) → x
Node::Neg(a) => match self.node(a) {
Node::Neg(inner) => inner,
// Neg(ZERO) → ZERO
_ if a == ExprId::ZERO => ExprId::ZERO,
// Constant folding: Neg(Lit(v)) → Lit(-v)
Node::Lit(bits) => {
let v = f64::from_bits(bits);
self.lit(-v)
}
_ => expr,
},
// Recip(Recip(x)) → x
Node::Recip(a) => match self.node(a) {
Node::Recip(inner) => inner,
// Constant folding: Recip(Lit(v)) → Lit(1/v)
Node::Lit(bits) => {
let v = f64::from_bits(bits);
self.lit(1.0 / v)
}
_ => expr,
},
// --- Cancellation ---
// Add(x, Neg(x)) → ZERO
Node::Add(a, b) => {
if let Node::Neg(inner) = self.node(b) {
if inner == a {
return ExprId::ZERO;
}
}
if let Node::Neg(inner) = self.node(a) {
if inner == b {
return ExprId::ZERO;
}
}
// Constant folding: Add(Lit(a), Lit(b)) → Lit(a+b)
if let (Some(va), Some(vb)) = (self.node(a).as_f64(), self.node(b).as_f64()) {
return self.lit(va + vb);
}
expr
}
Node::Mul(a, b) => {
// Mul(x, Recip(x)) → ONE
if let Node::Recip(inner) = self.node(b) {
if inner == a {
return ExprId::ONE;
}
}
if let Node::Recip(inner) = self.node(a) {
if inner == b {
return ExprId::ONE;
}
}
// Constant folding: Mul(Lit(a), Lit(b)) → Lit(a*b)
if let (Some(va), Some(vb)) = (self.node(a).as_f64(), self.node(b).as_f64()) {
return self.lit(va * vb);
}
expr
}
// Constant folding for unary ops
Node::Sqrt(a) => {
if let Some(v) = self.node(a).as_f64() {
self.lit(v.sqrt())
} else {
expr
}
}
Node::Sin(a) => {
if let Some(v) = self.node(a).as_f64() {
self.lit(v.sin())
} else {
expr
}
}
Node::Exp2(a) => {
if let Some(v) = self.node(a).as_f64() {
self.lit(v.exp2())
} else {
expr
}
}
Node::Log2(a) => {
if let Some(v) = self.node(a).as_f64() {
self.lit(v.log2())
} else {
expr
}
}
// Select constant folding
Node::Select(c, a, b) => {
if let Some(vc) = self.node(c).as_f64() {
if vc > 0.0 { a } else { b }
} else {
expr
}
}
_ => expr,
}
}
}
#[cfg(test)]
mod tests {
use super::graph::ExprGraph;
use super::node::ExprId;
#[test]
fn simplify_add_zero() {
let mut g = ExprGraph::new();
let x = g.var(0);
let sum = g.add(x, ExprId::ZERO);
let s = g.simplify(sum);
assert_eq!(s, x);
let sum2 = g.add(ExprId::ZERO, x);
let s2 = g.simplify(sum2);
assert_eq!(s2, x);
}
#[test]
fn simplify_mul_one() {
let mut g = ExprGraph::new();
let x = g.var(0);
let prod = g.mul(x, ExprId::ONE);
let s = g.simplify(prod);
assert_eq!(s, x);
}
#[test]
fn simplify_mul_zero() {
let mut g = ExprGraph::new();
let x = g.var(0);
let prod = g.mul(x, ExprId::ZERO);
let s = g.simplify(prod);
assert_eq!(s, ExprId::ZERO);
}
#[test]
fn simplify_neg_neg() {
let mut g = ExprGraph::new();
let x = g.var(0);
let nn = g.neg(x);
let nnn = g.neg(nn);
let s = g.simplify(nnn);
assert_eq!(s, x);
}
#[test]
fn simplify_recip_recip() {
let mut g = ExprGraph::new();
let x = g.var(0);
let r = g.recip(x);
let rr = g.recip(r);
let s = g.simplify(rr);
assert_eq!(s, x);
}
#[test]
fn simplify_cancel_add_neg() {
let mut g = ExprGraph::new();
let x = g.var(0);
let nx = g.neg(x);
let sum = g.add(x, nx);
let s = g.simplify(sum);
assert_eq!(s, ExprId::ZERO);
}
#[test]
fn simplify_cancel_mul_recip() {
let mut g = ExprGraph::new();
let x = g.var(0);
let rx = g.recip(x);
let prod = g.mul(x, rx);
let s = g.simplify(prod);
assert_eq!(s, ExprId::ONE);
}
#[test]
fn simplify_constant_fold_add() {
let mut g = ExprGraph::new();
let a = g.lit(3.0);
let b = g.lit(4.0);
let sum = g.add(a, b);
let s = g.simplify(sum);
let result: f64 = g.eval(s, &[]);
assert!((result - 7.0).abs() < 1e-10);
}
#[test]
fn simplify_constant_fold_mul() {
let mut g = ExprGraph::new();
let a = g.lit(3.0);
let b = g.lit(4.0);
let prod = g.mul(a, b);
let s = g.simplify(prod);
let result: f64 = g.eval(s, &[]);
assert!((result - 12.0).abs() < 1e-10);
}
#[test]
fn simplify_neg_zero() {
let mut g = ExprGraph::new();
let nz = g.neg(ExprId::ZERO);
let s = g.simplify(nz);
// Neg(Lit(0)) → Lit(-0) which is 0.0 in bits check
// Actually -0.0 has different bits than 0.0, so this creates a new lit.
// But functionally it's still zero. Let's just verify the value.
let result: f64 = g.eval(s, &[]);
assert!(result == 0.0);
}
#[test]
fn simplify_derivative() {
// d/dx (x*x) = 2x after simplification
let mut g = ExprGraph::new();
let x = g.var(0);
let xx = g.mul(x, x);
let d = g.diff(xx, 0);
// Before simplification, d = Add(Mul(ONE, x), Mul(x, ONE))
// After: Add(x, x)
let s = g.simplify(d);
let result: f64 = g.eval(s, &[5.0]);
assert!((result - 10.0).abs() < 1e-10);
}
}