symplex 0.22.3

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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! Dedicated trigonometric simplification.
//!
//! Goes beyond the pattern-based rules in `pattern.rs` by trying
//! exhaustive Pythagorean replacements, double-angle formulas,
//! trig combination, and trig expansion.
//!
//! Multiple strategies are attempted (choice-set approach) and the
//! result with the fewest operations (measured by
//! [`count_ops`]) is returned.

use crate::base::arena::Arena;
use crate::base::node::{ExprId, ExprNode};
use crate::base::walk;
use crate::simplify::simplify_engine::count_ops;
use crate::transforms::pattern::{Pattern, Rule};

/// Walk the expression tree and return `true` if any node matches the predicate.
/// Short-circuits on first match for efficiency.
fn walk_has_node_type(arena: &Arena, expr: ExprId, predicate: impl Fn(&ExprNode) -> bool) -> bool {
    let post_order = walk::post_order_ids(arena, expr);
    for &id in &post_order {
        if predicate(arena.node(id)) {
            return true;
        }
    }
    false
}

use rustc_hash::FxHashMap;

/// Apply trigonometric simplification rules exhaustively.
///
/// Strategy (choice-set): try several rewrite variants and keep the smallest.
///
/// 1. Original expression (baseline)
/// 2. Apply existing pattern rules (sin²+cos²→1, etc.)
/// 3. Replace every sin²(x) with 1−cos²(x), then simplify
/// 4. Replace every cos²(x) with 1−sin²(x), then simplify
/// 5. trig_combine (product-to-sum, double-angle identities)
/// 6. expand_trig then eval + pattern simplify
pub(crate) fn trigsimp(arena: &mut Arena, expr: ExprId) -> ExprId {
    // Early exit: if no trig nodes, nothing to simplify
    let has_trig = walk_has_node_type(arena, expr, |node| {
        matches!(
            node,
            ExprNode::Sin(_)
                | ExprNode::Cos(_)
                | ExprNode::Tan(_)
                | ExprNode::Asin(_)
                | ExprNode::Acos(_)
                | ExprNode::Atan(_)
        )
    });

    if !has_trig {
        tracing::debug!("trigsimp: skipping all strategies (no trig nodes)");
        return expr;
    }

    // Strategy 1: original expression (baseline)
    let s0 = expr;

    // Strategy 2: eval → pattern-rule simplification
    let s1 = apply_pattern_rules(arena, expr);

    // Strategy 3: sin²→1−cos² replacement
    let s2 = replace_sin2_with_1_minus_cos2(arena, expr);

    // Strategy 4: cos²→1−sin² replacement
    let s3 = replace_cos2_with_1_minus_sin2(arena, expr);

    // Strategy 5: trig_combine (product-to-sum, double-angle)
    let s4 = strategy_trig_combine(arena, expr);

    // Strategy 6: expand_trig then eval + simplify
    let s5 = strategy_expand_trig_then_simplify(arena, expr);

    // Strategy 7: sum/difference, double-angle and hyperbolic identity rules
    let s6 = strategy_trig_identity_rules(arena, expr);

    let candidates = [s0, s1, s2, s3, s4, s5, s6];
    let _strategy_names = [
        "original",
        "pattern_rules",
        "sin2_to_1_minus_cos2",
        "cos2_to_1_minus_sin2",
        "trig_combine",
        "expand_trig_then_simplify",
        "trig_identity_rules",
    ];

    // Pick the candidate with the lowest operation count.
    let best_idx = candidates
        .iter()
        .enumerate()
        .min_by_key(|&(_, &e)| count_ops(arena, e))
        .map(|(i, _)| i)
        .unwrap_or(0);

    candidates[best_idx]
}

// ── Strategy 2: pattern rules ──────────────────────────────────────────

/// Eval → pattern-rule simplification (the standard simplify path).
fn apply_pattern_rules(arena: &mut Arena, expr: ExprId) -> ExprId {
    let evaled = crate::transforms::eval::eval(arena, expr);
    let rules = crate::transforms::pattern::basic_rules(arena);
    let (result, _) = crate::transforms::pattern::apply_rules(arena, evaled, &rules);
    result
}

// ── Strategy 3: sin²(x) → 1 − cos²(x) ────────────────────────────────

