alkahest-cas 3.3.0

High-performance computer algebra kernel: symbolic expressions, polynomials, Gröbner bases, JIT, and Arb ball arithmetic.
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
//! The [`DifferentialField`] abstraction — Risch **M4** foundation.
//!
//! M4 makes the Risch differential-equation machinery polymorphic over the
//! *tower level* so the elementary-integration recursion can descend through
//! nested mixed algebraic/transcendental towers.  This module introduces the
//! foundational abstraction only:
//!
//! - [`DifferentialField`]: a differential field `K` with derivation `D`,
//!   exposing the Risch sub-algorithms the recursion needs at each level.
//! - Concrete implementations that **wrap the existing solvers** — no new math:
//!   * [`RationalDiffField`] for `ℚ(x)` (wraps
//!     [`solve_rational_rde_generalized`]),
//!   * [`DifferentialField`] for [`ExpTowerField`] (wraps [`solve_tower_rde`]),
//!   * [`DifferentialField`] for [`LogTowerField`] (wraps the field-generic
//!     `solve_tower_rde_generic`).
//!
//! **Additive / non-rewiring.** Nothing here changes any production integration
//! path; `integrate_risch` dispatch is untouched.  The trait is exercised by the
//! equivalence unit tests below (which assert it faithfully reproduces the
//! existing solvers) and will be consumed by the M4 PR2 multi-generator
//! recursive integrator.
//!
//! ## Relationship to [`CoeffField`]
//!
//! [`CoeffField`] is the *scalar* field abstraction (arithmetic + an optional
//! `derivation`) the polynomial-quotient core is generic over.  Every field that
//! implements `DifferentialField` here either *is* a `CoeffField` (the tower
//! fields) or is backed by one ([`RationalDiffField`] is backed by
//! [`RationalFunctionField`]).  `DifferentialField` layers the Risch *DE solvers*
//! on top of that scalar structure; it is deliberately a separate trait so that
//! a level may carry solvers a bare `CoeffField` does not.

use super::alg_field::{RatFn, RationalFunctionField};
use super::number_field::CoeffField;
use super::rational_rde::solve_rational_rde_generalized;
use super::tower_field::{
    solve_tower_rde, solve_tower_rde_generic, ExpTowerField, LogTowerField, TExpr,
};

// ===========================================================================
// The trait
// ===========================================================================

/// A differential field `K` with derivation `D`, supporting the Risch
/// sub-algorithms the elementary-integration recursion needs at each tower
/// level.
///
/// The field-structure methods mirror [`CoeffField`] (and, for the
/// implementations in this module, simply delegate to one); the value
/// `DifferentialField` adds over `CoeffField` is the **Risch DE machinery**
/// ([`rational_rde`](DifferentialField::rational_rde) and the PR2+ stubs
/// [`limited_integrate`](DifferentialField::limited_integrate) /
/// [`param_log_deriv`](DifferentialField::param_log_deriv)) made polymorphic
/// over the level.
pub trait DifferentialField {
    /// Element type of the field.
    type Elem: Clone + std::fmt::Debug;

    // --- field structure (mirrors CoeffField) ---

    /// The additive identity `0`.
    fn zero(&self) -> Self::Elem;
    /// The multiplicative identity `1`.
    fn one(&self) -> Self::Elem;
    /// `a + b`.
    fn add(&self, a: &Self::Elem, b: &Self::Elem) -> Self::Elem;
    /// `a − b`.
    fn sub(&self, a: &Self::Elem, b: &Self::Elem) -> Self::Elem;
    /// `a · b`.
    fn mul(&self, a: &Self::Elem, b: &Self::Elem) -> Self::Elem;
    /// `−a`.
    fn neg(&self, a: &Self::Elem) -> Self::Elem;
    /// `a⁻¹`, or `None` if `a` is zero.
    fn inv(&self, a: &Self::Elem) -> Option<Self::Elem>;
    /// Is `a` the zero element?
    fn is_zero(&self, a: &Self::Elem) -> bool;
    /// Are `a` and `b` equal?
    fn eq(&self, a: &Self::Elem, b: &Self::Elem) -> bool;

    /// The derivation `D` of the field.
    fn derivation(&self, a: &Self::Elem) -> Self::Elem;

    /// Is `a` a constant (`D(a) = 0`)?  Default: `is_zero(derivation(a))`.
    fn is_constant(&self, a: &Self::Elem) -> bool {
        self.is_zero(&self.derivation(a))
    }

