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
//! End-to-end Risch integration tests.
//!
//! These tests exercise the full `expr.integrate(&x)` path — from the
//! public `Ex` API through the heuristic integrator and the Risch
//! rational-function pipeline (Hermite + Rothstein-Trager), and verify
//! results by numerical FTC checks:
//!
//!   d/dx(∫ f dx) ≈ f   at multiple test points
//!
//! This catches mathematical errors that structural tests miss.

use symplex::prelude::*;

// ═══════════════════════════════════════════════════════════════════════════
// Helpers
// ═══════════════════════════════════════════════════════════════════════════

/// Verify the Fundamental Theorem of Calculus numerically:
///   d/dx(result) ≈ integrand  at several test points.
///
/// `points` are integer x-values to test at.  We substitute each,
/// evaluate both sides to f64, and compare within `tol`.
fn verify_ftc(integrand: &Ex, result: &Ex, x: &Ex, points: &[i64], tol: f64, label: &str) {
    let d_result = result.diff(x);
    let mut checked = 0;
    for &pt in points {
        let lhs = d_result.eval_f64_with(&[(x, pt)]);
        let rhs = integrand.eval_f64_with(&[(x, pt)]);
        match (lhs, rhs) {
            (Ok(l), Ok(r)) if l.is_finite() && r.is_finite() => {
                let err = (l - r).abs();
                let scale = r.abs().max(1.0);
                assert!(
                    err / scale < tol,
                    "{label}: FTC failed at x={pt}: d/dx(result)={l:.8}, integrand={r:.8}, err={err:.2e}"
                );
                checked += 1;
            }
            _ => {
                // Evaluation failed at this point (singularity, etc.) — skip.
            }
        }
    }
    assert!(
        checked >= 1,
        "{label}: FTC check was vacuous — no point evaluated successfully"
    );
}

/// Check that an integral result does NOT contain unevaluated Integral nodes.
fn assert_evaluated(result: &Ex, label: &str) {
    assert!(
        !result.has_unevaluated(),
        "{label}: result contains unevaluated Integral node: {}",
        result
    );
}

// Test points that avoid 0 (singularity for 1/x) and ±1 (common roots).
const SAFE_POINTS: &[i64] = &[-3, -2, 2, 3, 5, 7];
// Test points that include 0 but avoid ±1.
const POINTS_WITH_ZERO: &[i64] = &[-3, -2, 0, 2, 3, 5];
// Strictly positive points (for ln(x)).
const POSITIVE_POINTS: &[i64] = &[2, 3, 5, 7, 10];

// ═══════════════════════════════════════════════════════════════════════════
// Group 4: End-to-end integration tests
// ═══════════════════════════════════════════════════════════════════════════

#[test]
fn e2e_polynomial() {
    // ∫ (x³ + 2x) dx = x⁴/4 + x²
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = expr!(ctx, x ^ 3 + 2 * x);
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ x³+2x dx");
    verify_ftc(
        &integrand,
        &result,
        &x,
        POINTS_WITH_ZERO,
        1e-8,
        "∫ x³+2x dx",
    );
}

#[test]
fn e2e_one_over_x() {
    // ∫ 1/x dx = ln|x|
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = &ctx.int(1) / &x;
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ 1/x dx");
    verify_ftc(&integrand, &result, &x, SAFE_POINTS, 1e-8, "∫ 1/x dx");
}

#[test]
fn e2e_one_over_x_squared() {
    // ∫ 1/x² dx = -1/x
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = &ctx.int(1) / &x.powi(2);
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ 1/x² dx");
    verify_ftc(&integrand, &result, &x, SAFE_POINTS, 1e-8, "∫ 1/x² dx");
}

#[test]
fn e2e_one_over_x_cubed() {
    // ∫ 1/x³ dx = -1/(2x²)   (Hermite reduction)
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = &ctx.int(1) / &x.powi(3);
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ 1/x³ dx");
    verify_ftc(&integrand, &result, &x, SAFE_POINTS, 1e-8, "∫ 1/x³ dx");
}

#[test]
fn e2e_one_over_x_squared_minus_1() {
    // ∫ 1/(x²-1) dx = ½ ln|x-1| - ½ ln|x+1|  (partial fractions / Rothstein-Trager)
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = &ctx.int(1) / &expr!(ctx, x ^ 2 - 1);
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ 1/(x²-1) dx");
    // Avoid x = ±1 (poles).
    verify_ftc(
        &integrand,
        &result,
        &x,
        &[-3, -2, 2, 3, 5],
        1e-8,
        "∫ 1/(x²-1) dx",
    );
}

#[test]
fn e2e_repeated_quadratic() {
    // ∫ 1/(x²+1)² dx = x/(2(x²+1)) + (1/2)·arctan(x)
    //
    // Hermite reduction extracts the rational part x/(2(x²+1)).
    // The remainder 1/(2(x²+1)) has algebraic residues (±i/2),
    // so Rothstein-Trager flags it as algebraic.  The recursive
    // integration then resolves it via the standard-form detector
    // (arctan).
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let denom = expr!(ctx, (x ^ 2 + 1) ^ 2);
    let integrand = &ctx.int(1) / &denom;
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ 1/(x²+1)² dx");
    verify_ftc(
        &integrand,
        &result,
        &x,
        POINTS_WITH_ZERO,
        1e-8,
        "∫ 1/(x²+1)² dx",
    );
}

