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
339
340
// Copyright 2026 Mahmoud Harmouch.
//
// Licensed under the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! # Symbolic Expression Tools
//!
//! This module provides high-level helpers that operate on [`Expression`] trees:
//!
//! - Symbolic differentiation via [`symbolic_diff`].
//! - Algebraic simplification via [`simplify`].
//! - Complexity scoring via [`complexity_score`].
//! - Numerical gradient estimation via [`numerical_gradient`] (central differences).
//! - Jacobian matrix computation via [`jacobian`].
//! - Functional composition via [`compose`].
//! - Substitution of sub-expressions via the internal `substitute` helper.
//!
//! All functions are pure and do not mutate the input [`Expression`].
use crateExpression;
use crateTensor;
use HashMap;
/// Returns the symbolic partial derivative of `expr` with respect to `var`.
///
/// Differentiation rules are applied recursively over the expression tree.
/// See [`Expression::symbolic_diff`] for the full rule set.
///
/// # Arguments
///
/// * `expr` - The expression to differentiate.
/// * `var` - The name of the variable to differentiate with respect to.
///
/// # Returns
///
/// (`Expression`): The (unsimplified) derivative expression.
///
/// # Examples
///
/// ```
/// use lmm::traits::Simulatable;
/// use lmm::symbolic::symbolic_diff;
/// use lmm::equation::Expression;
///
/// // d/dx (x²) = 2x
/// let x_sq = Expression::Pow(
/// Box::new(Expression::Variable("x".into())),
/// Box::new(Expression::Constant(2.0)),
/// );
/// let deriv = symbolic_diff(&x_sq, "x").simplify();
/// let mut env = std::collections::HashMap::new();
/// env.insert("x".to_string(), 3.0);
/// assert!((deriv.evaluate(&env).unwrap() - 6.0).abs() < 1e-9);
/// ```
/// Algebraically simplifies `expr` using constant folding and identity rules.
///
/// # Arguments
///
/// * `expr` - The expression to simplify.
///
/// # Returns
///
/// (`Expression`): A semantically equivalent but structurally simpler expression.
///
/// # Examples
///
/// ```
/// use lmm::traits::Simulatable;
/// use lmm::symbolic::simplify;
/// use lmm::equation::Expression;
///
/// let zero = Expression::Mul(
/// Box::new(Expression::Constant(0.0)),
/// Box::new(Expression::Variable("x".into())),
/// );
/// let s = simplify(&zero);
/// assert!(matches!(s, Expression::Constant(c) if c == 0.0));
/// ```
/// Returns the number of nodes in the expression tree (a proxy for model complexity).
///
/// Used by [`crate::compression::mdl_score`] to penalise large expressions.
///
/// # Arguments
///
/// * `expr` - The expression to measure.
///
/// # Returns
///
/// (`usize`): Number of nodes in the expression tree.
///
/// # Examples
///
/// ```
/// use lmm::traits::Simulatable;
/// use lmm::symbolic::complexity_score;
/// use lmm::equation::Expression;
///
/// let e = Expression::Add(
/// Box::new(Expression::Variable("x".into())),
/// Box::new(Expression::Constant(1.0)),
/// );
/// assert_eq!(complexity_score(&e), 3);
/// ```
/// Formats `expr` as a human-readable infix string.
///
/// # Arguments
///
/// * `expr` - The expression to format.
///
/// # Returns
///
/// (`String`): Infix text representation.
///
/// # Examples
///
/// ```
/// use lmm::traits::Simulatable;
/// use lmm::symbolic::format_expr;
/// use lmm::equation::Expression;
///
/// let e = Expression::Add(
/// Box::new(Expression::Variable("x".into())),
/// Box::new(Expression::Constant(2.0)),
/// );
/// assert_eq!(format_expr(&e), "(x + 2)");
/// ```
/// Estimates the partial derivative of `expr` with respect to `var` at `data` using
/// **central finite differences**: `(f(x+h) - f(x-h)) / (2h)`.
///
/// # Arguments
///
/// * `expr` - The expression to differentiate numerically.
/// * `var` - The variable to perturb.
/// * `data` - Bindings for all variables as `(name, value)` pairs.
/// * `h` - Finite-difference step size (typically `1e-5`).
///
/// # Returns
///
/// (`Option<f64>`): Numerical derivative, or `None` when `var` is not in `data` or
/// the expression fails to evaluate.
///
/// # Examples
///
/// ```
/// use lmm::traits::Simulatable;
/// use lmm::symbolic::numerical_gradient;
/// use lmm::equation::Expression;
///
/// // f(x) = x²; f'(x) at x=3 ≈ 6
/// let expr = Expression::Pow(
/// Box::new(Expression::Variable("x".into())),
/// Box::new(Expression::Constant(2.0)),
/// );
/// let grad = numerical_gradient(&expr, "x", &[("x", 3.0)], 1e-5).unwrap();
/// assert!((grad - 6.0).abs() < 1e-4);
/// ```
/// Computes the Jacobian matrix of `exprs` with respect to `vars` at `point`.
///
/// Returns a matrix `J[i][j] = ∂exprs[i]/∂vars[j]` evaluated analytically via symbolic
/// differentiation.
///
/// # Arguments
///
/// * `exprs` - The output expressions (one per row of J).
/// * `vars` - The input variable names (one per column of J).
/// * `point` - The point at which to evaluate; components mapped positionally to `vars`.
///
/// # Returns
///
/// (`Vec<Vec<f64>>`): Jacobian matrix of shape `[exprs.len() × vars.len()]`.
///
/// # Time Complexity
///
/// O(|exprs| · |vars| · depth) for symbolic differentiation plus evaluation.
///
/// # Examples
///
/// ```
/// use lmm::traits::Simulatable;
/// use lmm::symbolic::jacobian;
/// use lmm::equation::Expression;
/// use lmm::tensor::Tensor;
///
/// // f(x, y) = [x + y, x*y]; Jacobian at (1, 2) = [[1,1],[2,1]]
/// let fx = Expression::Add(
/// Box::new(Expression::Variable("x".into())),
/// Box::new(Expression::Variable("y".into())),
/// );
/// let fy = Expression::Mul(
/// Box::new(Expression::Variable("x".into())),
/// Box::new(Expression::Variable("y".into())),
/// );
/// let j = jacobian(&[fx, fy], &["x", "y"], &Tensor::from_vec(vec![1.0, 2.0]));
/// assert!((j[0][0] - 1.0).abs() < 1e-9); // ∂(x+y)/∂x
/// assert!((j[1][0] - 2.0).abs() < 1e-9); // ∂(x*y)/∂x at (1,2) = y = 2
/// ```
/// use lmm::traits::Simulatable;
/// Composes two expressions: `compose(outer, inner, var)` returns `outer[var ↦ inner]`.
///
/// # Arguments
///
/// * `outer` - The outer function expression.
/// * `inner` - The inner function expression substituted for `var`.
/// * `var` - The variable in `outer` to replace.
///
/// # Returns
///
/// (`Expression`): The composed expression.
///
/// # Examples
///
/// ```
/// use lmm::traits::Simulatable;
/// use lmm::symbolic::compose;
/// use lmm::equation::Expression;
///
/// // outer = x², inner = (x + 1); compose(outer, inner, "x") = (x+1)²
/// let outer = Expression::Pow(
/// Box::new(Expression::Variable("x".into())),
/// Box::new(Expression::Constant(2.0)),
/// );
/// let inner = Expression::Add(
/// Box::new(Expression::Variable("x".into())),
/// Box::new(Expression::Constant(1.0)),
/// );
/// let composed = compose(&outer, &inner, "x");
/// let mut env = std::collections::HashMap::new();
/// env.insert("x".to_string(), 2.0);
/// // (2+1)² = 9
/// assert!((composed.evaluate(&env).unwrap() - 9.0).abs() < 1e-9);
/// ```
/// Substitutes every occurrence of variable `var` in `expr` with `replacement`.
///
/// This is a structural tree rewrite - it does not evaluate or simplify the result.
///
/// # Arguments
///
/// * `expr` - Source expression tree.
/// * `var` - Variable name to replace.
/// * `replacement` - Expression to insert in place of `var`.
///
/// # Returns
///
/// (`Expression`): The rewritten expression.
// Copyright 2026 Mahmoud Harmouch.
//
// Licensed under the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.