quantsupport 0.1.2

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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
use core::fmt;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};

use crate::ad::node::TapeNode;
use crate::ad::tape::{Tape, TAPE};
use crate::utils::errors::{QSError, Result};

use std::cmp::Ordering;
use std::ptr::NonNull;

/// Represents a number that can be used in differentiable functions.
/// 
/// ## Example
/// ```
/// use quantsupport::ad::adreal::ADReal;
/// use quantsupport::ad::adreal::FloatExt;
/// use quantsupport::ad::adreal::IsReal;
/// use quantsupport::ad::tape::Tape;
/// 
/// Tape::start_recording();
/// let x = ADReal::new(0.0);
/// let expr = x.cos();
/// let out: ADReal = expr.into();
/// out.backward().unwrap();
/// assert_eq!(x.adjoint().unwrap(), 0.0); // derivative of cos(x) wrt x = -sin(x) = 0 at x=0
/// assert_eq!(out.adjoint().unwrap(), 1.0);
/// ```
#[derive(Clone, Copy, Default)]
pub struct ADReal {
    val: f64,
    node: Option<NonNull<TapeNode>>,
}

unsafe impl Sync for ADReal {}
unsafe impl Send for ADReal {}

/// Conversion helpers for numeric types used by this crate.
pub trait IsReal
where
    Self: Sized + Copy + Add + Sub + Mul + Div + PartialEq + PartialOrd,
{
    /// Creates a new numeric value from the given scalar in f64.
    fn new(v: f64) -> Self;
    /// Returns the underlying scalar value.
    fn value(&self) -> f64;
    /// Returns one as base-type.
    fn one() -> Self;
    /// Returns zero as base-type.
    fn zero() -> Self;
}

impl IsReal for f64 {
    #[inline]
    fn new(v: f64) -> Self {
        v
    }

    #[inline]
    fn value(&self) -> f64 {
        *self
    }

    #[inline]
    fn one() -> Self {
        1.0
    }
    #[inline]
    fn zero() -> Self {
        0.0
    }
}

impl IsReal for ADReal {
    #[inline]
    fn new(val: f64) -> Self {
        let node = TAPE.with_borrow_mut(Tape::new_leaf);
        Self { val, node }
    }
    #[inline]
    fn value(&self) -> f64 {
        self.val
    }
    #[inline]
    fn one() -> Self {
        Self::new(1.0)
    }
    #[inline]
    fn zero() -> Self {
        Self::new(0.0)
    }
}

/// A differentiable expression that can record its contribution to the tape.
/// 
/// This trait is implemented by `ADReal` and can be used to define complex expressions 
/// that automatically record their derivatives, allowing for more efficient memory usage.
pub trait Expr: Clone {
    /// Returns the scalar value of the expression.
    fn inner_value(&self) -> f64;
    /// Pushes this expression's adjoint contribution into the tape node.
    fn push_adj(&self, parent: &mut TapeNode, adj: f64);
}

impl fmt::Debug for ADReal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ADReal({}, Node: {:?})", self.val, self.node)
    }
}

impl fmt::Display for ADReal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ADReal({})", self.val)
    }
}

impl ADReal {
    /// Sets the active tape for the current thread.
    pub fn set_tape(t: Tape) {
        TAPE.set(t);
    }

    /// Returns the adjoint for this value if it is on the tape.
    ///
    /// ## Errors
    /// Returns an error if this node is not indexed in the tape.
    ///
    /// ## Safety
    /// This function accesses raw pointers from the tape and assumes they are valid.
    #[inline]
    pub fn adjoint(&self) -> Result<f64> {
        self.node
            .map(|p| unsafe { p.as_ref().adj })
            .ok_or(QSError::NodeNotIndexedInTapeErr)
    }

    /// Runs a full backward pass from this node to the start of the tape.
    ///
    /// ## Errors
    /// Returns an error if this node is not indexed in the tape.    
    pub fn backward(&self) -> Result<()> {
        let root = self.node.ok_or(QSError::NodeNotIndexedInTapeErr)?;

        TAPE.with_borrow_mut(|tape| {
            tape.mut_node(root)
                .ok_or(QSError::NodeNotIndexedInTapeErr)?
                .adj = 1.0;
            tape.propagate_from(root)
        })
    }

    /// Runs a backward pass from the current mark down to the start.
    ///
    /// ## Errors
    /// Returns an error if this node is not indexed in the tape.
    pub fn backward_mark_to_start(&self) -> Result<()> {
        let root: NonNull<TapeNode> = self.node.ok_or(QSError::NodeNotIndexedInTapeErr)?;

        TAPE.with_borrow_mut(|tape| {
            tape.mut_node(root)
                .ok_or(QSError::NodeNotIndexedInTapeErr)?
                .adj = 1.0;
            tape.propagate_mark_to_start()
        })
    }