#[test]
fn e2e_2x_plus_1_over_x_plus_1_squared() {
    // ∫ (2x+1)/(x+1)² dx — Hermite reduction + possible log part.
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let numer = expr!(ctx, 2 * x + 1);
    let denom = expr!(ctx, (x + 1) ^ 2);
    let integrand = &numer / &denom;
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ (2x+1)/(x+1)² dx");
    // Avoid x = -1 (pole).
    verify_ftc(
        &integrand,
        &result,
        &x,
        &[-3, -2, 0, 2, 3, 5],
        1e-8,
        "∫ (2x+1)/(x+1)² dx",
    );
}

#[test]
fn e2e_sin_x() {
    // ∫ sin(x) dx = -cos(x)
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = x.sin();
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ sin(x) dx");
    verify_ftc(
        &integrand,
        &result,
        &x,
        POINTS_WITH_ZERO,
        1e-8,
        "∫ sin(x) dx",
    );
}

#[test]
fn e2e_cos_x() {
    // ∫ cos(x) dx = sin(x)
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = x.cos();
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ cos(x) dx");
    verify_ftc(
        &integrand,
        &result,
        &x,
        POINTS_WITH_ZERO,
        1e-8,
        "∫ cos(x) dx",
    );
}

#[test]
fn e2e_exp_x() {
    // ∫ exp(x) dx = exp(x)
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = x.exp();
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ exp(x) dx");
    verify_ftc(
        &integrand,
        &result,
        &x,
        &[-2, -1, 0, 1, 2],
        1e-8,
        "∫ exp(x) dx",
    );
}

#[test]
fn e2e_x_times_exp_x() {
    // ∫ x·exp(x) dx = (x-1)·exp(x)  (by parts)
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = &x * &x.exp();
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ x·exp(x) dx");
    verify_ftc(
        &integrand,
        &result,
        &x,
        &[-2, -1, 0, 1, 2],
        1e-8,
        "∫ x·exp(x) dx",
    );
}

#[test]
fn e2e_ln_x() {
    // ∫ ln(x) dx = x·ln(x) - x  (by parts or Risch log case)
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = x.ln();
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ ln(x) dx");
    verify_ftc(&integrand, &result, &x, POSITIVE_POINTS, 1e-8, "∫ ln(x) dx");
}

#[test]
fn e2e_one_over_x_ln_x() {
    // ∫ 1/(x·ln(x)) dx = ln(ln(x))
    //
    // The expression 1/(x·ln(x)) is stored as Pow(Mul(x, Ln(x)), -1).
    // The Pow arm distributes the inverse: Mul(x^(-1), ln(x)^(-1)).
    // The Mul arm's u-sub then finds u = ln(x), du = 1/x dx,
    // giving ∫ 1/u du = ln(u) = ln(ln(x)).
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = &ctx.int(1) / &(&x * &x.ln());
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ 1/(x·ln(x)) dx");
    // Only use x > 1 so ln(x) > 0.
    verify_ftc(
        &integrand,
        &result,
        &x,
        &[2, 3, 5, 7],
        1e-6,
        "∫ 1/(x·ln(x)) dx",
    );
}

#[test]
fn e2e_x_squared_exp_x() {
    // ∫ x²·exp(x) dx = (x² - 2x + 2)·exp(x)
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = &x.powi(2) * &x.exp();
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ x²·exp(x) dx");
    verify_ftc(
        &integrand,
        &result,
        &x,
        &[-2, -1, 0, 1, 2],
        1e-7,
        "∫ x²·exp(x) dx",
    );
}

// ═══════════════════════════════════════════════════════════════════════════
// Group 4 continued: Definite integrals
// ═══════════════════════════════════════════════════════════════════════════

#[test]
fn e2e_definite_x_squared_0_to_1() {
    // ∫₀¹ x² dx = 1/3
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let result = expr!(ctx, x ^ 2).integrate_definite(&x, &ctx.int(0), &ctx.int(1));
    let s = format!("{result}");
    assert_eq!(s, "1/3", "∫₀¹ x² dx should be 1/3, got: {s}");
}

#[test]
fn e2e_definite_sin_0_to_pi() {
    // ∫₀^π sin(x) dx = 2
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let result = x.sin().integrate_definite(&x, &ctx.int(0), &ctx.pi());
    let result_eval = result.eval();
    let s = format!("{result_eval}");
    assert_eq!(s, "2", "∫₀^π sin(x) dx should be 2, got: {s}");
}

// ═══════════════════════════════════════════════════════════════════════════
// Group 6: Regression guards — Risch wiring must not break existing integrals
// ═══════════════════════════════════════════════════════════════════════════

