quantsupport 0.1.6

Rust quantitative finance library for derivatives pricing, yield-curve bootstrapping, AAD risk, Monte Carlo exposure, and XVA.
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
/*
This file is part of QuantSupport's Rust rewrite and adaptation of the
derivatives scripting code written by Antoine Savine in 2018.

The original code is the strict intellectual property of Antoine Savine.

A license to use and alter the original code for personal and commercial
applications is freely granted to any person or company that purchased a copy
of the book:

Modern Computational Finance: Scripting for Derivatives and XVA
Jesper Andreasen and Antoine Savine
Wiley, 2018

This attribution and license notice must be preserved at the top of this file.
*/

use std::cell::{Cell, RefCell};

use crate::{
    ad::expr::FloatExt,
    scripting::{
        data::simulationdata::{Scenario, SimulationData},
        nodes::{node::Node, node::SpotUnderlying, traits::NodeConstVisitor},
        utils::errors::{Result, ScriptingError},
        visitors::evaluator::{CapturedCashflow, Value},
        NumericType,
    },
    time::{date::Date, daycounter::DayCounter},
};

const EPS: f64 = 1.0e-12;
const ONE_MINUS_EPS: f64 = 1.0 - EPS;
/// Width of an implicit `if` call spread relative to the values being
/// compared. Two percent keeps pathwise AAD stable for digital payoffs while
/// leaving the transition narrow relative to the underlying level.
const AUTO_SMOOTHING_RELATIVE_WIDTH: f64 = 0.02;
const AUTO_SMOOTHING_MIN_WIDTH: f64 = 1.0e-8;

/// Single-scenario evaluator that smooths conditional branch transitions.
pub struct FuzzyEvaluator<'a> {
    variables: RefCell<Vec<Value>>,
    digit_stack: RefCell<Vec<NumericType>>,
    boolean_stack: RefCell<Vec<bool>>,
    string_stack: RefCell<Vec<String>>,
    array_stack: RefCell<Vec<Vec<Value>>>,
    is_lhs_variable: RefCell<bool>,
    lhs_variable: RefCell<Option<Node>>,
    scenario: Option<&'a Scenario>,
    current_event: RefCell<usize>,
    current_event_date: RefCell<Option<Date>>,
    valuation_date: Option<Date>,
    captured_payment_id: Option<usize>,
    captured_payment_value: RefCell<Option<NumericType>>,
    capture_cashflows: bool,
    captured_cashflows: RefCell<Vec<CapturedCashflow>>,
    branch_weight: RefCell<NumericType>,

    /// Stack of truth degrees (`dt`) produced while evaluating conditions.
    dt_stack: RefCell<Vec<NumericType>>,

    /// Default smoothing width (ε) when a node does not override it.
    eps: f64,
    auto_scale_comparisons: bool,

    /// Temporary variable stores per *nested-if* level.
    /// `[level][var_index]`
    var_store0: RefCell<Vec<Vec<NumericType>>>,
    var_store1: RefCell<Vec<Vec<NumericType>>>,

    /// Current *nested-if* depth (0 = outside any `if`).
    nested_if_lvl: Cell<usize>,
}

impl<'a> FuzzyEvaluator<'a> {
    /// Creates an evaluator with variable storage for the maximum conditional depth.
    pub fn new(n_vars: usize, max_nested_ifs: usize) -> Self {
        let mut var_store0 = Vec::with_capacity(max_nested_ifs);
        let mut var_store1 = Vec::with_capacity(max_nested_ifs);
        for _ in 0..max_nested_ifs {
            var_store0.push(vec![NumericType::zero(); n_vars]);
            var_store1.push(vec![NumericType::zero(); n_vars]);
        }
        Self {
            variables: RefCell::new(vec![Value::Null; n_vars]),
            digit_stack: RefCell::new(Vec::new()),
            boolean_stack: RefCell::new(Vec::new()),
            string_stack: RefCell::new(Vec::new()),
            array_stack: RefCell::new(Vec::new()),
            is_lhs_variable: RefCell::new(false),
            lhs_variable: RefCell::new(None),
            scenario: None,
            current_event: RefCell::new(0),
            current_event_date: RefCell::new(None),
            valuation_date: None,
            captured_payment_id: None,
            captured_payment_value: RefCell::new(None),
            capture_cashflows: false,
            captured_cashflows: RefCell::new(Vec::new()),
            branch_weight: RefCell::new(NumericType::one()),
            dt_stack: RefCell::new(Vec::new()),
            eps: EPS,
            auto_scale_comparisons: true,
            var_store0: RefCell::new(var_store0),
            var_store1: RefCell::new(var_store1),
            nested_if_lvl: Cell::new(0),
        }
    }