    /// Runs a backward pass from the end of the tape down to the current mark.
    ///
    /// ## Errors
    /// Returns an error if this node is not indexed in the tape.
    pub fn backward_to_mark(&self) -> Result<()> {
        let root: NonNull<TapeNode> = self.node.ok_or(QSError::NodeNotIndexedInTapeErr)?;

        TAPE.with_borrow_mut(|tape| {
            tape.mut_node(root)
                .ok_or(QSError::NodeNotIndexedInTapeErr)?
                .adj = 1.0;
            tape.propagate_to_mark()
        })
    }

    /// Attaches this value to the current tape if it is not already recorded.
    pub fn put_on_tape(&mut self) {
        if self.node.is_some() {
            return; // already on a tape
        }

        TAPE.with_borrow_mut(|tape| {
            let node = tape.new_leaf();
            self.node = node;
        });
    }

    /// Ensures this value is registered on the tape, creating a new leaf node if necessary.
    /// This is called automatically during expression evaluation if the value hasn't been registered yet.
    /// Returns a copy of self with the node properly registered, or returns self unchanged if already registered.
    #[must_use]
    pub fn ensure_on_tape(&self) -> Self {
        if self.node.is_some() {
            return *self;
        }

        let mut result = *self;
        result.put_on_tape();
        result
    }

    /// Check if this value is already indexed on a tape.
    #[must_use]
    pub const fn is_on_tape(&self) -> bool {
        self.node.is_some()
    }
}

impl Expr for ADReal {
    #[inline]
    /// Returns the scalar value for use in tape recording.
    fn inner_value(&self) -> f64 {
        self.val
    }

    /// Pushes this value into the parent tape node with the given derivative.
    fn push_adj(&self, parent: &mut TapeNode, deriv: f64) {
        if let Some(p) = self.node {
            parent.childs.push(p);
            parent.derivs.push(deriv);
        }
    }
}

/// Records an expression into the tape, returning the resulting [`ADReal`].
/// This function automatically registers any unregistered [`ADReal`] operands on the tape
/// before evaluating the expression, ensuring proper derivative computation.
fn flatten<E: Expr + Clone>(e: &E) -> ADReal {
    let mut node = TapeNode::default();
    e.push_adj(&mut node, 1.0);

    // Try to record the node. If it fails (tape not active), return a regular ADReal
    // with the computed value but without a node.
    let ptr_opt = TAPE.with_borrow_mut(|tape| tape.record(node));

    ADReal {
        val: e.inner_value(),
        node: ptr_opt,
    }
}

impl PartialEq for ADReal {
    fn eq(&self, o: &Self) -> bool {
        self.val == o.val
    }
}
impl PartialOrd for ADReal {
    fn partial_cmp(&self, o: &Self) -> Option<Ordering> {
        self.val.partial_cmp(&o.val)
    }
}

/// A constant expression wrapper for interoperability.
#[derive(Clone, Copy, PartialEq, PartialOrd)]
pub struct Const(pub f64);

impl IsReal for Const {
    fn new(v: f64) -> Self {
        Self(v)
    }

    fn one() -> Self {
        Self(1.0)
    }

    fn value(&self) -> f64 {
        self.0
    }

    fn zero() -> Self {
        Self(0.0)
    }
}

impl From<f64> for Const {
    #[inline]
    /// Converts a [`f64`] into a constant expression.
    fn from(v: f64) -> Self {
        Self(v)
    }
}

impl From<f32> for Const {
    #[inline]
    /// Converts a [`f32`] into a constant expression.
    fn from(v: f32) -> Self {
        Self(f64::from(v))
    }
}

impl From<i32> for Const {
    #[inline]
    /// Converts an [`i32`] into a constant expression.
    fn from(v: i32) -> Self {
        Self(f64::from(v))
    }
}

impl From<u32> for Const {
    #[inline]
    /// Converts a [`u32`] into a constant expression.
    fn from(v: u32) -> Self {
        Self(f64::from(v))
    }
}

impl From<Const> for f64 {
    #[inline]
    /// Extracts the underlying [`f64`] from a constant expression.
    fn from(c: Const) -> Self {
        c.0
    }
}

impl Expr for Const {
    #[inline]
    /// Returns the scalar value of the constant expression.
    fn inner_value(&self) -> f64 {
        self.0
    }
    #[inline]
    /// Constants do not contribute adjoints to the tape.
    fn push_adj(&self, _: &mut TapeNode, _: f64) {}
}

/// A binary operation definition for the expression system.
pub trait BinOp {
    /// Evaluates the operator on the input values.
    fn eval(l: f64, r: f64) -> f64;
    /// Computes the derivative with respect to the left operand.
    fn d_left(l: f64, r: f64) -> f64;
    /// Computes the derivative with respect to the right operand.
    fn d_right(l: f64, r: f64) -> f64;
}