#[test]
fn risch_doesnt_regress_sin_x() {
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let result = x.sin().integrate(&x);
    assert_evaluated(&result, "∫ sin(x) dx regression");
    verify_ftc(
        &x.sin(),
        &result,
        &x,
        POINTS_WITH_ZERO,
        1e-8,
        "sin(x) regression",
    );
}

#[test]
fn risch_doesnt_regress_cos_x() {
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let result = x.cos().integrate(&x);
    assert_evaluated(&result, "∫ cos(x) dx regression");
    verify_ftc(
        &x.cos(),
        &result,
        &x,
        POINTS_WITH_ZERO,
        1e-8,
        "cos(x) regression",
    );
}

#[test]
fn risch_doesnt_regress_exp_x() {
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let result = x.exp().integrate(&x);
    assert_evaluated(&result, "∫ exp(x) dx regression");
    verify_ftc(
        &x.exp(),
        &result,
        &x,
        &[-2, -1, 0, 1, 2],
        1e-8,
        "exp(x) regression",
    );
}

#[test]
fn risch_doesnt_regress_x_exp_x_by_parts() {
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = &x * &x.exp();
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ x·exp(x) dx regression");
    verify_ftc(
        &integrand,
        &result,
        &x,
        &[-2, -1, 0, 1, 2],
        1e-8,
        "x·exp(x) regression",
    );
}

#[test]
fn risch_doesnt_regress_x_sin_x_by_parts() {
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = &x * &x.sin();
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ x·sin(x) dx regression");
    verify_ftc(
        &integrand,
        &result,
        &x,
        POINTS_WITH_ZERO,
        1e-8,
        "x·sin(x) regression",
    );
}

#[test]
fn risch_doesnt_regress_polynomial_power_rule() {
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = expr!(ctx, 5 * x ^ 4 + 3 * x ^ 2 + 1);
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ 5x⁴+3x²+1 dx regression");
    verify_ftc(
        &integrand,
        &result,
        &x,
        POINTS_WITH_ZERO,
        1e-8,
        "poly regression",
    );
}

#[test]
fn risch_doesnt_regress_trig_identity() {
    // ∫ sin²(x) dx — not affected by Risch (not a rational function)
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = x.sin().powi(2);
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ sin²(x) dx regression");
    verify_ftc(
        &integrand,
        &result,
        &x,
        POINTS_WITH_ZERO,
        1e-7,
        "sin²(x) regression",
    );
}

#[test]
fn risch_doesnt_regress_partial_fractions() {
    // ∫ 1/(x²-1) dx — existing partial fractions AND Risch both handle this.
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    let integrand = &ctx.int(1) / &expr!(ctx, x ^ 2 - 1);
    let result = integrand.integrate(&x);
    assert_evaluated(&result, "∫ 1/(x²-1) dx regression");
    verify_ftc(
        &integrand,
        &result,
        &x,
        &[-3, -2, 2, 3, 5],
        1e-8,
        "1/(x²-1) regression",
    );
}

// ═══════════════════════════════════════════════════════════════════════════
// FTC verification for known-answer integrals
// ═══════════════════════════════════════════════════════════════════════════

#[test]
fn ftc_x_to_the_n() {
    // ∫ xⁿ dx for n = 0..6, verify FTC at multiple points.
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    for n in 0..=6 {
        let integrand = x.powi(n);
        let result = integrand.integrate(&x);
        assert_evaluated(&result, &format!("∫ x^{n} dx"));
        verify_ftc(
            &integrand,
            &result,
            &x,
            POINTS_WITH_ZERO,
            1e-8,
            &format!("∫ x^{n} dx"),
        );
    }
}

#[test]
fn ftc_one_over_x_to_the_n() {
    // ∫ x^(-n) dx for n = 1..5, verify FTC.
    let ctx = Context::new();
    symplex::syms!(ctx; x);
    for n in 1..=5 {
        let integrand = x.powi(-n);
        let result = integrand.integrate(&x);
        assert_evaluated(&result, &format!("∫ x^(-{n}) dx"));
        verify_ftc(
            &integrand,
            &result,
            &x,
            SAFE_POINTS,
            1e-7,
            &format!("∫ x^(-{n}) dx"),
        );
    }
}

#[test]
fn ftc_simple_rational_functions() {
    // A suite of simple rational functions, all verified by FTC.
    let ctx = Context::new();
    symplex::syms!(ctx; x);

    let test_cases: Vec<(&str, Ex, &[i64])> = vec![
        ("1/(x+1)", &ctx.int(1) / &(&x + 1), &[-3, -2, 0, 2, 3]),
        ("1/(x+2)", &ctx.int(1) / &(&x + 2), &[-3, -1, 0, 1, 3]),
        ("x/(x+1)", &x / &(&x + 1), &[-3, -2, 0, 2, 3]),
        (
            "1/(x²+1)",
            &ctx.int(1) / &(&x.powi(2) + 1),
            &[-3, -2, 0, 2, 3],
        ),
    ];

    for (label, integrand, points) in &test_cases {
        let result = integrand.integrate(&x);
        assert_evaluated(&result, label);
        verify_ftc(integrand, &result, &x, points, 1e-7, label);
    }
}