    // --- the Risch sub-algorithms, polymorphic over the level ---

    /// Solve the Risch differential equation `D(y) + f·y = g` for `y ∈ K`.
    ///
    /// Returns `Some(y)` when an elementary solution **in this field** exists,
    /// `None` otherwise.  Every implementation in this module *verifies* its
    /// candidate in-field before returning it, so a `Some` is always correct.
    ///
    /// The precise meaning of `None` depends on the level: for `ℚ(x)` the
    /// underlying solver is a decision procedure (so `None` certifies "no
    /// rational solution exists"); for the tower fields the underlying solver is
    /// verification-guarded over a bounded ansatz, so `None` means "no solution
    /// found within the search bounds", **not** a proof of non-existence.  See
    /// each implementation's docs.
    fn rational_rde(&self, f: &Self::Elem, g: &Self::Elem) -> Option<Self::Elem>;

    /// LimitedIntegrate (Bronstein §7.1): given `g` and `D`-generators
    /// `w₁…wₙ ∈ K`, find `v ∈ K` and constants `c₁…cₙ` with
    /// `g = D(v) + Σᵢ cᵢ · D(wᵢ)/wᵢ`.
    ///
    /// **Not yet implemented at any level.**  The default returns `None`,
    /// meaning "declined / not yet implemented" — it is **not** a proof that no
    /// such decomposition exists.  Declared here so the abstraction is complete
    /// for PR2+ to fill in.
    fn limited_integrate(
        &self,
        g: &Self::Elem,
        ws: &[Self::Elem],
    ) -> Option<(Self::Elem, Vec<Self::Elem>)> {
        let _ = (g, ws);
        None
    }

    /// ParametricLogarithmicDerivative (Bronstein §7.3): decide whether
    /// `f = (n/m)·D(w)/w + D(v)/v` for some integers `n, m` and `v, w ∈ K`.
    /// On success returns `(n, m, v)`.
    ///
    /// **Not yet implemented at any level.**  The default returns `None`,
    /// meaning "declined / not yet implemented" — **not** a proof of
    /// non-existence.  Declared here so the abstraction is complete for PR2+.
    fn param_log_deriv(&self, f: &Self::Elem, w: &Self::Elem) -> Option<(i64, i64, Self::Elem)> {
        let _ = (f, w);
        None
    }
}

// ===========================================================================
// ℚ(x) — wraps solve_rational_rde_generalized
// ===========================================================================

/// The base differential field `ℚ(x)` with derivation `d/dx`.
///
/// An element is a [`RatFn`] (a reduced rational function over `ℚ`).  Field
/// arithmetic and the derivation delegate to the existing
/// [`RationalFunctionField`] [`CoeffField`];
/// [`rational_rde`](DifferentialField::rational_rde) wraps
/// [`solve_rational_rde_generalized`].
#[derive(Clone, Debug, Default)]
pub struct RationalDiffField {
    inner: RationalFunctionField,
}

impl RationalDiffField {
    /// Build the `ℚ(x)` differential field.
    pub fn new() -> Self {
        Self::default()
    }
}

impl DifferentialField for RationalDiffField {
    type Elem = RatFn;

    fn zero(&self) -> RatFn {
        self.inner.zero()
    }
    fn one(&self) -> RatFn {
        self.inner.one()
    }
    fn add(&self, a: &RatFn, b: &RatFn) -> RatFn {
        self.inner.add(a, b)
    }
    fn sub(&self, a: &RatFn, b: &RatFn) -> RatFn {
        self.inner.sub(a, b)
    }
    fn mul(&self, a: &RatFn, b: &RatFn) -> RatFn {
        self.inner.mul(a, b)
    }
    fn neg(&self, a: &RatFn) -> RatFn {
        self.inner.neg(a)
    }
    fn inv(&self, a: &RatFn) -> Option<RatFn> {
        self.inner.inv(a)
    }
    fn is_zero(&self, a: &RatFn) -> bool {
        self.inner.is_zero(a)
    }
    fn eq(&self, a: &RatFn, b: &RatFn) -> bool {
        self.inner.eq(a, b)
    }
    fn derivation(&self, a: &RatFn) -> RatFn {
        self.inner.derivation(a)
    }

