quantsupport 0.1.5

Rust library for derivative pricing and risk analytics.
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
//! Expression-template system for automatic differentiation.
//!
//! Provides [`Expr`], [`BinOp`], [`UnOp`], operators,
//! [`BinExpr`], [`UnExpr`], [`FloatExt`], and free-standing transcendentals.

use std::cmp::Ordering;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};

use crate::ad::node::TapeNode;
use crate::ad::scalar::{InnerScalar, Scalar};
use crate::ad::tape::TapeHolder;

// Re-import sibling types so that the sealed impls and operator macros can
// refer to them without consumers having to spell a longer path.
use super::constant::Const;
use super::dual::Dual;

// ═══════════════════════════════════════════════════════════════════════════
//  Sealed trait — prevents external crates from implementing Expr
// ═══════════════════════════════════════════════════════════════════════════

mod sealed {
    pub trait Sealed {}
    impl<T> Sealed for super::Dual<T> {}
    impl<T> Sealed for super::Const<T> {}
    impl<T, L, R, O> Sealed for super::BinExpr<T, L, R, O> {}
    impl<T, A, O> Sealed for super::UnExpr<T, A, O> {}
}

// ═══════════════════════════════════════════════════════════════════════════
//  Expr, BinOp, UnOp traits
// ═══════════════════════════════════════════════════════════════════════════

/// A differentiable expression node in the expression-template tree.
///
/// Every arithmetic operation on [`Dual<T>`] values returns a lazy
/// expression type ([`BinExpr`] or [`UnExpr`]) instead of immediately
/// recording on the tape. Call [`.into()`](Into::into) on the final
/// expression to flatten the entire tree into a single tape node,
/// producing a `Dual<T>` again.
///
/// This trait is **sealed** — only types defined in this module
/// ([`Dual`], [`Const`], [`BinExpr`], [`UnExpr`]) implement it.
pub trait Expr<T>: sealed::Sealed + Clone {
    /// Returns the scalar value of the expression.
    fn inner_value(&self) -> T;
    /// Recursively pushes adjoint (derivative) contributions into a tape node.
    fn push_adj(&self, parent: &mut TapeNode<T>, adj: T);
}

/// Defines a binary operation for the expression-template system.
pub trait BinOp<T> {
    /// Evaluates the operator on the two operand values.
    fn eval(l: T, r: T) -> T;
    /// Partial derivative with respect to the left operand.
    fn d_left(l: T, r: T) -> T;
    /// Partial derivative with respect to the right operand.
    fn d_right(l: T, r: T) -> T;
}

/// Defines a unary operation for the expression-template system.
pub trait UnOp<T> {
    /// Evaluates the operator on the input value.
    fn eval(x: T) -> T;
    /// Derivative of the operation. `x` is the original input, `v` is `eval(x)`.
    fn deriv(x: T, v: T) -> T;
}

// ═══════════════════════════════════════════════════════════════════════════
//  Binary op structs
// ═══════════════════════════════════════════════════════════════════════════

/// Binary addition operator.
#[derive(Clone, Copy, Debug)]
pub struct AddOp;
impl<T: InnerScalar> BinOp<T> for AddOp {
    #[inline]
    fn eval(l: T, r: T) -> T {
        l + r
    }
    #[inline]
    fn d_left(_l: T, _r: T) -> T {
        T::one()
    }
    #[inline]
    fn d_right(_l: T, _r: T) -> T {
        T::one()
    }
}

/// Binary subtraction operator.
#[derive(Clone, Copy, Debug)]
pub struct SubOp;
impl<T: InnerScalar> BinOp<T> for SubOp {
    #[inline]
    fn eval(l: T, r: T) -> T {
        l - r
    }
    #[inline]
    fn d_left(_l: T, _r: T) -> T {
        T::one()
    }
    #[inline]
    fn d_right(_l: T, _r: T) -> T {
        T::zero() - T::one()
    }
}

