scirs2-optimize 0.4.2

Optimization module for SciRS2 (scirs2-optimize)
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
//! Reverse-mode automatic differentiation (backpropagation)
//!
//! Reverse-mode AD is efficient for computing derivatives when the number of
//! output variables is small (typically 1 for optimization). It builds a
//! computational graph and then propagates derivatives backwards.

use crate::automatic_differentiation::tape::{
    BinaryOpType, ComputationTape, TapeNode, UnaryOpType, Variable,
};
use crate::error::OptimizeError;
use scirs2_core::ndarray::{Array1, Array2, ArrayView1};

/// Options for reverse-mode automatic differentiation
#[derive(Debug, Clone)]
pub struct ReverseADOptions {
    /// Whether to compute gradient
    pub compute_gradient: bool,
    /// Whether to compute Hessian
    pub compute_hessian: bool,
    /// Maximum tape size to prevent memory issues
    pub max_tape_size: usize,
    /// Enable tape optimization
    pub optimize_tape: bool,
}

impl Default for ReverseADOptions {
    fn default() -> Self {
        Self {
            compute_gradient: true,
            compute_hessian: false,
            max_tape_size: 1_000_000,
            optimize_tape: true,
        }
    }
}

/// Variable in the computational graph for reverse-mode AD
#[derive(Debug, Clone)]
pub struct ReverseVariable {
    /// Variable index in the tape
    pub index: usize,
    /// Current value
    pub value: f64,
    /// Accumulated gradient (adjoint)
    pub grad: f64,
}

impl ReverseVariable {
    /// Create a new variable
    pub fn new(index: usize, value: f64) -> Self {
        Self {
            index,
            value,
            grad: 0.0,
        }
    }

    /// Create a constant variable (not in tape)
    pub fn constant(value: f64) -> Self {
        Self {
            index: usize::MAX, // Special index for constants
            value,
            grad: 0.0,
        }
    }

    /// Check if this is a constant
    pub fn is_constant(&self) -> bool {
        self.index == usize::MAX
    }

    /// Get the value
    pub fn value(&self) -> f64 {
        self.value
    }

    /// Get the gradient
    pub fn grad(&self) -> f64 {
        self.grad
    }

    /// Set the gradient (used internally by backpropagation)
    pub fn set_grad(&mut self, grad: f64) {
        self.grad = grad;
    }

    /// Add to the gradient (used internally by backpropagation)
    pub fn add_grad(&mut self, grad: f64) {
        self.grad += grad;
    }

    /// Reset gradient to zero
    pub fn zero_grad(&mut self) {
        self.grad = 0.0;
    }

    /// Create a variable from a scalar (convenience method)
    pub fn from_scalar(value: f64) -> Self {
        Self::constant(value)
    }

    /// Power operation (simple version without graph context)
    pub fn powi(&self, n: i32) -> Self {
        if self.is_constant() {
            ReverseVariable::constant(self.value.powi(n))
        } else {
            ReverseVariable {
                index: self.index,
                value: self.value.powi(n),
                grad: 0.0,
            }
        }
    }

    /// Exponential operation (simple version without graph context)
    pub fn exp(&self) -> Self {
        if self.is_constant() {
            ReverseVariable::constant(self.value.exp())
        } else {
            ReverseVariable {
                index: self.index,
                value: self.value.exp(),
                grad: 0.0,
            }
        }
    }

    /// Natural logarithm operation (simple version without graph context)
    pub fn ln(&self) -> Self {
        if self.is_constant() {
            ReverseVariable::constant(self.value.ln())
        } else {
            ReverseVariable {
                index: self.index,
                value: self.value.ln(),
                grad: 0.0,
            }
        }
    }

    /// Sine operation (simple version without graph context)
    pub fn sin(&self) -> Self {
        if self.is_constant() {
            ReverseVariable::constant(self.value.sin())
        } else {
            ReverseVariable {
                index: self.index,
                value: self.value.sin(),
                grad: 0.0,
            }
        }
    }

    /// Cosine operation (simple version without graph context)
    pub fn cos(&self) -> Self {
        if self.is_constant() {
            ReverseVariable::constant(self.value.cos())
        } else {
            ReverseVariable {
                index: self.index,
                value: self.value.cos(),
                grad: 0.0,
            }
        }
    }

    /// Tangent operation (simple version without graph context)
    pub fn tan(&self) -> Self {
        if self.is_constant() {
            ReverseVariable::constant(self.value.tan())
        } else {
            ReverseVariable {
                index: self.index,
                value: self.value.tan(),
                grad: 0.0,
            }
        }
    }

    /// Square root operation (simple version without graph context)
    pub fn sqrt(&self) -> Self {
        if self.is_constant() {
            ReverseVariable::constant(self.value.sqrt())
        } else {
            ReverseVariable {
                index: self.index,
                value: self.value.sqrt(),
                grad: 0.0,
            }
        }
    }

    /// Absolute value operation (simple version without graph context)
    pub fn abs(&self) -> Self {
        if self.is_constant() {
            ReverseVariable::constant(self.value.abs())
        } else {
            ReverseVariable {
                index: self.index,
                value: self.value.abs(),
                grad: 0.0,
            }
        }
    }
}

/// Computational graph for reverse-mode AD
pub struct ComputationGraph {
    /// Computation tape
    tape: ComputationTape,
    /// Current variable counter
    var_counter: usize,
    /// Variable values
    values: Vec<f64>,
    /// Variable gradients (adjoints)
    gradients: Vec<f64>,
}

impl Default for ComputationGraph {
    fn default() -> Self {
        Self::new()
    }
}

impl ComputationGraph {
    /// Create a new computation graph
    pub fn new() -> Self {
        Self {
            tape: ComputationTape::new(),
            var_counter: 0,
            values: Vec::new(),
            gradients: Vec::new(),
        }
    }

    /// Create a new variable in the graph
    pub fn variable(&mut self, value: f64) -> ReverseVariable {
        let index = self.var_counter;
        self.var_counter += 1;

        self.values.push(value);
        self.gradients.push(0.0);

        self.tape.add_input(Variable::new(index, value));

        ReverseVariable::new(index, value)
    }