/// Binary addition operator.
#[derive(Clone, Copy, Debug)]
pub struct AddOp;
impl BinOp for AddOp {
    #[inline]
    /// Evaluates the operator on the input values.
    fn eval(l: f64, r: f64) -> f64 {
        l + r
    }
    #[inline]
    /// Returns the derivative with respect to the left operand.
    fn d_left(_: f64, _: f64) -> f64 {
        1.0
    }
    #[inline]
    /// Returns the derivative with respect to the right operand.
    fn d_right(_: f64, _: f64) -> f64 {
        1.0
    }
}

///  Binary subtraction operator.
#[derive(Clone, Copy, Debug)]
pub struct SubOp;
impl BinOp for SubOp {
    #[inline]
    /// Evaluates the operator on the input values.
    fn eval(l: f64, r: f64) -> f64 {
        l - r
    }
    #[inline]
    /// Returns the derivative with respect to the left operand.
    fn d_left(_: f64, _: f64) -> f64 {
        1.0
    }
    #[inline]
    /// Returns the derivative with respect to the right operand.
    fn d_right(_: f64, _: f64) -> f64 {
        -1.0
    }
}

/// Binary multiplication operator.
#[derive(Clone, Copy, Debug)]
pub struct MulOp;
impl BinOp for MulOp {
    #[inline]
    /// Evaluates the operator on the input values.
    fn eval(l: f64, r: f64) -> f64 {
        l * r
    }
    #[inline]
    /// Returns the derivative with respect to the left operand.
    fn d_left(_: f64, r: f64) -> f64 {
        r
    }
    #[inline]
    /// Returns the derivative with respect to the right operand.
    fn d_right(l: f64, _: f64) -> f64 {
        l
    }
}

/// Binary division operator.
#[derive(Clone, Copy, Debug)]
pub struct DivOp;
impl BinOp for DivOp {
    #[inline]
    /// Evaluates the operator on the input values.
    fn eval(l: f64, r: f64) -> f64 {
        l / r
    }
    #[inline]
    /// Returns the derivative with respect to the left operand.
    fn d_left(_: f64, r: f64) -> f64 {
        1.0 / r
    }
    #[inline]
    /// Returns the derivative with respect to the right operand.
    fn d_right(l: f64, r: f64) -> f64 {
        -l / (r * r)
    }
}

/// Binary power operator.
#[derive(Clone, Copy, Debug)]
pub struct PowOp;
impl BinOp for PowOp {
    #[inline]
    /// Evaluates the operator on the input values.
    fn eval(l: f64, r: f64) -> f64 {
        l.powf(r)
    }
    #[inline]
    /// Returns the derivative with respect to the left operand.
    fn d_left(l: f64, r: f64) -> f64 {
        r * l.powf(r - 1.0)
    }
    #[inline]
    /// Returns the derivative with respect to the right operand.
    fn d_right(l: f64, r: f64) -> f64 {
        l.powf(r) * l.ln()
    }
}

/// Binary maximum operator.
#[derive(Clone, Copy, Debug)]
pub struct MaxOp;
impl BinOp for MaxOp {
    #[inline]
    /// Evaluates the operator on the input values.
    fn eval(l: f64, r: f64) -> f64 {
        l.max(r)
    }
    #[inline]
    /// Returns the derivative with respect to the left operand.
    fn d_left(l: f64, r: f64) -> f64 {
        if l > r {
            1.0
        } else {
            0.0
        }
    }
    #[inline]
    /// Returns the derivative with respect to the right operand.
    fn d_right(l: f64, r: f64) -> f64 {
        if r > l {
            1.0
        } else {
            0.0
        }
    }
}

/// Binary minimum operator.
#[derive(Clone, Copy, Debug)]
pub struct MinOp;
impl BinOp for MinOp {
    #[inline]
    /// Evaluates the operator on the input values.
    fn eval(l: f64, r: f64) -> f64 {
        l.min(r)
    }
    #[inline]
    /// Returns the derivative with respect to the left operand.
    fn d_left(l: f64, r: f64) -> f64 {
        if l < r {
            1.0
        } else {
            0.0
        }
    }
    #[inline]
    /// Returns the derivative with respect to the right operand.
    fn d_right(l: f64, r: f64) -> f64 {
        if r < l {
            1.0
        } else {
            0.0
        }
    }
}

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

