antecedent-expr 0.5.2

Arena-backed symbolic IR for causal functionals (estimands) in the Antecedent engine; start with the `antecedent` crate
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
//! Arena-backed causal-functional IR.
//!
//! # Modules
//!
//! - [`estimand`] — identified estimand + method tags
//! - [`eval`] — compiled evaluators over providers
//! - [`simplify`] — algebraic simplification
//! - [`pretty`] / [`latex`] — display helpers
//! - [`provider`] — distribution / table / posterior providers
//!
//! SPDX-License-Identifier: MIT OR Apache-2.0

#![forbid(unsafe_code)]
#![deny(missing_docs)]

pub mod estimand;
pub mod eval;
pub mod latex;
pub mod pretty;
pub mod provider;
pub mod simplify;

pub use estimand::{EstimandMethod, IdentifiedEstimand, RdDesignParams};
pub use eval::CompiledEvaluator;
pub use provider::{
    Assignment, DistributionProvider, EmpiricalTableProvider, EvalContext, EvalError, FactorSpec,
    GaussianDensityProvider, PosteriorDrawProvider, QuadratureNodes,
};
pub use simplify::SimplifyError;

use latex::latex_expr;
use pretty::pretty_expr;

use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

use antecedent_core::{Value, VariableId};

/// Opaque expression node id.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ExprId(u32);

impl ExprId {
    /// Create from a raw index (tests / deserialization).
    #[must_use]
    pub const fn from_raw(raw: u32) -> Self {
        Self(raw)
    }

    /// Raw index.
    #[must_use]
    pub const fn raw(self) -> u32 {
        self.0
    }
}

/// Interned sorted variable set id.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct VarSetId(u32);

impl VarSetId {
    /// Create from a raw index (deserialization).
    #[must_use]
    pub const fn from_raw(raw: u32) -> Self {
        Self(raw)
    }

    /// Raw index.
    #[must_use]
    pub const fn raw(self) -> u32 {
        self.0
    }
}

/// Interned intervention-set id (hard assignments `do(V := value)`).
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct InterventionSetId(u32);

impl InterventionSetId {
    /// Create from a raw index (deserialization).
    #[must_use]
    pub const fn from_raw(raw: u32) -> Self {
        Self(raw)
    }

    /// Raw index.
    #[must_use]
    pub const fn raw(self) -> u32 {
        self.0
    }
}

/// One hard intervention assignment in an interned set.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct InterventionAssignment {
    /// Target variable.
    pub variable: VariableId,
    /// Assigned value under `do(·)`.
    pub value: Value,
}

/// Contrast operator between two expressions.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum ContrastOp {
    /// Left − right.
    Difference,
}

/// Domain reference for a distribution .
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum DomainRef {
    /// Observational P(·).
    Observational,
    /// Interventional P(· | do(·)).
    Interventional,
}

/// Outcome function id .
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct OutcomeExprId(VariableId);

impl OutcomeExprId {
    /// Identity outcome Y.
    #[must_use]
    pub const fn identity(variable: VariableId) -> Self {
        Self(variable)
    }

    /// Underlying variable.
    #[must_use]
    pub const fn variable(self) -> VariableId {
        self.0
    }
}

/// Expression list id (product children).
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct ExprListId(u32);

impl ExprListId {
    /// Create from a raw index (deserialization).
    #[must_use]
    pub const fn from_raw(raw: u32) -> Self {
        Self(raw)
    }

    /// Raw index.
    #[must_use]
    pub const fn raw(self) -> u32 {
        self.0
    }
}