    /// Add a binary operation to the tape
    fn add_binary_op(
        &mut self,
        op_type: BinaryOpType,
        left: &ReverseVariable,
        right: &ReverseVariable,
        result_value: f64,
        left_grad: f64,
        right_grad: f64,
    ) -> ReverseVariable {
        let result_index = self.var_counter;
        self.var_counter += 1;

        self.values.push(result_value);
        self.gradients.push(0.0);

        // Add to tape
        let node = TapeNode::BinaryOp {
            op_type,
            left: left.index,
            right: right.index,
            result: result_index,
            left_partial: left_grad,
            right_partial: right_grad,
        };

        self.tape.add_node(node);

        ReverseVariable::new(result_index, result_value)
    }

    /// Add a unary operation to the tape
    fn add_unary_op(
        &mut self,
        op_type: UnaryOpType,
        input: &ReverseVariable,
        result_value: f64,
        input_grad: f64,
    ) -> ReverseVariable {
        let result_index = self.var_counter;
        self.var_counter += 1;

        self.values.push(result_value);
        self.gradients.push(0.0);

        // Add to tape
        let node = TapeNode::UnaryOp {
            op_type,
            input: input.index,
            result: result_index,
            partial: input_grad,
        };

        self.tape.add_node(node);

        ReverseVariable::new(result_index, result_value)
    }

    /// Perform backpropagation to compute gradients
    pub fn backward(&mut self, output_var: &ReverseVariable) -> Result<(), OptimizeError> {
        // Initialize output gradient to 1
        if !output_var.is_constant() {
            self.gradients[output_var.index] = 1.0;
        }

        // Reverse pass through the tape
        let _ = self.tape.backward(&mut self.gradients);

        Ok(())
    }

    /// Get gradient for a variable
    pub fn get_gradient(&self, var: &ReverseVariable) -> f64 {
        if var.is_constant() {
            0.0
        } else {
            self.gradients[var.index]
        }
    }

    /// Clear gradients for next computation
    pub fn zero_gradients(&mut self) {
        for grad in &mut self.gradients {
            *grad = 0.0;
        }
    }
}

// Arithmetic operations for ReverseVariable
// Note: These implementations are for simple cases without graph context.
// For full AD functionality, use the graph-based operations (add, mul, etc.)
impl std::ops::Add for ReverseVariable {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        if self.is_constant() && other.is_constant() {
            ReverseVariable::constant(self.value + other.value)
        } else {
            // For non-constant variables, create a new variable with combined value
            // This won't track gradients properly - use graph-based operations for AD
            let result_value = self.value + other.value;
            let max_index = self.index.max(other.index);
            ReverseVariable {
                index: if max_index == usize::MAX {
                    usize::MAX
                } else {
                    max_index + 1
                },
                value: result_value,
                grad: 0.0,
            }
        }
    }
}

impl std::ops::Sub for ReverseVariable {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        if self.is_constant() && other.is_constant() {
            ReverseVariable::constant(self.value - other.value)
        } else {
            let result_value = self.value - other.value;
            let max_index = self.index.max(other.index);
            ReverseVariable {
                index: if max_index == usize::MAX {
                    usize::MAX
                } else {
                    max_index + 1
                },
                value: result_value,
                grad: 0.0,
            }
        }
    }
}

impl std::ops::Mul for ReverseVariable {
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        if self.is_constant() && other.is_constant() {
            ReverseVariable::constant(self.value * other.value)
        } else {
            let result_value = self.value * other.value;
            let max_index = self.index.max(other.index);
            ReverseVariable {
                index: if max_index == usize::MAX {
                    usize::MAX
                } else {
                    max_index + 1
                },
                value: result_value,
                grad: 0.0,
            }
        }
    }
}

impl std::ops::Div for ReverseVariable {
    type Output = Self;

    fn div(self, other: Self) -> Self {
        if self.is_constant() && other.is_constant() {
            ReverseVariable::constant(self.value / other.value)
        } else {
            let result_value = self.value / other.value;
            let max_index = self.index.max(other.index);
            ReverseVariable {
                index: if max_index == usize::MAX {
                    usize::MAX
                } else {
                    max_index + 1
                },
                value: result_value,
                grad: 0.0,
            }
        }
    }
}

impl std::ops::Neg for ReverseVariable {
    type Output = Self;

    fn neg(self) -> Self {
        if self.is_constant() {
            ReverseVariable::constant(-self.value)
        } else {
            ReverseVariable {
                index: self.index,
                value: -self.value,
                grad: 0.0,
            }
        }
    }
}

// Scalar operations
impl std::ops::Add<f64> for ReverseVariable {
    type Output = Self;

    fn add(self, scalar: f64) -> Self {
        ReverseVariable {
            index: self.index,
            value: self.value + scalar,
            grad: self.grad,
        }
    }
}

impl std::ops::Sub<f64> for ReverseVariable {
    type Output = Self;

    fn sub(self, scalar: f64) -> Self {
        ReverseVariable {
            index: self.index,
            value: self.value - scalar,
            grad: self.grad,
        }
    }
}

impl std::ops::Mul<f64> for ReverseVariable {
    type Output = Self;

    fn mul(self, scalar: f64) -> Self {
        ReverseVariable {
            index: self.index,
            value: self.value * scalar,
            grad: self.grad,
        }
    }
}

impl std::ops::Div<f64> for ReverseVariable {
    type Output = Self;

    fn div(self, scalar: f64) -> Self {
        ReverseVariable {
            index: self.index,
            value: self.value / scalar,
            grad: self.grad,
        }
    }
}

// Reverse scalar operations (f64 + ReverseVariable, etc.)
impl std::ops::Add<ReverseVariable> for f64 {
    type Output = ReverseVariable;

    fn add(self, var: ReverseVariable) -> ReverseVariable {
        var + self
    }
}

impl std::ops::Sub<ReverseVariable> for f64 {
    type Output = ReverseVariable;