    /// Solve `D(y) + f·y = g` over `ℚ(x)` by wrapping
    /// [`solve_rational_rde_generalized`].
    ///
    /// The underlying routine is a decision procedure for a *rational* solution:
    /// `None` means no `y ∈ ℚ(x)` satisfies the equation (e.g. `f = 0, g = 1/x`
    /// ⇒ `∫1/x = log x ∉ ℚ(x)`).
    fn rational_rde(&self, f: &RatFn, g: &RatFn) -> Option<RatFn> {
        let (num, den) =
            solve_rational_rde_generalized(f.numer(), f.denom(), g.numer(), g.denom())?;
        Some(RatFn::new(num, den))
    }
}

// ===========================================================================
// Exponential tower ℚ(x)(t), t = exp(η) — wraps solve_tower_rde
// ===========================================================================

impl DifferentialField for ExpTowerField {
    type Elem = TExpr;

    fn zero(&self) -> TExpr {
        <Self as CoeffField>::zero(self)
    }
    fn one(&self) -> TExpr {
        <Self as CoeffField>::one(self)
    }
    fn add(&self, a: &TExpr, b: &TExpr) -> TExpr {
        <Self as CoeffField>::add(self, a, b)
    }
    fn sub(&self, a: &TExpr, b: &TExpr) -> TExpr {
        <Self as CoeffField>::sub(self, a, b)
    }
    fn mul(&self, a: &TExpr, b: &TExpr) -> TExpr {
        <Self as CoeffField>::mul(self, a, b)
    }
    fn neg(&self, a: &TExpr) -> TExpr {
        <Self as CoeffField>::neg(self, a)
    }
    fn inv(&self, a: &TExpr) -> Option<TExpr> {
        <Self as CoeffField>::inv(self, a)
    }
    fn is_zero(&self, a: &TExpr) -> bool {
        <Self as CoeffField>::is_zero(self, a)
    }
    fn eq(&self, a: &TExpr, b: &TExpr) -> bool {
        <Self as CoeffField>::eq(self, a, b)
    }
    fn derivation(&self, a: &TExpr) -> TExpr {
        <Self as CoeffField>::derivation(self, a)
    }

    /// Solve `D(v) + f·v = g` over the exponential tower `ℚ(x)(eᵑ)` by wrapping
    /// [`solve_tower_rde`] (with `omega = f`, `c = g`).
    ///
    /// The underlying solver is verification-guarded over a bounded ansatz, so a
    /// `Some` is always a correct solution but `None` only means "no solution
    /// found within the search bounds" — not a non-elementarity certificate.
    fn rational_rde(&self, f: &TExpr, g: &TExpr) -> Option<TExpr> {
        solve_tower_rde(self, f, g)
    }
}

// ===========================================================================
// Logarithmic tower ℚ(x)(t), t = log(h) — wraps solve_tower_rde_generic
// ===========================================================================

impl DifferentialField for LogTowerField {
    type Elem = TExpr;

    fn zero(&self) -> TExpr {
        <Self as CoeffField>::zero(self)
    }
    fn one(&self) -> TExpr {
        <Self as CoeffField>::one(self)
    }
    fn add(&self, a: &TExpr, b: &TExpr) -> TExpr {
        <Self as CoeffField>::add(self, a, b)
    }
    fn sub(&self, a: &TExpr, b: &TExpr) -> TExpr {
        <Self as CoeffField>::sub(self, a, b)
    }
    fn mul(&self, a: &TExpr, b: &TExpr) -> TExpr {
        <Self as CoeffField>::mul(self, a, b)
    }
    fn neg(&self, a: &TExpr) -> TExpr {
        <Self as CoeffField>::neg(self, a)
    }
    fn inv(&self, a: &TExpr) -> Option<TExpr> {
        <Self as CoeffField>::inv(self, a)
    }
    fn is_zero(&self, a: &TExpr) -> bool {
        <Self as CoeffField>::is_zero(self, a)
    }
    fn eq(&self, a: &TExpr, b: &TExpr) -> bool {
        <Self as CoeffField>::eq(self, a, b)
    }
    fn derivation(&self, a: &TExpr) -> TExpr {
        <Self as CoeffField>::derivation(self, a)
    }

    /// Solve `D(v) + f·v = g` over the logarithmic tower `ℚ(x)(log h)` by
    /// wrapping the field-generic `solve_tower_rde_generic` (with `omega = f`,
    /// `c = g`).  Same verification-guarded semantics as the exp-tower impl: a
    /// `Some` is correct; `None` means "not found within bounds".
    fn rational_rde(&self, f: &TExpr, g: &TExpr) -> Option<TExpr> {
        solve_tower_rde_generic(self, f, g)
    }
}