/// Semantic expression node (no derivation metadata).
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum ExprNode {
    /// Joint / conditional distribution factor.
    Distribution {
        /// Variables in the factor.
        variables: VarSetId,
        /// Conditioning set.
        conditioned_on: VarSetId,
        /// Intervention set (empty for observational).
        intervention: InterventionSetId,
        /// Domain.
        domain: DomainRef,
    },
    /// Product of factors.
    Product(ExprListId),
    /// Discrete marginalization.
    SumOut {
        /// Variables summed out.
        variables: VarSetId,
        /// Body.
        expr: ExprId,
    },
    /// Continuous marginalization.
    IntegralOut {
        /// Variables integrated out.
        variables: VarSetId,
        /// Body.
        expr: ExprId,
    },
    /// Ratio of expressions.
    Ratio {
        /// Numerator.
        numerator: ExprId,
        /// Denominator.
        denominator: ExprId,
    },
    /// Expectation of an outcome under a distribution.
    Expectation {
        /// Outcome function.
        function: OutcomeExprId,
        /// Distribution expression.
        distribution: ExprId,
    },
    /// Contrast of two expectations / functionals.
    Contrast {
        /// Left side.
        left: ExprId,
        /// Right side.
        right: ExprId,
        /// Operator.
        op: ContrastOp,
    },
}

/// Separate derivation metadata keyed by expression id.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DerivationMeta {
    /// Human-readable rule tag (e.g. `backdoor.adjustment`).
    pub rule: Arc<str>,
    /// Optional note.
    pub note: Option<Arc<str>>,
}

/// Arena for causal expressions with interned variable sets.
#[derive(Clone, Debug, Default)]
pub struct CausalExprArena {
    nodes: Vec<ExprNode>,
    var_sets: Vec<Arc<[VariableId]>>,
    var_set_index: HashMap<Arc<[VariableId]>, VarSetId>,
    interventions: Vec<Arc<[InterventionAssignment]>>,
    intervention_index: HashMap<Arc<[InterventionAssignment]>, InterventionSetId>,
    lists: Vec<Arc<[ExprId]>>,
    list_index: HashMap<Arc<[ExprId]>, ExprListId>,
    /// Hash-cons map from node → id.
    node_index: HashMap<ExprNode, ExprId>,
    /// Derivation metadata (optional; not part of semantic equality).
    derivation: HashMap<u32, DerivationMeta>,
    /// Cached id of the interned empty variable set. The empty sets are
    /// requested by nearly every builder and evaluator; caching skips the
    /// intern-table lookup on repeat calls.
    empty_var_set_id: Option<VarSetId>,
    /// Cached id of the interned empty intervention set (see above).
    empty_intervention_set_id: Option<InterventionSetId>,
}

impl CausalExprArena {
    /// Empty arena.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Intern a sorted variable set (sorts and dedups input).
    pub fn intern_var_set(&mut self, vars: impl IntoIterator<Item = VariableId>) -> VarSetId {
        let mut v: Vec<VariableId> = vars.into_iter().collect();
        v.sort_unstable();
        v.dedup();
        // Borrow-based lookup: allocate the Arc key only on a cache miss.
        if let Some(id) = self.var_set_index.get(v.as_slice()) {
            return *id;
        }
        let key: Arc<[VariableId]> = Arc::from(v);
        let id = VarSetId(u32::try_from(self.var_sets.len()).expect("var set id"));
        self.var_sets.push(Arc::clone(&key));
        self.var_set_index.insert(key, id);
        id
    }

    /// Intern a hard-intervention assignment set (sorted by variable id).
    pub fn intern_intervention_assignments(
        &mut self,
        assignments: impl IntoIterator<Item = InterventionAssignment>,
    ) -> InterventionSetId {
        let mut v: Vec<InterventionAssignment> = assignments.into_iter().collect();
        v.sort_by_key(|a| a.variable.raw());
        v.dedup_by_key(|a| a.variable.raw());
        if let Some(id) = self.intervention_index.get(v.as_slice()) {
            return *id;
        }
        let key: Arc<[InterventionAssignment]> = Arc::from(v);
        let id = InterventionSetId(u32::try_from(self.interventions.len()).expect("id"));
        self.interventions.push(Arc::clone(&key));
        self.intervention_index.insert(key, id);
        id
    }

    /// Intern an intervention over variables only (value unspecified / placeholder).
    pub fn intern_intervention_set(
        &mut self,
        vars: impl IntoIterator<Item = VariableId>,
    ) -> InterventionSetId {
        self.intern_intervention_assignments(
            vars.into_iter()
                .map(|variable| InterventionAssignment { variable, value: Value::f64(f64::NAN) }),
        )
    }