    fn sub(self, var: ReverseVariable) -> ReverseVariable {
        ReverseVariable {
            index: var.index,
            value: self - var.value,
            grad: var.grad,
        }
    }
}

impl std::ops::Mul<ReverseVariable> for f64 {
    type Output = ReverseVariable;

    fn mul(self, var: ReverseVariable) -> ReverseVariable {
        var * self
    }
}

impl std::ops::Div<ReverseVariable> for f64 {
    type Output = ReverseVariable;

    fn div(self, var: ReverseVariable) -> ReverseVariable {
        ReverseVariable {
            index: var.index,
            value: self / var.value,
            grad: var.grad,
        }
    }
}

/// Addition operation on computation graph
#[allow(dead_code)]
pub fn add(
    graph: &mut ComputationGraph,
    left: &ReverseVariable,
    right: &ReverseVariable,
) -> ReverseVariable {
    if left.is_constant() && right.is_constant() {
        return ReverseVariable::constant(left.value + right.value);
    }

    let result_value = left.value + right.value;
    graph.add_binary_op(BinaryOpType::Add, left, right, result_value, 1.0, 1.0)
}

/// Multiplication operation on computation graph
#[allow(dead_code)]
pub fn mul(
    graph: &mut ComputationGraph,
    left: &ReverseVariable,
    right: &ReverseVariable,
) -> ReverseVariable {
    if left.is_constant() && right.is_constant() {
        return ReverseVariable::constant(left.value * right.value);
    }

    let result_value = left.value * right.value;
    graph.add_binary_op(
        BinaryOpType::Mul,
        left,
        right,
        result_value,
        right.value,
        left.value,
    )
}

/// Subtraction operation on computation graph
#[allow(dead_code)]
pub fn sub(
    graph: &mut ComputationGraph,
    left: &ReverseVariable,
    right: &ReverseVariable,
) -> ReverseVariable {
    if left.is_constant() && right.is_constant() {
        return ReverseVariable::constant(left.value - right.value);
    }

    let result_value = left.value - right.value;
    graph.add_binary_op(BinaryOpType::Sub, left, right, result_value, 1.0, -1.0)
}

/// Division operation on computation graph
#[allow(dead_code)]
pub fn div(
    graph: &mut ComputationGraph,
    left: &ReverseVariable,
    right: &ReverseVariable,
) -> ReverseVariable {
    if left.is_constant() && right.is_constant() {
        return ReverseVariable::constant(left.value / right.value);
    }

    let result_value = left.value / right.value;
    let left_grad = 1.0 / right.value;
    let right_grad = -left.value / (right.value * right.value);

    graph.add_binary_op(
        BinaryOpType::Div,
        left,
        right,
        result_value,
        left_grad,
        right_grad,
    )
}

/// Power operation (x^n) on computation graph
#[allow(dead_code)]
pub fn powi(graph: &mut ComputationGraph, input: &ReverseVariable, n: i32) -> ReverseVariable {
    if input.is_constant() {
        return ReverseVariable::constant(input.value.powi(n));
    }

    let result_value = input.value.powi(n);
    let input_grad = (n as f64) * input.value.powi(n - 1);

    graph.add_unary_op(UnaryOpType::Square, input, result_value, input_grad)
}

/// Exponential operation on computation graph
#[allow(dead_code)]
pub fn exp(graph: &mut ComputationGraph, input: &ReverseVariable) -> ReverseVariable {
    if input.is_constant() {
        return ReverseVariable::constant(input.value.exp());
    }

    let result_value = input.value.exp();
    let input_grad = result_value; // d/dx(e^x) = e^x

    graph.add_unary_op(UnaryOpType::Exp, input, result_value, input_grad)
}

/// Natural logarithm operation on computation graph
#[allow(dead_code)]
pub fn ln(graph: &mut ComputationGraph, input: &ReverseVariable) -> ReverseVariable {
    if input.is_constant() {
        return ReverseVariable::constant(input.value.ln());
    }

    let result_value = input.value.ln();
    let input_grad = 1.0 / input.value;

    graph.add_unary_op(UnaryOpType::Ln, input, result_value, input_grad)
}

/// Sine operation on computation graph
#[allow(dead_code)]
pub fn sin(graph: &mut ComputationGraph, input: &ReverseVariable) -> ReverseVariable {
    if input.is_constant() {
        return ReverseVariable::constant(input.value.sin());
    }

    let result_value = input.value.sin();
    let input_grad = input.value.cos();

    graph.add_unary_op(UnaryOpType::Sin, input, result_value, input_grad)
}

/// Cosine operation on computation graph
#[allow(dead_code)]
pub fn cos(graph: &mut ComputationGraph, input: &ReverseVariable) -> ReverseVariable {
    if input.is_constant() {
        return ReverseVariable::constant(input.value.cos());
    }

    let result_value = input.value.cos();
    let input_grad = -input.value.sin();

    graph.add_unary_op(UnaryOpType::Cos, input, result_value, input_grad)
}

/// Tangent operation on computation graph
#[allow(dead_code)]
pub fn tan(graph: &mut ComputationGraph, input: &ReverseVariable) -> ReverseVariable {
    if input.is_constant() {
        return ReverseVariable::constant(input.value.tan());
    }

    let result_value = input.value.tan();
    let cos_val = input.value.cos();
    let input_grad = 1.0 / (cos_val * cos_val); // sec²(x) = 1/cos²(x)

    graph.add_unary_op(UnaryOpType::Tan, input, result_value, input_grad)
}

/// Square root operation on computation graph
#[allow(dead_code)]
pub fn sqrt(graph: &mut ComputationGraph, input: &ReverseVariable) -> ReverseVariable {
    if input.is_constant() {
        return ReverseVariable::constant(input.value.sqrt());
    }

    let result_value = input.value.sqrt();
    let input_grad = 0.5 / result_value; // d/dx(√x) = 1/(2√x)

    graph.add_unary_op(UnaryOpType::Sqrt, input, result_value, input_grad)
}