impl<L: Expr, R: Expr, O: BinOp> BinExpr<L, R, O> {
    #[inline]
    /// Constructs a new binary expression and caches its value.
    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<L: Expr, R: Expr, O: BinOp + Clone> Expr for BinExpr<L, R, O> {
    #[inline]
    /// Returns the cached scalar value of the expression.
    fn inner_value(&self) -> f64 {
        self.val
    }
    /// Pushes adjoint contributions for the left and right child expressions.
    fn push_adj(&self, parent: &mut TapeNode, adj: f64) {
        self.l.push_adj(
            parent,
            adj * O::d_left(self.l.inner_value(), self.r.inner_value()),
        );
        self.r.push_adj(
            parent,
            adj * O::d_right(self.l.inner_value(), self.r.inner_value()),
        );
    }
}

/// A unary operation definition for the expression system.
pub trait UnOp {
    /// Evaluates the operator on the input value.
    fn eval(x: f64) -> f64;
    /// Computes the derivative with respect to the input.
    fn deriv(x: f64, v: f64) -> f64;
}

macro_rules! un_op {
    ($name:ident, $doc:expr, $eval:expr, $d:expr) => {
        #[doc = $doc]
        #[derive(Clone, Copy, Debug)]
        pub struct $name;
        impl UnOp for $name {
            #[inline]
            /// Evaluates the unary operator.
            fn eval(x: f64) -> f64 {
                $eval(x)
            }
            #[inline]
            /// Returns the derivative of the unary operator.
            fn deriv(x: f64, v: f64) -> f64 {
                $d(x, v)
            }
        }
    };
}

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

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

impl<A: Expr, O: UnOp> UnExpr<A, O> {
    #[inline]
    /// Constructs a new unary expression and caches its value.
    fn new(a: A) -> Self {
        let val = O::eval(a.inner_value());
        Self {
            a,
            val,
            _ph: std::marker::PhantomData,
        }
    }
}

impl<A: Expr, O: UnOp + Clone> Expr for UnExpr<A, O> {
    #[inline]
    /// Returns the cached scalar value of the expression.
    fn inner_value(&self) -> f64 {
        self.val
    }
    /// Pushes adjoint contributions for the child expression.
    fn push_adj(&self, parent: &mut TapeNode, adj: f64) {
        self.a
            .push_adj(parent, adj * O::deriv(self.a.inner_value(), self.val));
    }
}

macro_rules! impl_bin_ops_local {
    ($Self:ty) => {
        impl<Rhs> Add<Rhs> for $Self
        where
            Rhs: Expr + Clone,
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Rhs, AddOp>;
            fn add(self, rhs: Rhs) -> Self::Output {
                BinExpr::new(self, rhs)
            }
        }
        impl Add<f64> for $Self
        where
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Const, AddOp>;
            fn add(self, rhs: f64) -> Self::Output {
                BinExpr::new(self, Const(rhs))
            }
        }

        impl<Rhs> Sub<Rhs> for $Self
        where
            Rhs: Expr + Clone,
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Rhs, SubOp>;
            fn sub(self, rhs: Rhs) -> Self::Output {
                BinExpr::new(self, rhs)
            }
        }
        impl Sub<f64> for $Self
        where
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Const, SubOp>;
            fn sub(self, rhs: f64) -> Self::Output {
                BinExpr::new(self, Const(rhs))
            }
        }

        impl<Rhs> Mul<Rhs> for $Self
        where
            Rhs: Expr + Clone,
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Rhs, MulOp>;
            fn mul(self, rhs: Rhs) -> Self::Output {
                BinExpr::new(self, rhs)
            }
        }
        impl Mul<f64> for $Self
        where
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Const, MulOp>;
            fn mul(self, rhs: f64) -> Self::Output {
                BinExpr::new(self, Const(rhs))
            }
        }

        impl<Rhs> Div<Rhs> for $Self
        where
            Rhs: Expr + Clone,
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Rhs, DivOp>;
            fn div(self, rhs: Rhs) -> Self::Output {
                BinExpr::new(self, rhs)
            }
        }
        impl Div<f64> for $Self
        where
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Const, DivOp>;
            fn div(self, rhs: f64) -> Self::Output {
                BinExpr::new(self, Const(rhs))
            }
        }

        impl Neg for $Self
        where
            Self: Expr + Clone,
        {
            type Output = BinExpr<Const, Self, SubOp>;
            fn neg(self) -> Self::Output {
                BinExpr::new(Const(0.0), self)
            }
        }
    };
}

impl_bin_ops_local!(ADReal);

impl_bin_ops_local!(Const);

