antecedent-estimate 0.5.2

Frequentist and Bayesian estimators for identified causal effects 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
//! Propensity-based estimators: weighting, stratification, and matching.
//!
//! All estimators here require propensity-based positivity diagnostics
//! ([`OverlapPolicy::RequireDiagnostics`](crate::OverlapPolicy::RequireDiagnostics)) —
//! [`OverlapPolicy::ExplicitOverride`](crate::OverlapPolicy::ExplicitOverride) is refused
//! because positivity is mandatory for propensity/matching methods.
//!
//! Bootstrap standard errors **refit the propensity model on every resample** rather than
//! reusing the point-estimate propensity scores. This is more expensive than score-reuse,
//! but it propagates first-stage estimation uncertainty into the second-stage effect.
//! [`antecedent_stats::PropensityWorkspace`] scratch (IRLS design/Cholesky buffers) is reused
//! across replicates to keep per-replicate cost to a single GLM refit.
//!
//! **Matching caveat:** for nearest-neighbor matching with a fixed number of matches, the
//! nonparametric bootstrap is asymptotically invalid (Abadie–Imbens 2008). Matching
//! estimators expose Abadie–Imbens (2006) analytic SEs with donor-reuse counts; treat any
//! matching bootstrap SE as diagnostic only.
//!
//! SPDX-License-Identifier: MIT OR Apache-2.0

#![allow(
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    clippy::similar_names,
    clippy::too_many_arguments,
    clippy::needless_range_loop,
    clippy::manual_memcpy,
    clippy::needless_pass_by_value
)]

mod distance;
mod matching;
mod prepare;
mod stratification;
pub(crate) mod weighting;

pub use distance::DistanceMatching;
pub use matching::{CaliperScale, PropensityMatching};
pub use prepare::{
    PreparedPropensityProblem, PropensityEstimationWorkspace, PropensityModel,
    default_propensity_overlap,
};
pub(crate) use prepare::{
    clamp_scores, clip_of, gather, gather_into, prepare_propensity_problem_with_registry,
    split_by_treatment, trim_of, trim_retained_rows,
};
pub use stratification::PropensityStratification;
pub use weighting::PropensityWeighting;

use crate::overlap::{IpwTarget, OverlapReport};

/// Build the mandatory positivity [`OverlapReport`] shared by every propensity-based
/// estimator's `fit`, from a prepared problem's `overlap`/`treatment`/`target_weights` fields.
///
/// `weights` carries computed IPW weights when the caller has them on hand — only
/// [`weighting::PropensityWeighting`] does; every other propensity estimator (and AIPW) passes
/// `None`.
pub(crate) fn propensity_overlap_report(
    problem: &PreparedPropensityProblem,
    scores: &[f64],
    weights: Option<&[f64]>,
    ipw_target: Option<IpwTarget>,
) -> OverlapReport {
    OverlapReport::from_propensities(
        scores,
        weights,
        problem.overlap,
        Some(&problem.treatment),
        ipw_target,
        problem.target_weights.as_deref(),
    )
}

#[cfg(test)]
#[allow(clippy::many_single_char_names, clippy::float_cmp)]
mod tests {
    use std::sync::Arc;

    use antecedent_core::{
        AssumptionSet, AverageEffectQuery, CausalSchemaBuilder, DistributionRef, ExecutionContext,
        MeasurementSpec, RoleHint, SmallRoleSet, TargetPopulation, ValueType, VariableId,
    };
    use antecedent_data::{
        Float64Column, OwnedColumn, OwnedColumnarStorage, TableView, TabularData, ValidityBitmap,
    };
    use antecedent_expr::ExprId;
    use antecedent_expr::IdentifiedEstimand;
    use antecedent_kernels::standard_normal;

    use super::*;
    use crate::error::EstimationError;
    use crate::overlap::OverlapPolicy;
    use crate::propensity::weighting::{hajek_difference, hajek_influence_se};

    fn confounded_scm(n: usize, seed: u64) -> (TabularData, IdentifiedEstimand) {
        let (t, y, z) = confounded_columns(n, seed);
        build_dataset(t, y, z)
    }