    /// Overrides the smoothing width and disables automatic comparison scaling.
    pub fn with_eps(mut self, eps: f64) -> Self {
        self.eps = eps;
        self.auto_scale_comparisons = false;
        self
    }

    /// Assigns the market-data scenario used by financial expressions.
    pub fn with_scenario(mut self, scenario: &'a Scenario) -> Self {
        self.scenario = Some(scenario);
        self
    }

    #[must_use]
    /// Excludes payments on or before `valuation_date`.
    pub const fn with_valuation_date(mut self, valuation_date: Date) -> Self {
        self.valuation_date = Some(valuation_date);
        self
    }

    #[must_use]
    /// Captures the undiscounted amount produced by one indexed payment.
    pub const fn with_payment_capture(mut self, payment_id: usize) -> Self {
        self.captured_payment_id = Some(payment_id);
        self
    }

    /// Records every executed payment's date, currency, and amounts,
    /// weighted by the smoothed branch probability.
    #[must_use]
    pub const fn with_cashflow_capture(mut self) -> Self {
        self.capture_cashflows = true;
        self
    }

    /// Returns the payments recorded while cashflow capture was enabled.
    #[must_use]
    pub fn captured_cashflows(&self) -> Vec<CapturedCashflow> {
        self.captured_cashflows.borrow().clone()
    }

    /// Returns a snapshot of runtime variables.
    pub fn variables(&self) -> Vec<Value> {
        self.variables.borrow().clone()
    }

    /// Resizes runtime variable storage to `n` slots.
    pub fn with_variables(self, n: usize) -> Self {
        self.variables.borrow_mut().resize(n, Value::Null);
        self
    }

    /// Sets the active event index.
    pub fn with_current_event(self, event: usize) -> Self {
        *self.current_event.borrow_mut() = event;
        self
    }

    /// Returns market data for the active event.
    ///
    /// # Errors
    /// Returns an error if no scenario is set or the event index is invalid.
    pub fn current_market_data(&self) -> Result<&SimulationData> {
        let scenario = self
            .scenario
            .ok_or(ScriptingError::EvaluationError("No scenario set".into()))?;
        scenario
            .get(*self.current_event.borrow())
            .ok_or(ScriptingError::EvaluationError("Event not found".into()))
    }

    /// Returns the active event index.
    pub fn current_event(&self) -> usize {
        *self.current_event.borrow()
    }

    /// Replaces the active event index.
    pub fn set_current_event(&self, event: usize) {
        *self.current_event.borrow_mut() = event;
    }

    /// Stores `val` in variable slot `idx`, extending storage if required.
    pub fn set_variable(&self, idx: usize, val: Value) {
        let mut vars = self.variables.borrow_mut();
        if idx >= vars.len() {
            vars.resize(idx + 1, Value::Null);
        }
        vars[idx] = val;
    }

    /// Returns a snapshot of the numeric evaluation stack.
    pub fn digit_stack(&self) -> Vec<NumericType> {
        self.digit_stack.borrow().clone()
    }

    /// Returns a snapshot of the Boolean evaluation stack.
    pub fn boolean_stack(&self) -> Vec<bool> {
        self.boolean_stack.borrow().clone()
    }

    #[must_use]
    /// Returns the selected payment amount if its branch was evaluated.
    pub fn captured_payment_value(&self) -> Option<NumericType> {
        *self.captured_payment_value.borrow()
    }

    /// Call-spread centred on 0, width `eps`.
    fn c_spr(&self, x: NumericType, eps: f64) -> NumericType {
        let half = eps * 0.5;
        if x < -half {
            NumericType::zero()
        } else if x > half {
            NumericType::one()
        } else {
            ((x + half) / eps).into()
        }
    }

    /// Call-spread on explicit bounds `[lb, rb]`.
    fn c_spr_bounds(&self, x: NumericType, lb: f64, rb: f64) -> NumericType {
        if x < lb {
            NumericType::zero()
        } else if x > rb {
            NumericType::one()
        } else {
            ((x - lb) / (rb - lb)).into()
        }
    }

    /// Butterfly centred on 0, width `eps`.
    fn bfly(&self, x: NumericType, eps: f64) -> NumericType {
        let half = eps * 0.5;
        if x < -half || x > half {
            NumericType::zero()
        } else {
            ((-x.abs() + half) / half).into()
        }
    }

    /// Butterfly with explicit bounds `lb < 0 < rb`.
    fn bfly_bounds(&self, x: NumericType, lb: f64, rb: f64) -> NumericType {
        if x < lb || x > rb {
            NumericType::zero()
        } else if x < 0.0 {
            (NumericType::one() - x / lb).into()
        } else {
            (NumericType::one() - x / rb).into()
        }
    }