macro_rules! impl_bin_ops_expr {
    ($Expr:ident) => {
        impl<L, R, O, Rhs> Add<Rhs> for $Expr<L, R, O>
        where
            Rhs: Expr + Clone,
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Rhs, AddOp>;
            fn add(self, rhs: Rhs) -> Self::Output {
                BinExpr::new(self, rhs)
            }
        }
        impl<L, R, O> Add<f64> for $Expr<L, R, O>
        where
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Const, AddOp>;
            fn add(self, rhs: f64) -> Self::Output {
                BinExpr::new(self, Const(rhs))
            }
        }

        /* Sub ------------------------------------------------------- */
        impl<L, R, O, Rhs> Sub<Rhs> for $Expr<L, R, O>
        where
            Rhs: Expr + Clone,
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Rhs, SubOp>;
            fn sub(self, rhs: Rhs) -> Self::Output {
                BinExpr::new(self, rhs)
            }
        }
        impl<L, R, O> Sub<f64> for $Expr<L, R, O>
        where
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Const, SubOp>;
            fn sub(self, rhs: f64) -> Self::Output {
                BinExpr::new(self, Const(rhs))
            }
        }

        /* Mul ------------------------------------------------------- */
        impl<L, R, O, Rhs> Mul<Rhs> for $Expr<L, R, O>
        where
            Rhs: Expr + Clone,
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Rhs, MulOp>;
            fn mul(self, rhs: Rhs) -> Self::Output {
                BinExpr::new(self, rhs)
            }
        }
        impl<L, R, O> Mul<f64> for $Expr<L, R, O>
        where
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Const, MulOp>;
            fn mul(self, rhs: f64) -> Self::Output {
                BinExpr::new(self, Const(rhs))
            }
        }

        /* Div ------------------------------------------------------- */
        impl<L, R, O, Rhs> Div<Rhs> for $Expr<L, R, O>
        where
            Rhs: Expr + Clone,
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Rhs, DivOp>;
            fn div(self, rhs: Rhs) -> Self::Output {
                BinExpr::new(self, rhs)
            }
        }
        impl<L, R, O> Div<f64> for $Expr<L, R, O>
        where
            Self: Expr + Clone,
        {
            type Output = BinExpr<Self, Const, DivOp>;
            fn div(self, rhs: f64) -> Self::Output {
                BinExpr::new(self, Const(rhs))
            }
        }

        /* Neg ------------------------------------------------------- */
        impl<L, R, O> Neg for $Expr<L, R, O>
        where
            Self: Expr + Clone,
        {
            type Output = BinExpr<Const, Self, SubOp>;
            fn neg(self) -> Self::Output {
                BinExpr::new(Const(0.0), self)
            }
        }
    };
}

impl_bin_ops_expr!(BinExpr);