    fn confounded_columns(n: usize, seed: u64) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
        let mut rng = ExecutionContext::for_tests(seed).rng.stream(0x1234_u64);

        let mut z = vec![0.0; n];
        let mut t = vec![0.0; n];
        let mut y = vec![0.0; n];
        for i in 0..n {
            let zi = standard_normal(&mut rng);
            let logit = -0.5 + zi;
            let p = 1.0 / (1.0 + (-logit).exp());
            let ti = if rng.next_f64() < p { 1.0 } else { 0.0 };
            let noise = standard_normal(&mut rng) * 0.5;
            z[i] = zi;
            t[i] = ti;
            y[i] = 2.0 * ti + zi + noise;
        }
        (t, y, z)
    }

    /// `confounded_scm` plus one extreme-propensity treated outlier: `z = -8` puts its raw
    /// propensity near 2e-4 (outside any reasonable trim band) while `y = 1000` wrecks any
    /// estimator that fails to exclude it.
    fn confounded_scm_with_outlier(n: usize, seed: u64) -> (TabularData, IdentifiedEstimand) {
        let (mut t, mut y, mut z) = confounded_columns(n, seed);
        t.push(1.0);
        y.push(1000.0);
        z.push(-8.0);
        build_dataset(t, y, z)
    }

    fn build_dataset(t: Vec<f64>, y: Vec<f64>, z: Vec<f64>) -> (TabularData, IdentifiedEstimand) {
        let n = t.len();
        let mut b = CausalSchemaBuilder::new();
        b.add_variable(
            "t",
            ValueType::Continuous,
            SmallRoleSet::from_hint(RoleHint::TreatmentCandidate),
            None,
            None,
            MeasurementSpec::default(),
        )
        .unwrap();
        b.add_variable(
            "y",
            ValueType::Continuous,
            SmallRoleSet::from_hint(RoleHint::OutcomeCandidate),
            None,
            None,
            MeasurementSpec::default(),
        )
        .unwrap();
        b.add_variable(
            "z",
            ValueType::Continuous,
            SmallRoleSet::from_hint(RoleHint::Context),
            None,
            None,
            MeasurementSpec::default(),
        )
        .unwrap();
        let schema = b.build().unwrap();
        let cols = vec![
            OwnedColumn::Float64(
                Float64Column::new(
                    VariableId::from_raw(0),
                    Arc::from(t),
                    ValidityBitmap::all_valid(n),
                )
                .unwrap(),
            ),
            OwnedColumn::Float64(
                Float64Column::new(
                    VariableId::from_raw(1),
                    Arc::from(y),
                    ValidityBitmap::all_valid(n),
                )
                .unwrap(),
            ),
            OwnedColumn::Float64(
                Float64Column::new(
                    VariableId::from_raw(2),
                    Arc::from(z),
                    ValidityBitmap::all_valid(n),
                )
                .unwrap(),
            ),
        ];
        let storage = OwnedColumnarStorage::try_new(schema, cols, None, None).unwrap();
        let estimand = IdentifiedEstimand::backdoor(
            "backdoor.adjustment",
            Arc::from([VariableId::from_raw(2)]),
            ExprId::from_raw(0),
        );
        (TabularData::new(storage), estimand)
    }

    fn ctx() -> ExecutionContext {
        ExecutionContext::for_tests(7)
    }

    /// Diagnostics-mandatory policy with an explicit trim band for the outlier tests.
    fn trim_overlap() -> OverlapPolicy {
        OverlapPolicy::RequireDiagnostics { clip: Some(0.01), trim: Some(0.02) }
    }

    #[test]
    fn weighting_recovers_ate_two() {
        let (data, estimand) = confounded_scm(800, 1);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1));
        let est = PropensityWeighting { bootstrap_replicates: 30, ..PropensityWeighting::new() };
        let prep = est.prepare(&data, &estimand, &query).unwrap();
        let mut ws = PropensityEstimationWorkspace::default();
        let effect = est.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();
        assert!((effect.ate - 2.0).abs() < 0.3, "ate={}", effect.ate);
        assert!(effect.se_bootstrap.is_some());
        assert!(effect.overlap_report.is_some());
    }

    #[test]
    fn weighting_att_target_population() {
        let (data, estimand) = confounded_scm(800, 2);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1))
                .with_target_population(TargetPopulation::Treated);
        let est = PropensityWeighting { bootstrap_replicates: 0, ..PropensityWeighting::new() };
        let prep = est.prepare(&data, &estimand, &query).unwrap();
        let mut ws = PropensityEstimationWorkspace::default();
        let effect = est.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();
        assert!((effect.ate - 2.0).abs() < 0.4, "att={}", effect.ate);
    }

    #[test]
    fn weighting_trim_analytic_se_uses_retained_n() {
        let (data, estimand) = confounded_scm_with_outlier(800, 21);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1));
        let untrimmed =
            PropensityWeighting { bootstrap_replicates: 0, ..PropensityWeighting::new() };
        let trimmed = PropensityWeighting { overlap: trim_overlap(), ..untrimmed.clone() };
        let mut ws = PropensityEstimationWorkspace::default();
        let raw = untrimmed
            .fit(
                &untrimmed.prepare(&data, &estimand, &query).unwrap(),
                &mut ws,
                &ctx(),
                AssumptionSet::new(),
            )
            .unwrap();
        let clean = trimmed
            .fit(
                &trimmed.prepare(&data, &estimand, &query).unwrap(),
                &mut ws,
                &ctx(),
                AssumptionSet::new(),
            )
            .unwrap();
        assert!(raw.se_analytic.is_finite() && clean.se_analytic.is_finite());
        assert!(clean.overlap_report.as_ref().unwrap().excluded_fraction > 0.0);
    }

    #[test]
    fn weighting_rejects_explicit_override() {
        let (data, estimand) = confounded_scm(200, 3);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1));
        let est = PropensityWeighting {
            overlap: OverlapPolicy::ExplicitOverride,
            ..PropensityWeighting::new()
        };
        let err = est.prepare(&data, &estimand, &query).unwrap_err();
        assert!(matches!(err, EstimationError::Overlap { .. }));
    }

    #[test]
    fn stratification_recovers_ate_two() {
        let (data, estimand) = confounded_scm(800, 4);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1));
        let est = PropensityStratification {
            bootstrap_replicates: 30,
            ..PropensityStratification::new()
        };
        let prep = est.prepare(&data, &estimand, &query).unwrap();
        let mut ws = PropensityEstimationWorkspace::default();
        let effect = est.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();
        assert!((effect.ate - 2.0).abs() < 0.3, "ate={}", effect.ate);
        assert!(effect.se_bootstrap.is_some());
    }

    #[test]
    fn stratification_rejects_explicit_override() {
        let (data, estimand) = confounded_scm(200, 5);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1));
        let est = PropensityStratification {
            overlap: OverlapPolicy::ExplicitOverride,
            ..PropensityStratification::new()
        };
        let err = est.prepare(&data, &estimand, &query).unwrap_err();
        assert!(matches!(err, EstimationError::Overlap { .. }));
    }

    #[test]
    fn propensity_matching_recovers_att() {
        let (data, estimand) = confounded_scm(800, 6);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1))
                .with_target_population(TargetPopulation::Treated);
        let est = PropensityMatching { bootstrap_replicates: 30, ..PropensityMatching::new() };
        let prep = est.prepare(&data, &estimand, &query).unwrap();
        let mut ws = PropensityEstimationWorkspace::default();
        let effect = est.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();
        assert!((effect.ate - 2.0).abs() < 0.3, "att={}", effect.ate);
        assert!(effect.se_bootstrap.is_some());
    }

    #[test]
    fn matching_index_reused_across_compatible_point_fits() {
        let (data, estimand) = confounded_scm(400, 7);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1))
                .with_target_population(TargetPopulation::Treated);
        let est = PropensityMatching { bootstrap_replicates: 0, ..PropensityMatching::new() };
        let prep = est.prepare(&data, &estimand, &query).unwrap();
        let mut ws = PropensityEstimationWorkspace::default();
        let _ = est.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();
        let builds_after_first = ws.matching_index_builds;
        assert!(builds_after_first >= 1);
        let _ = est.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();
        assert_eq!(
            ws.matching_index_builds, builds_after_first,
            "identical donor geometry must not rebuild MatchingIndex"
        );
    }

    #[test]
    fn bootstrap_reuses_propensity_workspace_buffers() {
        let (data, estimand) = confounded_scm(400, 10);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1));
        let est = PropensityWeighting { bootstrap_replicates: 40, ..PropensityWeighting::new() };
        let prep = est.prepare(&data, &estimand, &query).unwrap();
        let mut ws = PropensityEstimationWorkspace::default();
        let _ = est.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();
        let ols_grows = ws.propensity.ols.grow_count;
        let score_grows = ws.propensity.scores_grow_count;
        let scratch_ptr = ws.propensity.ols.scratch.as_ptr();
        let _ = est.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();
        assert_eq!(ws.propensity.ols.grow_count, ols_grows);
        assert_eq!(ws.propensity.scores_grow_count, score_grows);
        assert_eq!(ws.propensity.ols.scratch.as_ptr(), scratch_ptr);
    }

    #[test]
    fn propensity_matching_rejects_explicit_override() {
        let (data, estimand) = confounded_scm(200, 7);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1))
                .with_target_population(TargetPopulation::Treated);
        let est = PropensityMatching {
            overlap: OverlapPolicy::ExplicitOverride,
            ..PropensityMatching::new()
        };
        let err = est.prepare(&data, &estimand, &query).unwrap_err();
        assert!(matches!(err, EstimationError::Overlap { .. }));
    }

    #[test]
    fn distance_matching_recovers_att() {
        let (data, estimand) = confounded_scm(800, 8);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1))
                .with_target_population(TargetPopulation::Treated);
        let est = DistanceMatching { bootstrap_replicates: 30, ..DistanceMatching::new() };
        let prep = est.prepare(&data, &estimand, &query).unwrap();
        let mut ws = PropensityEstimationWorkspace::default();
        let effect = est.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();
        assert!((effect.ate - 2.0).abs() < 0.3, "att={}", effect.ate);
        assert!(effect.se_bootstrap.is_some());
        assert!(effect.overlap_report.is_some());
    }

    #[test]
    fn distance_matching_rejects_explicit_override() {
        let (data, estimand) = confounded_scm(200, 9);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1))
                .with_target_population(TargetPopulation::Treated);
        let est = DistanceMatching {
            overlap: OverlapPolicy::ExplicitOverride,
            ..DistanceMatching::new()
        };
        let err = est.prepare(&data, &estimand, &query).unwrap_err();
        assert!(matches!(err, EstimationError::Overlap { .. }));
    }

    #[test]
    fn prepare_rejects_non_binary_treatment_column() {
        // {1,2}-coded treatment must be refused, not silently dichotomized at t > 0.5.
        let (t, y, z) = confounded_columns(100, 11);
        let t: Vec<f64> = t.iter().map(|&ti| ti + 1.0).collect();
        let (data, estimand) = build_dataset(t, y, z);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1));
        let est = PropensityWeighting::new();
        let err = est.prepare(&data, &estimand, &query).unwrap_err();
        assert!(matches!(err, EstimationError::Data(_)), "err={err:?}");
        assert!(err.to_string().contains("binary treatment column"), "err={err}");
    }

    #[test]
    fn hajek_difference_errors_on_zero_weight_arm() {
        // All treated weight trimmed away: must surface an error, not a silent NaN.
        let treatment = [1.0, 1.0, 0.0, 0.0];
        let outcome = [3.0, 4.0, 1.0, 2.0];
        let weights = [0.0, 0.0, 1.0, 1.0];
        let err = hajek_difference(&treatment, &outcome, &weights).unwrap_err();
        assert!(matches!(err, EstimationError::Data(_)), "err={err:?}");
    }

    #[test]
    fn hajek_influence_se_zero_weight_rows_dilute_n() {
        // One treated unit trimmed (w=0). Same Hajek ψ, different n: full-sample
        // SE is anti-conservative relative to the retained-row SE.
        let t_full = [1.0, 1.0, 0.0, 0.0];
        let y_full = [3.0, 5.0, 1.0, 2.0];
        let w_full = [2.0, 0.0, 1.0, 1.0];
        let e_full = [0.5, 0.01, 0.5, 0.5];
        let se_full = hajek_influence_se(&t_full, &y_full, &w_full, &e_full, &[], 0).unwrap();
        let t_kept = [1.0, 0.0, 0.0];
        let y_kept = [3.0, 1.0, 2.0];
        let w_kept = [2.0, 1.0, 1.0];
        let e_kept = [0.5, 0.5, 0.5];
        let se_kept = hajek_influence_se(&t_kept, &y_kept, &w_kept, &e_kept, &[], 0).unwrap();
        assert!(
            se_kept > se_full,
            "retained-n SE must exceed full-n SE with zero-weight rows; full={se_full} kept={se_kept}"
        );
    }

    #[test]
    fn stratification_trim_excludes_extreme_propensity_unit() {
        let (data, estimand) = confounded_scm_with_outlier(800, 12);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1));
        let untrimmed =
            PropensityStratification { bootstrap_replicates: 0, ..PropensityStratification::new() };
        let trimmed = PropensityStratification { overlap: trim_overlap(), ..untrimmed.clone() };

        let mut ws = PropensityEstimationWorkspace::default();
        let prep = untrimmed.prepare(&data, &estimand, &query).unwrap();
        let raw = untrimmed.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();
        let prep = trimmed.prepare(&data, &estimand, &query).unwrap();
        let clean = trimmed.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();

        assert!((raw.ate - 2.0).abs() > 1.0, "outlier should distort untrimmed ate={}", raw.ate);
        assert!((clean.ate - 2.0).abs() < 0.35, "trimmed ate={}", clean.ate);
        let report = clean.overlap_report.as_ref().unwrap();
        assert!(report.excluded_fraction > 0.0, "trim must report exclusions");
    }

    #[test]
    fn propensity_matching_trim_excludes_extreme_propensity_unit() {
        let (data, estimand) = confounded_scm_with_outlier(800, 13);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1))
                .with_target_population(TargetPopulation::Treated);
        let untrimmed = PropensityMatching { bootstrap_replicates: 0, ..PropensityMatching::new() };
        let trimmed = PropensityMatching { overlap: trim_overlap(), ..untrimmed.clone() };

        let mut ws = PropensityEstimationWorkspace::default();
        let prep = untrimmed.prepare(&data, &estimand, &query).unwrap();
        let raw = untrimmed.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();
        let prep = trimmed.prepare(&data, &estimand, &query).unwrap();
        let clean = trimmed.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();

        assert!((raw.ate - 2.0).abs() > 1.0, "outlier should distort untrimmed att={}", raw.ate);
        assert!((clean.ate - 2.0).abs() < 0.35, "trimmed att={}", clean.ate);
        let report = clean.overlap_report.as_ref().unwrap();
        assert!(report.excluded_fraction > 0.0, "trim must report exclusions");
    }

    #[test]
    fn propensity_matching_trim_gathers_multiway_labels() {
        let (data, estimand) = confounded_scm_with_outlier(800, 15);
        let n = data.row_count();
        let dim_a: Vec<u32> = (0..n).map(|i| u32::try_from(i % 20).unwrap_or(0)).collect();
        let dim_b: Vec<u32> = (0..n).map(|i| u32::try_from(i % 15).unwrap_or(0)).collect();
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1))
                .with_target_population(TargetPopulation::Treated);
        let est = PropensityMatching {
            bootstrap_replicates: 0,
            overlap: trim_overlap(),
            se_kind: crate::se::AnalyticSeKind::Multiway,
            multiway_ids: Some(vec![dim_a, dim_b]),
            ..PropensityMatching::new()
        };
        let mut ws = PropensityEstimationWorkspace::default();
        let fit = est
            .fit(
                &est.prepare(&data, &estimand, &query).unwrap(),
                &mut ws,
                &ctx(),
                AssumptionSet::new(),
            )
            .unwrap();
        assert!(fit.se_analytic.is_finite() && fit.se_analytic > 0.0);
        assert!(fit.overlap_report.as_ref().unwrap().excluded_fraction > 0.0);
    }

    #[test]
    fn distance_matching_trim_excludes_extreme_propensity_unit() {
        let (data, estimand) = confounded_scm_with_outlier(800, 14);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1))
                .with_target_population(TargetPopulation::Treated);
        let untrimmed = DistanceMatching { bootstrap_replicates: 0, ..DistanceMatching::new() };
        let trimmed = DistanceMatching { overlap: trim_overlap(), ..untrimmed.clone() };

        let mut ws = PropensityEstimationWorkspace::default();
        let prep = untrimmed.prepare(&data, &estimand, &query).unwrap();
        let raw = untrimmed.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();
        let prep = trimmed.prepare(&data, &estimand, &query).unwrap();
        let clean = trimmed.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();

        assert!((raw.ate - 2.0).abs() > 1.0, "outlier should distort untrimmed att={}", raw.ate);
        assert!((clean.ate - 2.0).abs() < 0.35, "trimmed att={}", clean.ate);
        let report = clean.overlap_report.as_ref().unwrap();
        assert!(report.excluded_fraction > 0.0, "trim must report exclusions");
    }

    #[test]
    fn distance_matching_trim_gathers_multiway_labels() {
        let (data, estimand) = confounded_scm_with_outlier(800, 16);
        let n = data.row_count();
        let dim_a: Vec<u32> = (0..n).map(|i| u32::try_from(i % 20).unwrap_or(0)).collect();
        let dim_b: Vec<u32> = (0..n).map(|i| u32::try_from(i % 15).unwrap_or(0)).collect();
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1))
                .with_target_population(TargetPopulation::Treated);
        let est = DistanceMatching {
            bootstrap_replicates: 0,
            overlap: trim_overlap(),
            se_kind: crate::se::AnalyticSeKind::Multiway,
            multiway_ids: Some(vec![dim_a, dim_b]),
            ..DistanceMatching::new()
        };
        let mut ws = PropensityEstimationWorkspace::default();
        let fit = est
            .fit(
                &est.prepare(&data, &estimand, &query).unwrap(),
                &mut ws,
                &ctx(),
                AssumptionSet::new(),
            )
            .unwrap();
        assert!(fit.se_analytic.is_finite() && fit.se_analytic > 0.0);
        assert!(fit.overlap_report.as_ref().unwrap().excluded_fraction > 0.0);
    }

    #[test]
    fn custom_distribution_ipw_recovers_weighted_ate() {
        use antecedent_core::PopulationRegistry;

        // Uniform weights → same as ATE; half-weight on control → still recovers ~2.
        let (data, estimand) = confounded_scm(1_200, 21);
        let n = data.row_count();
        let mut weights = vec![1.0; n];
        for w in weights.iter_mut().take(n / 2) {
            *w = 0.5;
        }
        let dist = DistributionRef::from_raw(7);
        let mut registry = PopulationRegistry::new();
        registry.insert_distribution(dist, weights);

        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1))
                .with_target_population(TargetPopulation::CustomDistribution(dist));
        let mut est = PropensityWeighting::new();
        est.bootstrap_replicates = 0;
        est.population_registry = Some(registry);
        let prep = est.prepare(&data, &estimand, &query).unwrap();
        assert!(prep.target_weights.is_some());
        let mut ws = PropensityEstimationWorkspace::default();
        let fit = est.fit(&prep, &mut ws, &ctx(), AssumptionSet::new()).unwrap();
        assert!((fit.ate - 2.0).abs() < 0.35, "weighted ate={}", fit.ate);
    }

    #[test]
    fn custom_distribution_without_registry_is_unsupported() {
        let (data, estimand) = confounded_scm(200, 22);
        let query =
            AverageEffectQuery::binary_ate(VariableId::from_raw(0), VariableId::from_raw(1))
                .with_target_population(TargetPopulation::CustomDistribution(
                    DistributionRef::from_raw(1),
                ));
        let est = PropensityWeighting::new();
        let err = est.prepare(&data, &estimand, &query).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("PopulationRegistry")
                || msg.contains("registry")
                || msg.contains("Unsupported"),
            "err={msg}"
        );
    }
}