symplex 0.17.0

Exact symbolic mathematics for Rust: calculus, summation, solving, linear algebra, transforms, compile-time dimensional analysis, and Rust/C code generation
Documentation
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! Performance measurement for simplification strategies.
//!
//! These are **benchmarks, not tests**: they print timings and assert
//! nothing, and in a debug build they take ~75 s in total.  They are
//! therefore `#[ignore]`d by default.  Run with:
//!   cd symplex && cargo test --test perf simplify_perf_test:: --release -- --ignored --nocapture 2>&1
//!
//! The one non-ignored test (`perf_inputs_simplify_correctly`) checks the
//! *values* the benchmarks compute, so a regression in the simplifier on
//! these inputs is still caught by the regular suite.

use std::time::{Duration, Instant};
use symplex::prelude::*;

const ITERATIONS: u32 = 100;

// ── Helpers ────────────────────────────────────────────────────────────

/// Time a closure over `ITERATIONS` runs, returning (total, average).
fn bench<F: FnMut()>(mut f: F) -> (Duration, Duration) {
    // Warm-up: 5 iterations to stabilize caches / JIT / branch predictors.
    for _ in 0..5 {
        f();
    }
    let start = Instant::now();
    for _ in 0..ITERATIONS {
        f();
    }
    let total = start.elapsed();
    let avg = total / ITERATIONS;
    (total, avg)
}

fn report(label: &str, avg: Duration) {
    if avg.as_micros() > 1000 {
        println!("  {label:<45} {:>8.2} ms", avg.as_secs_f64() * 1000.0);
    } else {
        println!("  {label:<45} {:>8.2} µs", avg.as_nanos() as f64 / 1000.0);
    }
}

fn section(title: &str) {
    println!();
    println!("╔══════════════════════════════════════════════════════════════╗");
    println!("║ {title:<60} ║");
    println!("╚══════════════════════════════════════════════════════════════╝");
}

// ── 1. Simple polynomial: x³ + 2x + 1 ─────────────────────────────────

#[test]
#[ignore = "benchmark: prints timings only (~10-30 s in debug); run with --ignored --nocapture --release"]
fn perf_simple_polynomial() {
    section("1. Simple polynomial: x³ + 2x + 1");

    let ctx = Context::new();
    let x = ctx.symbol("x");
    let build = || x.powi(3) + &x * 2 + 1;

    // Pre-build so we measure simplification, not construction.
    let expr = build();
    println!("  Input:  {expr}");
    println!("  simplify()       → {}", expr.simplify());
    println!("  smart_simplify() → {}", expr.simplify());
    println!("  full_simplify()  → {}", expr.simplify());
    println!("  simplify_trace() → {}", expr.simplify());
    println!();

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("smart_simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("full_simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("simplify_trace() [pattern-rules only]", avg);
}

// ── 2. Trig expression: sin²(x) + cos²(x) ────────────────────────────

#[test]
#[ignore = "benchmark: prints timings only (~10-30 s in debug); run with --ignored --nocapture --release"]
fn perf_trig_identity() {
    section("2. Trig identity: sin²(x) + cos²(x)");

    let ctx = Context::new();
    let x = ctx.symbol("x");
    let expr = x.sin().powi(2) + x.cos().powi(2);

    println!("  Input:  {expr}");
    println!("  simplify()       → {}", expr.simplify());
    println!("  smart_simplify() → {}", expr.simplify());
    println!("  full_simplify()  → {}", expr.simplify());
    println!("  simplify_trace() → {}", expr.simplify());
    println!();

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("smart_simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("full_simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("simplify_trace() [pattern-rules only]", avg);
}

// ── 3. Large polynomial: 20-term polynomial ────────────────────────────

#[test]
#[ignore = "benchmark: prints timings only (~10-30 s in debug); run with --ignored --nocapture --release"]
fn perf_large_polynomial() {
    section("3. Large polynomial (20 terms)");

    let ctx = Context::new();
    let x = ctx.symbol("x");

    // Build: 1x^20 + 2x^19 + 3x^18 + ... + 20x + 21
    let mut expr = ctx.int(21);
    for i in 1..=20i64 {
        let coeff = ctx.int(i);
        expr += coeff * x.powi(21 - i);
    }

    println!("  Input:  {expr}");
    println!(
        "  (expression has {} characters in display form)",
        format!("{expr}").len()
    );
    let simplified = expr.simplify();
    println!("  simplify()       → {simplified}");
    let smart = expr.simplify();
    println!("  smart_simplify() → {smart}");
    // Note: full_simplify can be slow on large polys, we still measure it.
    println!();

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("smart_simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("full_simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("simplify_trace() [pattern-rules only]", avg);
}

// ── 4. Already-simple expression: just `x` ─────────────────────────────

#[test]
#[ignore = "benchmark: prints timings only (~10-30 s in debug); run with --ignored --nocapture --release"]
fn perf_already_simple() {
    section("4. Already simple: x (no-op case for tight loops)");

    let ctx = Context::new();
    let x = ctx.symbol("x");

    println!("  Input:  {x}");
    println!("  simplify()       → {}", x.simplify());
    println!("  smart_simplify() → {}", x.simplify());
    println!("  full_simplify()  → {}", x.simplify());
    println!();

    let (_, avg) = bench(|| {
        let _ = x.simplify();
    });
    report("simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = x.simplify();
    });
    report("smart_simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = x.simplify();
    });
    report("full_simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = x.simplify();
    });
    report("simplify_trace() [pattern-rules only]", avg);

    // Also measure a simple numeric constant
    println!();
    let five = ctx.int(5);
    println!("  Input:  {five}  (numeric literal)");

    let (_, avg) = bench(|| {
        let _ = five.simplify();
    });
    report("simplify()  [numeric literal 5]", avg);

    let (_, avg) = bench(|| {
        let _ = five.simplify();
    });
    report("smart_simplify()  [numeric literal 5]", avg);

    let (_, avg) = bench(|| {
        let _ = five.simplify();
    });
    report("full_simplify()  [numeric literal 5]", avg);
}