    /// Empty var set.
    pub fn empty_var_set(&mut self) -> VarSetId {
        if let Some(id) = self.empty_var_set_id {
            return id;
        }
        let id = self.intern_var_set([]);
        self.empty_var_set_id = Some(id);
        id
    }

    /// Empty intervention set.
    pub fn empty_intervention_set(&mut self) -> InterventionSetId {
        if let Some(id) = self.empty_intervention_set_id {
            return id;
        }
        let id = self.intern_intervention_assignments([]);
        self.empty_intervention_set_id = Some(id);
        id
    }

    /// Look up a var set.
    #[must_use]
    pub fn var_set(&self, id: VarSetId) -> &[VariableId] {
        &self.var_sets[id.0 as usize]
    }

    /// Look up intervention assignments.
    #[must_use]
    pub fn intervention_assignments(&self, id: InterventionSetId) -> &[InterventionAssignment] {
        &self.interventions[id.0 as usize]
    }

    /// Variables appearing in an intervention set (legacy helper).
    #[must_use]
    pub fn intervention_set(&self, id: InterventionSetId) -> Vec<VariableId> {
        self.intervention_assignments(id).iter().map(|a| a.variable).collect()
    }

    /// Intern an expression list.
    pub fn intern_list(&mut self, exprs: impl IntoIterator<Item = ExprId>) -> ExprListId {
        let v: Vec<ExprId> = exprs.into_iter().collect();
        if let Some(id) = self.list_index.get(v.as_slice()) {
            return *id;
        }
        let key: Arc<[ExprId]> = Arc::from(v);
        let id = ExprListId(u32::try_from(self.lists.len()).expect("list id"));
        self.lists.push(Arc::clone(&key));
        self.list_index.insert(key, id);
        id
    }

    /// Borrow an interned expression list.
    #[must_use]
    pub fn list(&self, id: ExprListId) -> &[ExprId] {
        &self.lists[id.0 as usize]
    }

    /// Hash-cons an expression node.
    pub fn intern(&mut self, node: ExprNode) -> ExprId {
        if let Some(id) = self.node_index.get(&node) {
            return *id;
        }
        let id = ExprId(u32::try_from(self.nodes.len()).expect("expr id"));
        self.nodes.push(node.clone());
        self.node_index.insert(node, id);
        id
    }

    /// Attach derivation metadata (does not affect semantic equality).
    pub fn set_derivation(&mut self, id: ExprId, meta: DerivationMeta) {
        self.derivation.insert(id.0, meta);
    }

    /// Attach derivation metadata only when absent (never overwrites ID rules).
    pub fn set_derivation_if_absent(&mut self, id: ExprId, meta: DerivationMeta) {
        self.derivation.entry(id.0).or_insert(meta);
    }

    /// Simplify `root` with worklist-style bottom-up rewrite + memoization.
    ///
    /// # Errors
    ///
    /// [`SimplifyError`] if a `SumOut`/`IntegralOut` binds a variable absent from its
    /// body's free variables — an ill-formed estimand. See [`SimplifyError`] docs.
    pub fn simplify(&mut self, root: ExprId) -> Result<ExprId, SimplifyError> {
        simplify::simplify(self, root)
    }

    /// Borrow derivation metadata.
    #[must_use]
    pub fn derivation(&self, id: ExprId) -> Option<&DerivationMeta> {
        self.derivation.get(&id.0)
    }

    /// Borrow a node.
    #[must_use]
    pub fn node(&self, id: ExprId) -> &ExprNode {
        &self.nodes[id.0 as usize]
    }

    /// Number of nodes.
    #[must_use]
    pub fn len(&self) -> usize {
        self.nodes.len()
    }

    /// Whether empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    /// Number of interned variable sets (for serialization).
    #[must_use]
    pub fn var_set_count(&self) -> usize {
        self.var_sets.len()
    }

    /// Number of interned intervention sets (for serialization).
    #[must_use]
    pub fn intervention_set_count(&self) -> usize {
        self.interventions.len()
    }

    /// Number of interned expression lists (for serialization).
    #[must_use]
    pub fn list_count(&self) -> usize {
        self.lists.len()
    }