/// Binary multiplication operator.
#[derive(Clone, Copy, Debug)]
pub struct MulOp;
impl<T: InnerScalar> BinOp<T> for MulOp {
    #[inline]
    fn eval(l: T, r: T) -> T {
        l * r
    }
    #[inline]
    fn d_left(_l: T, r: T) -> T {
        r
    }
    #[inline]
    fn d_right(l: T, _r: T) -> T {
        l
    }
}

/// Binary division operator.
#[derive(Clone, Copy, Debug)]
pub struct DivOp;
impl<T: InnerScalar> BinOp<T> for DivOp {
    #[inline]
    fn eval(l: T, r: T) -> T {
        l / r
    }
    #[inline]
    fn d_left(_l: T, r: T) -> T {
        T::one() / r
    }
    #[inline]
    fn d_right(l: T, r: T) -> T {
        T::zero() - l / (r * r)
    }
}

/// Binary power operator.
#[derive(Clone, Copy, Debug)]
pub struct PowOp;
impl<T: InnerScalar> BinOp<T> for PowOp {
    #[inline]
    fn eval(l: T, r: T) -> T {
        l.pows(r)
    }
    #[inline]
    fn d_left(l: T, r: T) -> T {
        r * l.pows(r - T::one())
    }
    #[inline]
    fn d_right(l: T, r: T) -> T {
        l.pows(r) * l.ln()
    }
}

/// Binary maximum operator.
#[derive(Clone, Copy, Debug)]
pub struct MaxOp;
impl<T: InnerScalar> BinOp<T> for MaxOp {
    #[inline]
    fn eval(l: T, r: T) -> T {
        l.max_val(r)
    }
    #[inline]
    fn d_left(l: T, r: T) -> T {
        if l.value() > r.value() {
            T::one()
        } else {
            T::zero()
        }
    }
    #[inline]
    fn d_right(l: T, r: T) -> T {
        if r.value() > l.value() {
            T::one()
        } else {
            T::zero()
        }
    }
}