macro_rules! impl_assign {
    ($Trait:ident, $func:ident, $Op:ident, $sym:tt) => {
        impl<E> $Trait<E> for ADReal
        where
            E: Expr + Clone,
        {
            fn $func(&mut self, rhs: E) {
                *self = flatten(&(self.clone() $sym rhs));
            }
        }
        impl $Trait<f64> for ADReal {
            fn $func(&mut self, rhs: f64) {
                *self = flatten(&(self.clone() $sym Const(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, /);

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

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

/// Returns the exponential of an expression.
#[inline]
pub fn exp<A: Expr + Clone>(a: A) -> UnExpr<A, ExpOp> {
    UnExpr::new(a)
}

/// Returns the natural logarithm of an expression.
#[inline]
pub fn log<A: Expr + Clone>(a: A) -> UnExpr<A, LogOp> {
    UnExpr::new(a)
}

/// Returns the square root of an expression.
#[inline]
pub fn sqrt<A: Expr + Clone>(a: A) -> UnExpr<A, SqrtOp> {
    UnExpr::new(a)
}
#[inline]
/// Returns the absolute value of an expression.
pub fn fabs<A: Expr + Clone>(a: A) -> UnExpr<A, FabsOp> {
    UnExpr::new(a)
}

/// Returns the sine of an expression.
#[inline]
pub fn sin<A: Expr + Clone>(a: A) -> UnExpr<A, SinOp> {
    UnExpr::new(a)
}

/// Returns the cosine of an expression.
#[inline]
pub fn cos<A: Expr + Clone>(a: A) -> UnExpr<A, CosOp> {
    UnExpr::new(a)
}

/// Returns the absolute value of an expression.
#[inline]
pub fn abs<A: Expr + Clone>(a: A) -> UnExpr<A, AbsOp> {
    UnExpr::new(a)
}

/// Raises one expression to the power of another.
#[inline]
pub fn pow<L: Expr + Clone, R: Expr + Clone>(l: L, r: R) -> BinExpr<L, R, PowOp> {
    BinExpr::new(l, r)
}

/// Returns the maximum of two expressions.
#[inline]
pub fn max<L: Expr + Clone, R: Expr + Clone>(l: L, r: R) -> BinExpr<L, R, MaxOp> {
    BinExpr::new(l, r)
}

/// Returns the minimum of two expressions.
#[inline]
pub fn min<L: Expr + Clone, R: Expr + Clone>(l: L, r: R) -> BinExpr<L, R, MinOp> {
    BinExpr::new(l, r)
}

impl<L, R, O> From<BinExpr<L, R, O>> for ADReal
where
    L: Expr + Clone,
    R: Expr + Clone,
    O: BinOp + Clone,
{
    /// Flattens a binary expression into an [`ADReal`] and records it.
    fn from(e: BinExpr<L, R, O>) -> Self {
        flatten(&e)
    }
}
impl<A, O> From<UnExpr<A, O>> for ADReal
where
    A: Expr + Clone,
    O: UnOp + Clone,
{
    /// Flattens a unary expression into an [`ADReal`] and records it.
    fn from(e: UnExpr<A, O>) -> Self {
        flatten(&e)
    }
}
impl From<f64> for ADReal {
    /// Converts a [`f64`] into an [`ADReal`], recording if the tape is active.
    fn from(v: f64) -> Self {
        Self::new(v)
    }
}
impl From<f32> for ADReal {
    /// Converts a [`f32`] into an [`ADReal`], recording if the tape is active.
    fn from(v: f32) -> Self {
        Self::new(f64::from(v))
    }
}
impl From<i32> for ADReal {
    /// Converts an [`i32`] into an [`ADReal`], recording if the tape is active.
    fn from(v: i32) -> Self {
        Self::new(f64::from(v))
    }
}
impl From<Const> for ADReal {
    /// Converts a [`Const`] expression into an [`ADReal`].
    fn from(v: Const) -> Self {
        Self::new(v.0)
    }
}

/// Convenience methods for common floating-point operations on expressions.
pub trait FloatExt: Expr + Clone + Sized {
    #[inline]
    /// Returns `e^x` for the expression.
    fn exp(self) -> UnExpr<Self, ExpOp> {
        UnExpr::new(self)
    }
    #[inline]
    /// Returns the natural logarithm of the expression.
    fn ln(self) -> UnExpr<Self, LogOp> {
        UnExpr::new(self)
    }
    #[inline]
    /// Returns the sine of the expression.
    fn sin(self) -> UnExpr<Self, SinOp> {
        UnExpr::new(self)
    }
    #[inline]
    /// Returns the cosine of the expression.
    fn cos(self) -> UnExpr<Self, CosOp> {
        UnExpr::new(self)
    }
    #[inline]
    /// Returns the absolute value of the expression.
    fn abs(self) -> UnExpr<Self, AbsOp> {
        UnExpr::new(self)
    }

    #[inline]
    /// Raises the expression to a constant power.
    fn powf(self, p: f64) -> BinExpr<Self, Const, PowOp> {
        BinExpr::new(self, Const(p))
    }

    #[inline]
    /// Returns the square root of the expression.
    fn sqrt(self) -> UnExpr<Self, SqrtOp> {
        UnExpr::new(self)
    }

    #[inline]
    /// Raises the expression to the power of another expression.
    fn pow_expr<R: Expr + Clone>(self, p: R) -> BinExpr<Self, R, PowOp> {
        BinExpr::new(self, p)
    }

    #[inline]
    /// Returns the minimum of two expressions.
    fn min<R: Expr + Clone>(self, r: R) -> BinExpr<Self, R, MinOp> {
        BinExpr::new(self, r)
    }

    #[inline]
    /// Returns the maximum of two expressions.
    fn max<R: Expr + Clone>(self, r: R) -> BinExpr<Self, R, MaxOp> {
        BinExpr::new(self, r)
    }
}
impl<T: Expr + Clone> FloatExt for T {}

impl<A, O, Rhs> Add<Rhs> for UnExpr<A, O>
where
    Rhs: Expr + Clone,
    Self: Expr + Clone,
{
    type Output = BinExpr<Self, Rhs, AddOp>;
    fn add(self, rhs: Rhs) -> Self::Output {
        BinExpr::new(self, rhs)
    }
}
impl<A, O> Add<f64> for UnExpr<A, O>
where
    Self: Expr + Clone,
{
    type Output = BinExpr<Self, Const, AddOp>;
    fn add(self, rhs: f64) -> Self::Output {
        BinExpr::new(self, Const(rhs))
    }
}

impl<A, O, Rhs> Sub<Rhs> for UnExpr<A, O>
where
    Rhs: Expr + Clone,
    Self: Expr + Clone,
{
    type Output = BinExpr<Self, Rhs, SubOp>;
    fn sub(self, rhs: Rhs) -> Self::Output {
        BinExpr::new(self, rhs)
    }
}
impl<A, O> Sub<f64> for UnExpr<A, O>
where
    Self: Expr + Clone,
{
    type Output = BinExpr<Self, Const, SubOp>;
    fn sub(self, rhs: f64) -> Self::Output {
        BinExpr::new(self, Const(rhs))
    }
}

impl<A, O, Rhs> Mul<Rhs> for UnExpr<A, O>
where
    Rhs: Expr + Clone,
    Self: Expr + Clone,
{
    type Output = BinExpr<Self, Rhs, MulOp>;
    fn mul(self, rhs: Rhs) -> Self::Output {
        BinExpr::new(self, rhs)
    }
}
impl<A, O> Mul<f64> for UnExpr<A, O>
where
    Self: Expr + Clone,
{
    type Output = BinExpr<Self, Const, MulOp>;
    fn mul(self, rhs: f64) -> Self::Output {
        BinExpr::new(self, Const(rhs))
    }
}

impl<A, O, Rhs> Div<Rhs> for UnExpr<A, O>
where
    Rhs: Expr + Clone,
    Self: Expr + Clone,
{
    type Output = BinExpr<Self, Rhs, DivOp>;
    fn div(self, rhs: Rhs) -> Self::Output {
        BinExpr::new(self, rhs)
    }
}
impl<A, O> Div<f64> for UnExpr<A, O>
where
    Self: Expr + Clone,
{
    type Output = BinExpr<Self, Const, DivOp>;
    fn div(self, rhs: f64) -> Self::Output {
        BinExpr::new(self, Const(rhs))
    }
}

impl<A, O> Neg for UnExpr<A, O>
where
    Self: Expr + Clone,
{
    type Output = BinExpr<Const, Self, SubOp>;
    fn neg(self) -> Self::Output {
        BinExpr::new(Const(0.0), self)
    }
}

impl PartialEq<f64> for ADReal {
    #[inline]
    fn eq(&self, rhs: &f64) -> bool {
        self.value() == *rhs
    }
}

impl PartialOrd<f64> for ADReal {
    #[inline]
    fn partial_cmp(&self, rhs: &f64) -> Option<Ordering> {
        self.value().partial_cmp(rhs)
    }
}

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

    static TEST_MUTEX: Mutex<()> = Mutex::new(());

    fn with_tape_test<F: FnOnce()>(f: F) {
        // If a previous test panicked while holding the mutex the lock becomes
        // poisoned; recover by taking the inner guard so subsequent tests can
        // continue instead of failing with a poison error.
        let _guard = TEST_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        Tape::stop_recording();
        Tape::rewind_to_init();
        f();
        Tape::stop_recording();
    }

    #[test]
    fn compare_and_flatten() {
        with_tape_test(|| {
            let x = ADReal::new(5.0);
            let y = abs(x - 2.0);
            assert!(y > 2.0); // value-based comparison
            let z: ADReal = (y + 1.0).into();
            assert_eq!(z.value(), 4.0);
        });
    }

    #[test]
    fn backprop_basic() {
        with_tape_test(|| {
            Tape::start_recording();
            let a = ADReal::new(3.0);
            let b = ADReal::new(4.0);
            let expr = (a * b).sin();
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }

    #[test]
    fn test_late_tape_recording() {
        with_tape_test(|| {
            let mut a = ADReal::new(3.0);
            // println!("a: {:?}", a);
            Tape::start_recording(); // start recording
            a.put_on_tape();
            // println!("a: {:?}", a);
            let expr = a * a;
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(a.adjoint().unwrap(), 6.0);
        });
    }

    #[test]
    fn backprop_with_const() {
        with_tape_test(|| {
            Tape::start_recording();
            let a = ADReal::new(3.0);
            let b = Const(4.0);
            let expr = (a * b).sin();
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }

    #[test]
    fn tape_reset() {
        with_tape_test(|| {
            Tape::start_recording();
            let a = ADReal::new(3.0);
            let b = ADReal::new(4.0);
            let expr = (a * b).sin();
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(out.adjoint().unwrap(), 1.0);

            Tape::reset_adjoints(); // reset adjoints
            assert_eq!(out.adjoint().unwrap(), 0.0); // should be zero now
        });
    }

    #[test]
    fn tape_propagate_mark() {
        with_tape_test(|| {
            Tape::start_recording();
            let a = ADReal::new(3.0);
            let b = ADReal::new(4.0);
            let expr = (a * b).sin();
            let out: ADReal = expr.into();
            out.backward_to_mark().unwrap(); // propagate to the current mark
            assert_eq!(out.adjoint().unwrap(), 1.0); // should be 1.0
        });
    }

    #[test]
    fn tape_backward_to_mark() {
        with_tape_test(|| {
            Tape::start_recording();
            let a = ADReal::new(3.0);
            let b = ADReal::new(4.0);
            let expr = (a * b).sin();
            let out: ADReal = expr.into();
            out.backward_to_mark().unwrap(); // propagate to the current mark
            assert_eq!(out.adjoint().unwrap(), 1.0); // should be 1.0

            out.backward().unwrap(); // propagate from mark to start
            assert_eq!(out.adjoint().unwrap(), 1.0); // should still be 1.0
        });
    }

    #[test]
    fn check_exp_derivate() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(2.0);
            let expr = exp(x);
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), f64::exp(2.0)); // derivative of exp(x) wrt x
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }

    #[test]
    fn check_log_derivative() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(2.0);
            let expr = log(x);
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), 1.0 / 2.0); // derivative of log(x) wrt x
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }
    #[test]
    fn check_sqrt_derivative() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(4.0);
            let expr = sqrt(x);
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), 0.5 / 2.0); // derivative of sqrt(x) wrt x
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }
    #[test]
    fn check_sin_derivative() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(0.0);
            let expr = sin(x);
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), 1.0); // derivative of sin(x) wrt x
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }
    #[test]
    fn check_cos_derivative() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(0.0);
            let expr = cos(x);
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), 0.0); // derivative of cos(x) wrt x
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }
    #[test]
    fn check_abs_derivative() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(-3.0);
            let expr = abs(x);
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), -1.0); // derivative of abs(x) wrt x
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }
    #[test]
    fn check_pow_derivative() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(2.0);
            let expr = pow(x, Const(3.0));
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), 3.0 * 2.0f64.powi(2)); // derivative of x^3 wrt x at x=2
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }
    #[test]
    fn check_max_derivative() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(2.0);
            let y = ADReal::new(3.0);
            let expr = max(x, y);
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), 0.0); // derivative wrt x
            assert_eq!(y.adjoint().unwrap(), 1.0); // derivative wrt y
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }
    #[test]
    fn check_min_derivative() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(2.0);
            let y = ADReal::new(3.0);
            let expr = min(x, y);
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), 1.0); // derivative wrt x
            assert_eq!(y.adjoint().unwrap(), 0.0); // derivative wrt y
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }
    #[test]
    fn check_flattening() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(5.0);
            let y = ADReal::new(3.0);
            let expr = (x + y) * 2.0;
            let out: ADReal = expr.into();
            assert_eq!(out.value(), 16.0); // (5 + 3) * 2 = 16
            out.backward().unwrap();
            assert_eq!(out.adjoint().unwrap(), 1.0); // should be 1.0 after propagation
        });
    }

    #[test]
    fn check_add_derivative() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(2.0);
            let y = ADReal::new(3.0);
            let expr = x + y;
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), 1.0);
            assert_eq!(y.adjoint().unwrap(), 1.0);
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }

    #[test]
    fn check_sub_derivative() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(5.0);
            let y = ADReal::new(2.0);
            let expr = x - y;
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), 1.0);
            assert_eq!(y.adjoint().unwrap(), -1.0);
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }

    #[test]
    fn check_mul_derivative() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(4.0);
            let y = ADReal::new(2.0);
            let expr = x * y;
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), 2.0);
            assert_eq!(y.adjoint().unwrap(), 4.0);
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }

    #[test]
    fn check_div_derivative() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(6.0);
            let y = ADReal::new(3.0);
            let expr = x / y;
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert!((x.adjoint().unwrap() - (1.0 / 3.0)).abs() < 1e-12);
            assert!((y.adjoint().unwrap() + (6.0 / 9.0)).abs() < 1e-12);
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }

    #[test]
    fn check_fabs_derivative() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(-2.0);
            let expr = fabs(x);
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), -1.0);
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }

    #[test]
    fn check_pow_variable_exponent() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(2.0);
            let y = ADReal::new(3.0);
            let expr = pow(x, y);
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), 3.0 * 2.0f64.powi(2));
            assert!(8.0f64.mul_add(-2.0f64.ln(), y.adjoint().unwrap()).abs() < 1e-12);
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }

    #[test]
    fn check_max_derivative_x_greater() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(5.0);
            let y = ADReal::new(3.0);
            let expr = max(x, y);
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), 1.0);
            assert_eq!(y.adjoint().unwrap(), 0.0);
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }

    #[test]
    fn check_min_derivative_y_less() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(5.0);
            let y = ADReal::new(3.0);
            let expr = min(x, y);
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), 0.0);
            assert_eq!(y.adjoint().unwrap(), 1.0);
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }

    #[test]
    fn check_abs_positive_derivative() {
        with_tape_test(|| {
            Tape::start_recording();
            let x = ADReal::new(3.0);
            let expr = abs(x);
            let out: ADReal = expr.into();
            out.backward().unwrap();
            assert_eq!(x.adjoint().unwrap(), 1.0);
            assert_eq!(out.adjoint().unwrap(), 1.0);
        });
    }

    #[test]
    fn test_reassigning() {
        with_tape_test(|| {
            Tape::start_recording();

            let a0 = ADReal::new(5.0);
            let b = ADReal::new(3.0);
            let mut a = a0;
            a *= b;
            let c = a;
            assert_eq!(c.value(), 15.0);

            c.backward().unwrap();

            assert_eq!(a0.adjoint().unwrap(), 3.0);
            assert_eq!(b.adjoint().unwrap(), 5.0);
            assert_eq!(c.adjoint().unwrap(), 1.0);
        });
    }

    #[test]
    fn multithread_recording_derivatives() {
        with_tape_test(|| {
            let handle = std::thread::spawn(|| {
                Tape::start_recording();
                let x = ADReal::new(2.0);
                let y = ADReal::new(3.0);
                let expr = x * y + x;
                let out: ADReal = expr.into();
                out.backward().unwrap();
                (
                    x.adjoint().unwrap(),
                    y.adjoint().unwrap(),
                    out.adjoint().unwrap(),
                )
            });

            let (dx, dy, dout) = handle.join().unwrap();
            assert_eq!(dx, 4.0);
            assert_eq!(dy, 2.0);
            assert_eq!(dout, 1.0);
        });
    }
}