    /// Build the backdoor adjustment functional for ATE:
    /// `E[Y | do(T=active)] − E[Y | do(T=control)]` under adjustment by Z.
    pub fn backdoor_ate(
        &mut self,
        treatment: VariableId,
        outcome: VariableId,
        adjustment: &[VariableId],
        active: Value,
        control: Value,
    ) -> ExprId {
        let left = self.backdoor_potential_outcome(treatment, outcome, adjustment, active);
        let right = self.backdoor_potential_outcome(treatment, outcome, adjustment, control);
        let contrast = self.intern(ExprNode::Contrast { left, right, op: ContrastOp::Difference });
        self.set_derivation(
            contrast,
            DerivationMeta {
                rule: Arc::from("backdoor.adjustment"),
                note: Some(Arc::from(format!("ATE adjustment set size {}", adjustment.len()))),
            },
        );
        contrast
    }

    fn backdoor_potential_outcome(
        &mut self,
        treatment: VariableId,
        outcome: VariableId,
        adjustment: &[VariableId],
        level: Value,
    ) -> ExprId {
        let z = self.intern_var_set(adjustment.iter().copied());
        let y = self.intern_var_set([outcome]);
        let empty = self.empty_var_set();
        let empty_i = self.empty_intervention_set();
        let do_t = self.intern_intervention_assignments([InterventionAssignment {
            variable: treatment,
            value: level,
        }]);

        let dist_body = self.intern(ExprNode::Distribution {
            variables: y,
            conditioned_on: z,
            intervention: do_t,
            domain: DomainRef::Interventional,
        });
        let z_marg = self.intern(ExprNode::Distribution {
            variables: z,
            conditioned_on: empty,
            intervention: empty_i,
            domain: DomainRef::Observational,
        });
        let product = {
            let list = self.intern_list([dist_body, z_marg]);
            self.intern(ExprNode::Product(list))
        };
        let summed = self.intern(ExprNode::SumOut { variables: z, expr: product });
        self.intern(ExprNode::Expectation {
            function: OutcomeExprId::identity(outcome),
            distribution: summed,
        })
    }

    /// Build the front-door functional for ATE:
    /// `E[Y | do(T=active)] − E[Y | do(T=control)]`, mediated through `M` via
    /// `sum_m P(m | t) * sum_t' P(y | m, t') P(t')` (FD condition 2 reduces
    /// `P(m | do(t))` to the observational `P(m | t)`).
    pub fn frontdoor_ate(
        &mut self,
        treatment: VariableId,
        outcome: VariableId,
        mediators: &[VariableId],
        active: Value,
        control: Value,
    ) -> ExprId {
        let left = self.frontdoor_potential_outcome(treatment, outcome, mediators, active);
        let right = self.frontdoor_potential_outcome(treatment, outcome, mediators, control);
        let contrast = self.intern(ExprNode::Contrast { left, right, op: ContrastOp::Difference });
        self.set_derivation(
            contrast,
            DerivationMeta {
                rule: Arc::from("frontdoor"),
                note: Some(Arc::from(format!("front-door mediator set size {}", mediators.len()))),
            },
        );
        contrast
    }

    /// Linear temporal-mediation path-product ATE contrast (same product-of-coefficients
    /// geometry as front-door under a linear SEM, tagged `temporal_mediation` — not front-door).
    pub fn temporal_mediation_ate(
        &mut self,
        treatment: VariableId,
        outcome: VariableId,
        mediators: &[VariableId],
        active: Value,
        control: Value,
    ) -> ExprId {
        let left = self.frontdoor_potential_outcome(treatment, outcome, mediators, active);
        let right = self.frontdoor_potential_outcome(treatment, outcome, mediators, control);
        let contrast = self.intern(ExprNode::Contrast { left, right, op: ContrastOp::Difference });
        self.set_derivation(
            contrast,
            DerivationMeta {
                rule: Arc::from("temporal_mediation"),
                note: Some(Arc::from(format!(
                    "linear temporal mediation path-product; mediator set size {}",
                    mediators.len()
                ))),
            },
        );
        contrast
    }