/// Walk bottom-up and replace every `sin(x)^2` with `1 − cos(x)^2`,
/// then run eval + pattern simplification on the result.
fn replace_sin2_with_1_minus_cos2(arena: &mut Arena, expr: ExprId) -> ExprId {
    let replaced = walk_replace_trig_square(arena, expr, TrigKind::Sin);
    let evaled = crate::transforms::eval::eval(arena, replaced);
    let expanded = crate::transforms::expand::expand(arena, evaled);
    let evaled2 = crate::transforms::eval::eval(arena, expanded);
    let rules = crate::transforms::pattern::basic_rules(arena);
    let (result, _) = crate::transforms::pattern::apply_rules(arena, evaled2, &rules);
    result
}

// ── Strategy 4: cos²(x) → 1 − sin²(x) ────────────────────────────────

/// Walk bottom-up and replace every `cos(x)^2` with `1 − sin(x)^2`,
/// then run eval + pattern simplification on the result.
fn replace_cos2_with_1_minus_sin2(arena: &mut Arena, expr: ExprId) -> ExprId {
    let replaced = walk_replace_trig_square(arena, expr, TrigKind::Cos);
    let evaled = crate::transforms::eval::eval(arena, replaced);
    let expanded = crate::transforms::expand::expand(arena, evaled);
    let evaled2 = crate::transforms::eval::eval(arena, expanded);
    let rules = crate::transforms::pattern::basic_rules(arena);
    let (result, _) = crate::transforms::pattern::apply_rules(arena, evaled2, &rules);
    result
}

// ── Strategy 5: trig_combine ───────────────────────────────────────────

/// Apply trig_combine (product-to-sum, double-angle) then eval + simplify.
fn strategy_trig_combine(arena: &mut Arena, expr: ExprId) -> ExprId {
    let evaled = crate::transforms::eval::eval(arena, expr);
    let combined = crate::simplify::trig_combine::trig_combine(arena, evaled);
    let evaled2 = crate::transforms::eval::eval(arena, combined);
    let rules = crate::transforms::pattern::basic_rules(arena);
    let (result, _) = crate::transforms::pattern::apply_rules(arena, evaled2, &rules);
    result
}

// ── Strategy 6: expand_trig then simplify ──────────────────────────────

/// Expand trig functions (addition formulas, multi-angle), then
/// eval + pattern simplify.
fn strategy_expand_trig_then_simplify(arena: &mut Arena, expr: ExprId) -> ExprId {
    let evaled = crate::transforms::eval::eval(arena, expr);
    let expanded = crate::simplify::trig_expand::expand_trig(arena, evaled);
    let evaled2 = crate::transforms::eval::eval(arena, expanded);
    let rules = crate::transforms::pattern::basic_rules(arena);
    let (result, _) = crate::transforms::pattern::apply_rules(arena, evaled2, &rules);
    result
}

// ── Strategy 7: trig identity rules ──────────────────────────────────────────

/// Apply [`trig_identity_rules`] to a fixpoint (bounded), then eval.
fn strategy_trig_identity_rules(arena: &mut Arena, expr: ExprId) -> ExprId {
    let rules = trig_identity_rules(arena);
    let mut current = crate::transforms::eval::eval(arena, expr);
    for _ in 0..8 {
        let (next, steps) = crate::transforms::pattern::apply_rules(arena, current, &rules);
        let next = crate::transforms::eval::eval(arena, next);
        if steps.is_empty() || next == current {
            break;
        }
        current = next;
    }
    current
}

/// Build a two-wild pattern rule `lhs → rhs` from closures over the wild ids.
fn rule2(
    arena: &mut Arena,
    name: &'static str,
    lhs: impl Fn(&mut Arena, ExprId, ExprId) -> ExprId,
    rhs: impl Fn(&mut Arena, ExprId, ExprId) -> ExprId,
) -> Rule {
    let (a, wa) = arena.wild();
    let (b, wb) = arena.wild();
    let root = lhs(arena, a, b);
    let template = rhs(arena, a, b);
    let mut wilds = rustc_hash::FxHashMap::default();
    wilds.insert(a, wa);
    wilds.insert(b, wb);
    Rule::new(name, Pattern { root, wilds }, template)
}