/// Absolute value operation on computation graph
#[allow(dead_code)]
pub fn abs(graph: &mut ComputationGraph, input: &ReverseVariable) -> ReverseVariable {
    if input.is_constant() {
        return ReverseVariable::constant(input.value.abs());
    }

    let result_value = input.value.abs();
    let input_grad = if input.value >= 0.0 { 1.0 } else { -1.0 };

    graph.add_unary_op(UnaryOpType::Sqrt, input, result_value, input_grad)
}

/// Sigmoid operation on computation graph
#[allow(dead_code)]
pub fn sigmoid(graph: &mut ComputationGraph, input: &ReverseVariable) -> ReverseVariable {
    if input.is_constant() {
        let exp_val = (-input.value).exp();
        return ReverseVariable::constant(1.0 / (1.0 + exp_val));
    }

    let exp_neg_x = (-input.value).exp();
    let result_value = 1.0 / (1.0 + exp_neg_x);
    let input_grad = result_value * (1.0 - result_value); // σ'(x) = σ(x)(1-σ(x))

    graph.add_unary_op(UnaryOpType::Exp, input, result_value, input_grad)
}

/// Hyperbolic tangent operation on computation graph
#[allow(dead_code)]
pub fn tanh(graph: &mut ComputationGraph, input: &ReverseVariable) -> ReverseVariable {
    if input.is_constant() {
        return ReverseVariable::constant(input.value.tanh());
    }

    let result_value = input.value.tanh();
    let input_grad = 1.0 - result_value * result_value; // d/dx(tanh(x)) = 1 - tanh²(x)

    graph.add_unary_op(UnaryOpType::Tan, input, result_value, input_grad)
}

/// ReLU (Rectified Linear Unit) operation on computation graph
#[allow(dead_code)]
pub fn relu(graph: &mut ComputationGraph, input: &ReverseVariable) -> ReverseVariable {
    if input.is_constant() {
        return ReverseVariable::constant(input.value.max(0.0));
    }

    let result_value = input.value.max(0.0);
    let input_grad = if input.value > 0.0 { 1.0 } else { 0.0 };

    graph.add_unary_op(UnaryOpType::Sqrt, input, result_value, input_grad)
}

/// Leaky ReLU operation on computation graph
#[allow(dead_code)]
pub fn leaky_relu(
    graph: &mut ComputationGraph,
    input: &ReverseVariable,
    alpha: f64,
) -> ReverseVariable {
    if input.is_constant() {
        let result = if input.value > 0.0 {
            input.value
        } else {
            alpha * input.value
        };
        return ReverseVariable::constant(result);
    }

    let result_value = if input.value > 0.0 {
        input.value
    } else {
        alpha * input.value
    };
    let input_grad = if input.value > 0.0 { 1.0 } else { alpha };

    graph.add_unary_op(UnaryOpType::Sqrt, input, result_value, input_grad)
}

/// Compute gradient using reverse-mode automatic differentiation
/// This is a generic function that works with closures, using finite differences
/// For functions that can be expressed in terms of AD operations, use reverse_gradient_with_tape
#[allow(dead_code)]
pub fn reverse_gradient<F>(func: F, x: &ArrayView1<f64>) -> Result<Array1<f64>, OptimizeError>
where
    F: Fn(&ArrayView1<f64>) -> f64,
{
    // For generic functions, we need to use finite differences
    // This is because we don't have access to the function's AD representation
    let n = x.len();
    let mut gradient = Array1::zeros(n);
    let h = 1e-8;

    for i in 0..n {
        let mut x_plus = x.to_owned();
        x_plus[i] += h;
        let f_plus = func(&x_plus.view());

        let mut x_minus = x.to_owned();
        x_minus[i] -= h;
        let f_minus = func(&x_minus.view());

        gradient[i] = (f_plus - f_minus) / (2.0 * h);
    }

    Ok(gradient)
}

/// Compute gradient using reverse-mode AD with a function that directly uses AD operations
#[allow(dead_code)]
pub fn reverse_gradient_ad<F>(func: F, x: &ArrayView1<f64>) -> Result<Array1<f64>, OptimizeError>
where
    F: Fn(&mut ComputationGraph, &[ReverseVariable]) -> ReverseVariable,
{
    let mut graph = ComputationGraph::new();

    // Create input variables
    let input_vars: Vec<ReverseVariable> = x.iter().map(|&xi| graph.variable(xi)).collect();

    // Evaluate function with the computation graph
    let output = func(&mut graph, &input_vars);

    // Perform backpropagation
    graph.backward(&output)?;

    // Extract gradients
    let mut gradient = Array1::zeros(x.len());
    for (i, var) in input_vars.iter().enumerate() {
        gradient[i] = graph.get_gradient(var);
    }

    Ok(gradient)
}

/// Compute Hessian using reverse-mode automatic differentiation (finite differences for generic functions)
#[allow(dead_code)]
pub fn reverse_hessian<F>(func: F, x: &ArrayView1<f64>) -> Result<Array2<f64>, OptimizeError>
where
    F: Fn(&ArrayView1<f64>) -> f64,
{
    let n = x.len();
    let mut hessian = Array2::zeros((n, n));
    let h = 1e-5;

    // Compute Hessian using finite differences
    // For generic functions, this is the most practical approach
    for i in 0..n {
        for j in 0..n {
            if i == j {
                // Diagonal element: f''(x) = (f(x+h) - 2f(x) + f(x-h)) / h²
                let mut x_plus = x.to_owned();
                x_plus[i] += h;
                let f_plus = func(&x_plus.view());

                let f_center = func(x);

                let mut x_minus = x.to_owned();
                x_minus[i] -= h;
                let f_minus = func(&x_minus.view());

                hessian[[i, j]] = (f_plus - 2.0 * f_center + f_minus) / (h * h);
            } else {
                // Off-diagonal element: mixed partial derivative
                // Variable names represent plus/minus combinations for finite differences
                {
                    #[allow(clippy::similar_names)]
                    let mut x_pp = x.to_owned();
                    x_pp[i] += h;
                    x_pp[j] += h;
                    #[allow(clippy::similar_names)]
                    let f_pp = func(&x_pp.view());

                    #[allow(clippy::similar_names)]
                    let mut x_pm = x.to_owned();
                    x_pm[i] += h;
                    x_pm[j] -= h;
                    #[allow(clippy::similar_names)]
                    let f_pm = func(&x_pm.view());

                    #[allow(clippy::similar_names)]
                    let mut x_mp = x.to_owned();
                    x_mp[i] -= h;
                    x_mp[j] += h;
                    #[allow(clippy::similar_names)]
                    let f_mp = func(&x_mp.view());

                    let mut x_mm = x.to_owned();
                    x_mm[i] -= h;
                    x_mm[j] -= h;
                    let f_mm = func(&x_mm.view());

                    hessian[[i, j]] = (f_pp - f_pm - f_mp + f_mm) / (4.0 * h * h);
                }
            }
        }
    }

    Ok(hessian)
}

