rssn 0.2.9

A comprehensive scientific computing library for Rust, aiming for feature parity with NumPy and SymPy.
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
#![allow(deprecated)]

use std::hash::Hash;
use std::hash::Hasher;
use std::sync::Arc;

use super::dag_mgr::DagNode;
use super::dag_mgr::DagOp;
use super::expr::Distribution;
use super::expr::Expr;
use crate::symbolic::unit_unification::UnitQuantity;

impl DagNode {
    /// Converts a DAG node into an `Expr` (AST) structure.
    ///
    /// This is an iterative implementation to avoid stack overflow on deep trees.
    ///
    /// # Errors
    /// Returns an error if the node limit is exceeded or if any child cannot be converted.
    #[allow(clippy::too_many_lines)]
    pub fn to_expr(&self) -> Result<Expr, String> {
        use std::collections::HashMap;

        // Iterative implementation using explicit stack to prevent stack overflow
        // This uses a post-order (bottom-up) traversal strategy

        const MAX_NODES: usize = 100_000;

        const MAX_CHILDREN: usize = 10000;

        // Memoization: maps node hash to its converted Expr
        let mut memo: HashMap<u64, Expr> = HashMap::new();

        // Work stack: nodes to process
        let mut work_stack: Vec<Arc<Self>> = vec![Arc::new(self.clone())];

        // Track which nodes we've pushed to avoid cycles
        let mut visited: HashMap<u64, bool> = HashMap::new();

        let mut nodes_processed = 0;

        while let Some(node) = work_stack.pop() {
            // Safety check: prevent processing too many nodes
            nodes_processed += 1;

            if nodes_processed > MAX_NODES {
                return Err(format!(
                    "Exceeded maximum \
                     node limit of \
                     {MAX_NODES}"
                ));
            }

            // If already converted, skip
            if memo.contains_key(&node.hash) {
                continue;
            }

            // Safety check: limit children count
            if node.children.len() > MAX_CHILDREN {
                return Err(format!(
                    "Node has too \
                     many children \
                     ({}), exceeds \
                     limit of {}",
                    node.children.len(),
                    MAX_CHILDREN
                ));
            }

            // Check if all children are already converted
            let children_ready = node
                .children
                .iter()
                .all(|child| memo.contains_key(&child.hash));

            if children_ready {
                // All children converted, now convert this node
                let children_exprs: Vec<Expr> = node
                    .children
                    .iter()
                    .filter_map(|child| memo.get(&child.hash).cloned())
                    .collect();

                // Helper macro to create Arc from children_exprs
                macro_rules! arc {
                    ($idx:expr_2021) => {
                        if $idx < children_exprs.len() {
                            Arc::new(children_exprs[$idx].clone())
                        } else {
                            return Err(format!(
                                "Index {} out of bounds for children array of length {}",
                                $idx,
                                children_exprs.len()
                            ));
                        }
                    };
                }

                let expr = match &node.op {
                    // --- Leaf Nodes ---
                    | DagOp::Constant(c) => Expr::Constant(c.into_inner()),
                    | DagOp::BigInt(i) => Expr::BigInt(i.clone()),
                    | DagOp::Rational(r) => Expr::Rational(r.clone()),
                    | DagOp::Boolean(b) => Expr::Boolean(*b),
                    | DagOp::Variable(s) => Expr::Variable(s.clone()),
                    | DagOp::Pattern(s) => Expr::Pattern(s.clone()),
                    | DagOp::Domain(s) => Expr::Domain(s.clone()),
                    | DagOp::Pi => Expr::Pi,
                    | DagOp::E => Expr::E,
                    | DagOp::Infinity => Expr::Infinity,
                    | DagOp::NegativeInfinity => Expr::NegativeInfinity,
                    | DagOp::InfiniteSolutions => Expr::InfiniteSolutions,
                    | DagOp::NoSolution => Expr::NoSolution,

                    // --- Operators with associated data ---
                    | DagOp::Derivative(s) => {
                        if children_exprs.is_empty() {
                            return Err("Derivative operator requires at least 1 child".to_string());
                        }

                        Expr::Derivative(arc!(0), s.clone())
                    },
                    | DagOp::DerivativeN(s) => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "DerivativeN operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::DerivativeN(arc!(0), s.clone(), arc!(1))
                    },
                    | DagOp::Limit(s) => {
                        if children_exprs.len() < 2 {
                            return Err("Limit operator requires at least 2 children".to_string());
                        }

                        Expr::Limit(arc!(0), s.clone(), arc!(1))
                    },
                    | DagOp::Solve(s) => {
                        if children_exprs.is_empty() {
                            return Err("Solve operator requires at least 1 child".to_string());
                        }

                        Expr::Solve(arc!(0), s.clone())
                    },
                    | DagOp::ConvergenceAnalysis(s) => {
                        if children_exprs.is_empty() {
                            return Err("ConvergenceAnalysis operator requires at least 1 child"
                                .to_string());
                        }

                        Expr::ConvergenceAnalysis(arc!(0), s.clone())
                    },
                    | DagOp::ForAll(s) => {
                        if children_exprs.is_empty() {
                            return Err("ForAll operator requires at least 1 child".to_string());
                        }

                        Expr::ForAll(s.clone(), arc!(0))
                    },
                    | DagOp::Exists(s) => {
                        if children_exprs.is_empty() {
                            return Err("Exists operator requires at least 1 child".to_string());
                        }

                        Expr::Exists(s.clone(), arc!(0))
                    },
                    | DagOp::Substitute(s) => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "Substitute operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::Substitute(arc!(0), s.clone(), arc!(1))
                    },
                    | DagOp::Ode { func, var } => {
                        if children_exprs.is_empty() {
                            return Err("Ode operator requires at least 1 child".to_string());
                        }

                        Expr::Ode {
                            equation: arc!(0),
                            func: func.clone(),
                            var: var.clone(),
                        }
                    },
                    | DagOp::Pde { func, vars } => {
                        if children_exprs.is_empty() {
                            return Err("Pde operator requires at least 1 child".to_string());
                        }

                        Expr::Pde {
                            equation: arc!(0),
                            func: func.clone(),
                            vars: vars.clone(),
                        }
                    },
                    | DagOp::Predicate { name } => {
                        Expr::Predicate {
                            name: name.clone(),
                            args: children_exprs.clone(),
                        }
                    },
                    | DagOp::Path(pt) => {
                        if children_exprs.len() < 2 {
                            return Err("Path operator requires at least 2 children".to_string());
                        }

                        Expr::Path(pt.clone(), arc!(0), arc!(1))
                    },
                    | DagOp::Interval(incl_lower, incl_upper) => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "Interval operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::Interval(arc!(0), arc!(1), *incl_lower, *incl_upper)
                    },
                    | DagOp::RootOf { index } => {
                        if children_exprs.is_empty() {
                            return Err("RootOf operator requires at least 1 child".to_string());
                        }

                        Expr::RootOf {
                            poly: arc!(0),
                            index: *index,
                        }
                    },
                    | DagOp::SparsePolynomial(p) => Expr::SparsePolynomial(p.clone()),
                    | DagOp::QuantityWithValue(u) => {
                        if children_exprs.is_empty() {
                            return Err(
                                "QuantityWithValue operator requires at least 1 child".to_string()
                            );
                        }

                        Expr::QuantityWithValue(arc!(0), u.clone())
                    },

                    // --- Binary operators ---
                    | DagOp::Add => {
                        if children_exprs.len() < 2 {
                            return Err("Add operator requires at least 2 children".to_string());
                        }

                        if children_exprs.len() == 2 {
                            Expr::Add(arc!(0), arc!(1))
                        } else {
                            Expr::AddList(children_exprs.clone())
                        }
                    },
                    | DagOp::Sub => {
                        if children_exprs.len() < 2 {
                            return Err("Sub operator requires at least 2 children".to_string());
                        }

                        Expr::Sub(arc!(0), arc!(1))
                    },
                    | DagOp::Mul => {
                        if children_exprs.len() < 2 {
                            return Err("Mul operator requires at least 2 children".to_string());
                        }

                        if children_exprs.len() == 2 {
                            Expr::Mul(arc!(0), arc!(1))
                        } else {
                            Expr::MulList(children_exprs.clone())
                        }
                    },
                    | DagOp::Div => {
                        if children_exprs.len() < 2 {
                            return Err("Div operator requires at least 2 children".to_string());
                        }

                        Expr::Div(arc!(0), arc!(1))
                    },
                    | DagOp::Eq => {
                        if children_exprs.len() < 2 {
                            return Err("Eq operator requires at least 2 children".to_string());
                        }

                        Expr::Eq(arc!(0), arc!(1))
                    },
                    | DagOp::Lt => {
                        if children_exprs.len() < 2 {
                            return Err("Lt operator requires at least 2 children".to_string());
                        }

                        Expr::Lt(arc!(0), arc!(1))
                    },
                    | DagOp::Gt => {
                        if children_exprs.len() < 2 {
                            return Err("Gt operator requires at least 2 children".to_string());
                        }

                        Expr::Gt(arc!(0), arc!(1))
                    },
                    | DagOp::Le => {
                        if children_exprs.len() < 2 {
                            return Err("Le operator requires at least 2 children".to_string());
                        }

                        Expr::Le(arc!(0), arc!(1))
                    },
                    | DagOp::Ge => {
                        if children_exprs.len() < 2 {
                            return Err("Ge operator requires at least 2 children".to_string());
                        }

                        Expr::Ge(arc!(0), arc!(1))
                    },
                    | DagOp::LogBase => {
                        if children_exprs.len() < 2 {
                            return Err("LogBase operator requires at least 2 children".to_string());
                        }

                        Expr::LogBase(arc!(0), arc!(1))
                    },
                    | DagOp::Atan2 => {
                        if children_exprs.len() < 2 {
                            return Err("Atan2 operator requires at least 2 children".to_string());
                        }

                        Expr::Atan2(arc!(0), arc!(1))
                    },
                    | DagOp::Binomial => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "Binomial operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::Binomial(arc!(0), arc!(1))
                    },
                    | DagOp::Beta => {
                        if children_exprs.len() < 2 {
                            return Err("Beta operator requires at least 2 children".to_string());
                        }

                        Expr::Beta(arc!(0), arc!(1))
                    },
                    | DagOp::BesselJ => {
                        if children_exprs.len() < 2 {
                            return Err("BesselJ operator requires at least 2 children".to_string());
                        }

                        Expr::BesselJ(arc!(0), arc!(1))
                    },
                    | DagOp::BesselY => {
                        if children_exprs.len() < 2 {
                            return Err("BesselY operator requires at least 2 children".to_string());
                        }

                        Expr::BesselY(arc!(0), arc!(1))
                    },
                    | DagOp::LegendreP => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "LegendreP operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::LegendreP(arc!(0), arc!(1))
                    },
                    | DagOp::LaguerreL => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "LaguerreL operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::LaguerreL(arc!(0), arc!(1))
                    },
                    | DagOp::HermiteH => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "HermiteH operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::HermiteH(arc!(0), arc!(1))
                    },
                    | DagOp::KroneckerDelta => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "KroneckerDelta operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::KroneckerDelta(arc!(0), arc!(1))
                    },
                    | DagOp::Permutation => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "Permutation operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::Permutation(arc!(0), arc!(1))
                    },
                    | DagOp::Combination => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "Combination operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::Combination(arc!(0), arc!(1))
                    },
                    | DagOp::FallingFactorial => {
                        if children_exprs.len() < 2 {
                            return Err("FallingFactorial operator requires at least 2 children"
                                .to_string());
                        }

                        Expr::FallingFactorial(arc!(0), arc!(1))
                    },
                    | DagOp::RisingFactorial => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "RisingFactorial operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::RisingFactorial(arc!(0), arc!(1))
                    },
                    | DagOp::Xor => {
                        if children_exprs.len() < 2 {
                            return Err("Xor operator requires at least 2 children".to_string());
                        }

                        Expr::Xor(arc!(0), arc!(1))
                    },
                    | DagOp::Implies => {
                        if children_exprs.len() < 2 {
                            return Err("Implies operator requires at least 2 children".to_string());
                        }

                        Expr::Implies(arc!(0), arc!(1))
                    },
                    | DagOp::Equivalent => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "Equivalent operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::Equivalent(arc!(0), arc!(1))
                    },
                    | DagOp::Gcd => {
                        if children_exprs.len() < 2 {
                            return Err("Gcd operator requires at least 2 children".to_string());
                        }

                        Expr::Gcd(arc!(0), arc!(1))
                    },
                    | DagOp::Mod => {
                        if children_exprs.len() < 2 {
                            return Err("Mod operator requires at least 2 children".to_string());
                        }

                        Expr::Mod(arc!(0), arc!(1))
                    },
                    | DagOp::Max => {
                        if children_exprs.len() < 2 {
                            return Err("Max operator requires at least 2 children".to_string());
                        }

                        Expr::Max(arc!(0), arc!(1))
                    },
                    | DagOp::MatrixMul => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "MatrixMul operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::MatrixMul(arc!(0), arc!(1))
                    },
                    | DagOp::MatrixVecMul => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "MatrixVecMul operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::MatrixVecMul(arc!(0), arc!(1))
                    },
                    | DagOp::Apply => {
                        if children_exprs.len() < 2 {
                            return Err("Apply operator requires at least 2 children".to_string());
                        }

                        Expr::Apply(arc!(0), arc!(1))
                    },

                    // --- Unary operators ---
                    | DagOp::Neg => {
                        if children_exprs.is_empty() {
                            return Err("Neg operator requires at least 1 child".to_string());
                        }

                        Expr::Neg(arc!(0))
                    },
                    | DagOp::Power => {
                        if children_exprs.len() < 2 {
                            return Err("Power operator requires at least 2 children".to_string());
                        }

                        Expr::Power(arc!(0), arc!(1))
                    },
                    | DagOp::Sin => {
                        if children_exprs.is_empty() {
                            return Err("Sin operator requires at least 1 child".to_string());
                        }

                        Expr::Sin(arc!(0))
                    },
                    | DagOp::Cos => {
                        if children_exprs.is_empty() {
                            return Err("Cos operator requires at least 1 child".to_string());
                        }

                        Expr::Cos(arc!(0))
                    },
                    | DagOp::Tan => {
                        if children_exprs.is_empty() {
                            return Err("Tan operator requires at least 1 child".to_string());
                        }

                        Expr::Tan(arc!(0))
                    },
                    | DagOp::Exp => {
                        if children_exprs.is_empty() {
                            return Err("Exp operator requires at least 1 child".to_string());
                        }

                        Expr::Exp(arc!(0))
                    },
                    | DagOp::Log => {
                        if children_exprs.is_empty() {
                            return Err("Log operator requires at least 1 child".to_string());
                        }

                        Expr::Log(arc!(0))
                    },
                    | DagOp::Abs => {
                        if children_exprs.is_empty() {
                            return Err("Abs operator requires at least 1 child".to_string());
                        }

                        Expr::Abs(arc!(0))
                    },
                    | DagOp::Sqrt => {
                        if children_exprs.is_empty() {
                            return Err("Sqrt operator requires at least 1 child".to_string());
                        }

                        Expr::Sqrt(arc!(0))
                    },
                    | DagOp::Transpose => {
                        if children_exprs.is_empty() {
                            return Err("Transpose operator requires at least 1 child".to_string());
                        }

                        Expr::Transpose(arc!(0))
                    },
                    | DagOp::Inverse => {
                        if children_exprs.is_empty() {
                            return Err("Inverse operator requires at least 1 child".to_string());
                        }

                        Expr::Inverse(arc!(0))
                    },
                    | DagOp::Sec => {
                        if children_exprs.is_empty() {
                            return Err("Sec operator requires at least 1 child".to_string());
                        }

                        Expr::Sec(arc!(0))
                    },
                    | DagOp::Csc => {
                        if children_exprs.is_empty() {
                            return Err("Csc operator requires at least 1 child".to_string());
                        }

                        Expr::Csc(arc!(0))
                    },
                    | DagOp::Cot => {
                        if children_exprs.is_empty() {
                            return Err("Cot operator requires at least 1 child".to_string());
                        }

                        Expr::Cot(arc!(0))
                    },
                    | DagOp::ArcSin => {
                        if children_exprs.is_empty() {
                            return Err("ArcSin operator requires at least 1 child".to_string());
                        }

                        Expr::ArcSin(arc!(0))
                    },
                    | DagOp::ArcCos => {
                        if children_exprs.is_empty() {
                            return Err("ArcCos operator requires at least 1 child".to_string());
                        }

                        Expr::ArcCos(arc!(0))
                    },
                    | DagOp::ArcTan => {
                        if children_exprs.is_empty() {
                            return Err("ArcTan operator requires at least 1 child".to_string());
                        }

                        Expr::ArcTan(arc!(0))
                    },
                    | DagOp::ArcSec => {
                        if children_exprs.is_empty() {
                            return Err("ArcSec operator requires at least 1 child".to_string());
                        }

                        Expr::ArcSec(arc!(0))
                    },
                    | DagOp::ArcCsc => {
                        if children_exprs.is_empty() {
                            return Err("ArcCsc operator requires at least 1 child".to_string());
                        }

                        Expr::ArcCsc(arc!(0))
                    },
                    | DagOp::ArcCot => {
                        if children_exprs.is_empty() {
                            return Err("ArcCot operator requires at least 1 child".to_string());
                        }

                        Expr::ArcCot(arc!(0))
                    },
                    | DagOp::Sinh => {
                        if children_exprs.is_empty() {
                            return Err("Sinh operator requires at least 1 child".to_string());
                        }

                        Expr::Sinh(arc!(0))
                    },
                    | DagOp::Cosh => {
                        if children_exprs.is_empty() {
                            return Err("Cosh operator requires at least 1 child".to_string());
                        }

                        Expr::Cosh(arc!(0))
                    },
                    | DagOp::Tanh => {
                        if children_exprs.is_empty() {
                            return Err("Tanh operator requires at least 1 child".to_string());
                        }

                        Expr::Tanh(arc!(0))
                    },
                    | DagOp::Sech => {
                        if children_exprs.is_empty() {
                            return Err("Sech operator requires at least 1 child".to_string());
                        }

                        Expr::Sech(arc!(0))
                    },
                    | DagOp::Csch => {
                        if children_exprs.is_empty() {
                            return Err("Csch operator requires at least 1 child".to_string());
                        }

                        Expr::Csch(arc!(0))
                    },
                    | DagOp::Coth => {
                        if children_exprs.is_empty() {
                            return Err("Coth operator requires at least 1 child".to_string());
                        }

                        Expr::Coth(arc!(0))
                    },
                    | DagOp::ArcSinh => {
                        if children_exprs.is_empty() {
                            return Err("ArcSinh operator requires at least 1 child".to_string());
                        }

                        Expr::ArcSinh(arc!(0))
                    },
                    | DagOp::ArcCosh => {
                        if children_exprs.is_empty() {
                            return Err("ArcCosh operator requires at least 1 child".to_string());
                        }

                        Expr::ArcCosh(arc!(0))
                    },
                    | DagOp::ArcTanh => {
                        if children_exprs.is_empty() {
                            return Err("ArcTanh operator requires at least 1 child".to_string());
                        }

                        Expr::ArcTanh(arc!(0))
                    },
                    | DagOp::ArcSech => {
                        if children_exprs.is_empty() {
                            return Err("ArcSech operator requires at least 1 child".to_string());
                        }

                        Expr::ArcSech(arc!(0))
                    },
                    | DagOp::ArcCsch => {
                        if children_exprs.is_empty() {
                            return Err("ArcCsch operator requires at least 1 child".to_string());
                        }

                        Expr::ArcCsch(arc!(0))
                    },
                    | DagOp::ArcCoth => {
                        if children_exprs.is_empty() {
                            return Err("ArcCoth operator requires at least 1 child".to_string());
                        }

                        Expr::ArcCoth(arc!(0))
                    },
                    | DagOp::Factorial => {
                        if children_exprs.is_empty() {
                            return Err("Factorial operator requires at least 1 child".to_string());
                        }

                        Expr::Factorial(arc!(0))
                    },
                    | DagOp::Boundary => {
                        if children_exprs.is_empty() {
                            return Err("Boundary operator requires at least 1 child".to_string());
                        }

                        Expr::Boundary(arc!(0))
                    },
                    | DagOp::Gamma => {
                        if children_exprs.is_empty() {
                            return Err("Gamma operator requires at least 1 child".to_string());
                        }

                        Expr::Gamma(arc!(0))
                    },
                    | DagOp::Erf => {
                        if children_exprs.is_empty() {
                            return Err("Erf operator requires at least 1 child".to_string());
                        }

                        Expr::Erf(arc!(0))
                    },
                    | DagOp::Erfc => {
                        if children_exprs.is_empty() {
                            return Err("Erfc operator requires at least 1 child".to_string());
                        }

                        Expr::Erfc(arc!(0))
                    },
                    | DagOp::Erfi => {
                        if children_exprs.is_empty() {
                            return Err("Erfi operator requires at least 1 child".to_string());
                        }

                        Expr::Erfi(arc!(0))
                    },
                    | DagOp::Zeta => {
                        if children_exprs.is_empty() {
                            return Err("Zeta operator requires at least 1 child".to_string());
                        }

                        Expr::Zeta(arc!(0))
                    },
                    | DagOp::Digamma => {
                        if children_exprs.is_empty() {
                            return Err("Digamma operator requires at least 1 child".to_string());
                        }

                        Expr::Digamma(arc!(0))
                    },
                    | DagOp::Not => {
                        if children_exprs.is_empty() {
                            return Err("Not operator requires at least 1 child".to_string());
                        }

                        Expr::Not(arc!(0))
                    },
                    | DagOp::Floor => {
                        if children_exprs.is_empty() {
                            return Err("Floor operator requires at least 1 child".to_string());
                        }

                        Expr::Floor(arc!(0))
                    },
                    | DagOp::IsPrime => {
                        if children_exprs.is_empty() {
                            return Err("IsPrime operator requires at least 1 child".to_string());
                        }

                        Expr::IsPrime(arc!(0))
                    },
                    | DagOp::GeneralSolution => {
                        if children_exprs.is_empty() {
                            return Err(
                                "GeneralSolution operator requires at least 1 child".to_string()
                            );
                        }

                        Expr::GeneralSolution(arc!(0))
                    },
                    | DagOp::ParticularSolution => {
                        if children_exprs.is_empty() {
                            return Err(
                                "ParticularSolution operator requires at least 1 child".to_string()
                            );
                        }

                        Expr::ParticularSolution(arc!(0))
                    },

                    // --- Complex structures ---
                    | DagOp::Matrix { rows: _, cols } => {
                        if children_exprs.len().is_multiple_of(*cols) {
                            let reconstructed_matrix: Vec<Vec<Expr>> =
                                children_exprs.chunks(*cols).map(<[Expr]>::to_vec).collect();

                            Expr::Matrix(reconstructed_matrix)
                        } else {
                            let complete_rows = (children_exprs.len() / cols) * cols;

                            let reconstructed_matrix: Vec<Vec<Expr>> = children_exprs
                                .iter()
                                .take(complete_rows)
                                .cloned()
                                .collect::<Vec<_>>()
                                .chunks(*cols)
                                .map(<[Expr]>::to_vec)
                                .collect();

                            Expr::Matrix(reconstructed_matrix)
                        }
                    },
                    | DagOp::Complex => {
                        if children_exprs.len() < 2 {
                            return Err("Complex operator requires at least 2 children".to_string());
                        }

                        Expr::Complex(arc!(0), arc!(1))
                    },
                    | DagOp::Integral => {
                        if children_exprs.len() < 4 {
                            return Err(
                                "Integral operator requires at least 4 children".to_string()
                            );
                        }

                        Expr::Integral {
                            integrand: arc!(0),
                            var: arc!(1),
                            lower_bound: arc!(2),
                            upper_bound: arc!(3),
                        }
                    },
                    | DagOp::VolumeIntegral => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "VolumeIntegral operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::VolumeIntegral {
                            scalar_field: arc!(0),
                            volume: arc!(1),
                        }
                    },
                    | DagOp::SurfaceIntegral => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "SurfaceIntegral operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::SurfaceIntegral {
                            vector_field: arc!(0),
                            surface: arc!(1),
                        }
                    },
                    | DagOp::Sum => {
                        if children_exprs.len() < 4 {
                            return Err("Sum operator requires at least 4 children".to_string());
                        }

                        Expr::Sum {
                            body: arc!(0),
                            var: arc!(1),
                            from: arc!(2),
                            to: arc!(3),
                        }
                    },
                    | DagOp::Series(s) => {
                        if children_exprs.len() < 3 {
                            return Err("Series operator requires at least 3 children".to_string());
                        }

                        Expr::Series(arc!(0), s.clone(), arc!(1), arc!(2))
                    },
                    | DagOp::Summation(s) => {
                        if children_exprs.len() < 3 {
                            return Err(
                                "Summation operator requires at least 3 children".to_string()
                            );
                        }

                        Expr::Summation(arc!(0), s.clone(), arc!(1), arc!(2))
                    },
                    | DagOp::Product(s) => {
                        if children_exprs.len() < 3 {
                            return Err("Product operator requires at least 3 children".to_string());
                        }

                        Expr::Product(arc!(0), s.clone(), arc!(1), arc!(2))
                    },
                    | DagOp::AsymptoticExpansion(s) => {
                        if children_exprs.len() < 3 {
                            return Err(
                                "AsymptoticExpansion operator requires at least 3 children"
                                    .to_string(),
                            );
                        }

                        Expr::AsymptoticExpansion(arc!(0), s.clone(), arc!(1), arc!(2))
                    },
                    | DagOp::ParametricSolution => {
                        if children_exprs.len() < 2 {
                            return Err("ParametricSolution operator requires at least 2 children"
                                .to_string());
                        }

                        Expr::ParametricSolution {
                            x: arc!(0),
                            y: arc!(1),
                        }
                    },
                    | DagOp::Fredholm => {
                        if children_exprs.len() < 4 {
                            return Err(
                                "Fredholm operator requires at least 4 children".to_string()
                            );
                        }

                        Expr::Fredholm(arc!(0), arc!(1), arc!(2), arc!(3))
                    },
                    | DagOp::Volterra => {
                        if children_exprs.len() < 4 {
                            return Err(
                                "Volterra operator requires at least 4 children".to_string()
                            );
                        }

                        Expr::Volterra(arc!(0), arc!(1), arc!(2), arc!(3))
                    },
                    | DagOp::Distribution => {
                        if children_exprs.is_empty() {
                            return Err(
                                "Distribution operator requires at least 1 child".to_string()
                            );
                        }

                        Expr::Distribution(children_exprs[0].clone_box_dist()?)
                    },
                    | DagOp::Quantity => {
                        if children_exprs.is_empty() {
                            return Err("Quantity operator requires at least 1 child".to_string());
                        }

                        Expr::Quantity(children_exprs[0].clone_box_quant()?)
                    },

                    // --- List operators ---
                    | DagOp::Vector => Expr::Vector(children_exprs.clone()),
                    | DagOp::And => Expr::And(children_exprs.clone()),
                    | DagOp::Or => Expr::Or(children_exprs.clone()),
                    | DagOp::Union => Expr::Union(children_exprs.clone()),
                    | DagOp::Polynomial => Expr::Polynomial(children_exprs.clone()),
                    | DagOp::System => Expr::System(children_exprs.clone()),
                    | DagOp::Solutions => Expr::Solutions(children_exprs.clone()),
                    | DagOp::Tuple => Expr::Tuple(children_exprs.clone()),

                    // --- Custom ---
                    | DagOp::CustomZero => Expr::CustomZero,
                    | DagOp::CustomString(s) => Expr::CustomString(s.clone()),
                    | DagOp::CustomArcOne => {
                        if children_exprs.is_empty() {
                            return Err(
                                "CustomArcOne operator requires at least 1 child".to_string()
                            );
                        }

                        Expr::CustomArcOne(arc!(0))
                    },
                    | DagOp::CustomArcTwo => {
                        if children_exprs.len() < 2 {
                            return Err(
                                "CustomArcTwo operator requires at least 2 children".to_string()
                            );
                        }

                        Expr::CustomArcTwo(arc!(0), arc!(1))
                    },
                    | DagOp::CustomArcThree => {
                        if children_exprs.len() < 3 {
                            return Err(
                                "CustomArcThree operator requires at least 3 children".to_string()
                            );
                        }

                        Expr::CustomArcThree(arc!(0), arc!(1), arc!(2))
                    },
                    | DagOp::CustomArcFour => {
                        if children_exprs.len() < 4 {
                            return Err(
                                "CustomArcFour operator requires at least 4 children".to_string()
                            );
                        }

                        Expr::CustomArcFour(arc!(0), arc!(1), arc!(2), arc!(3))
                    },
                    | DagOp::CustomArcFive => {
                        if children_exprs.len() < 5 {
                            return Err(
                                "CustomArcFive operator requires at least 5 children".to_string()
                            );
                        }

                        Expr::CustomArcFive(arc!(0), arc!(1), arc!(2), arc!(3), arc!(4))
                    },
                    | DagOp::CustomVecOne => Expr::CustomVecOne(children_exprs.clone()),
                    | DagOp::CustomVecTwo => {
                        return Err("CustomVecTwo to_expr is ambiguous".to_string());
                    },
                    | DagOp::CustomVecThree => {
                        return Err("CustomVecThree to_expr is ambiguous".to_string());
                    },
                    | DagOp::CustomVecFour => {
                        return Err("CustomVecFour to_expr is ambiguous".to_string());
                    },
                    | DagOp::CustomVecFive => {
                        return Err("CustomVecFive to_expr is ambiguous".to_string());
                    },

                    | DagOp::UnaryList(s) => {
                        if children_exprs.is_empty() {
                            return Err(format!(
                                "UnaryList operator {s} requires at least 1 child"
                            ));
                        }

                        Expr::UnaryList(s.clone(), arc!(0))
                    },
                    | DagOp::BinaryList(s) => {
                        if children_exprs.len() < 2 {
                            return Err(format!(
                                "BinaryList operator {s} requires at least 2 children"
                            ));
                        }

                        Expr::BinaryList(s.clone(), arc!(0), arc!(1))
                    },
                    | DagOp::NaryList(s) => Expr::NaryList(s.clone(), children_exprs.clone()),
                };

                // Store the converted expression
                memo.insert(node.hash, expr);
            } else {
                // Not all children ready, push node back and push children
                work_stack.push(node.clone());

                // Push children in reverse order (so they're processed in correct order)
                if visited.insert(node.hash, true).is_none() {
                    for child in node.children.iter().rev() {
                        if !memo.contains_key(&child.hash) {
                            work_stack.push(child.clone());
                        }
                    }
                }
            }
        }

        // Return the converted expression for the root node
        memo.get(&self.hash).cloned().ok_or_else(|| {
            "Failed to convert \
                 root node"
                .to_string()
        })
    }

    /// Creates a new `DagNode` with the given operation and children.
    ///
    /// Automatically handles hashing and enforces safety limits on the number of children.
    #[must_use]
    pub fn new(
        op: DagOp,
        children: Vec<Arc<Self>>,
    ) -> Arc<Self> {
        // Safety check: limit number of children to prevent excessive memory allocation
        const MAX_CHILDREN: usize = 10000;

        if children.len() > MAX_CHILDREN {
            // This should not happen in normal usage, but we handle it gracefully
            // by truncating the children list - this is a defensive programming approach
            let safe_children: Vec<_> = children.into_iter().take(MAX_CHILDREN).collect();

            let mut hasher = std::collections::hash_map::DefaultHasher::new();

            op.hash(&mut hasher);

            safe_children.hash(&mut hasher);

            let hash = hasher.finish();

            return Arc::new(Self {
                op,
                children: safe_children,
                hash,
                id: 0,
            });
        }

        let mut hasher = std::collections::hash_map::DefaultHasher::new();

        op.hash(&mut hasher);

        children.hash(&mut hasher);

        let hash = hasher.finish();

        Arc::new(Self {
            op,
            children,
            hash,
            id: 0,
        })
    }
}

impl Expr {
    /// Clones the distribution if the expression represents a probability distribution.
    ///
    /// # Errors
    /// Returns an error if the expression is not a distribution.
    pub fn clone_box_dist(&self) -> Result<Arc<dyn Distribution>, String> {
        if let Self::Distribution(d) = self {
            Ok(d.clone_box())
        } else {
            Err("Cannot clone into \
                 Distribution"
                .to_string())
        }
    }

    /// Clones the unit quantity if the expression represents a quantity.
    ///
    /// # Errors
    /// Returns an error if the expression is not a quantity.
    pub fn clone_box_quant(&self) -> Result<Arc<UnitQuantity>, String> {
        if let Self::Quantity(q) = self {
            Ok(q.clone())
        } else {
            Err("Cannot clone into \
                 UnitQuantity"
                .to_string())
        }
    }
}