/// Binary minimum operator.
#[derive(Clone, Copy, Debug)]
pub struct MinOp;
impl<T: InnerScalar> BinOp<T> for MinOp {
    #[inline]
    fn eval(l: T, r: T) -> T {
        l.min_val(r)
    }
    #[inline]
    fn d_left(l: T, r: T) -> T {
        if l.value() < r.value() {
            T::one()
        } else {
            T::zero()
        }
    }
    #[inline]
    fn d_right(l: T, r: T) -> T {
        if r.value() < l.value() {
            T::one()
        } else {
            T::zero()
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
//  Unary op structs (macro-generated)
// ═══════════════════════════════════════════════════════════════════════════

macro_rules! un_op {
    ($name:ident, $doc:expr, $eval:expr, $d:expr) => {
        #[doc = $doc]
        #[derive(Clone, Copy, Debug)]
        pub struct $name;
        impl<T: InnerScalar> UnOp<T> for $name {
            #[inline]
            fn eval(x: T) -> T {
                $eval(x)
            }
            #[inline]
            fn deriv(x: T, v: T) -> T {
                $d(x, v)
            }
        }
    };
}

un_op!(
    ExpOp,
    "Unary exponential operator.",
    Scalar::exp,
    |_x: T, v: T| v
);
un_op!(
    LogOp,
    "Unary natural logarithm operator.",
    Scalar::ln,
    |x: T, _v: T| T::one() / x
);
un_op!(
    SqrtOp,
    "Unary square root operator.",
    Scalar::sqrt,
    |_x: T, v: T| T::scalar(0.5) / v
);
un_op!(
    FabsOp,
    "Unary absolute value operator (alias).",
    Scalar::abs,
    |x: T, _v: T| if x.value() >= 0.0 {
        T::one()
    } else {
        T::zero() - T::one()
    }
);
un_op!(SinOp, "Unary sine operator.", Scalar::sin, |x: T, _v: T| x
    .cos());
un_op!(
    CosOp,
    "Unary cosine operator.",
    Scalar::cos,
    |x: T, _v: T| T::zero() - x.sin()
);
un_op!(
    AbsOp,
    "Unary absolute value operator.",
    Scalar::abs,
    |x: T, _v: T| if x.value() >= 0.0 {
        T::one()
    } else {
        T::zero() - T::one()
    }
);

// ═══════════════════════════════════════════════════════════════════════════
//  BinExpr
// ═══════════════════════════════════════════════════════════════════════════

/// A lazy binary expression over two child expressions.
#[derive(Clone, Copy)]
pub struct BinExpr<T, L, R, O> {
    l: L,
    r: R,
    val: T,
    _ph: std::marker::PhantomData<O>,
}

impl<T: InnerScalar, L: Expr<T>, R: Expr<T>, O: BinOp<T>> BinExpr<T, L, R, O> {
    #[inline]
    pub(crate) fn new(l: L, r: R) -> Self {
        let val = O::eval(l.inner_value(), r.inner_value());
        Self {
            l,
            r,
            val,
            _ph: std::marker::PhantomData,
        }
    }
}

impl<T: InnerScalar, L: Expr<T>, R: Expr<T>, O: BinOp<T> + Clone> Expr<T> for BinExpr<T, L, R, O> {
    #[inline]
    fn inner_value(&self) -> T {
        self.val
    }
    fn push_adj(&self, parent: &mut TapeNode<T>, adj: T) {
        let lv = self.l.inner_value();
        let rv = self.r.inner_value();
        self.l.push_adj(parent, adj * O::d_left(lv, rv));
        self.r.push_adj(parent, adj * O::d_right(lv, rv));
    }
}

// ═══════════════════════════════════════════════════════════════════════════
//  UnExpr
// ═══════════════════════════════════════════════════════════════════════════

/// A lazy unary expression over a child expression.
#[derive(Clone, Copy)]
pub struct UnExpr<T, A, O> {
    a: A,
    val: T,
    _ph: std::marker::PhantomData<O>,
}

impl<T: InnerScalar, A: Expr<T>, O: UnOp<T>> UnExpr<T, A, O> {
    #[inline]
    pub(crate) fn new(a: A) -> Self {
        let val = O::eval(a.inner_value());
        Self {
            a,
            val,
            _ph: std::marker::PhantomData,
        }
    }
}

impl<T: InnerScalar, A: Expr<T>, O: UnOp<T> + Clone> Expr<T> for UnExpr<T, A, O> {
    #[inline]
    fn inner_value(&self) -> T {
        self.val
    }
    fn push_adj(&self, parent: &mut TapeNode<T>, adj: T) {
        self.a
            .push_adj(parent, adj * O::deriv(self.a.inner_value(), self.val));
    }
}

// ═══════════════════════════════════════════════════════════════════════════
//  flatten — records an expression tree into one tape node
// ═══════════════════════════════════════════════════════════════════════════

/// Records an expression tree into one tape node, returning a [`Dual<T>`].
pub(crate) fn flatten<T: TapeHolder + InnerScalar, E: Expr<T>>(e: &E) -> Dual<T> {
    let mut node = TapeNode::default();
    e.push_adj(&mut node, T::one());
    let ptr_opt = T::with_tape(|tape| tape.record(node));
    Dual::from_raw(e.inner_value(), ptr_opt)
}

// ═══════════════════════════════════════════════════════════════════════════
//  Expr<T> for Dual<T>
// ═══════════════════════════════════════════════════════════════════════════

impl<T: TapeHolder + InnerScalar> Expr<T> for Dual<T> {
    #[inline]
    fn inner_value(&self) -> T {
        self.val()
    }
    fn push_adj(&self, parent: &mut TapeNode<T>, deriv: T) {
        if let Some(p) = self.node_ptr() {
            parent.push_child(p, deriv);
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
//  Expr<T> for Const<T>
// ═══════════════════════════════════════════════════════════════════════════

impl<T: InnerScalar> Expr<T> for Const<T> {
    #[inline]
    fn inner_value(&self) -> T {
        self.0
    }
    #[inline]
    fn push_adj(&self, _: &mut TapeNode<T>, _: T) {}
}

// ═══════════════════════════════════════════════════════════════════════════
//  Operator impls — expression-template style  (Dual, Const, BinExpr, UnExpr)
// ═══════════════════════════════════════════════════════════════════════════

macro_rules! impl_bin_ops_for {
    (simple $Self:ty, $T:ident) => {
        impl<$T: TapeHolder + InnerScalar, Rhs: Expr<$T> + Clone> Add<Rhs> for $Self
        where
            Self: Expr<$T> + Clone,
        {
            type Output = BinExpr<$T, Self, Rhs, AddOp>;
            fn add(self, rhs: Rhs) -> Self::Output {
                BinExpr::new(self, rhs)
            }
        }
        impl<$T: TapeHolder + InnerScalar> Add<f64> for $Self
        where
            Self: Expr<$T> + Clone,
        {
            type Output = BinExpr<$T, Self, Const<$T>, AddOp>;
            fn add(self, rhs: f64) -> Self::Output {
                BinExpr::new(self, Const($T::scalar(rhs)))
            }
        }
        impl<$T: TapeHolder + InnerScalar, Rhs: Expr<$T> + Clone> Sub<Rhs> for $Self
        where
            Self: Expr<$T> + Clone,
        {
            type Output = BinExpr<$T, Self, Rhs, SubOp>;
            fn sub(self, rhs: Rhs) -> Self::Output {
                BinExpr::new(self, rhs)
            }
        }
        impl<$T: TapeHolder + InnerScalar> Sub<f64> for $Self
        where
            Self: Expr<$T> + Clone,
        {
            type Output = BinExpr<$T, Self, Const<$T>, SubOp>;
            fn sub(self, rhs: f64) -> Self::Output {
                BinExpr::new(self, Const($T::scalar(rhs)))
            }
        }
        impl<$T: TapeHolder + InnerScalar, Rhs: Expr<$T> + Clone> Mul<Rhs> for $Self
        where
            Self: Expr<$T> + Clone,
        {
            type Output = BinExpr<$T, Self, Rhs, MulOp>;
            fn mul(self, rhs: Rhs) -> Self::Output {
                BinExpr::new(self, rhs)
            }
        }
        impl<$T: TapeHolder + InnerScalar> Mul<f64> for $Self
        where
            Self: Expr<$T> + Clone,
        {
            type Output = BinExpr<$T, Self, Const<$T>, MulOp>;
            fn mul(self, rhs: f64) -> Self::Output {
                BinExpr::new(self, Const($T::scalar(rhs)))
            }
        }
        impl<$T: TapeHolder + InnerScalar, Rhs: Expr<$T> + Clone> Div<Rhs> for $Self
        where
            Self: Expr<$T> + Clone,
        {
            type Output = BinExpr<$T, Self, Rhs, DivOp>;
            fn div(self, rhs: Rhs) -> Self::Output {
                BinExpr::new(self, rhs)
            }
        }
        impl<$T: TapeHolder + InnerScalar> Div<f64> for $Self
        where
            Self: Expr<$T> + Clone,
        {
            type Output = BinExpr<$T, Self, Const<$T>, DivOp>;
            fn div(self, rhs: f64) -> Self::Output {
                BinExpr::new(self, Const($T::scalar(rhs)))
            }
        }
        impl<$T: TapeHolder + InnerScalar> Neg for $Self
        where
            Self: Expr<$T> + Clone,
        {
            type Output = BinExpr<$T, Const<$T>, Self, SubOp>;
            fn neg(self) -> Self::Output {
                BinExpr::new(Const($T::zero()), self)
            }
        }
    };
}

impl_bin_ops_for!(simple Dual<T>, T);
impl_bin_ops_for!(simple Const<T>, T);

// -- BinExpr operators -------------------------------------------------------

impl<T: TapeHolder + InnerScalar, L, R, O, Rhs> Add<Rhs> for BinExpr<T, L, R, O>
where
    Rhs: Expr<T> + Clone,
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Rhs, AddOp>;
    fn add(self, rhs: Rhs) -> Self::Output {
        BinExpr::new(self, rhs)
    }
}
impl<T: TapeHolder + InnerScalar, L, R, O> Add<f64> for BinExpr<T, L, R, O>
where
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Const<T>, AddOp>;
    fn add(self, rhs: f64) -> Self::Output {
        BinExpr::new(self, Const(T::scalar(rhs)))
    }
}
impl<T: TapeHolder + InnerScalar, L, R, O, Rhs> Sub<Rhs> for BinExpr<T, L, R, O>
where
    Rhs: Expr<T> + Clone,
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Rhs, SubOp>;
    fn sub(self, rhs: Rhs) -> Self::Output {
        BinExpr::new(self, rhs)
    }
}
impl<T: TapeHolder + InnerScalar, L, R, O> Sub<f64> for BinExpr<T, L, R, O>
where
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Const<T>, SubOp>;
    fn sub(self, rhs: f64) -> Self::Output {
        BinExpr::new(self, Const(T::scalar(rhs)))
    }
}
impl<T: TapeHolder + InnerScalar, L, R, O, Rhs> Mul<Rhs> for BinExpr<T, L, R, O>
where
    Rhs: Expr<T> + Clone,
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Rhs, MulOp>;
    fn mul(self, rhs: Rhs) -> Self::Output {
        BinExpr::new(self, rhs)
    }
}
impl<T: TapeHolder + InnerScalar, L, R, O> Mul<f64> for BinExpr<T, L, R, O>
where
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Const<T>, MulOp>;
    fn mul(self, rhs: f64) -> Self::Output {
        BinExpr::new(self, Const(T::scalar(rhs)))
    }
}
impl<T: TapeHolder + InnerScalar, L, R, O, Rhs> Div<Rhs> for BinExpr<T, L, R, O>
where
    Rhs: Expr<T> + Clone,
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Rhs, DivOp>;
    fn div(self, rhs: Rhs) -> Self::Output {
        BinExpr::new(self, rhs)
    }
}
impl<T: TapeHolder + InnerScalar, L, R, O> Div<f64> for BinExpr<T, L, R, O>
where
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Const<T>, DivOp>;
    fn div(self, rhs: f64) -> Self::Output {
        BinExpr::new(self, Const(T::scalar(rhs)))
    }
}
impl<T: TapeHolder + InnerScalar, L, R, O> Neg for BinExpr<T, L, R, O>
where
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Const<T>, Self, SubOp>;
    fn neg(self) -> Self::Output {
        BinExpr::new(Const(T::zero()), self)
    }
}