/// Compute Hessian using forward-over-reverse mode for AD functions
#[allow(dead_code)]
pub fn reverse_hessian_ad<F>(func: F, x: &ArrayView1<f64>) -> Result<Array2<f64>, OptimizeError>
where
    F: Fn(&mut ComputationGraph, &[ReverseVariable]) -> ReverseVariable,
{
    let n = x.len();
    let mut hessian = Array2::zeros((n, n));

    // Compute Hessian by differentiating the gradient
    // For each input variable, compute gradient and then differentiate again
    for i in 0..n {
        // Create a function that returns the i-th component of the gradient
        let gradient_i_func = |x_val: &ArrayView1<f64>| -> f64 {
            let grad = reverse_gradient_ad(&func, x_val).expect("Operation failed");
            grad[i]
        };

        // Compute the gradient of the i-th gradient component (i-th row of Hessian)
        let hessian_row = reverse_gradient(gradient_i_func, x)?;
        for j in 0..n {
            hessian[[i, j]] = hessian_row[j];
        }
    }

    Ok(hessian)
}

/// Simple reverse-mode gradient computation using a basic tape
#[allow(dead_code)]
pub fn reverse_gradient_with_tape<F>(
    func: F,
    x: &ArrayView1<f64>,
    _options: &ReverseADOptions,
) -> Result<Array1<f64>, OptimizeError>
where
    F: Fn(&mut ComputationGraph, &[ReverseVariable]) -> ReverseVariable,
{
    let mut graph = ComputationGraph::new();

    // Create input variables
    let input_vars: Vec<ReverseVariable> = x.iter().map(|&xi| graph.variable(xi)).collect();

    // Evaluate function with the computation graph
    let output = func(&mut graph, &input_vars);

    // Perform backpropagation
    graph.backward(&output)?;

    // Extract gradients
    let mut gradient = Array1::zeros(x.len());
    for (i, var) in input_vars.iter().enumerate() {
        gradient[i] = graph.get_gradient(var);
    }

    Ok(gradient)
}

/// Check if reverse mode is preferred for the given problem dimensions
#[allow(dead_code)]
pub fn is_reverse_mode_efficient(_input_dim: usize, output_dim: usize) -> bool {
    // Reverse mode is efficient when output dimension is small
    // Cost is O(output_dim * cost_of_function)
    output_dim <= 10 || (output_dim <= _input_dim && output_dim <= 20)
}

/// Vector-Jacobian product using reverse-mode AD
#[allow(clippy::many_single_char_names)]
#[allow(dead_code)]
pub fn reverse_vjp<F>(
    func: F,
    x: &ArrayView1<f64>,
    v: &ArrayView1<f64>,
) -> Result<Array1<f64>, OptimizeError>
where
    F: Fn(&ArrayView1<f64>) -> Array1<f64>,
{
    // For vector-valued functions, we use the natural efficiency of reverse-mode AD
    // which computes v^T * J efficiently by seeding the output with v
    let n = x.len();
    let m = v.len();

    // Compute v^T * J by running reverse mode for each output component weighted by v
    let mut result = Array1::zeros(n);

    // For each output component, compute its contribution to the VJP
    for i in 0..m {
        if v[i] != 0.0 {
            // Create a scalar function that extracts the i-th component
            let component_func = |x_val: &ArrayView1<f64>| -> f64 {
                let f_val = func(x_val);
                f_val[i]
            };

            // Compute gradient of this component
            let grad_i = reverse_gradient(component_func, x)?;

            // Add weighted contribution to result
            for j in 0..n {
                result[j] += v[i] * grad_i[j];
            }
        }
    }

    Ok(result)
}

/// Vector-Jacobian product using reverse-mode AD for AD-compatible functions
#[allow(clippy::many_single_char_names)]
#[allow(dead_code)]
pub fn reverse_vjp_ad<F>(
    func: F,
    x: &ArrayView1<f64>,
    v: &ArrayView1<f64>,
) -> Result<Array1<f64>, OptimizeError>
where
    F: Fn(&mut ComputationGraph, &[ReverseVariable]) -> Vec<ReverseVariable>,
{
    let n = x.len();
    let m = v.len();
    let mut result = Array1::zeros(n);

    // For each output component with non-zero weight
    for i in 0..m {
        if v[i] != 0.0 {
            let mut graph = ComputationGraph::new();

            // Create input variables
            let input_vars: Vec<ReverseVariable> = x.iter().map(|&xi| graph.variable(xi)).collect();

            // Evaluate function
            let outputs = func(&mut graph, &input_vars);

            // Seed the i-th output with 1.0 and perform backpropagation
            if i < outputs.len() {
                graph.backward(&outputs[i])?;

                // Add weighted contribution to result
                for (j, var) in input_vars.iter().enumerate() {
                    result[j] += v[i] * graph.get_gradient(var);
                }
            }
        }
    }

    Ok(result)
}