/// Build a one-wild pattern rule `lhs → rhs`.
fn rule1(
    arena: &mut Arena,
    name: &'static str,
    lhs: impl Fn(&mut Arena, ExprId) -> ExprId,
    rhs: impl Fn(&mut Arena, ExprId) -> ExprId,
) -> Rule {
    let (a, wa) = arena.wild();
    let root = lhs(arena, a);
    let template = rhs(arena, a);
    let mut wilds = rustc_hash::FxHashMap::default();
    wilds.insert(a, wa);
    Rule::new(name, Pattern { root, wilds }, template)
}

/// Trigonometric and hyperbolic identity rules, matched
/// associatively-commutatively (so they fire inside larger sums and
/// products):
///
/// | Rule                     | Rewrite                                          |
/// |--------------------------|--------------------------------------------------|
/// | `sin_add`                | `sin a·cos b + cos a·sin b → sin(a + b)`          |
/// | `sin_sub`                | `sin a·cos b − cos a·sin b → sin(a − b)`          |
/// | `cos_add`                | `cos a·cos b − sin a·sin b → cos(a + b)`          |
/// | `cos_sub`                | `cos a·cos b + sin a·sin b → cos(a − b)`          |
/// | `cos_double_sq`          | `cos²a − sin²a → cos 2a`                         |
/// | `cos_double_sin`         | `1 − 2·sin²a → cos 2a`                           |
/// | `cos_double_cos`         | `2·cos²a − 1 → cos 2a`                           |
/// | `sin_double`             | `2·sin a·cos a → sin 2a` (any numeric multiple)  |
/// | `one_minus_cos_sq`       | `1 − cos²a → sin²a`                              |
/// | `one_minus_sin_sq`       | `1 − sin²a → cos²a`                              |
/// | `sinh_double`            | `2·sinh a·cosh a → sinh 2a`                      |
/// | `cosh_double`            | `cosh²a + sinh²a → cosh 2a`                      |
/// | `cosh_sinh_sq`           | `cosh²a − sinh²a → 1`                            |
/// | `sin_div_cos` / `sinh_div_cosh` | `sin a / cos a → tan a`, `sinh a / cosh a → tanh a` |
///
/// Every rule is an exact identity for all complex arguments.
pub(crate) fn trig_identity_rules(arena: &mut Arena) -> Vec<Rule> {
    let two = arena.int(2);
    let neg_two = arena.int(-2);
    let neg_one = arena.neg_one;
    let one = arena.one;

    vec![
        rule2(
            arena,
            "sin_add",
            |ar, a, b| {
                let (sa, cb, ca, sb) = (ar.sin(a), ar.cos(b), ar.cos(a), ar.sin(b));
                let t1 = ar.mul(&[sa, cb]);
                let t2 = ar.mul(&[ca, sb]);
                ar.add(&[t1, t2])
            },
            |ar, a, b| {
                let s = ar.add(&[a, b]);
                ar.sin(s)
            },
        ),
        rule2(
            arena,
            "sin_sub",
            |ar, a, b| {
                let (sa, cb, ca, sb) = (ar.sin(a), ar.cos(b), ar.cos(a), ar.sin(b));
                let t1 = ar.mul(&[sa, cb]);
                let t2 = ar.mul(&[neg_one, ca, sb]);
                ar.add(&[t1, t2])
            },
            |ar, a, b| {
                let d = ar.sub(a, b);
                ar.sin(d)
            },
        ),
        rule2(
            arena,
            "cos_add",
            |ar, a, b| {
                let (ca, cb, sa, sb) = (ar.cos(a), ar.cos(b), ar.sin(a), ar.sin(b));
                let t1 = ar.mul(&[ca, cb]);
                let t2 = ar.mul(&[neg_one, sa, sb]);
                ar.add(&[t1, t2])
            },
            |ar, a, b| {
                let s = ar.add(&[a, b]);
                ar.cos(s)
            },
        ),
        rule2(
            arena,
            "cos_sub",
            |ar, a, b| {
                let (ca, cb, sa, sb) = (ar.cos(a), ar.cos(b), ar.sin(a), ar.sin(b));
                let t1 = ar.mul(&[ca, cb]);
                let t2 = ar.mul(&[sa, sb]);
                ar.add(&[t1, t2])
            },
            |ar, a, b| {
                let d = ar.sub(a, b);
                ar.cos(d)
            },
        ),
        rule1(
            arena,
            "cos_double_sq",
            |ar, a| {
                let (ca, sa) = (ar.cos(a), ar.sin(a));
                let c2 = ar.pow(ca, two);
                let s2 = ar.pow(sa, two);
                let ns2 = ar.mul(&[neg_one, s2]);
                ar.add(&[c2, ns2])
            },
            |ar, a| {
                let d = ar.mul(&[two, a]);
                ar.cos(d)
            },
        ),
        rule1(
            arena,
            "cos_double_sin",
            |ar, a| {
                let sa = ar.sin(a);
                let s2 = ar.pow(sa, two);
                let t = ar.mul(&[neg_two, s2]);
                ar.add(&[one, t])
            },
            |ar, a| {
                let d = ar.mul(&[two, a]);
                ar.cos(d)
            },
        ),
        rule1(
            arena,
            "cos_double_cos",
            |ar, a| {
                let ca = ar.cos(a);
                let c2 = ar.pow(ca, two);
                let t = ar.mul(&[two, c2]);
                ar.add(&[neg_one, t])
            },
            |ar, a| {
                let d = ar.mul(&[two, a]);
                ar.cos(d)
            },
        ),
        rule1(
            arena,
            "sin_double",
            |ar, a| {
                let (sa, ca) = (ar.sin(a), ar.cos(a));
                ar.mul(&[two, sa, ca])
            },
            |ar, a| {
                let d = ar.mul(&[two, a]);
                ar.sin(d)
            },
        ),
        rule1(
            arena,
            "one_minus_cos_sq",
            |ar, a| {
                let ca = ar.cos(a);
                let c2 = ar.pow(ca, two);
                let t = ar.mul(&[neg_one, c2]);
                ar.add(&[one, t])
            },
            |ar, a| {
                let sa = ar.sin(a);
                ar.pow(sa, two)
            },
        ),
        rule1(
            arena,
            "one_minus_sin_sq",
            |ar, a| {
                let sa = ar.sin(a);
                let s2 = ar.pow(sa, two);
                let t = ar.mul(&[neg_one, s2]);
                ar.add(&[one, t])
            },
            |ar, a| {
                let ca = ar.cos(a);
                ar.pow(ca, two)
            },
        ),
        rule1(
            arena,
            "sinh_double",
            |ar, a| {
                let (sa, ca) = (ar.sinh(a), ar.cosh(a));
                ar.mul(&[two, sa, ca])
            },
            |ar, a| {
                let d = ar.mul(&[two, a]);
                ar.sinh(d)
            },
        ),
        rule1(
            arena,
            "cosh_double",
            |ar, a| {
                let (ca, sa) = (ar.cosh(a), ar.sinh(a));
                let c2 = ar.pow(ca, two);
                let s2 = ar.pow(sa, two);
                ar.add(&[c2, s2])
            },
            |ar, a| {
                let d = ar.mul(&[two, a]);
                ar.cosh(d)
            },
        ),
        rule1(
            arena,
            "cosh_sinh_sq",
            |ar, a| {
                let (ca, sa) = (ar.cosh(a), ar.sinh(a));
                let c2 = ar.pow(ca, two);
                let s2 = ar.pow(sa, two);
                let ns2 = ar.mul(&[neg_one, s2]);
                ar.add(&[c2, ns2])
            },
            |ar, _a| ar.one,
        ),
        rule1(
            arena,
            "sin_div_cos",
            |ar, a| {
                let (sa, ca) = (ar.sin(a), ar.cos(a));
                let inv = ar.pow(ca, neg_one);
                ar.mul(&[sa, inv])
            },
            |ar, a| ar.tan(a),
        ),
        rule1(
            arena,
            "sinh_div_cosh",
            |ar, a| {
                let (sa, ca) = (ar.sinh(a), ar.cosh(a));
                let inv = ar.pow(ca, neg_one);
                ar.mul(&[sa, inv])
            },
            |ar, a| ar.tanh(a),
        ),
    ]
}