    fn frontdoor_potential_outcome(
        &mut self,
        treatment: VariableId,
        outcome: VariableId,
        mediators: &[VariableId],
        level: Value,
    ) -> ExprId {
        let m = self.intern_var_set(mediators.iter().copied());
        let y = self.intern_var_set([outcome]);
        let t = self.intern_var_set([treatment]);
        let m_and_t = self.intern_var_set(mediators.iter().copied().chain([treatment]));
        let empty = self.empty_var_set();
        let empty_i = self.empty_intervention_set();
        let do_t = self.intern_intervention_assignments([InterventionAssignment {
            variable: treatment,
            value: level,
        }]);

        // P(m | t): observational under FD condition 2; treatment level bound so
        // the evaluator treats it as fixed (not free).
        let m_given_t = self.intern(ExprNode::Distribution {
            variables: m,
            conditioned_on: t,
            intervention: do_t,
            domain: DomainRef::Observational,
        });
        // P(y | m, t').
        let y_given_m_t = self.intern(ExprNode::Distribution {
            variables: y,
            conditioned_on: m_and_t,
            intervention: empty_i,
            domain: DomainRef::Observational,
        });
        // P(t').
        let t_marginal = self.intern(ExprNode::Distribution {
            variables: t,
            conditioned_on: empty,
            intervention: empty_i,
            domain: DomainRef::Observational,
        });
        let inner_product = {
            let list = self.intern_list([y_given_m_t, t_marginal]);
            self.intern(ExprNode::Product(list))
        };
        let inner_summed = self.intern(ExprNode::SumOut { variables: t, expr: inner_product });
        let outer_product = {
            let list = self.intern_list([m_given_t, inner_summed]);
            self.intern(ExprNode::Product(list))
        };
        let outer_summed = self.intern(ExprNode::SumOut { variables: m, expr: outer_product });
        self.intern(ExprNode::Expectation {
            function: OutcomeExprId::identity(outcome),
            distribution: outer_summed,
        })
    }

    /// Build the Wald IV functional for binary instrument `Z`:
    /// `(E[Y|Z=1] − E[Y|Z=0]) / (E[T|Z=1] − E[T|Z=0])`.
    ///
    /// `active` / `control` are recorded in derivation metadata (treatment contrast
    /// scaling); the ratio itself conditions on instrument levels 1 and 0.
    pub fn iv_wald(
        &mut self,
        treatment: VariableId,
        outcome: VariableId,
        instruments: &[VariableId],
        active: &Value,
        control: &Value,
    ) -> ExprId {
        let z = instruments.first().copied().unwrap_or(treatment);
        let z1 = Value::f64(1.0);
        let z0 = Value::f64(0.0);
        let outcome_given_z1 = self.observational_conditional_mean(outcome, z, z1.clone());
        let outcome_given_z0 = self.observational_conditional_mean(outcome, z, z0.clone());
        let treatment_given_z1 = self.observational_conditional_mean(treatment, z, z1);
        let treatment_given_z0 = self.observational_conditional_mean(treatment, z, z0);
        let num = self.intern(ExprNode::Contrast {
            left: outcome_given_z1,
            right: outcome_given_z0,
            op: ContrastOp::Difference,
        });
        let den = self.intern(ExprNode::Contrast {
            left: treatment_given_z1,
            right: treatment_given_z0,
            op: ContrastOp::Difference,
        });
        let ratio = self.intern(ExprNode::Ratio { numerator: num, denominator: den });
        self.set_derivation(
            ratio,
            DerivationMeta {
                rule: Arc::from("iv.wald"),
                note: Some(Arc::from(format!(
                    "Wald IV ratio using {} instrument(s); treatment contrast [{active:?}, {control:?}]",
                    instruments.len()
                ))),
            },
        );
        ratio
    }

    /// Observational `E[outcome | conditioner = level]`.
    ///
    /// The conditioning level is bound via an intervention assignment so the
    /// evaluator treats it as fixed (not free), while the factor remains
    /// observational `P(outcome | conditioner)`.
    fn observational_conditional_mean(
        &mut self,
        outcome: VariableId,
        conditioner: VariableId,
        level: Value,
    ) -> ExprId {
        let y = self.intern_var_set([outcome]);
        let z = self.intern_var_set([conditioner]);
        let bind = self.intern_intervention_assignments([InterventionAssignment {
            variable: conditioner,
            value: level,
        }]);
        let dist = self.intern(ExprNode::Distribution {
            variables: y,
            conditioned_on: z,
            intervention: bind,
            domain: DomainRef::Observational,
        });
        self.intern(ExprNode::Expectation {
            function: OutcomeExprId::identity(outcome),
            distribution: dist,
        })
    }