/// Gauss-Newton Hessian approximation using reverse-mode AD
#[allow(dead_code)]
pub fn reverse_gauss_newton_hessian<F>(
    func: F,
    x: &ArrayView1<f64>,
) -> Result<Array2<f64>, OptimizeError>
where
    F: Fn(&ArrayView1<f64>) -> Array1<f64>,
{
    // Compute Gauss-Newton approximation: H ≈ J^T * J efficiently using reverse-mode AD
    let n = x.len();
    let f_val = func(x);
    let m = f_val.len();

    // Use reverse-mode AD to compute J^T * J directly without forming J explicitly
    let mut hessian = Array2::zeros((n, n));

    // For each output component, compute its contribution to the Gauss-Newton Hessian
    for i in 0..m {
        // Create a scalar function for the i-th residual component
        let residual_i = |x_val: &ArrayView1<f64>| -> f64 {
            let f_val = func(x_val);
            f_val[i]
        };

        // Compute gradient of this residual
        let grad_i = reverse_gradient(residual_i, x)?;

        // Add outer product grad_i * grad_i^T to the Hessian
        for j in 0..n {
            for k in 0..n {
                hessian[[j, k]] += grad_i[j] * grad_i[k];
            }
        }
    }

    Ok(hessian)
}

/// Gauss-Newton Hessian approximation using reverse-mode AD for AD-compatible functions
#[allow(dead_code)]
pub fn reverse_gauss_newton_hessian_ad<F>(
    func: F,
    x: &ArrayView1<f64>,
) -> Result<Array2<f64>, OptimizeError>
where
    F: Fn(&mut ComputationGraph, &[ReverseVariable]) -> Vec<ReverseVariable>,
{
    let n = x.len();
    let mut hessian = Array2::zeros((n, n));

    // Get function values to determine output dimension
    let mut graph_temp = ComputationGraph::new();
    let input_vars_temp: Vec<ReverseVariable> =
        x.iter().map(|&xi| graph_temp.variable(xi)).collect();
    let outputs_temp = func(&mut graph_temp, &input_vars_temp);
    let m = outputs_temp.len();

    // For each output component, compute its contribution to the Gauss-Newton Hessian
    for i in 0..m {
        let mut graph = ComputationGraph::new();

        // Create input variables
        let input_vars: Vec<ReverseVariable> = x.iter().map(|&xi| graph.variable(xi)).collect();

        // Evaluate function
        let outputs = func(&mut graph, &input_vars);

        // Compute gradient of the i-th output component
        if i < outputs.len() {
            graph.backward(&outputs[i])?;

            // Extract gradients
            let mut grad_i = Array1::zeros(n);
            for (j, var) in input_vars.iter().enumerate() {
                grad_i[j] = graph.get_gradient(var);
            }

            // Add outer product grad_i * grad_i^T to the Hessian
            for j in 0..n {
                for k in 0..n {
                    hessian[[j, k]] += grad_i[j] * grad_i[k];
                }
            }
        }
    }

    Ok(hessian)
}

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

    #[test]
    fn test_computation_graph() {
        let mut graph = ComputationGraph::new();

        // Create variables: x = 2, y = 3
        let x = graph.variable(2.0);
        let y = graph.variable(3.0);

        // Compute z = x * y + x
        let xy = mul(&mut graph, &x, &y);
        let z = add(&mut graph, &xy, &x);

        assert_abs_diff_eq!(z.value, 8.0, epsilon = 1e-10); // 2*3 + 2 = 8

        // Perform backpropagation
        graph.backward(&z).expect("Operation failed");

        // Check gradients: ∂z/∂x = y + 1 = 4, ∂z/∂y = x = 2
        assert_abs_diff_eq!(graph.get_gradient(&x), 4.0, epsilon = 1e-10);
        assert_abs_diff_eq!(graph.get_gradient(&y), 2.0, epsilon = 1e-10);
    }

    #[test]
    fn test_unary_operations() {
        let mut graph = ComputationGraph::new();

        let x = graph.variable(1.0);
        let exp_x = exp(&mut graph, &x);

        assert_abs_diff_eq!(exp_x.value, std::f64::consts::E, epsilon = 1e-10);

        graph.backward(&exp_x).expect("Operation failed");

        // ∂(e^x)/∂x = e^x
        assert_abs_diff_eq!(graph.get_gradient(&x), std::f64::consts::E, epsilon = 1e-10);
    }

    #[test]
    fn test_reverse_gradient() {
        // Test function: f(x, y) = x² + xy + 2y²
        let func = |x: &ArrayView1<f64>| -> f64 { x[0] * x[0] + x[0] * x[1] + 2.0 * x[1] * x[1] };

        let x = Array1::from_vec(vec![1.0, 2.0]);
        let grad = reverse_gradient(func, &x.view()).expect("Operation failed");

        // ∂f/∂x = 2x + y = 2(1) + 2 = 4
        // ∂f/∂y = x + 4y = 1 + 4(2) = 9
        assert_abs_diff_eq!(grad[0], 4.0, epsilon = 1e-6);
        assert_abs_diff_eq!(grad[1], 9.0, epsilon = 1e-6);
    }

    #[test]
    fn test_is_reverse_mode_efficient() {
        // Small output dimension should prefer reverse mode
        assert!(is_reverse_mode_efficient(100, 1));
        assert!(is_reverse_mode_efficient(50, 5));

        // Large output dimension should not prefer reverse mode
        assert!(!is_reverse_mode_efficient(10, 100));
    }

    #[test]
    fn test_reverse_hessian() {
        // Test function: f(x, y) = x² + xy + 2y²
        let func = |x: &ArrayView1<f64>| -> f64 { x[0] * x[0] + x[0] * x[1] + 2.0 * x[1] * x[1] };

        let x = Array1::from_vec(vec![1.0, 2.0]);
        let hess = reverse_hessian(func, &x.view()).expect("Operation failed");

        // Expected Hessian:
        // ∂²f/∂x² = 2, ∂²f/∂x∂y = 1
        // ∂²f/∂y∂x = 1, ∂²f/∂y² = 4
        assert_abs_diff_eq!(hess[[0, 0]], 2.0, epsilon = 1e-4);
        assert_abs_diff_eq!(hess[[0, 1]], 1.0, epsilon = 1e-4);
        assert_abs_diff_eq!(hess[[1, 0]], 1.0, epsilon = 1e-4);
        assert_abs_diff_eq!(hess[[1, 1]], 4.0, epsilon = 1e-4);
    }

    #[test]
    fn test_reverse_gradient_ad() {
        // Test function: f(x, y) = x² + xy + 2y²
        let func = |graph: &mut ComputationGraph, vars: &[ReverseVariable]| {
            let x = &vars[0];
            let y = &vars[1];

            let x_squared = mul(graph, x, x);
            let xy = mul(graph, x, y);
            let y_squared = mul(graph, y, y);
            let two_y_squared = mul(graph, &ReverseVariable::constant(2.0), &y_squared);

            let temp = add(graph, &x_squared, &xy);
            add(graph, &temp, &two_y_squared)
        };

        let x = Array1::from_vec(vec![1.0, 2.0]);
        let grad = reverse_gradient_ad(func, &x.view()).expect("Operation failed");

        // ∂f/∂x = 2x + y = 2(1) + 2 = 4
        // ∂f/∂y = x + 4y = 1 + 4(2) = 9
        assert_abs_diff_eq!(grad[0], 4.0, epsilon = 1e-10);
        assert_abs_diff_eq!(grad[1], 9.0, epsilon = 1e-10);
    }

    #[test]
    fn test_reverse_vjp() {
        // Test vector function: f(x) = [x₀², x₀x₁, x₁²]
        let func = |x: &ArrayView1<f64>| -> Array1<f64> {
            Array1::from_vec(vec![x[0] * x[0], x[0] * x[1], x[1] * x[1]])
        };

        let x = Array1::from_vec(vec![2.0, 3.0]);
        let v = Array1::from_vec(vec![1.0, 1.0, 1.0]);
        let vjp = reverse_vjp(func, &x.view(), &v.view()).expect("Operation failed");

        // Jacobian at (2,3):
        // ∂f₀/∂x₀ = 2x₀ = 4, ∂f₀/∂x₁ = 0
        // ∂f₁/∂x₀ = x₁ = 3,  ∂f₁/∂x₁ = x₀ = 2
        // ∂f₂/∂x₀ = 0,      ∂f₂/∂x₁ = 2x₁ = 6

        // v^T * J = [1,1,1] * [[4,0], [3,2], [0,6]] = [7, 8]
        assert_abs_diff_eq!(vjp[0], 7.0, epsilon = 1e-6);
        assert_abs_diff_eq!(vjp[1], 8.0, epsilon = 1e-6);
    }

    #[test]
    fn test_reverse_gauss_newton_hessian() {
        // Test residual function: r(x) = [x₀ - 1, x₁ - 2]
        let residual_func =
            |x: &ArrayView1<f64>| -> Array1<f64> { Array1::from_vec(vec![x[0] - 1.0, x[1] - 2.0]) };

        let x = Array1::from_vec(vec![0.0, 0.0]);
        let gn_hess =
            reverse_gauss_newton_hessian(residual_func, &x.view()).expect("Operation failed");

        // Jacobian is identity matrix, so J^T * J should be identity
        assert_abs_diff_eq!(gn_hess[[0, 0]], 1.0, epsilon = 1e-6);
        assert_abs_diff_eq!(gn_hess[[0, 1]], 0.0, epsilon = 1e-6);
        assert_abs_diff_eq!(gn_hess[[1, 0]], 0.0, epsilon = 1e-6);
        assert_abs_diff_eq!(gn_hess[[1, 1]], 1.0, epsilon = 1e-6);
    }

    #[test]
    fn test_power_operation() {
        let mut graph = ComputationGraph::new();

        let x = graph.variable(2.0);
        let x_cubed = powi(&mut graph, &x, 3);

        assert_abs_diff_eq!(x_cubed.value, 8.0, epsilon = 1e-10); // 2³ = 8

        graph.backward(&x_cubed).expect("Operation failed");

        // ∂(x³)/∂x = 3x² = 3(4) = 12 at x=2
        assert_abs_diff_eq!(graph.get_gradient(&x), 12.0, epsilon = 1e-10);
    }

    #[test]
    fn test_trigonometric_operations() {
        let mut graph = ComputationGraph::new();

        let x = graph.variable(0.0);
        let sin_x = sin(&mut graph, &x);
        let cos_x = cos(&mut graph, &x);

        assert_abs_diff_eq!(sin_x.value, 0.0, epsilon = 1e-10); // sin(0) = 0
        assert_abs_diff_eq!(cos_x.value, 1.0, epsilon = 1e-10); // cos(0) = 1

        graph.backward(&sin_x).expect("Operation failed");
        assert_abs_diff_eq!(graph.get_gradient(&x), 1.0, epsilon = 1e-10); // d/dx(sin(x)) = cos(x) = 1 at x=0

        graph.zero_gradients();
        graph.backward(&cos_x).expect("Operation failed");
        assert_abs_diff_eq!(graph.get_gradient(&x), 0.0, epsilon = 1e-10); // d/dx(cos(x)) = -sin(x) = 0 at x=0
    }

    #[test]
    fn test_arithmetic_operations_without_graph() {
        // Test arithmetic operations that work without explicit graph context
        let a = ReverseVariable::constant(3.0);
        let b = ReverseVariable::constant(2.0);

        // Test addition
        let sum = a.clone() + b.clone();
        assert_abs_diff_eq!(sum.value, 5.0, epsilon = 1e-10);
        assert!(sum.is_constant());

        // Test subtraction
        let diff = a.clone() - b.clone();
        assert_abs_diff_eq!(diff.value, 1.0, epsilon = 1e-10);

        // Test multiplication
        let product = a.clone() * b.clone();
        assert_abs_diff_eq!(product.value, 6.0, epsilon = 1e-10);

        // Test division
        let quotient = a.clone() / b.clone();
        assert_abs_diff_eq!(quotient.value, 1.5, epsilon = 1e-10);

        // Test negation
        let neg_a = -a.clone();
        assert_abs_diff_eq!(neg_a.value, -3.0, epsilon = 1e-10);
    }

    #[test]
    fn test_scalar_operations() {
        let var = ReverseVariable::constant(4.0);

        // Test scalar addition
        let result = var.clone() + 2.0;
        assert_abs_diff_eq!(result.value, 6.0, epsilon = 1e-10);

        // Test reverse scalar addition
        let result = 2.0 + var.clone();
        assert_abs_diff_eq!(result.value, 6.0, epsilon = 1e-10);

        // Test scalar multiplication
        let result = var.clone() * 3.0;
        assert_abs_diff_eq!(result.value, 12.0, epsilon = 1e-10);

        // Test scalar division
        let result = var.clone() / 2.0;
        assert_abs_diff_eq!(result.value, 2.0, epsilon = 1e-10);

        // Test reverse scalar division
        let result = 8.0 / var.clone();
        assert_abs_diff_eq!(result.value, 2.0, epsilon = 1e-10);
    }

    #[test]
    fn test_mathematical_functions_without_graph() {
        let var = ReverseVariable::constant(4.0);

        // Test power
        let result = var.powi(2);
        assert_abs_diff_eq!(result.value, 16.0, epsilon = 1e-10);

        // Test square root
        let result = var.sqrt();
        assert_abs_diff_eq!(result.value, 2.0, epsilon = 1e-10);

        // Test exponential
        let var_zero = ReverseVariable::constant(0.0);
        let result = var_zero.exp();
        assert_abs_diff_eq!(result.value, 1.0, epsilon = 1e-10);

        // Test natural logarithm
        let var_e = ReverseVariable::constant(std::f64::consts::E);
        let result = var_e.ln();
        assert_abs_diff_eq!(result.value, 1.0, epsilon = 1e-10);

        // Test trigonometric functions
        let var_zero = ReverseVariable::constant(0.0);
        assert_abs_diff_eq!(var_zero.sin().value, 0.0, epsilon = 1e-10);
        assert_abs_diff_eq!(var_zero.cos().value, 1.0, epsilon = 1e-10);
        assert_abs_diff_eq!(var_zero.tan().value, 0.0, epsilon = 1e-10);
    }

    #[test]
    fn test_advanced_operations_with_graph() {
        let mut graph = ComputationGraph::new();

        // Test sigmoid function
        let x = graph.variable(0.0);
        let sig = sigmoid(&mut graph, &x);
        assert_abs_diff_eq!(sig.value, 0.5, epsilon = 1e-10); // sigmoid(0) = 0.5

        graph.backward(&sig).expect("Operation failed");
        assert_abs_diff_eq!(graph.get_gradient(&x), 0.25, epsilon = 1e-10); // sigmoid'(0) = 0.25

        // Test ReLU function
        graph.zero_gradients();
        let x_pos = graph.variable(2.0);
        let relu_pos = relu(&mut graph, &x_pos);
        assert_abs_diff_eq!(relu_pos.value, 2.0, epsilon = 1e-10);

        graph.backward(&relu_pos).expect("Operation failed");
        assert_abs_diff_eq!(graph.get_gradient(&x_pos), 1.0, epsilon = 1e-10); // ReLU'(2) = 1

        // Test ReLU for negative input
        let mut graph2 = ComputationGraph::new();
        let x_neg = graph2.variable(-1.0);
        let relu_neg = relu(&mut graph2, &x_neg);
        assert_abs_diff_eq!(relu_neg.value, 0.0, epsilon = 1e-10);

        graph2.backward(&relu_neg).expect("Operation failed");
        assert_abs_diff_eq!(graph2.get_gradient(&x_neg), 0.0, epsilon = 1e-10); // ReLU'(-1) = 0
    }

    #[test]
    fn test_leaky_relu() {
        let mut graph = ComputationGraph::new();

        // Test Leaky ReLU with positive input
        let x_pos = graph.variable(2.0);
        let leaky_pos = leaky_relu(&mut graph, &x_pos, 0.01);
        assert_abs_diff_eq!(leaky_pos.value, 2.0, epsilon = 1e-10);

        graph.backward(&leaky_pos).expect("Operation failed");
        assert_abs_diff_eq!(graph.get_gradient(&x_pos), 1.0, epsilon = 1e-10);

        // Test Leaky ReLU with negative input
        let mut graph2 = ComputationGraph::new();
        let x_neg = graph2.variable(-2.0);
        let leaky_neg = leaky_relu(&mut graph2, &x_neg, 0.01);
        assert_abs_diff_eq!(leaky_neg.value, -0.02, epsilon = 1e-10);

        graph2.backward(&leaky_neg).expect("Operation failed");
        assert_abs_diff_eq!(graph2.get_gradient(&x_neg), 0.01, epsilon = 1e-10);
    }

    #[test]
    fn test_complex_expression() {
        let mut graph = ComputationGraph::new();

        // Test complex expression: f(x, y) = sigmoid(x² + y) * tanh(x - y)
        let x = graph.variable(1.0);
        let y = graph.variable(0.5);

        let x_squared = mul(&mut graph, &x, &x);
        let x_sq_plus_y = add(&mut graph, &x_squared, &y);
        let sig_term = sigmoid(&mut graph, &x_sq_plus_y);

        let x_minus_y = sub(&mut graph, &x, &y);
        let tanh_term = tanh(&mut graph, &x_minus_y);

        let result = mul(&mut graph, &sig_term, &tanh_term);

        // Verify the computation produces a reasonable result
        assert!(result.value.is_finite());
        assert!(result.value > 0.0); // Both sigmoid and tanh(0.5) are positive

        // Test backpropagation
        graph.backward(&result).expect("Operation failed");

        // Gradients should be finite and non-zero
        let grad_x = graph.get_gradient(&x);
        let grad_y = graph.get_gradient(&y);

        assert!(grad_x.is_finite());
        assert!(grad_y.is_finite());
        assert!(grad_x != 0.0);
        assert!(grad_y != 0.0);
    }
}