// ── Shared replacement infrastructure ──────────────────────────────────────

/// Which trig function's square to replace.
#[derive(Clone, Copy, PartialEq, Eq)]
enum TrigKind {
    Sin,
    Cos,
}

/// Walk an expression bottom-up and replace `trig(x)^2` with
/// `1 − other_trig(x)^2` where `trig` is the specified kind.
///
/// Uses the same manual post-order + cache pattern as `expand.rs`.
fn walk_replace_trig_square(arena: &mut Arena, expr: ExprId, kind: TrigKind) -> ExprId {
    let post_order = walk::post_order_ids(arena, expr);
    let mut cache: FxHashMap<ExprId, ExprId> = FxHashMap::default();

    for &id in &post_order {
        // First, try to apply the trig-square replacement at this node.
        if let Some(replaced) = try_replace_trig_square(arena, id, &cache, kind) {
            cache.insert(id, replaced);
            continue;
        }

        // Otherwise, rebuild with substituted children (standard pattern).
        let rebuilt = crate::base::walk::rebuild_with_cache(arena, id, &cache);
        cache.insert(id, rebuilt);
    }

    cache.get(&expr).copied().unwrap_or(expr)
}

/// Check if `id` is `Pow(Sin/Cos(x), 2)` and, if so, return
/// `1 − Pow(Cos/Sin(x), 2)` (with children already mapped through cache).
fn try_replace_trig_square(
    arena: &mut Arena,
    id: ExprId,
    cache: &FxHashMap<ExprId, ExprId>,
    kind: TrigKind,
) -> Option<ExprId> {
    let node = arena.node(id).clone();

    if let ExprNode::Pow(base, exp) = node {
        // Check that exponent is the integer 2.
        if !is_integer_two(arena, exp) {
            return None;
        }

        let base_node = arena.node(base).clone();
        let inner = match (&base_node, kind) {
            (ExprNode::Sin(inner), TrigKind::Sin) => Some(*inner),
            (ExprNode::Cos(inner), TrigKind::Cos) => Some(*inner),
            _ => None,
        }?;

        // Map the inner argument through the cache (children are
        // already processed in post-order).
        let new_inner = cache.get(&inner).copied().unwrap_or(inner);

        // Build the replacement: 1 − other_trig(new_inner)^2
        let other = match kind {
            TrigKind::Sin => arena.cos(new_inner),
            TrigKind::Cos => arena.sin(new_inner),
        };
        let two = arena.int(2);
        let other_sq = arena.pow(other, two);
        let one = arena.one;
        let result = arena.sub(one, other_sq);
        return Some(result);
    }

    None
}