// -- UnExpr operators --------------------------------------------------------

impl<T: TapeHolder + InnerScalar, A, O2, Rhs> Add<Rhs> for UnExpr<T, A, O2>
where
    Rhs: Expr<T> + Clone,
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Rhs, AddOp>;
    fn add(self, rhs: Rhs) -> Self::Output {
        BinExpr::new(self, rhs)
    }
}
impl<T: TapeHolder + InnerScalar, A, O2> Add<f64> for UnExpr<T, A, O2>
where
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Const<T>, AddOp>;
    fn add(self, rhs: f64) -> Self::Output {
        BinExpr::new(self, Const(T::scalar(rhs)))
    }
}
impl<T: TapeHolder + InnerScalar, A, O2, Rhs> Sub<Rhs> for UnExpr<T, A, O2>
where
    Rhs: Expr<T> + Clone,
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Rhs, SubOp>;
    fn sub(self, rhs: Rhs) -> Self::Output {
        BinExpr::new(self, rhs)
    }
}
impl<T: TapeHolder + InnerScalar, A, O2> Sub<f64> for UnExpr<T, A, O2>
where
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Const<T>, SubOp>;
    fn sub(self, rhs: f64) -> Self::Output {
        BinExpr::new(self, Const(T::scalar(rhs)))
    }
}
impl<T: TapeHolder + InnerScalar, A, O2, Rhs> Mul<Rhs> for UnExpr<T, A, O2>
where
    Rhs: Expr<T> + Clone,
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Rhs, MulOp>;
    fn mul(self, rhs: Rhs) -> Self::Output {
        BinExpr::new(self, rhs)
    }
}
impl<T: TapeHolder + InnerScalar, A, O2> Mul<f64> for UnExpr<T, A, O2>
where
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Const<T>, MulOp>;
    fn mul(self, rhs: f64) -> Self::Output {
        BinExpr::new(self, Const(T::scalar(rhs)))
    }
}
impl<T: TapeHolder + InnerScalar, A, O2, Rhs> Div<Rhs> for UnExpr<T, A, O2>
where
    Rhs: Expr<T> + Clone,
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Rhs, DivOp>;
    fn div(self, rhs: Rhs) -> Self::Output {
        BinExpr::new(self, rhs)
    }
}
impl<T: TapeHolder + InnerScalar, A, O2> Div<f64> for UnExpr<T, A, O2>
where
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Self, Const<T>, DivOp>;
    fn div(self, rhs: f64) -> Self::Output {
        BinExpr::new(self, Const(T::scalar(rhs)))
    }
}
impl<T: TapeHolder + InnerScalar, A, O2> Neg for UnExpr<T, A, O2>
where
    Self: Expr<T> + Clone,
{
    type Output = BinExpr<T, Const<T>, Self, SubOp>;
    fn neg(self) -> Self::Output {
        BinExpr::new(Const(T::zero()), self)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
//  Comparison for BinExpr / UnExpr
// ═══════════════════════════════════════════════════════════════════════════

impl<T: InnerScalar, L, R, O> PartialEq for BinExpr<T, L, R, O>
where
    L: Expr<T>,
    R: Expr<T>,
    O: BinOp<T> + Clone,
{
    fn eq(&self, rhs: &Self) -> bool {
        self.inner_value().value() == rhs.inner_value().value()
    }
}
impl<T: InnerScalar, L, R, O> PartialOrd for BinExpr<T, L, R, O>
where
    L: Expr<T>,
    R: Expr<T>,
    O: BinOp<T> + Clone,
{
    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
        self.inner_value()
            .value()
            .partial_cmp(&rhs.inner_value().value())
    }
}
impl<T: InnerScalar, L, R, O> PartialEq<f64> for BinExpr<T, L, R, O>
where
    L: Expr<T>,
    R: Expr<T>,
    O: BinOp<T> + Clone,
{
    fn eq(&self, rhs: &f64) -> bool {
        self.inner_value().value() == *rhs
    }
}
impl<T: InnerScalar, L, R, O> PartialOrd<f64> for BinExpr<T, L, R, O>
where
    L: Expr<T>,
    R: Expr<T>,
    O: BinOp<T> + Clone,
{
    fn partial_cmp(&self, rhs: &f64) -> Option<Ordering> {
        self.inner_value().value().partial_cmp(rhs)
    }
}
impl<T: InnerScalar, A, O> PartialEq for UnExpr<T, A, O>
where
    A: Expr<T>,
    O: UnOp<T> + Clone,
{
    fn eq(&self, rhs: &Self) -> bool {
        self.inner_value().value() == rhs.inner_value().value()
    }
}
impl<T: InnerScalar, A, O> PartialOrd for UnExpr<T, A, O>
where
    A: Expr<T>,
    O: UnOp<T> + Clone,
{
    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
        self.inner_value()
            .value()
            .partial_cmp(&rhs.inner_value().value())
    }
}
impl<T: InnerScalar, A, O> PartialEq<f64> for UnExpr<T, A, O>
where
    A: Expr<T>,
    O: UnOp<T> + Clone,
{
    fn eq(&self, rhs: &f64) -> bool {
        self.inner_value().value() == *rhs
    }
}
impl<T: InnerScalar, A, O> PartialOrd<f64> for UnExpr<T, A, O>
where
    A: Expr<T>,
    O: UnOp<T> + Clone,
{
    fn partial_cmp(&self, rhs: &f64) -> Option<Ordering> {
        self.inner_value().value().partial_cmp(rhs)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
//  FloatExt — lazy transcendentals for any expression
// ═══════════════════════════════════════════════════════════════════════════

/// Lazy transcendental methods available on any expression-template node.
pub trait FloatExt<T: InnerScalar>: Expr<T> + Clone + Sized {
    /// Returns `e^x` lazily.
    #[inline]
    fn exp(self) -> UnExpr<T, Self, ExpOp> {
        UnExpr::new(self)
    }
    /// Returns the natural logarithm lazily.
    #[inline]
    fn ln(self) -> UnExpr<T, Self, LogOp> {
        UnExpr::new(self)
    }
    /// Returns the square root lazily.
    #[inline]
    fn sqrt(self) -> UnExpr<T, Self, SqrtOp> {
        UnExpr::new(self)
    }
    /// Returns the sine lazily.
    #[inline]
    fn sin(self) -> UnExpr<T, Self, SinOp> {
        UnExpr::new(self)
    }
    /// Returns the cosine lazily.
    #[inline]
    fn cos(self) -> UnExpr<T, Self, CosOp> {
        UnExpr::new(self)
    }
    /// Returns the absolute value lazily.
    #[inline]
    fn abs(self) -> UnExpr<T, Self, AbsOp> {
        UnExpr::new(self)
    }
    /// Raises the expression to a constant power lazily.
    #[inline]
    fn powf(self, p: f64) -> BinExpr<T, Self, Const<T>, PowOp> {
        BinExpr::new(self, Const(T::scalar(p)))
    }
    /// Raises the expression to the power of another expression lazily.
    #[inline]
    fn pow_expr<R: Expr<T> + Clone>(self, p: R) -> BinExpr<T, Self, R, PowOp> {
        BinExpr::new(self, p)
    }
    /// Returns the minimum of two expressions lazily.
    #[inline]
    fn min<R: Expr<T> + Clone>(self, r: R) -> BinExpr<T, Self, R, MinOp> {
        BinExpr::new(self, r)
    }
    /// Returns the maximum of two expressions lazily.
    #[inline]
    fn max<R: Expr<T> + Clone>(self, r: R) -> BinExpr<T, Self, R, MaxOp> {
        BinExpr::new(self, r)
    }
}

impl<T: InnerScalar, E: Expr<T> + Clone> FloatExt<T> for E {}

// ═══════════════════════════════════════════════════════════════════════════
//  Assign ops  (flatten + assign)
// ═══════════════════════════════════════════════════════════════════════════

macro_rules! impl_assign {
    ($Trait:ident, $func:ident, $Op:ident, $sym:tt) => {
        impl<T: TapeHolder + InnerScalar, E: Expr<T> + Clone> $Trait<E> for Dual<T> {
            fn $func(&mut self, rhs: E) {
                *self = flatten(&(self.clone() $sym rhs));
            }
        }
        impl<T: TapeHolder + InnerScalar> $Trait<f64> for Dual<T> {
            fn $func(&mut self, rhs: f64) {
                *self = flatten(&(self.clone() $sym Const(T::scalar(rhs))));
            }
        }
    };
}

impl_assign!(AddAssign, add_assign, AddOp, +);
impl_assign!(SubAssign, sub_assign, SubOp, -);
impl_assign!(MulAssign, mul_assign, MulOp, *);
impl_assign!(DivAssign, div_assign, DivOp, /);

// ═══════════════════════════════════════════════════════════════════════════
//  From conversions — flattening expressions into Dual<T>
// ═══════════════════════════════════════════════════════════════════════════

impl<T, L, R, O> From<BinExpr<T, L, R, O>> for Dual<T>
where
    T: TapeHolder + InnerScalar,
    L: Expr<T> + Clone,
    R: Expr<T> + Clone,
    O: BinOp<T> + Clone,
{
    fn from(e: BinExpr<T, L, R, O>) -> Self {
        flatten(&e)
    }
}

impl<T, A, O> From<UnExpr<T, A, O>> for Dual<T>
where
    T: TapeHolder + InnerScalar,
    A: Expr<T> + Clone,
    O: UnOp<T> + Clone,
{
    fn from(e: UnExpr<T, A, O>) -> Self {
        flatten(&e)
    }
}

impl<T: TapeHolder + InnerScalar> From<f64> for Dual<T> {
    fn from(v: f64) -> Self {
        Self::new(v)
    }
}

impl<T: TapeHolder + InnerScalar> From<Const<T>> for Dual<T> {
    fn from(c: Const<T>) -> Self {
        Self::constant(c.0)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
//  Rem (expression-template compatible)
// ═══════════════════════════════════════════════════════════════════════════

impl<T: TapeHolder + InnerScalar> std::ops::Rem for Dual<T> {
    type Output = Self;
    fn rem(self, r: Self) -> Self {
        Self::constant(T::scalar(self.value() % r.value()))
    }
}
impl<T: TapeHolder + InnerScalar> std::ops::Rem<f64> for Dual<T> {
    type Output = Self;
    fn rem(self, r: f64) -> Self {
        Self::constant(T::scalar(self.value() % r))
    }
}

// ═══════════════════════════════════════════════════════════════════════════
//  Free-standing transcendental functions
// ═══════════════════════════════════════════════════════════════════════════

/// Returns the exponential of an expression.
#[inline]
pub fn exp<T: InnerScalar, A: Expr<T> + Clone>(a: A) -> UnExpr<T, A, ExpOp> {
    UnExpr::new(a)
}
/// Returns the natural logarithm of an expression.
#[inline]
pub fn log<T: InnerScalar, A: Expr<T> + Clone>(a: A) -> UnExpr<T, A, LogOp> {
    UnExpr::new(a)
}
/// Returns the square root of an expression.
#[inline]
pub fn sqrt<T: InnerScalar, A: Expr<T> + Clone>(a: A) -> UnExpr<T, A, SqrtOp> {
    UnExpr::new(a)
}
/// Returns the absolute value of an expression.
#[inline]
pub fn abs<T: InnerScalar, A: Expr<T> + Clone>(a: A) -> UnExpr<T, A, AbsOp> {
    UnExpr::new(a)
}
/// Returns the absolute value of an expression (alias).
#[inline]
pub fn fabs<T: InnerScalar, A: Expr<T> + Clone>(a: A) -> UnExpr<T, A, FabsOp> {
    UnExpr::new(a)
}
/// Returns the sine of an expression.
#[inline]
pub fn sin<T: InnerScalar, A: Expr<T> + Clone>(a: A) -> UnExpr<T, A, SinOp> {
    UnExpr::new(a)
}
/// Returns the cosine of an expression.
#[inline]
pub fn cos<T: InnerScalar, A: Expr<T> + Clone>(a: A) -> UnExpr<T, A, CosOp> {
    UnExpr::new(a)
}
/// Raises one expression to the power of another.
#[inline]
pub fn pow<T: InnerScalar, L: Expr<T> + Clone, R: Expr<T> + Clone>(
    l: L,
    r: R,
) -> BinExpr<T, L, R, PowOp> {
    BinExpr::new(l, r)
}
/// Returns the maximum of two expressions.
#[inline]
pub fn max<T: InnerScalar, L: Expr<T> + Clone, R: Expr<T> + Clone>(
    l: L,
    r: R,
) -> BinExpr<T, L, R, MaxOp> {
    BinExpr::new(l, r)
}
/// Returns the minimum of two expressions.
#[inline]
pub fn min<T: InnerScalar, L: Expr<T> + Clone, R: Expr<T> + Clone>(
    l: L,
    r: R,
) -> BinExpr<T, L, R, MinOp> {
    BinExpr::new(l, r)
}