    /// Evaluate a canonical comparison expression and select its smoothing
    /// width. `IfConditionTransform` rewrites comparisons to `(lhs-rhs) > 0`;
    /// evaluating the two sides separately lets ordinary `if` statements use
    /// a scale-aware band even when the threshold is held in a script variable.
    fn comparison_input(&self, node: &Node) -> Result<(NumericType, f64)> {
        if self.auto_scale_comparisons {
            if let Node::Subtract(data) = node {
                if data.children.len() == 2 {
                    self.const_visit(&data.children[0])?;
                    let left = self.digit_stack.borrow_mut().pop().ok_or_else(|| {
                        ScriptingError::EvaluationError(
                            "comparison left side produced no numeric value".into(),
                        )
                    })?;
                    self.const_visit(&data.children[1])?;
                    let right = self.digit_stack.borrow_mut().pop().ok_or_else(|| {
                        ScriptingError::EvaluationError(
                            "comparison right side produced no numeric value".into(),
                        )
                    })?;
                    let scale = left.value().abs().max(right.value().abs());
                    let eps = (scale * AUTO_SMOOTHING_RELATIVE_WIDTH).max(AUTO_SMOOTHING_MIN_WIDTH);
                    return Ok(((left - right).into(), eps));
                }
            }
        }

        self.const_visit(node)?;
        let value = self.digit_stack.borrow_mut().pop().ok_or_else(|| {
            ScriptingError::EvaluationError("comparison produced no numeric value".into())
        })?;
        Ok((value, self.eps))
    }
}

impl<'a> NodeConstVisitor for FuzzyEvaluator<'a> {
    type Output = Result<()>;