// ===========================================================================
// Tests — equivalence with the wrapped solvers + correctness in-field
// ===========================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::integrate::risch::poly_rde::QPoly;
    use rug::Rational;

    fn rat(n: i64) -> Rational {
        Rational::from(n)
    }

    /// A polynomial `RatFn` from ascending ℚ-coefficients.
    fn rf_poly(c: &[i64]) -> RatFn {
        let p: QPoly = c.iter().map(|&n| rat(n)).collect();
        RatFn::from_poly(&p)
    }

    // ---- ℚ(x): trait reproduces solve_rational_rde_generalized exactly ----

    /// Assert the trait result agrees with calling the underlying solver
    /// directly, and (when solvable) that `D(y) + f·y = g` holds in-field.
    fn check_qx(f: &RatFn, g: &RatFn) {
        let field = RationalDiffField::new();
        let trait_res = field.rational_rde(f, g);
        let direct = solve_rational_rde_generalized(f.numer(), f.denom(), g.numer(), g.denom())
            .map(|(n, d)| RatFn::new(n, d));
        assert_eq!(
            trait_res, direct,
            "trait rational_rde must match the wrapped solver exactly"
        );
        if let Some(y) = trait_res {
            // D(y) + f·y = g, verified in ℚ(x).
            let lhs = field.add(&field.derivation(&y), &field.mul(f, &y));
            assert!(
                field.eq(&lhs, g),
                "ℚ(x) RDE solution must satisfy D(y)+f·y=g; got y={y:?}"
            );
        }
    }

    #[test]
    fn qx_f0_g_2x_gives_x_squared() {
        // D(y) = 2x  ⇒  y = x².
        let field = RationalDiffField::new();
        let f = field.zero();
        let g = rf_poly(&[0, 2]); // 2x
        check_qx(&f, &g);
        let y = field.rational_rde(&f, &g).expect("solvable");
        assert!(
            field.eq(&y, &rf_poly(&[0, 0, 1])),
            "y should be x²; got {y:?}"
        );
    }

    #[test]
    fn qx_f1_known_solution() {
        // D(y) + y = x + 1  ⇒  y = x   (D(x) + x = 1 + x). ✓
        let field = RationalDiffField::new();
        let f = field.one();
        let g = rf_poly(&[1, 1]); // x + 1
        check_qx(&f, &g);
        let y = field.rational_rde(&f, &g).expect("solvable");
        assert!(field.eq(&y, &rf_poly(&[0, 1])), "y should be x; got {y:?}");
    }

    #[test]
    fn qx_f_const_g_const() {
        // D(y) + 2·y = 4  ⇒  constant y = 2.
        let field = RationalDiffField::new();
        let f = rf_poly(&[2]);
        let g = rf_poly(&[4]);
        check_qx(&f, &g);
        let y = field.rational_rde(&f, &g).expect("solvable");
        assert!(field.eq(&y, &rf_poly(&[2])), "y should be 2; got {y:?}");
    }

    #[test]
    fn qx_rational_f_solvable() {
        // f = 1/x, g = D(x) + (1/x)·x = 1 + 1 = 2  ⇒  y = x.
        // Exercises the generalized (rational-f) path.
        let field = RationalDiffField::new();
        let f = RatFn::new(vec![rat(1)], vec![rat(0), rat(1)]); // 1/x
        let y_expected = rf_poly(&[0, 1]); // x
        let g = field.add(&field.derivation(&y_expected), &field.mul(&f, &y_expected));
        check_qx(&f, &g);
        let y = field.rational_rde(&f, &g).expect("solvable");
        assert!(field.eq(&y, &y_expected), "y should be x; got {y:?}");
    }

    #[test]
    fn qx_ei_type_is_none() {
        // D(y) = 1/x  ⇒  y = log x ∉ ℚ(x): no rational solution.
        let field = RationalDiffField::new();
        let f = field.zero();
        let g = RatFn::new(vec![rat(1)], vec![rat(0), rat(1)]); // 1/x
        check_qx(&f, &g); // also asserts trait == direct (both None)
        assert!(field.rational_rde(&f, &g).is_none(), "1/x ⇒ None (Ei/Li)");
    }

    #[test]
    fn qx_derivation_and_is_constant() {
        let field = RationalDiffField::new();
        // D(x) = 1.
        let x = rf_poly(&[0, 1]);
        assert!(field.eq(&field.derivation(&x), &field.one()));
        assert!(!field.is_constant(&x));
        // D(c) = 0 for a constant.
        let c = rf_poly(&[7]);
        assert!(field.is_zero(&field.derivation(&c)));
        assert!(field.is_constant(&c));
        // D(x²) = 2x.
        let x2 = rf_poly(&[0, 0, 1]);
        assert!(field.eq(&field.derivation(&x2), &rf_poly(&[0, 2])));
    }

    // ---- exp tower: trait reproduces solve_tower_rde ----

    /// `x` as a `ℚ(x)(t)` constant-in-t element.
    fn x_elem() -> TExpr {
        TExpr::from_ratfn(rf_poly(&[0, 1]))
    }

    #[test]
    fn exp_tower_derivation_basics() {
        // η = x ⇒ η' = 1, t = eˣ.
        let field = ExpTowerField::new(RatFn::int(1));
        // D(t) = t  (i.e. D(exp x) = exp x).
        let t = TExpr::t();
        assert!(<ExpTowerField as DifferentialField>::eq(
            &field,
            &DifferentialField::derivation(&field, &t),
            &t
        ));
        assert!(!field.is_constant(&t));
        // D(x) = 1.
        let x = x_elem();
        assert!(<ExpTowerField as DifferentialField>::eq(
            &field,
            &DifferentialField::derivation(&field, &x),
            &DifferentialField::one(&field)
        ));
        // A pure ℚ constant is constant.
        let c = TExpr::int(5);
        assert!(field.is_constant(&c));
    }

    #[test]
    fn exp_tower_v_equals_t() {
        // D(v) + 0·v = t  ⇒  v = t.  Trait must match solve_tower_rde.
        let field = ExpTowerField::new(RatFn::int(1));
        let f = DifferentialField::zero(&field);
        let g = TExpr::t();
        let trait_res = DifferentialField::rational_rde(&field, &f, &g);
        let direct = solve_tower_rde(&field, &f, &g);
        assert_eq!(trait_res, direct, "trait must match solve_tower_rde");
        let v = trait_res.expect("v = t");
        assert_eq!(v, TExpr::t());
    }

    #[test]
    fn exp_tower_example15_component() {
        // Example-15 i=2 component in ℚ(x)(eˣ):
        //   ω₂ = (2/3)(1+t)/(x+t),  c₂ = [(2x+3)t + 5x]/(x+t)  ⇒  v₂ = 3x.
        let field = ExpTowerField::new(RatFn::int(1));
        let a = DifferentialField::add(&field, &x_elem(), &TExpr::t()); // x + t
        let a_prime = DifferentialField::derivation(&field, &a); // 1 + t
        let two_thirds = TExpr::from_ratfn(RatFn::new(vec![rat(2)], vec![rat(3)]));
        let inv_a = DifferentialField::inv(&field, &a).unwrap();
        let omega2 = DifferentialField::mul(
            &field,
            &two_thirds,
            &DifferentialField::mul(&field, &a_prime, &inv_a),
        );

        let num = vec![
            RatFn::from_poly(&vec![rat(0), rat(5)]), // 5x   · t⁰
            RatFn::from_poly(&vec![rat(3), rat(2)]), // 2x+3 · t¹
        ];
        let den = vec![
            RatFn::from_poly(&vec![rat(0), rat(1)]), // x · t⁰
            RatFn::int(1),                           // 1 · t¹
        ];
        let c2 = TExpr::new(num, den);

        let trait_res = DifferentialField::rational_rde(&field, &omega2, &c2);
        let direct = solve_tower_rde(&field, &omega2, &c2);
        assert_eq!(trait_res, direct, "trait must match solve_tower_rde");

        let v = trait_res.expect("Example-15 component is solvable");
        let expected = TExpr::from_ratfn(RatFn::from_poly(&vec![rat(0), rat(3)])); // 3x
        assert!(
            <ExpTowerField as DifferentialField>::eq(&field, &v, &expected),
            "v₂ should be 3x; got {v:?}"
        );
        // D(v) + ω·v = c, in-field.
        let lhs = DifferentialField::add(
            &field,
            &DifferentialField::derivation(&field, &v),
            &DifferentialField::mul(&field, &omega2, &v),
        );
        assert!(
            <ExpTowerField as DifferentialField>::eq(&field, &lhs, &c2),
            "D(v)+ω·v=c must hold in-field"
        );
    }

    #[test]
    fn exp_tower_nonelementary_is_none() {
        // D(v) = t/x  (∫eˣ/x = Ei): no solution within bounds ⇒ None.
        let field = ExpTowerField::new(RatFn::int(1));
        let f = DifferentialField::zero(&field);
        let inv_x = DifferentialField::inv(&field, &x_elem()).unwrap();
        let g = DifferentialField::mul(&field, &TExpr::t(), &inv_x); // t/x
        let trait_res = DifferentialField::rational_rde(&field, &f, &g);
        let direct = solve_tower_rde(&field, &f, &g);
        assert_eq!(trait_res, direct);
        assert!(trait_res.is_none(), "Ei-type ⇒ None");
    }

    // ---- log tower: trait reproduces solve_tower_rde_generic ----

    #[test]
    fn log_tower_derivation_basics() {
        // h = x ⇒ h'/h = 1/x, t = log(x).  D(t) = 1/x.
        let dh_over_h = RatFn::new(vec![rat(1)], vec![rat(0), rat(1)]); // 1/x
        let field = LogTowerField::new(dh_over_h.clone());
        let t = TExpr::t();
        let dt = DifferentialField::derivation(&field, &t);
        let expected = TExpr::from_ratfn(dh_over_h);
        assert!(
            <LogTowerField as DifferentialField>::eq(&field, &dt, &expected),
            "D(log x) = 1/x; got {dt:?}"
        );
        assert!(!field.is_constant(&t));
        // D(x) = 1.
        let x = x_elem();
        assert!(<LogTowerField as DifferentialField>::eq(
            &field,
            &DifferentialField::derivation(&field, &x),
            &DifferentialField::one(&field)
        ));
    }

    #[test]
    fn log_tower_v_equals_t() {
        // h = x, t = log x, D(t) = 1/x.  D(v) + 0·v = 1/x  ⇒  v = t = log x.
        let dh_over_h = RatFn::new(vec![rat(1)], vec![rat(0), rat(1)]); // 1/x
        let field = LogTowerField::new(dh_over_h.clone());
        let f = DifferentialField::zero(&field);
        let g = TExpr::from_ratfn(dh_over_h); // 1/x
        let trait_res = DifferentialField::rational_rde(&field, &f, &g);
        let direct = solve_tower_rde_generic(&field, &f, &g);
        assert_eq!(
            trait_res, direct,
            "trait must match solve_tower_rde_generic"
        );
        let v = trait_res.expect("v = log x");
        assert_eq!(v, TExpr::t());
        // Verify D(v) = g in-field.
        let lhs = DifferentialField::derivation(&field, &v);
        assert!(<LogTowerField as DifferentialField>::eq(&field, &lhs, &g));
    }

    #[test]
    fn log_tower_polynomial_in_t() {
        // h = x, t = log x.  D(t²) = 2t·(1/x).  So with f = 0,
        // g = 2t/x  ⇒  v = t² = (log x)².
        let dh_over_h = RatFn::new(vec![rat(1)], vec![rat(0), rat(1)]); // 1/x
        let field = LogTowerField::new(dh_over_h);
        let t = TExpr::t();
        let t2 = DifferentialField::mul(&field, &t, &t);
        let g = DifferentialField::derivation(&field, &t2); // 2t/x
        let f = DifferentialField::zero(&field);
        let trait_res = DifferentialField::rational_rde(&field, &f, &g);
        let direct = solve_tower_rde_generic(&field, &f, &g);
        assert_eq!(trait_res, direct);
        let v = trait_res.expect("v = (log x)²");
        assert!(
            <LogTowerField as DifferentialField>::eq(&field, &v, &t2),
            "v should be t²; got {v:?}"
        );
    }

    // ---- the PR2+ stubs decline (None), at every level ----

    #[test]
    fn stubs_decline() {
        let qx = RationalDiffField::new();
        assert!(qx.limited_integrate(&qx.one(), &[qx.one()]).is_none());
        assert!(qx.param_log_deriv(&qx.one(), &qx.one()).is_none());

        let exp = ExpTowerField::new(RatFn::int(1));
        let one_e = DifferentialField::one(&exp);
        assert!(exp
            .limited_integrate(&one_e, std::slice::from_ref(&one_e))
            .is_none());
        assert!(exp.param_log_deriv(&one_e, &one_e).is_none());
    }
}