    /// Pretty-print an expression (diagnostics only; not an equality key).
    #[must_use]
    pub fn pretty(&self, id: ExprId) -> String {
        pretty_expr(self, id)
    }

    /// Render an expression as LaTeX (diagnostics only; not an equality key).
    #[must_use]
    pub fn latex(&self, id: ExprId) -> String {
        latex_expr(self, id)
    }
}

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

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

    #[test]
    fn var_sets_are_sorted_and_interned() {
        let mut a = CausalExprArena::new();
        let s1 = a.intern_var_set([VariableId::from_raw(2), VariableId::from_raw(1)]);
        let s2 = a.intern_var_set([VariableId::from_raw(1), VariableId::from_raw(2)]);
        assert_eq!(s1, s2);
        assert_eq!(a.var_set(s1), &[VariableId::from_raw(1), VariableId::from_raw(2)]);
    }

    #[test]
    fn hash_cons_reuses_nodes() {
        let mut a = CausalExprArena::new();
        let empty = a.empty_var_set();
        let empty_i = a.empty_intervention_set();
        let n1 = a.intern(ExprNode::Distribution {
            variables: empty,
            conditioned_on: empty,
            intervention: empty_i,
            domain: DomainRef::Observational,
        });
        let n2 = a.intern(ExprNode::Distribution {
            variables: empty,
            conditioned_on: empty,
            intervention: empty_i,
            domain: DomainRef::Observational,
        });
        assert_eq!(n1, n2);
        assert_eq!(a.len(), 1);
    }

    #[test]
    fn backdoor_ate_contrasts_distinct_levels() {
        let mut a = CausalExprArena::new();
        let id = a.backdoor_ate(
            VariableId::from_raw(0),
            VariableId::from_raw(1),
            &[VariableId::from_raw(2)],
            Value::f64(1.0),
            Value::f64(0.0),
        );
        let meta = a.derivation(id).unwrap();
        assert_eq!(&*meta.rule, "backdoor.adjustment");
        let ExprNode::Contrast { left, right, .. } = a.node(id) else {
            panic!("expected contrast");
        };
        assert_ne!(left, right);
        let pretty = a.pretty(id);
        assert!(pretty.contains('') || pretty.contains("E["));
        let latex = a.latex(id);
        assert!(latex.contains("\\mathbb{E}") || latex.contains("\\mathrm{do}"));
        assert!(latex.contains('-'));
    }

    #[test]
    fn frontdoor_ate_contrasts_distinct_levels() {
        let mut a = CausalExprArena::new();
        let id = a.frontdoor_ate(
            VariableId::from_raw(0),
            VariableId::from_raw(1),
            &[VariableId::from_raw(2)],
            Value::f64(1.0),
            Value::f64(0.0),
        );
        let meta = a.derivation(id).unwrap();
        assert_eq!(&*meta.rule, "frontdoor");
        let ExprNode::Contrast { left, right, .. } = a.node(id) else {
            panic!("expected contrast");
        };
        assert_ne!(left, right);
    }

    #[test]
    fn iv_wald_is_ratio_of_instrument_contrasts() {
        let mut a = CausalExprArena::new();
        let id = a.iv_wald(
            VariableId::from_raw(0),
            VariableId::from_raw(1),
            &[VariableId::from_raw(2)],
            &Value::f64(1.0),
            &Value::f64(0.0),
        );
        let meta = a.derivation(id).unwrap();
        assert_eq!(&*meta.rule, "iv.wald");
        let ExprNode::Ratio { numerator, denominator } = a.node(id) else {
            panic!("expected Wald ratio");
        };
        assert!(matches!(a.node(*numerator), ExprNode::Contrast { .. }));
        assert!(matches!(a.node(*denominator), ExprNode::Contrast { .. }));
        assert_ne!(*numerator, *denominator);
    }
}