// ── 5. Deep expression: sin(sin(sin(...x...))) ────────────────────────

#[test]
#[ignore = "benchmark: prints timings only (~10-30 s in debug); run with --ignored --nocapture --release"]
fn perf_deep_nesting() {
    section("5. Deep nesting: sin(sin(sin(... x ...)))  depth=10");

    let ctx = Context::new();
    let x = ctx.symbol("x");

    // Build sin(sin(sin(... x ...))) 10 levels deep
    let mut expr = x.clone();
    for _ in 0..10 {
        expr = expr.sin();
    }

    println!("  Input:  {expr}");
    println!("  (display length: {} chars)", format!("{expr}").len());
    let simplified = expr.simplify();
    println!("  simplify()       → {simplified}");
    let smart = expr.simplify();
    println!("  smart_simplify() → {smart}");
    println!();

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("smart_simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("full_simplify()", avg);

    let (_, avg) = bench(|| {
        let _ = expr.simplify();
    });
    report("simplify_trace() [pattern-rules only]", avg);

    // Also measure depth=20
    println!();
    println!("  --- depth=20 ---");
    let mut deep = x.clone();
    for _ in 0..20 {
        deep = deep.sin();
    }
    println!("  (display length: {} chars)", format!("{deep}").len());

    let (_, avg) = bench(|| {
        let _ = deep.simplify();
    });
    report("simplify()  [depth=20]", avg);

    let (_, avg) = bench(|| {
        let _ = deep.simplify();
    });
    report("smart_simplify()  [depth=20]", avg);

    let (_, avg) = bench(|| {
        let _ = deep.simplify();
    });
    report("full_simplify()  [depth=20]", avg);
}

// ── 6. fu() cost on non-trig expressions ──────────────────────────────

#[test]
#[ignore = "benchmark: prints timings only (~10-30 s in debug); run with --ignored --nocapture --release"]
fn perf_fu_bailout_on_non_trig() {
    section("6. fu() bail-out cost on non-trig expressions");
    println!("  Measuring: does fu()/has_trig check add measurable overhead");
    println!("  to smart_simplify for purely algebraic expressions?");
    println!();

    let ctx = Context::new();
    let x = ctx.symbol("x");

    // Pure polynomial — no trig at all
    let poly = x.powi(3) + &x * 2 + 1;
    println!("  Non-trig expr: {poly}");

    let (_, avg_smart) = bench(|| {
        let _ = poly.simplify();
    });
    report("smart_simplify() [non-trig poly]", avg_smart);

    let (_, avg_trace) = bench(|| {
        let _ = poly.simplify();
    });
    report("simplify_trace() [non-trig poly, no fu]", avg_trace);

    // The difference tells us approximately how much fu's has_trig bail-out
    // plus the other gated strategies cost.
    let overhead_ns = if avg_smart > avg_trace {
        (avg_smart - avg_trace).as_nanos()
    } else {
        0
    };
    println!();
    println!(
        "  → Overhead of smart_simplify over pattern-rules-only: {:.2} µs",
        overhead_ns as f64 / 1000.0
    );
    println!("    (includes flag computation, eval, expand, factor_terms, fu bail-out)");

    // Now compare: trig expression to show fu actually costs something when it runs
    println!();
    let trig = x.sin().powi(2) + x.cos().powi(2);
    println!("  Trig expr: {trig}");

    let (_, avg_trig_smart) = bench(|| {
        let _ = trig.simplify();
    });
    report("smart_simplify() [with trig]", avg_trig_smart);

    let (_, avg_trig_trace) = bench(|| {
        let _ = trig.simplify();
    });
    report("simplify_trace() [with trig]", avg_trig_trace);

    let fu_cost_ns = if avg_trig_smart > avg_smart {
        (avg_trig_smart - avg_smart).as_nanos()
    } else {
        0
    };
    println!();
    println!(
        "  → Extra cost when trig IS present (fu + trig_expand + factor+fu): ~{:.2} µs",
        fu_cost_ns as f64 / 1000.0
    );
}

// ── 7. Consolidated approach simulation ────────────────────────────────

#[test]
#[ignore = "benchmark: prints timings only (~10-30 s in debug); run with --ignored --nocapture --release"]
fn perf_consolidated_approach() {
    section("7. Consolidated approach: simplify() = smart_simplify always");
    println!("  Simulating: .simplify() always runs smart_simplify (12+ strategies)");
    println!("              .simplify() iterates smart_simplify up to 10×");
    println!();
    println!("  Current .simplify() = simplify_trace() + smart_simplify(), pick best");
    println!("  Proposed .simplify() = smart_simplify() only");
    println!();

    let ctx = Context::new();
    let x = ctx.symbol("x");

    // Build a collection of representative expressions
    let cases: Vec<(&str, Ex)> = vec![
        ("x (atom)", x.clone()),
        ("x³ + 2x + 1", x.powi(3) + &x * 2 + 1),
        ("sin²(x) + cos²(x)", x.sin().powi(2) + x.cos().powi(2)),
        ("(x+1)² - x² - 2x", {
            let xp1 = &x + 1;
            &xp1.powi(2) - &x.powi(2) - &x * 2
        }),
        ("sin(sin(sin(x)))", x.sin().sin().sin()),
    ];

    println!(
        "  {:30} {:>14} {:>14} {:>14}",
        "Expression", "current .s()", "proposed .s()", "ratio"
    );
    println!("  {:-<30} {:-<14} {:-<14} {:-<14}", "", "", "", "");

    for (name, expr) in &cases {
        // Current: simplify() = simplify_trace + smart_simplify, pick best
        let (_, avg_current) = bench(|| {
            let _ = expr.simplify();
        });

        // Proposed: simplify() = smart_simplify only
        let (_, avg_proposed) = bench(|| {
            let _ = expr.simplify();
        });

        let ratio = if avg_proposed.as_nanos() > 0 && avg_current.as_nanos() > 0 {
            avg_proposed.as_nanos() as f64 / avg_current.as_nanos() as f64
        } else {
            f64::NAN
        };

        println!(
            "  {name:30} {:>11.2} µs {:>11.2} µs {:>11.2}×",
            avg_current.as_nanos() as f64 / 1000.0,
            avg_proposed.as_nanos() as f64 / 1000.0,
            ratio,
        );
    }

    // full_simplify timing for the most expensive case
    println!();
    println!("  full_simplify() timing (iterates up to 10× with cancel+expand+radical):");
    for (name, expr) in &cases {
        let (_, avg) = bench(|| {
            let _ = expr.simplify();
        });
        report(&format!("full_simplify()  [{name}]"), avg);
    }
}

// ── 8. Summary & Recommendation ───────────────────────────────────────

#[test]
#[ignore = "benchmark: prints timings only (~10-30 s in debug); run with --ignored --nocapture --release"]
fn perf_summary() {
    section("8. Summary — absolute cost of smart_simplify on atoms");
    println!("  The critical question: is smart_simplify too expensive for");
    println!("  expressions that are already simple (the no-op hot path)?");
    println!();

    let ctx = Context::new();
    let x = ctx.symbol("x");

    // Atom: just x
    let (_, avg_atom_smart) = bench(|| {
        let _ = x.simplify();
    });
    report("smart_simplify(x)  [atom]", avg_atom_smart);

    let (_, avg_atom_simp) = bench(|| {
        let _ = x.simplify();
    });
    report("simplify(x)  [current]", avg_atom_simp);

    let (_, avg_atom_full) = bench(|| {
        let _ = x.simplify();
    });
    report("full_simplify(x)", avg_atom_full);

    // Small expr
    let small = &x + 1;
    let (_, avg_small_smart) = bench(|| {
        let _ = small.simplify();
    });
    report("smart_simplify(x + 1)  [small]", avg_small_smart);

    let (_, avg_small_full) = bench(|| {
        let _ = small.simplify();
    });
    report("full_simplify(x + 1)", avg_small_full);

    println!();
    println!("  ┌─────────────────────────────────────────────────────────┐");
    println!("  │  RECOMMENDATION                                        │");
    println!("  │                                                        │");
    println!("  │  If smart_simplify(atom) < 5 µs:                       │");
    println!("  │    ✅ Consolidation is fine. The flag-based gating      │");
    println!("  │       makes the no-op path extremely cheap.             │");
    println!("  │                                                        │");
    println!("  │  If smart_simplify(atom) is 5–50 µs:                   │");
    println!("  │    ⚠️  Acceptable for most uses, but add a fast path    │");
    println!("  │       that skips strategy evaluation for atoms.         │");
    println!("  │                                                        │");
    println!("  │  If smart_simplify(atom) > 50 µs:                      │");
    println!("  │    ❌ Too slow for tight loops. Keep the split API.     │");
    println!("  │                                                        │");
    println!("  │  The actual numbers are printed above — check them!     │");
    println!("  └─────────────────────────────────────────────────────────┘");

    let atom_us = avg_atom_smart.as_nanos() as f64 / 1000.0;
    println!();
    if atom_us < 5.0 {
        println!(
            "  ✅ VERDICT: smart_simplify(atom) = {atom_us:.2} µs — consolidation is FAST ENOUGH."
        );
        println!("     The early-exit for atoms in smart_simplify makes it essentially free.");
    } else if atom_us < 50.0 {
        println!(
            "  ⚠️  VERDICT: smart_simplify(atom) = {atom_us:.2} µs — acceptable with caveats."
        );
        println!("     Consider keeping the atom early-exit and monitoring in benchmarks.");
    } else {
        println!(
            "  ❌ VERDICT: smart_simplify(atom) = {atom_us:.2} µs — too slow for consolidation."
        );
        println!("     Keep .simplify() as pattern-rules-only for hot paths.");
    }
}

// ── Correctness smoke test for the benchmark inputs (runs by default) ──

#[test]
fn perf_inputs_simplify_correctly() {
    let ctx = Context::new();
    let x = ctx.symbol("x");
    // 2. sin² + cos² = 1
    assert_eq!((x.sin().powi(2) + x.cos().powi(2)).simplify(), ctx.int(1));
    // 4. atoms are fixed points
    assert_eq!(x.simplify(), x);
    assert_eq!(ctx.int(5).simplify(), ctx.int(5));
    // 5. deep nesting is a fixed point and keeps its value
    let mut nested = x.clone();
    for _ in 0..10 {
        nested = nested.sin();
    }
    let simplified = nested.simplify();
    let at_half = |e: &Ex| e.subs(&x, &ctx.rational(1, 2)).eval_f64().unwrap();
    assert!((at_half(&simplified) - at_half(&nested)).abs() < 1e-14);
    let mut want = 0.5f64;
    for _ in 0..10 {
        want = want.sin();
    }
    assert!((at_half(&nested) - want).abs() < 1e-14);
    // 1./3. polynomial inputs: (x+1)^2 - (x^2 + 2x + 1) = 0
    let p = (&x + 1).powi(2) - (x.powi(2) + &x * 2 + 1);
    assert!(p.simplify().is_zero_structural(), "{}", p.simplify());
}