/// Returns `true` if `id` is the numeric literal 2.
fn is_integer_two(arena: &Arena, id: ExprId) -> bool {
    if let Some(val) = arena.as_num(id) {
        *val == num_rational::Ratio::from_integer(num_bigint::BigInt::from(2))
    } else {
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sym(arena: &mut Arena, name: &str) -> ExprId {
        arena.symbol(name)
    }

    fn display(arena: &Arena, id: ExprId) -> String {
        arena.display(id).to_string()
    }

    #[test]
    fn trigsimp_pythagorean_identity() {
        let mut arena = Arena::new();
        let x = sym(&mut arena, "x");
        let sin_x = arena.sin(x);
        let cos_x = arena.cos(x);
        let two = arena.int(2);
        let sin2 = arena.pow(sin_x, two);
        let cos2 = arena.pow(cos_x, two);
        let expr = arena.add(&[sin2, cos2]);

        let result = trigsimp(&mut arena, expr);
        assert_eq!(display(&arena, result), "1");
    }

    #[test]
    fn trigsimp_leaves_simple_trig_alone() {
        let mut arena = Arena::new();
        let x = sym(&mut arena, "x");
        let sin_x = arena.sin(x);

        let result = trigsimp(&mut arena, sin_x);
        assert_eq!(display(&arena, result), "sin(x)");
    }

    #[test]
    fn trigsimp_pythagorean_plus_constant() {
        let mut arena = Arena::new();
        let x = sym(&mut arena, "x");
        let sin_x = arena.sin(x);
        let cos_x = arena.cos(x);
        let two = arena.int(2);
        let sin2 = arena.pow(sin_x, two);
        let cos2 = arena.pow(cos_x, two);
        let five = arena.int(5);
        let expr = arena.add(&[sin2, cos2, five]);

        let result = trigsimp(&mut arena, expr);
        assert_eq!(display(&arena, result), "6");
    }

    #[test]
    fn trigsimp_trig_combine_strategy() {
        let mut arena = Arena::new();
        let x = sym(&mut arena, "x");
        let two = arena.int(2);
        let sin_x = arena.sin(x);
        let cos_x = arena.cos(x);
        // 2*sin(x)*cos(x) should simplify via trig_combine to sin(2x)
        let expr = arena.mul(&[two, sin_x, cos_x]);
        let result = trigsimp(&mut arena, expr);
        let result_ops = count_ops(&arena, result);
        let expr_ops = count_ops(&arena, expr);
        assert!(
            result_ops <= expr_ops,
            "trigsimp should not increase complexity: got {} ops vs original {} ops, result={}",
            result_ops,
            expr_ops,
            display(&arena, result)
        );
    }

    #[test]
    fn trigsimp_picks_best_strategy() {
        // Verify that the choice-set approach picks the simplest result
        let mut arena = Arena::new();
        let x = sym(&mut arena, "x");
        let sin_x = arena.sin(x);
        let cos_x = arena.cos(x);
        let two = arena.int(2);
        let sin2 = arena.pow(sin_x, two);
        let cos2 = arena.pow(cos_x, two);
        // cos²(x) - sin²(x) → cos(2x) via trig_combine
        let expr = arena.sub(cos2, sin2);
        let result = trigsimp(&mut arena, expr);
        let result_ops = count_ops(&arena, result);
        let expr_ops = count_ops(&arena, expr);
        assert!(
            result_ops <= expr_ops,
            "trigsimp should simplify cos²-sin²: got {} ops, original {} ops, result={}",
            result_ops,
            expr_ops,
            display(&arena, result)
        );
    }

    // ── trig identity rules ────────────────────────────────────────

    #[test]
    fn identity_rules_sum_difference_double_angle() {
        let mut arena = Arena::new();
        let (x, y) = (sym(&mut arena, "x"), sym(&mut arena, "y"));
        let rules = trig_identity_rules(&mut arena);
        let (sx, cx, sy, cy) = (arena.sin(x), arena.cos(x), arena.sin(y), arena.cos(y));
        let t1 = arena.mul(&[sx, cy]);
        let t2 = arena.mul(&[cx, sy]);
        let e = arena.add(&[t1, t2]);
        let (r, steps) = crate::transforms::pattern::apply_rules(&mut arena, e, &rules);
        assert_eq!(display(&arena, r), "sin(x + y)");
        assert_eq!(steps[0].rule_name, "sin_add");
        let two = arena.int(2);
        let d = arena.mul(&[two, sx, cx]);
        let (r, _) = crate::transforms::pattern::apply_rules(&mut arena, d, &rules);
        assert_eq!(display(&arena, r), "sin(2*x)");
        let sh = arena.sinh(x);
        let ch = arena.cosh(x);
        let dh = arena.mul(&[two, sh, ch]);
        let (r, _) = crate::transforms::pattern::apply_rules(&mut arena, dh, &rules);
        assert_eq!(display(&arena, r), "sinh(2*x)");
    }

    #[test]
    fn identity_rules_do_not_fire_on_mismatch() {
        let mut arena = Arena::new();
        let (x, y, z) = (
            sym(&mut arena, "x"),
            sym(&mut arena, "y"),
            sym(&mut arena, "z"),
        );
        let rules = trig_identity_rules(&mut arena);
        let (sx, cx, sz, cy) = (arena.sin(x), arena.cos(x), arena.sin(z), arena.cos(y));
        let t1 = arena.mul(&[sx, cy]);
        let t2 = arena.mul(&[cx, sz]);
        let e = arena.add(&[t1, t2]);
        let (r, steps) = crate::transforms::pattern::apply_rules(&mut arena, e, &rules);
        assert_eq!(r, e);
        assert!(steps.is_empty());
    }

    #[test]
    fn trigsimp_uses_identity_rules() {
        let mut arena = Arena::new();
        let x = sym(&mut arena, "x");
        let (cx, sx) = (arena.cos(x), arena.sin(x));
        let two = arena.int(2);
        let c2 = arena.pow(cx, two);
        let s2 = arena.pow(sx, two);
        let neg_two = arena.int(-2);
        let t = arena.mul(&[neg_two, s2]);
        let one = arena.one;
        let e = arena.add(&[one, t]); // 1 - 2 sin^2
        let r = trigsimp(&mut arena, e);
        assert_eq!(display(&arena, r), "cos(2*x)");
        let two_c2 = arena.mul(&[two, c2]);
        let neg_one = arena.neg_one;
        let f = arena.add(&[two_c2, neg_one]);
        let r = trigsimp(&mut arena, f);
        assert_eq!(display(&arena, r), "cos(2*x)");
    }
}