    fn const_visit(&self, node: &Node) -> Self::Output {
        match node {
            /* ─────────────── base / variables ─────────────── */
            Node::Base(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                Ok(())
            }
            Node::Variable(data) => {
                let name = &data.name;
                if *self.is_lhs_variable.borrow() {
                    *self.lhs_variable.borrow_mut() = Some(node.clone());
                    Ok(())
                } else {
                    match data.id {
                        None => Err(ScriptingError::EvaluationError(format!(
                            "Variable {} not indexed",
                            name
                        ))),
                        Some(id) => {
                            let vars = self.variables.borrow();
                            let value = vars.get(id).unwrap();
                            match value {
                                Value::Number(v) => self.digit_stack.borrow_mut().push(*v),
                                Value::Bool(v) => self.boolean_stack.borrow_mut().push(*v),
                                Value::String(v) => self.string_stack.borrow_mut().push(v.clone()),
                                Value::Array(a) => self.array_stack.borrow_mut().push(a.clone()),
                                Value::Null => {
                                    return Err(ScriptingError::EvaluationError(format!(
                                        "Variable {} not initialized",
                                        name
                                    )))
                                }
                            }
                            Ok(())
                        }
                    }
                }
            }
            Node::Spot(data) => {
                let id = data
                    .id
                    .ok_or(ScriptingError::EvaluationError("Spot not indexed".into()))?;
                let market_data = self
                    .scenario
                    .ok_or(ScriptingError::EvaluationError("No scenario set".into()))?
                    .get(*self.current_event.borrow())
                    .ok_or(ScriptingError::EvaluationError("Spot not found".into()))?;
                let value = match &data.underlying {
                    SpotUnderlying::Fx { .. } => market_data.get_fx(id)?,
                    SpotUnderlying::Equity(_) => market_data.get_spot(id)?,
                };
                self.digit_stack.borrow_mut().push(value);
                Ok(())
            }
            Node::Df(data) => {
                let id = data
                    .id
                    .ok_or(ScriptingError::EvaluationError("Df not indexed".into()))?;
                let market_data = self
                    .scenario
                    .ok_or(ScriptingError::EvaluationError("No scenario set".into()))?
                    .get(*self.current_event.borrow())
                    .ok_or(ScriptingError::EvaluationError("Df not found".into()))?;
                self.digit_stack.borrow_mut().push(market_data.get_df(id)?);
                Ok(())
            }
            Node::RateIndex(data) => {
                let id = data.id.ok_or(ScriptingError::EvaluationError(
                    "RateIndex not indexed".into(),
                ))?;
                let market_data = self
                    .scenario
                    .ok_or(ScriptingError::EvaluationError("No scenario set".into()))?
                    .get(*self.current_event.borrow())
                    .ok_or(ScriptingError::EvaluationError(
                        "RateIndex not found".into(),
                    ))?;
                self.digit_stack.borrow_mut().push(market_data.get_fwd(id)?);
                Ok(())
            }
            Node::Pays(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                let current_value = self.digit_stack.borrow_mut().pop().ok_or_else(|| {
                    ScriptingError::EvaluationError(
                        "payment expression produced no numeric value".to_string(),
                    )
                })?;

                let payment_date = data.date.or(*self.current_event_date.borrow());
                if self
                    .valuation_date
                    .zip(payment_date)
                    .is_some_and(|(valuation_date, payment_date)| payment_date <= valuation_date)
                {
                    self.digit_stack.borrow_mut().push(NumericType::zero());
                    return Ok(());
                }

                if self.captured_payment_id == data.id {
                    let weighted_value = (*self.branch_weight.borrow() * current_value).into();
                    let mut captured = self.captured_payment_value.borrow_mut();
                    *captured = Some(
                        captured.map_or(weighted_value, |value| (value + weighted_value).into()),
                    );
                }

                let market_data = self
                    .scenario
                    .ok_or(ScriptingError::EvaluationError("No scenario set".into()))?
                    .get(*self.current_event.borrow())
                    .ok_or(ScriptingError::EvaluationError("Event not found".into()))?
                    .clone();
                let df_id = data
                    .df_id
                    .ok_or(ScriptingError::EvaluationError("Pays not indexed".into()))?;
                let df = market_data.get_df(df_id)?;
                let numeraire = market_data.numeraire();
                let value: NumericType = if data.currency.is_some() {
                    let fx_id = data.spot_id.ok_or(ScriptingError::EvaluationError(
                        "Pays FX not indexed".into(),
                    ))?;
                    let fx = market_data.get_fx(fx_id)?;
                    ((current_value * df * fx) / numeraire).into()
                } else {
                    ((current_value * df) / numeraire).into()
                };
                if self.capture_cashflows {
                    if let Some(date) = payment_date {
                        let weight = *self.branch_weight.borrow();
                        let undiscounted: NumericType = (weight * current_value).into();
                        let discounted: NumericType = (weight * value).into();
                        self.captured_cashflows.borrow_mut().push((
                            date,
                            data.currency,
                            undiscounted.value(),
                            discounted.value(),
                        ));
                    }
                }
                self.digit_stack.borrow_mut().push(value);
                Ok(())
            }
            Node::Constant(data) => {
                self.digit_stack.borrow_mut().push(data.const_value.into());
                Ok(())
            }
            Node::String(value) => {
                self.string_stack.borrow_mut().push(value.clone());
                Ok(())
            }

            /* ─────────────── math ops ─────────────── */
            Node::Add(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                let right = self.digit_stack.borrow_mut().pop().unwrap();
                let left = self.digit_stack.borrow_mut().pop().unwrap();
                self.digit_stack.borrow_mut().push((left + right).into());
                Ok(())
            }
            Node::Subtract(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                let right = self.digit_stack.borrow_mut().pop().unwrap();
                let left = self.digit_stack.borrow_mut().pop().unwrap();
                self.digit_stack.borrow_mut().push((left - right).into());
                Ok(())
            }
            Node::Multiply(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                let right = self.digit_stack.borrow_mut().pop().unwrap();
                let left = self.digit_stack.borrow_mut().pop().unwrap();
                self.digit_stack.borrow_mut().push((left * right).into());
                Ok(())
            }
            Node::Divide(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                let right = self.digit_stack.borrow_mut().pop().unwrap();
                let left = self.digit_stack.borrow_mut().pop().unwrap();
                self.digit_stack.borrow_mut().push((left / right).into());
                Ok(())
            }
            Node::Assign(data) => {
                *self.is_lhs_variable.borrow_mut() = true;
                self.const_visit(&data.children[0])?;
                *self.is_lhs_variable.borrow_mut() = false;
                self.const_visit(&data.children[1])?;

                let variable = self.lhs_variable.borrow_mut().clone().unwrap();
                if let Node::Variable(var_data) = variable {
                    let id = var_data.id.ok_or(ScriptingError::EvaluationError(format!(
                        "Variable {} not indexed",
                        var_data.name
                    )))?;
                    let mut vars = self.variables.borrow_mut();
                    if !self.boolean_stack.borrow().is_empty() {
                        vars[id] = Value::Bool(self.boolean_stack.borrow_mut().pop().unwrap());
                    } else if !self.string_stack.borrow().is_empty() {
                        vars[id] = Value::String(self.string_stack.borrow_mut().pop().unwrap());
                    } else if !self.array_stack.borrow().is_empty() {
                        vars[id] = Value::Array(self.array_stack.borrow_mut().pop().unwrap());
                    } else {
                        vars[id] = Value::Number(self.digit_stack.borrow_mut().pop().unwrap());
                    }
                    Ok(())
                } else {
                    Err(ScriptingError::EvaluationError(
                        "Invalid variable assignment".into(),
                    ))
                }
            }
            Node::UnaryPlus(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                Ok(())
            }
            Node::UnaryMinus(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                let value = self.digit_stack.borrow_mut().pop().unwrap();
                self.digit_stack.borrow_mut().push((-value).into());
                Ok(())
            }
            Node::Min(data) | Node::Max(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                let right = self.digit_stack.borrow_mut().pop().unwrap();
                let left = self.digit_stack.borrow_mut().pop().unwrap();
                let result = if matches!(node, Node::Min(_)) {
                    left.min(right)
                } else {
                    left.max(right)
                };
                self.digit_stack.borrow_mut().push(result);
                Ok(())
            }
            Node::Pow(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                let exponent = self.digit_stack.borrow_mut().pop().unwrap();
                let base = self.digit_stack.borrow_mut().pop().unwrap();
                self.digit_stack.borrow_mut().push(base.pow_expr(exponent));
                Ok(())
            }
            Node::Ln(data) | Node::Exp(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                let value = self.digit_stack.borrow_mut().pop().unwrap();
                let result = if matches!(node, Node::Ln(_)) {
                    value.ln()
                } else {
                    value.exp()
                };
                self.digit_stack.borrow_mut().push(result);
                Ok(())
            }
            Node::Fif(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                let eps = self.digit_stack.borrow_mut().pop().unwrap();
                let right = self.digit_stack.borrow_mut().pop().unwrap();
                let left = self.digit_stack.borrow_mut().pop().unwrap();
                let value = self.digit_stack.borrow_mut().pop().unwrap();
                let half = eps * 0.5;
                let weight = (value + half).min(eps).max(NumericType::zero());
                self.digit_stack
                    .borrow_mut()
                    .push((right + ((left - right) / eps) * weight).into());
                Ok(())
            }
            Node::Cvg(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                let basis = self.string_stack.borrow_mut().pop().unwrap();
                let end = self.string_stack.borrow_mut().pop().unwrap();
                let start = self.string_stack.borrow_mut().pop().unwrap();
                let start = Date::from_str(&start, "%Y-%m-%d")?;
                let end = Date::from_str(&end, "%Y-%m-%d")?;
                let basis = DayCounter::try_from(basis)?;
                self.digit_stack
                    .borrow_mut()
                    .push(basis.year_fraction(start, end).into());
                Ok(())
            }
            Node::Append(data) => {
                *self.is_lhs_variable.borrow_mut() = true;
                self.const_visit(data.children.first().unwrap())?;
                *self.is_lhs_variable.borrow_mut() = false;
                self.const_visit(data.children.get(1).unwrap())?;

                let variable = self.lhs_variable.borrow().clone().ok_or_else(|| {
                    ScriptingError::EvaluationError("Invalid append target".to_string())
                })?;
                let Node::Variable(variable) = variable else {
                    return Err(ScriptingError::EvaluationError(
                        "Invalid append target".to_string(),
                    ));
                };
                let id = variable.id.ok_or_else(|| {
                    ScriptingError::EvaluationError(format!(
                        "Variable {} not indexed",
                        variable.name
                    ))
                })?;
                let value = if !self.boolean_stack.borrow().is_empty() {
                    Value::Bool(self.boolean_stack.borrow_mut().pop().unwrap())
                } else if !self.string_stack.borrow().is_empty() {
                    Value::String(self.string_stack.borrow_mut().pop().unwrap())
                } else if !self.array_stack.borrow().is_empty() {
                    Value::Array(self.array_stack.borrow_mut().pop().unwrap())
                } else {
                    Value::Number(self.digit_stack.borrow_mut().pop().unwrap())
                };
                let mut variables = self.variables.borrow_mut();
                match variables.get_mut(id).unwrap() {
                    Value::Array(array) => array.push(value),
                    slot @ Value::Null => *slot = Value::Array(vec![value]),
                    _ => {
                        return Err(ScriptingError::EvaluationError(
                            "Append on non-array".to_string(),
                        ))
                    }
                }
                Ok(())
            }
            Node::Mean(data) | Node::Std(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                let values = self.array_stack.borrow_mut().pop().unwrap_or_default();
                let numbers: Vec<NumericType> = values
                    .into_iter()
                    .filter_map(|value| match value {
                        Value::Number(number) => Some(number),
                        _ => None,
                    })
                    .collect();
                if numbers.is_empty() {
                    return Err(ScriptingError::EvaluationError(
                        "statistic of empty array".to_string(),
                    ));
                }
                let count = numbers.len() as f64;
                let mut sum = NumericType::zero();
                for number in &numbers {
                    sum += *number;
                }
                let result = if matches!(node, Node::Mean(_)) {
                    (sum / count).into()
                } else {
                    let mean = sum / count;
                    let mut variance = NumericType::zero();
                    for number in numbers {
                        let difference = number - mean;
                        variance += difference * difference;
                    }
                    (variance / count).sqrt().into()
                };
                self.digit_stack.borrow_mut().push(result);
                Ok(())
            }
            Node::Range(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                let end = self.digit_stack.borrow_mut().pop().unwrap();
                let start = self.digit_stack.borrow_mut().pop().unwrap();
                self.array_stack.borrow_mut().push(
                    ((start.value().round() as i64)..=(end.value().round() as i64))
                        .map(|value| Value::Number((value as f64).into()))
                        .collect(),
                );
                Ok(())
            }
            Node::List(data) => {
                let mut values = Vec::with_capacity(data.children.len());
                for child in &data.children {
                    self.const_visit(child)?;
                    let value = if !self.boolean_stack.borrow().is_empty() {
                        Value::Bool(self.boolean_stack.borrow_mut().pop().unwrap())
                    } else if !self.string_stack.borrow().is_empty() {
                        Value::String(self.string_stack.borrow_mut().pop().unwrap())
                    } else if !self.array_stack.borrow().is_empty() {
                        Value::Array(self.array_stack.borrow_mut().pop().unwrap())
                    } else {
                        Value::Number(self.digit_stack.borrow_mut().pop().unwrap())
                    };
                    values.push(value);
                }
                self.array_stack.borrow_mut().push(values);
                Ok(())
            }
            Node::Index(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                self.const_visit(&data.index)?;
                let index = self.digit_stack.borrow_mut().pop().unwrap().value().round() as usize;
                let values = self.array_stack.borrow_mut().pop().unwrap_or_default();
                let value = values.get(index).cloned().ok_or_else(|| {
                    ScriptingError::EvaluationError("Index out of bounds".to_string())
                })?;
                match value {
                    Value::Bool(value) => self.boolean_stack.borrow_mut().push(value),
                    Value::Number(value) => self.digit_stack.borrow_mut().push(value),
                    Value::String(value) => self.string_stack.borrow_mut().push(value),
                    Value::Array(value) => self.array_stack.borrow_mut().push(value),
                    Value::Null => self.array_stack.borrow_mut().push(Vec::new()),
                }
                Ok(())
            }
            Node::ForEach(data) => {
                self.const_visit(&data.node)?;
                let values = self.array_stack.borrow_mut().pop().unwrap_or_default();
                let id = data.id.ok_or_else(|| {
                    ScriptingError::EvaluationError("Loop variable not indexed".to_string())
                })?;
                for value in values {
                    self.set_variable(id, value);
                    for child in &data.children {
                        self.const_visit(child)?;
                    }
                }
                Ok(())
            }
            Node::NotEqual(data) => {
                for child in &data.children {
                    self.const_visit(child)?;
                }
                let right = self.digit_stack.borrow_mut().pop().unwrap();
                let left = self.digit_stack.borrow_mut().pop().unwrap();
                self.boolean_stack
                    .borrow_mut()
                    .push((right - left).abs() >= f64::EPSILON);
                Ok(())
            }

            /* ─────────────── literals ─────────────── */
            Node::True => {
                self.dt_stack.borrow_mut().push(NumericType::one());
                Ok(())
            }
            Node::False => {
                self.dt_stack.borrow_mut().push(NumericType::zero());
                Ok(())
            }

            /* ─────────────── comparison ─────────────── */
            Node::Equal(data) => {
                let (expr, eps) = self.comparison_input(&data.children[0])?;

                let dt = if data.discrete {
                    self.bfly_bounds(expr, data.lb, data.rb)
                } else {
                    self.bfly(expr, eps)
                };
                self.dt_stack.borrow_mut().push(dt);
                Ok(())
            }

            Node::Superior(data) | Node::SuperiorOrEqual(data) => {
                let (expr, eps) = self.comparison_input(&data.children[0])?;

                let dt = if data.discrete {
                    self.c_spr_bounds(expr, data.lb, data.rb)
                } else {
                    self.c_spr(expr, eps)
                };
                self.dt_stack.borrow_mut().push(dt);
                Ok(())
            }

            /* ─────────────── combinators ─────────────── */
            Node::And(data) => {
                self.const_visit(&data.children[0])?;
                self.const_visit(&data.children[1])?;
                let b2 = self.dt_stack.borrow_mut().pop().unwrap();
                let b1 = self.dt_stack.borrow_mut().pop().unwrap();
                let res: NumericType = (b1 * b2).into();
                self.dt_stack.borrow_mut().push(res);
                Ok(())
            }
            Node::Or(data) => {
                self.const_visit(&data.children[0])?;
                self.const_visit(&data.children[1])?;
                let b2 = self.dt_stack.borrow_mut().pop().unwrap();
                let b1 = self.dt_stack.borrow_mut().pop().unwrap();
                let dt: NumericType = (b1 + b2 - (b1 * b2)).into();
                self.dt_stack.borrow_mut().push(dt);
                Ok(())
            }
            Node::Not(data) => {
                self.const_visit(&data.children[0])?;
                let b = self.dt_stack.borrow_mut().pop().unwrap();
                let dt: NumericType = (NumericType::one() - b).into();
                self.dt_stack.borrow_mut().push(dt);
                Ok(())
            }

            /* ─────────────── if / else ─────────────── */
            Node::If(data) => {
                // keep 1-based depth like the C++ code
                self.nested_if_lvl.set(self.nested_if_lvl.get() + 1);
                let last_true = data.first_else.unwrap_or(data.children.len()) - 1;

                /* ── evaluate condition ── */
                self.const_visit(&data.children[0])?;
                let dt = self.dt_stack.borrow_mut().pop().unwrap();

                /* ── dt ≈ true ── */
                if dt.value() > ONE_MINUS_EPS {
                    for c in data.children.iter().skip(1).take(last_true) {
                        self.const_visit(c)?;
                    }
                }
                /* ── dt ≈ false ── */
                else if dt.value() < EPS {
                    if let Some(start) = data.first_else {
                        for c in data.children.iter().skip(start) {
                            self.const_visit(c)?;
                        }
                    }
                }
                /* ── fuzzy branch ── */
                else {
                    /* backup current values */

                    let parent_weight = *self.branch_weight.borrow();

                    let store0 = &mut self.var_store0.borrow_mut()[self.nested_if_lvl.get() - 1];

                    data.affected_vars.iter().for_each(|&idx| {
                        store0[idx] = match self.variables.borrow()[idx] {
                            Value::Number(n) => n,
                            _ => panic!("expected numeric var"),
                        }
                    });

                    /* evaluate “then”-branch */
                    *self.branch_weight.borrow_mut() = (parent_weight * dt).into();
                    for c in data.children.iter().skip(1).take(last_true) {
                        self.const_visit(c)?;
                    }

                    /* record “then” result and restore backup */

                    let store1 = &mut self.var_store1.borrow_mut()[self.nested_if_lvl.get() - 1];
                    data.affected_vars.iter().for_each(|&idx| {
                        let v = match self.variables.borrow()[idx] {
                            Value::Number(n) => n,
                            _ => panic!("expected numeric var"),
                        };
                        store1[idx] = v;
                        self.variables.borrow_mut()[idx] = Value::Number(store0[idx]);
                    });

                    /* evaluate “else”-branch (if any) */
                    *self.branch_weight.borrow_mut() =
                        (parent_weight * (NumericType::one() - dt)).into();
                    if let Some(start) = data.first_else {
                        for c in data.children.iter().skip(start) {
                            self.const_visit(c)?;
                        }
                    }

                    /* final fuzzy blend */
                    data.affected_vars.iter().for_each(|&idx| {
                        let v_true = store1[idx];
                        let v_false = match self.variables.borrow()[idx] {
                            Value::Number(n) => n,
                            _ => panic!("expected numeric var"),
                        };
                        let v = Value::Number((dt * v_true + (-dt + 1.0) * v_false).into());
                        self.variables.borrow_mut()[idx] = v;
                    });
                    *self.branch_weight.borrow_mut() = parent_weight;
                }

                /* leave this `if` */
                self.nested_if_lvl.set(self.nested_if_lvl.get() - 1);
                Ok(())
            }

            /* ─────────────── unhandled ─────────────── */
            _ => Err(ScriptingError::EvaluationError(
                "Node not implemented".into(),
            )),
        }
    }
}

impl FuzzyEvaluator<'_> {
    /// Evaluates every event and returns values keyed by variable name.
    ///
    /// # Errors
    /// Returns an error when an event expression cannot be evaluated.
    pub fn visit_events(
        &self,
        event_stream: &crate::scripting::nodes::event::EventStream,
        var_indexes: &std::collections::HashMap<String, usize>,
    ) -> Result<std::collections::HashMap<String, Value>> {
        event_stream
            .events()
            .iter()
            .enumerate()
            .try_for_each(|(event_index, event)| {
                self.set_current_event(event_index);
                *self.current_event_date.borrow_mut() = Some(event.event_date());
                self.const_visit(event.expr())
            })?;

        let variables = self.variables.borrow();
        Ok(var_indexes
            .iter()
            .filter_map(|(name, index)| {
                variables
                    .get(*index)
                    .cloned()
                    .map(|value| (name.clone(), value))
            })
            .collect())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        ad::{scalar::Scalar, tape::Tape},
        scripting::{
            nodes::traits::NodeVisitor,
            parsing::{lexer::Lexer, parser::Parser},
            visitors::{
                domainprocessor::DomainProcessor, ifprocessor::IfProcessor, varindexer::VarIndexer,
            },
        },
    };

    #[test]
    fn test_basic_assignment() {
        let script = "x = 1; y = x + 2;".to_string();
        let tokens = Lexer::new(script).tokenize().unwrap();
        let mut nodes = Parser::new(tokens).parse().unwrap();

        let indexer = VarIndexer::new();
        indexer.visit(&mut nodes).unwrap();

        let processor = IfProcessor::new();
        processor.visit(&mut nodes).unwrap();

        let evaluator =
            FuzzyEvaluator::new(indexer.get_variables_size(), processor.max_nested_ifs());
        evaluator.const_visit(&nodes).unwrap();

        assert_eq!(
            evaluator.variables(),
            vec![
                Value::Number(NumericType::new(1.0)),
                Value::Number(NumericType::new(3.0)),
            ]
        );
    }

    #[test]
    fn test_simple_if_condition() {
        let script = "x = 1; if x > 0 { x = 2; }".to_string();
        let tokens = Lexer::new(script).tokenize().unwrap();
        let mut nodes = Parser::new(tokens).parse().unwrap();

        let indexer = VarIndexer::new();
        indexer.visit(&mut nodes).unwrap();

        let processor = IfProcessor::new();
        processor.visit(&mut nodes).unwrap();

        let evaluator =
            FuzzyEvaluator::new(indexer.get_variables_size(), processor.max_nested_ifs());

        evaluator.const_visit(&nodes).unwrap();

        assert_eq!(
            evaluator.variables(),
            vec![Value::Number(NumericType::new(2.0))]
        );
    }

    #[test]
    fn test_simple_if_condition2() {
        let script = "x = 0; if x-1 > 0 { x = 2; }".to_string();
        let tokens = Lexer::new(script).tokenize().unwrap();
        let mut nodes = Parser::new(tokens).parse().unwrap();

        let indexer = VarIndexer::new();
        indexer.visit(&mut nodes).unwrap();

        let processor = IfProcessor::new();
        processor.visit(&mut nodes).unwrap();

        let evaluator =
            FuzzyEvaluator::new(indexer.get_variables_size(), processor.max_nested_ifs());

        evaluator.const_visit(&nodes).unwrap();

        assert_eq!(
            evaluator.variables(),
            vec![Value::Number(NumericType::new(0.0))]
        );
    }

    #[test]
    fn test_fuzzy_case() {
        Tape::start_recording_fwd();

        let script1 = "x = 0; y = 0; if x > 0 { y = 1; }".to_string();
        let tokens = Lexer::new(script1).tokenize().unwrap();
        let mut script1_nodes = Parser::new(tokens).parse().unwrap();

        let indexer = VarIndexer::new();
        indexer.visit(&mut script1_nodes).unwrap();

        let if_processor = IfProcessor::new();
        if_processor.visit(&mut script1_nodes).unwrap();
        let domain_processor = DomainProcessor::new(indexer.get_variables_size());
        domain_processor.visit(&mut script1_nodes).unwrap();

        let fuzzy_evaluator =
            FuzzyEvaluator::new(indexer.get_variables_size(), if_processor.max_nested_ifs())
                .with_eps(1.0);

        fuzzy_evaluator.const_visit(&script1_nodes).unwrap();

        let eval_vars = fuzzy_evaluator.variables();
        let y = match eval_vars.get(1).unwrap() {
            Value::Number(n) => {
                n.backward().unwrap();
                n.value()
            }
            _ => panic!("Expected y to be a number"),
        };

        let result = match eval_vars.get(0).unwrap() {
            Value::Number(n) => n.adjoint().unwrap(),
            _ => panic!("Expected x to be a number"),
        };

        assert!((result - 1.0).abs() < 1e-12, "Results do not match");
        assert!((y - 0.5).abs() < 1e-12, "y should be 0.5");

        Tape::stop_recording_fwd();
    }
}