moonbit_doubleML

    Pure-MoonBit port of doubleml-for-py: Double / Debiased Machine Learning for partial linear, IRM, IV, DID, SSM, APO(S), PQ, QTE, LPQ, CVaR, RDD, BLP, and policy-tree models

    doubleml
    DML
    causal-inference
    machine-learning
    debiased-estimation
    Download zip
    Author
    Version
    0.164.62
    License
    MIT
    Last updated
    6 days ago
    Downloads
    2K

    #moonbit_doubleML - Double / Debiased Machine Learning in MoonBit

    CI

    A pure-MoonBit port of the doubleml-for-py Python package -- the Python ecosystem's most mature Double / Debiased Machine Learning implementation -- with 22 estimators in total. 19 match a class of the same name in upstream; 2 are renamed -- DoubleMLRDD is upstream's RDD estimator (upstream calls it RDFlex) and DoubleMLDIDCrossSection is upstream's DoubleMLDIDCS; and 1, DoubleMLDIDCS, has no 1:1 upstream class -- it is this port's variant of upstream's multi-period DoubleMLDIDMulti, which upstream keeps in a single class that this port splits in two. Those provenance labels are re-measured against the installed doubleml 0.11.4 package, not asserted -- see the estimator table below and _verify/UPSTREAM_PROVENANCE.md.

    Targets library authors and tool developers who need causal inference, panel data estimation, instrumental variable estimation, regression discontinuity, policy evaluation, or interpretable machine learning inside the MoonBit ecosystem. Delivers one DoubleMLXxx::new(...).fit() API shape across all 22 estimators -- six take a different constructor, and those six are named in API reference -- with robust variance estimation and a reproducible validation pipeline (24 / 24 Python reference scripts PASS).

    Status: MIT, pure MoonBit, on native, wasm, wasm-gc and js, with 22 estimators. Development status below states what is verified against upstream and what is not claimed.

    #Features

    • ✅ 22 estimators in 19 source files -- PLR, IRM, PLIV, IIVM, the DID family (6), SSM, APO, APOS, PQ, QTE, LPQ, LPLR, CVAR, RDD, BLP, PLPR and PolicyTree. The table is below.
    • ✅ One API shape -- DoubleMLXxx::new(...).fit(). Two different sets of six differ -- six in their accessors, six in their constructors -- and both are named in API reference rather than left to be discovered.
    • ✅ Cross-fitting infrastructure -- kfold, repeated cross-fitting, stratified K-fold, a chacha8_rng(seed) PRNG, and Kahan summation.
    • ✅ Robust variance and inference -- heteroskedasticity-consistent (HC) standard errors, cluster-robust variance, multiplier bootstrap confidence intervals, joint CIs, and Romano-Wolf multiple-testing adjustment.
    • ✅ Propensity-score processing -- PSProcessorConfig: clipping, isotonic calibration, CV calibration, all reachable from an estimator.
    • ✅ Four backends -- native, wasm, wasm-gc, js -- all green under moon test --target <backend> --deny-warn.
    • ✅ 24 / 24 Python reference scripts PASS -- 25 of the 25 bit-exact items are IEEE-754 identical to CPython, and the 6 / 6 RNG keys are byte-identical.
    • ✅ No runtime third-party dependency -- the library imports nothing outside moonbitlang/core.
    • ✅ 21 runnable example binaries -- 16 CLI demos, plus examples/api_server/ (the HTTP service), examples/consumer_demo/, examples/fuzz/, and the two fixtures examples/bitexact/ and examples/parity/.

    Pure-MoonBit, all-4-backends port of doubleml-for-py -- 22 DoubleML* estimators in 19 source files. 19 are marked (upstream) and mirror a name-identical doubleml-for-py class; 2 are marked (upstream, renamed) -- DoubleMLRDD (upstream RDFlex) and DoubleMLDIDCrossSection (upstream DoubleMLDIDCS); and 1, DoubleMLDIDCS, is marked (upstream design, no 1:1 class). The DID family is where the naming crosses, so it is worth spelling out. Upstream's DoubleMLDIDCS is the repeated cross-sections estimator, which is this port's DoubleMLDIDCrossSection. Upstream's DoubleMLDIDMulti is the multi-period estimator, and upstream keeps it in one class -- this port splits it in two: DoubleMLDIDMulti is the 1:1 counterpart (it carries upstream's gt_combinations selector and upstream's standard / all / universal keywords), and DoubleMLDIDCS is the port's variant without the selector, which derives its own (g, t) grid and transcribes upstream's did_cs.py machinery. A 1:1 map cannot give one upstream class two counterparts, so DoubleMLDIDCS is labelled for what it is rather than given a partner by name coincidence. Three rows -- DoubleMLDIDCSBinary, DoubleMLLPLR, DoubleMLPLPR -- ship upstream, so each has a reference implementation.

    #Installation

    Requires moon 0.1.20261028 or newer. The package declares moonbitlang/async@0.22.7, and that published version imports moonbitlang/core/async -- a subpackage of the MoonBit core that older cores do not carry. On an older moon the dependency cannot be resolved at all: the build fails with "Cannot find import moonbitlang/core/async in moonbitlang/async@0.22.7". The core that ships with moon 0.1.20261028 provides it, and this release's tests, cross-checks and bit-exactness gate were run on that toolchain.

    git is the other prerequisite. Moon resolves the package registry by CLONING it with git -- the registry's remote is https://mooncakes.io/git/index -- so a machine without git cannot fetch the registry at all, and moon add fails before it resolves anything. The MoonBit toolchain bundles no git of its own.

    moon add riantr/moonbit_doubleML

    Then reference it from moon.mod:

    ///|
    import {
    "riantr/moonbit_doubleML@0.164.62",
    }

    #Quick Start

    Run these from the repository root -- the directory holding moon.work. moon test --target native prints the same total from either directory, but moon run examples/main and python validate_irm_with_python.py are repo-root paths and fail from inside moonbit_doubleML/.

    $ moon test --target native --deny-warn Total tests: 1118, passed: 1118, failed: 0. $ moon run examples/main === MoonBit DML PLR (partialling out) === true theta_0 = 1 estimated theta = 1.092018247331361 standard error = 0.08875683254582736 ... $ python validate_irm_with_python.py ====================================================================== PASS |mb - handrolled_nrep5| (theta) = 8.868664e-02 < max(MODEL_TOL=0.1, 2.0*handrolled_n5_se) = 1.912555e-01

    --target native is spelled out because the package's preferred_target is wasm-gc, where the suite is 1124 -- 1118 plus 6 doc tutorials; the per-target numbers are in the Status table. A bare moon test runs the suite on only one of the four declared backends -- on moon 0.1.20261028 it reports Total tests: 0 for wasm and native, runs the suite on wasm-gc (1124 tests), and never reports js -- so the per-target counts here come from explicit --target runs.

    // inside a function body -- MoonBit rejects a module-scope `let` bound to a call
    let data = @moonbit_doubleML.DoubleMLData::new(x, y, d) // x : Matrix, y / d : Array[Double]
    let fitted = @moonbit_doubleML.DoubleMLPLR::new(data, n_folds=2, n_rep=1, seed=3141).fit()
    let coef = fitted.coef() // Double
    let se = fitted.se() // Double
    let (lo, hi) = fitted.confint()

    Same shape for every other estimator -- e.g. @moonbit_doubleML.DoubleMLIRM::new(data, ml_g?, ml_m?, n_folds?, n_rep?, seed?).fit(), @moonbit_doubleML.DoubleMLDID::new(data, ml_g?, ml_m?, ...).fit().

    #The 22 estimators

    22 DoubleML* estimator structs in 19 production files -- 16 with one struct each, and three holding two (apo.mbt: DoubleMLAPO + DoubleMLAPOS; blp_policy.mbt: DoubleMLBLP + DoubleMLPolicyTree; quantile.mbt: DoubleMLPQ + DoubleMLQTE) -- out of 220 .mbt files in the package (65 production, 129 blackbox test, 26 whitebox test). All are reachable through the same DoubleMLXxx::new(...).fit() interface. The last column marks each row's upstream counterpart:

    ModelScoreDescription
    DoubleMLPLRpartialling-outpartially linear regression (upstream)
    DoubleMLIRMATEinteractive regression model (upstream)
    DoubleMLPLIVpartialling-outpartially linear IV regression (upstream)
    DoubleMLIIVMLATEinteractive IV model (upstream)
    DoubleMLDIDobservationaldifference-in-differences (upstream)
    DoubleMLDIDBinaryobservationalDID with binary outcome (upstream)
    DoubleMLDIDCSobservationalDID with staggered adoption (Callaway-Sant'Anna) (upstream design, no 1:1 class) -- the port's variant of upstream DoubleMLDIDMulti, without its gt_combinations selector
    DoubleMLDIDCSBinaryobservationalCS-DID with binary outcome (upstream)
    DoubleMLDIDMultiobservationalmulti-period DID with group-time ATT aggregation (upstream)
    DoubleMLDIDCrossSectionobservationalSant'Anna-Zhao 2020 cross-section DID (upstream, renamed) -- upstream DoubleMLDIDCS
    DoubleMLSSMMARsample selection (missing-at-random) (upstream)
    DoubleMLAPOpolicy scoreaverage potential outcomes for one treatment level (upstream)
    DoubleMLAPOSpolicy scoreaverage potential outcomes across several treatment levels (upstream)
    DoubleMLPQquantilepotential quantile (upstream)
    DoubleMLQTEquantilequantile treatment effect (upstream)
    DoubleMLLPQlocal polynomiallocal potential quantile (upstream)
    DoubleMLLPLRpartialling-outpartially logistic regression, Liu-Zhang-Zhou 2021 (upstream)
    DoubleMLCVARCVaRconditional value-at-risk (upstream)
    DoubleMLRDDlocal polynomialregression discontinuity (upstream, renamed) -- upstream RDFlex
    DoubleMLBLPIVbest linear predictor of treatment effect (upstream)
    DoubleMLPLPRpartialling-outpartially linear panel regression, Clarke-Polselli 2025 (upstream)
    DoubleMLPolicyTreepolicypolicy tree (upstream), + v0.98.0 honest split (honest = true) with leaf_se / policy_value_se

    The Score column is a prose label for the estimand family, not a machine string, and three vocabularies are in play. The port accepts 8 spellings -- partialling-out, partialling out, iv-type, IV-type, observational, experimental, nuisance_space and instrument -- and only 7 of the 22 estimators take a score argument at all: DoubleMLPLR on fit(), six others on new(). The upstream vocabulary is a different set of 15 spellings, and upstream doubleml-for-py 0.11.4 uses APO, ATE, PQ, LPQ, CVaR, LATE, ATTE, IV-type, experimental, instrument, missing-at-random, nonignorable, nuisance_space, observational and partialling out; it takes no score argument at all for RDFlex, DoubleMLBLP or DoubleMLPolicyTree. The doc/004_estimators tutorial lists the port's own strings, one row per estimator.

    How the names map. The estimator table's last column is the map; the derivation is in _verify/UPSTREAM_PROVENANCE.md and in ENGINEERING.md.

    #API reference

    One API shape, with the differences named -- every estimator is built DoubleMLXxx::new(...).fit(). The shape is uniform; the signature and the accessor set are not, and both sets of differences are listed here rather than discovered later. They are two different sets of six, and they overlap in only three estimators.

    The accessor differences:

    estimatorinstead ofbecause
    DoubleMLAPOScoef / se -> coefs / sesone estimate per treatment level
    DoubleMLQTEcoef / se -> coefs / sesone estimate per quantile
    DoubleMLDIDCScoef / se -> coef_at / se_atone ATT per (group, period)
    DoubleMLDIDMulticoef / se -> coef_at_idx / se_at_idxthe same cells, by row-major index
    DoubleMLBLPconfint -> confint_jointthe interval is for a contrast of the IV coefficient vector
    DoubleMLPolicyTreeno scalar coefficient at allleaf_influence, leaf_se, policy_value, policy_value_se

    The other 16 expose .coef() / .se() / .confint() / .bootstrap().

    The constructor differences -- which estimators take n_folds / n_rep / seed. This is a different partition from the accessor table above, so the two groups of "the other 16" are not the same sixteen:

    estimatorsn_foldsn_repseed
    the other 16yesyesyes
    DoubleMLPQ, DoubleMLQTE, DoubleMLLPQyesnoyes
    DoubleMLBLP, DoubleMLRDD, DoubleMLPolicyTreenonono

    The quantile estimators cross-fit once -- solve_pq has no repetition loop, so there is no n_rep to set. The last three take no cross-fitting option at all: DoubleMLBLP is given a basis and an orth signal, DoubleMLRDD fits locally around a cutoff, and DoubleMLPolicyTree splits the sample once for its honest split (its own split_seed).

    Constructor arguments also differ in ways a table cannot show: DoubleMLDIDBinary needs g_value / t_value_pre / t_value_eval, DoubleMLAPOS needs treatment_levels, DoubleMLPolicyTree needs features / orth_signal / depth / honest, and the DID variants take four data types, not one each: DoubleMLDIDData for DoubleMLDID, DoubleMLDIDBinaryData for DoubleMLDIDBinary, DoubleMLDIDCSData for DoubleMLDIDCS, DoubleMLDIDCSBinary AND DoubleMLDIDMulti, and DoubleMLDIDCrossSectionData for DoubleMLDIDCrossSection. The score argument is the one that moves between new() and fit(): DoubleMLPLR takes it on fit(), and DoubleMLDID, DoubleMLDIDBinary, DoubleMLDIDCrossSection, DoubleMLDIDCSBinary, DoubleMLLPLR and DoubleMLPLPR take it on new().

    Learner injection via LearnerDispatch -- the learner arguments are LearnerDispatch optionals, and the set differs by estimator, so there is no single argument to pass:

    learner argumentsestimators
    ml_g / ml_mDoubleMLAPO, DoubleMLAPOS, DoubleMLCVAR, DoubleMLDID, DoubleMLDIDBinary, DoubleMLDIDCS, DoubleMLDIDCSBinary, DoubleMLDIDCrossSection, DoubleMLDIDMulti, DoubleMLIRM, DoubleMLLPLR
    ml_l / ml_mDoubleMLPQ, DoubleMLQTE
    ml_g / ml_m / ml_rDoubleMLIIVM
    ml_g / ml_m / ml_piDoubleMLSSM
    ml_gDoubleMLBLP, DoubleMLRDD
    learner_l / learner_mDoubleMLPLR
    learnerDoubleMLPLIV, DoubleMLPLPR
    noneDoubleMLLPQ, DoubleMLPolicyTree

    That is 8 argument sets over the 22 estimators. ml_r is DoubleMLIIVM's instrument propensity (at fit() it reuses the constructor's choice) and ml_pi is DoubleMLSSM's selection propensity (at fit() it reuses the ml_m choice). The constructor default is LearnerDispatch::linear_regression() (OLS) -- except ml_m on the seven structs migrated to a classifier, named below. Built-in learners:

    learnerkindsample_weightnote
    LinearRegressionregressionWLSOLS, the default
    Ridgeregressionweightedv0.120.0+, L2 penalty, unpenalised intercept
    Lassoregressionweightedv0.120.0+, L1 penalty, coordinate descent
    ElasticNetregressionweightedv0.120.0+, the convex L1/L2 blend
    LogisticRegressionclassificationweighted IRLSbinary, IRLS Newton-Raphson
    RFClassifierclassificationweightedv0.117.0+, Breiman 2001, Gini splits
    GBClassifierclassificationweighted Newton leafv0.117.0+, Friedman 2001, binary log loss
    RFLearnerregressionweighted splits/leafBreiman 2001, MSE splits
    GBLearnerregressionweighted leafFriedman 2001, squared-error loss
    ConstantLearner, NoopLearnereitherignoredconstant / zero predictors

    Upstream doubleml is learner-agnostic -- ml_g / ml_m are any object with fit / predict -- so it inherits scikit-learn's whole learner surface. This package ships eleven. The three classification learners' predict returns P(y = 1 | x), never a hard label, because DML's AIPW correction divides by the fitted propensity.

    #Propensity processing

    ml_m is a classifier where the propensity carries identification -- and that is NOT everywhere. Upstream makes no OLS default: ml_m is a required argument, validated as regressor=False, classifier=True (irm.py:157) and read back with predict_proba (irm.py:161). Where m_hat is first-order in the score, an OLS propensity is unbounded, enters as 1 / m_hat, and propensity_clip (default 1e-6) merely caps that at 1e6 -- so nothing raises, it just returns wrong numbers. Measured on a fixture with true ATE = 1.5:

    ml_mcoefrv
    linear_regression-225.860.043
    logistic_regression1.440.842

    coef is the estimated effect; rv is upstream's robustness value -- the sensitivity-analysis reading of how much confounding the estimate survives, so higher is more robust. The OLS propensity lands at 0.043; the classifier reaches 0.842.

    The port used to default ml_m to LearnerDispatch::linear_regression() everywhere. Seven estimators now default to a classifier -- DoubleMLIRM, DoubleMLAPO, DoubleMLAPOS, DoubleMLSSM, DoubleMLPQ, DoubleMLQTE and DoubleMLLPLR -- their ml_m default is now LearnerDispatch::logistic_regression(LogisticRegression::new()), while ml_g deliberately stays OLS (it models E[y | x], not P(y = 1 | x)), so the two defaults diverge on purpose. LearnerDispatch::is_classifier() reports which constructors qualify.

    The migrations do NOT all have the same margin, and the gates are shaped accordingly. DoubleMLIRM on a saturated-propensity fixture (true ATE = 1.5) across three seeds: the default's worst bias is 0.1983, the OLS arm's smallest bias is 72.797 -- a 367x separation on the coefficient. DoubleMLAPO (true E[Y | D=1] = 1.2): the default's worst bias is 0.5307, the OLS arm's smallest bias is 5.2464 -- only ~10x. APO's standard error is the honest discriminator (0.270 vs 86.28, a 320x separation), because the mechanism is that an unbounded propensity makes 1 / m_hat explode and takes the variance with it.

    DoubleMLSSM is one of the four migrations of v0.132.0-v0.138.0 -- DoubleMLIRM, DoubleMLAPO, DoubleMLAPOS and DoubleMLSSM -- because its score carries two reciprocals, one per direction (ssm.mbt:73-74): the treatment propensity m and the selection propensity pi, so an unbounded regressor breaks both denominators independently. On a saturated fixture with true theta = 1.0, the OLS arm returns 242.116 with SE 185.45 where the classifier returns 1.177 with SE 0.0982 -- roughly 200x on the point estimate and 1900x on the standard error. Across three seeds the OLS coefficient also changes sign (+242, +106, -452); the classifier's spread over the same three seeds is 0.761.

    One caveat worth stating plainly: on a mild fixture, where the true propensity never reaches the 0.02/0.98 clamp, the two learners agree to three decimals and OLS is marginally better. The hazard is a property of the clamp, not of the estimator in general, and the gate suite pins both regimes so a future change cannot be scored on the flattering fixture alone.

    Eight structs still default ml_m to linear_regression(): DoubleMLCVAR, DoubleMLDID, DoubleMLDIDBinary, DoubleMLDIDCrossSection, DoubleMLDIDCS, DoubleMLDIDCSBinary, DoubleMLDIDMulti, DoubleMLIIVM. Until each is migrated, pass a classifier explicitly -- ml_m is a named argument on the constructor, so the learner goes where the estimator is built:

    // inside a function body -- MoonBit rejects a module-scope `let` bound to a call
    let fitted_cvar = @moonbit_doubleML.DoubleMLCVAR::new(
    data,
    ml_m=@moonbit_doubleML.LearnerDispatch::logistic_regression(
    @moonbit_doubleML.LogisticRegression::new(),
    ),
    ).fit()

    LearnerDispatch::random_forest_classifier(RFClassifier::new(...)) and LearnerDispatch::gradient_boosting_classifier(GBClassifier::new(...)) are the nonlinear options.

    The hazard is NOT uniform, and was measured per-estimator (v0.132.0-v0.142.0). Migrating DoubleMLDIDBinary was attempted and abandoned on the evidence: across four probe designs and ~14 configurations its OLS default matched a logistic one to within ~1e-4, and where they differed the OLS default was the BETTER of the pair. The reason is structural. In the observational DID score (did.mbt:97) the residual weight is (D - m) / (p_hat * (1 - m)), so the score never divides by m: for a treated row the m dependence cancels, and m reaches the control rows only. The score is doubly robust -- a correct g carries identification, leaving m second-order. IRM and APO need m for the estimand itself, which is why they showed a ~200-point error and DID shows ~0.0005. The sharpest DID case: at n=200 the CLASSIFIER default is worse on both bias (0.0776 vs 0.00050) and SE.

    EstimatorOLS defaultEvidence
    DoubleMLIRMhazardouscoef -225.86 vs 1.44
    DoubleMLAPOhazardousbias 5.246 vs 0.531; SE 86.28 vs 0.270
    DoubleMLAPOShazardousper-level bias to 436.11
    DoubleMLDIDBinarynot demonstrated4 designs, ~14 configs, ~1e-4
    DoubleMLDID, DoubleMLDIDCS, DoubleMLDIDCSBinary, DoubleMLDIDCrossSection, DoubleMLDIDMultinot demonstrateddoubly robust -- m cancels for treated rows
    DoubleMLSSMhazardous -- fixed in v0.138.0coef 242.116 vs 1.177
    DoubleMLCVARnot demonstrated2.300 vs 2.373
    DoubleMLQTEhazardous -- fixed in v0.139.0OLS arm frozen at -1.583 at the three measured taus 0.50 / 0.75 / 0.90
    DoubleMLIIVMnot demonstrated0.987 vs 1.031; SE 0.0047 vs 0.0747 (16x smaller)
    DoubleMLPLRnot demonstrated1.015 vs 1.103 -- OLS better
    DoubleMLLPLRnot demonstrated -- root-caused in v0.140.0-v0.142.0not an ml_m hazard; two failure modes; see below
    DoubleMLPQhazardous -- fixed in v0.139.0ignored its quantile entirely

    Every row above is a measured verdict. Six rows turned out hazardous: DoubleMLIRM (-225.86 vs 1.44), DoubleMLAPO (bias 5.246 vs 0.531), DoubleMLAPOS (per-level bias to 436.11), DoubleMLSSM (242.116 vs 1.177 -- its score divides by m*pi AND (1-m)*pi, two reciprocals in both directions, ssm.mbt:73-74), and DoubleMLPQ / DoubleMLQTE, which ignored their quantile outright. All six default to a classifier today. DoubleMLDIDBinary, DoubleMLCVAR, DoubleMLIIVM and DoubleMLPLR (whose propensity role is learner_m, not ml_m) kept their OLS default on measured evidence -- no flip was warranted. DoubleMLLPLR's degenerate standard error is real and was root-caused in v0.140.0, but it is not an ml_m defect -- see the note below.

    A static classifier (read the score: does it carry 1/m? is it doubly robust?) was used to prioritise the probes, and it reproduces the four hazardous verdicts of v0.132.0-v0.138.0 -- DoubleMLIRM, DoubleMLAPO, DoubleMLAPOS and DoubleMLSSM -- but DoubleMLIIVM refuted it, carrying 1/m and 1/(1-m) on every row and still measuring harmless. A reciprocal in the score is not sufficient for the hazard; the classifier is a way to decide what to measure first, nothing more.

    #Cross-fitting

    Cross-fitting infrastructure -- kfold, repeated cross-fitting, stratified K-fold (kfold_stratified), chacha8_rng-based seeded PRNG (chacha8_rng(seed)), and Kahan summation. Default seed=3141; same seed yields byte-identical DGP outputs across runs.

    Vectorised cross-fit helpers (v0.81.0+) -- vectorized.mbt exposes matrix_predict (Kahan-compensated X @ weights + bias), vector_add, vector_divide, vector_multiply, vector_scale and vector_subtract as public free functions. DoubleMLIRM::fit / fit_cluster / sensitivity_analysis and the matching DoubleMLPLR paths route the per-observation residual extraction through vector_subtract instead of an inlined per-iteration load / subtract, and 12 of the library's own files call it today. The vector_* helpers are pure element-wise loop wrappers today; matrix_predict is a Kahan-compensated matrix-vector product.

    #Examples

    21 examples/<bin>/ directories in moon.work. 16 are CLI-style numeric demos that print an estimate; measured per driver, 14 of the 16 print a true value and 11 of the 16 print a 95 % CI -- examples/pava and examples/splitting print neither, and examples/apos, examples/cluster and examples/ssm print a true value but no CI. examples/api_server/ is an HTTP service; examples/consumer_demo/ is the library-user pattern that mirrors what an external moon add riantr/moonbit_doubleML consumer would write; examples/fuzz/ is the property-based fuzz harness; and examples/bitexact/ and examples/parity/ are the MoonBit fixtures the bit-exact and LPLR parity validators drive.

    Every example's moon.mod pins the library at the release this document describes, so an example copied out of the tree and resolved there with moon update installs the same library these numbers came from.

    examples/apo/ and examples/apos/ are the pair worth reading together: APO returns the potential outcome AT one treatment level, APOS returns those levels plus pairwise CONTRASTS, and a contrast is off by the reference level's entire outcome. examples/apo/ prints both so the gap is visible rather than described.

    DriverModelDGPTrue theta
    examples/mainDoubleMLPLR + 11 others (IRM / PLIV / IIVM / DID / SSM / BLP / RDD / PQ / QTE / LPQ / PolicyTree)Simple partially linear, n=500, p=51.0
    examples/datasetsDoubleMLPLR + DoubleMLIRMSynthetic 401(k)-style, n=4000, 9 controls1.5
    examples/did_binaryDoubleMLDIDBinary2-period panel DID, 400 units1.0
    examples/did_csDoubleMLDIDCSStaggered CS-DID, 4 cohorts x 4 periods -- 3 treatment groups (cohort 0 is never treated)1.0
    examples/did_cs_binaryDoubleMLDIDCSBinaryStaggered CS-DID with binary outcome1.0
    examples/did_multiDoubleMLDIDMultiTop-level multi-period DID + aggregation1.0
    examples/did_cross_sectionDoubleMLDIDCrossSectionSant'Anna-Zhao 2020 cross-section DID, 500 units1.0
    examples/plprDoubleMLPLPRStatic-panel PLR (60 units x 4 periods)1.0
    examples/lplrDoubleMLLPLRPartially logistic regression, LZZ20200.5 (logit-scale alpha)
    examples/apoDoubleMLAPO3-level discrete treatment (D in 0/1/2): the LEVEL E[Y(t)]1.0 (E[Y(1)]) / 2.5 (E[Y(2)])
    examples/aposDoubleMLAPOS2-level discrete treatment: per-level E[Y(t)] PLUS pairwise CONTRASTS1.0 per level; contrast 0.0
    examples/cvarDoubleMLCVARCVaR at q=0.51.74
    examples/ssmDoubleMLSSMSharp synthetic treatment1.0
    examples/clusterDoubleMLPLIV / DoubleMLPLR + cluster_*Clustered data, cluster-robust SEs1.0
    examples/splittingDoubleMLPLR + set_sample_splittingExternal sample splitting (n=200, p=2)1.5
    examples/pavapava coreIsotonic regression, exact (no MC error)n/a -- fixed input cases, not a theta demo
    examples/fuzzwrappersRandom-property fuzz harness across 11 surfaces (native-only)n/a
    examples/bitexactfixtureThe bit-exact values and RNG keys validate_bitexact_with_python.py drivesn/a
    examples/parityfixtureThe LPLR nuisance-space / instrument values the parity gate drivesn/a
    examples/consumer_demolibrary-user patternMinimal end-to-end PLR (no estimator-specific extras)1.0
    examples/api_serverDoubleMLPLR + DoubleMLIRMHTTP service -- see belown/a

    CLI demos (all 16 run bare; most print an estimate against a true value):

    $ moon run examples/main $ moon run examples/datasets $ moon run examples/did_binary $ moon run examples/did_cs $ moon run examples/did_multi $ moon run examples/did_cross_section

    HTTP service:

    $ moon build --target native examples/api_server $ _build/native/debug/build/example/api_server/api_server.exe # listens on 127.0.0.1:4000 $ curl -s http://127.0.0.1:4000/healthz {"status":"ok"} $ curl -s -X POST http://127.0.0.1:4000/fit/plr \ -H 'Content-Type: application/json' \ -d '{"x":[[1.0,0.5],[2.0,1.5],[3.0,2.5],[4.0,3.5],[5.0,4.5],[6.0,5.5]],"y":[2.0,4.0,6.0,8.0,10.0,12.0],"d":[1.0,2.0,3.0,4.0,5.0,6.0],"n_folds":2,"seed":3141}' {"estimator":"plr","coef":2,"se":0,"ci_lo":2,"ci_hi":2,"n_obs":6,"n_features":2}

    The same api_server.wasm also runs under moonrun <path-to-the-wasm>. The listen port is hard-coded to 4000 in main.mbt, so the service ignores any argument it is given (see examples/api_server/README.md for the full PowerShell smoke recipe). The service is built directly on moonbitlang/async@0.22.7 -- no third-party HTTP framework is pulled in.

    #Common pitfalls and best practices

    #⚠️ Partially logistic regression: the small-n regime

    This port damps LPLR's Newton step so the answer stays finite; upstream does not. What follows is why that is a fragility the two implementations SHARE, and not a defect this port introduced.

    What the cause actually is, and why it is not a port defect. The port's own t_pred, m_pred, a_pred and beta were dumped on the exact n = 66 rows where the unclamped port dies, and handed to upstream's own solver. The t/m/a values are harmless; beta alone reproduces the divergence -- in all 8 of the 8 cells of the 16-cell swap that take beta from the port. And inside beta, it is not r_hat = t - beta * a that hurts but the Newton start value mean(beta), which upstream also uses verbatim (plm/lplr.py:326, np.average(beta)).

    Upstream never sets _coef_bounds for LPLR, so double_ml_score_mixins.py:149 runs root_scalar(..., method="newton") -- an unbracketed Newton from that same start. This port is structurally identical; the clamp is standing in for a robustness upstream does not have either. On the n = 66 rows the score is nearly flat past theta ≈ 3.5: at theta0 = 6.842 the score is -0.1119 but the derivative is -8.07e-05 -- down a factor of 344 from the -0.0277 it was at upstream's start value theta0 = 1.003 -- so the first step theta - score/deriv overshoots to about -1381 and overflows. That is the e+70 / e+122 / NaN mechanism, and the basin edge is draw-specific.

    The decisive number, on 40 pinned redraws of those same rows, with nothing instrumented -- upstream's own DoubleMLLPLR(...).fit(), reading .coef[0]: 17 of 40 (42%) return a non-finite or absurd coefficient (-648, 5.18e+70, 8.44e+122, 172149, nan × 4, …), raising upstream's own Could not find aroot of the score function warning on 18 of 40. Upstream's mean(beta) over those draws has mean 2.56, sd 3.39, range [-3.21, 13.85], and this port's 6.842 sits at the 90th percentile -- an unremarkable draw, not a port bias.

    So the clamp is not rescuing a defect this port introduced. It is covering a fragility upstream shares and does not guard against either, and on this row set it is what makes the port no worse rather than better. Record: _verify/LPLR_GATE_BLINDNESS_1680.md sections 25g-25h and 27.

    #✅ DO

    1. Pass a classifier for ml_m wherever the propensity carries identification. The estimators that need one default to logistic_regression; the ones that do not are named in Propensity processing above, with the measurement behind each. ml_g deliberately stays OLS -- it models E[y | x], not P(y = 1 | x). LearnerDispatch::is_classifier() reports which constructors qualify.
    2. Read the warnings. DoubleMLLPLR::fit() can return a degenerate standard error, and it says so rather than returning a confident wrong number. LPLR's outcome is BINARY, so it takes a DoubleMLBinaryData rather than the DoubleMLData the other estimators take -- DoubleMLBinaryData::new aborts on any outcome that is not 0 or 1:

      // inside a function body -- MoonBit rejects a module-scope `let` bound to a call
      let data = @moonbit_doubleML.DoubleMLBinaryData::new(x, y, d)
      let model = @moonbit_doubleML.DoubleMLLPLR::new(data).fit()
      for w in model.warnings() { println(w) }

    3. Treat n < 200 as ill-posed for partially logistic regression. Upstream genuinely is ill-posed there -- non-finite standard errors and root warnings -- while this port damps its Newton step to keep the answer finite. Which side breaks depends on n, so neither one is a safe reference for the other at that size.

    #❌ DON'T

    1. Don't read a small-n LPLR standard error as an estimate. At n = 500 the port and upstream agree to 0.007307 on the nuisance_space tier and to 0.010609 on the instrument tier. Below that the gate is a report, not a guarantee.
    2. Don't assume every adjust_ps call forwards cv. The adjust_ps call sites that do not forward cv are eight, in seven files: apo.mbt:320, cvar.mbt:736, cvar.mbt:1005, did.mbt:628, did_cross_section.mbt:615, did_cs_binary.mbt:374, quantile.mbt:217 and ssm.mbt:671. The only two that do are IRM's and IIVM's -- cv= is passed at irm.mbt:430 and iivm.mbt:525.
    3. DoubleMLRDD's shipped default arm is still the one absence. coef() / se() are homoskedastic and uncorrected, so they are a different estimator from rdrobust's default rather than a worse implementation of the same one, and matching them would be a re-specification rather than a bug fix. What pyexample_rdd.py gates is the arm that does match: tau_bc against upstream's tau.bc (measured gap 6.2e-15 absolute, 3.1e-15 relative) and tau_bc_se_rb against se.rb (1.9e-15 absolute, 1.4e-14 relative), both at relative bound 1e-11. The default arm is printed beside the gate on every run — ~5.9e-3 relative on the point estimate and 0.053x upstream's on the SE (~19x smaller) — so the divergence is visible rather than asserted.

    #Development status

    ItemValue
    Repositoryhttps://github.com/riantr/moonbit_doubleML
    Authorriantr
    LicenseMIT (port of upstream doubleml-for-py, BSD-3-Clause)
    moon.mod version0.164.62
    Toolchainmoon 0.1.20261028 -- the version this release's tests, cross-checks and bit-exactness gate were run on, and the version every number in this table was re-verified on; a bare moon from cli.moonbitlang.com may be newer
    Source layoutflat, moonbit_doubleML/ (the library)
    .mbt file count220 .mbt files (65 production + 129 blackbox test + 26 whitebox test)
    Estimators22 DoubleML* estimator structs (PLR / IRM / PLIV / IIVM / DID family / SSM / APO(S) / PQ / QTE / LPQ / LPLR / CVAR / RDD / BLP / PLPR / PolicyTree)
    Backendsnative, wasm, wasm-gc, js -- all pass moon test --target <backend> --deny-warn
    Tests (native / wasm / js)1118 / 1118 / 1118
    Tests (wasm-gc)1124 / 1124 (lib + 6 doc tutorials)
    Sandwich-variance coverage15 / 22 expose the scalar sandwich_se / cluster_sandwich_se / bias_corrected_coef; 4 more (DoubleMLAPOS, DoubleMLDIDCS, DoubleMLDIDMulti, DoubleMLQTE) expose per-cell variants sandwich_se_at / ..._at_idx; 3 expose none of that API (DoubleMLBLP, DoubleMLPolicyTree, DoubleMLRDD) -- but DoubleMLRDD (v0.96.0) and DoubleMLBLP (v0.97.0) do expose a heteroskedasticity-robust hac_se under their own name; DoubleMLPolicyTree exposes no robust SE at all. Introduced v0.79.0 (on DoubleMLIRM and DoubleMLPLR), extended to 19 / 22 by v0.100.0
    Python cross-checks24 / 24 PASS (validate_*_with_python.py); 25 of the 25 bit-exact items are IEEE-754 identical to CPython, and the 6 / 6 RNG keys are byte-identical
    HTTP serviceexamples/api_server/ -- hand-rolled on moonbitlang/async, no third-party framework

    #Validated against upstream, not only against ourselves

    Nine gates whose reference is UPSTREAM, not ours -- the pyexample_* family. Every script above compares the port against a second implementation. Two of them take that implementation from a third-party library -- validate_pava_with_python.py against scikit-learn's isotonic_regression, and validate_padjust_with_python.py against statsmodels' multipletests; the others take it from this repository or from the upstream wheel. A second implementation of our own can only catch a disagreement someone already thought to look for. The pyexample_* scripts instead run a reference implementation on the port's rows and compare that: not "does the port agree with our second implementation" but "does the port agree with upstream". The reference is upstream's own doubleml classes in eight of them, and rdrobust for the RDD arm -- doubleml-for-py and rdrobust are different packages.

    The validate_* family is not exclusively ours, though: 9 of its 24 scripts import the upstream doubleml wheel, and 2 of those gate the port against upstream and against a hand-rolled reference -- validate_did_cs_binary_with_python.py (the port's ATT against both) and validate_lplr_with_python.py (the port's coefficient against both). The other 7 import the wheel for context (validate_apos_with_python.py, validate_cluster_iv_with_python.py, validate_cluster_plr_with_python.py, validate_iivm_with_python.py, validate_irm_with_python.py, validate_pliv_with_python.py, validate_plpr_with_python.py); upstream's numbers are printed there, and in some of them upstream's own quantities are separately gated rows.

    Measured designs, one script per upstream class or family:

    scriptupstream classhow the two sides get their rows
    pyexample_did.pyDoubleMLDID on make_did_SZ2020upstream's own DGP
    pyexample_did_cs2021.pyDoubleMLDIDMulti on make_did_CS2021upstream's own DGP
    pyexample_did_binary.pyDoubleMLDIDBinaryshared rows
    pyexample_did_cs_binary.pyDoubleMLDIDCSBinaryshared rows
    pyexample_lplr.pyDoubleMLLPLRshared rows + pinned outer partition
    pyexample_pq.pyDoubleMLPQ / DoubleMLQTE / DoubleMLLPQinteger-only DGP, rebuilt independently on both sides
    pyexample_policytree.pyDoubleMLPolicyTreeinteger-only DGP; the label vector over every row is compared, because the port's builder and upstream's DecisionTreeClassifier differ in threshold convention, criterion and leaf rule
    pyexample_rdd.pyDoubleMLRDD vs rdrobustinteger-only DGP with genuine non-collinear noise; the bias-corrected arm is gated
    pyexample_suite.pythe core estimator familymixed

    #Numerical parity with CPython

    Bit-exact parity is a second, stronger tier. A tolerance cannot tell "the port is arithmetically identical to the reference" apart from "the port lands within 1e-4 of it". validate_bitexact_with_python.py compares IEEE-754 bit patterns instead, against examples/bitexact/. Measured scope, not assumed -- re-measured on moon 0.1.20261028 vs CPython 3.13.14, unchanged from the moon 0.1.20261012 vs CPython 3.14 pair it was first taken on:

    operationbit-exactwhy
    + - * /yesIEEE-754 requires correct rounding, so same operands in the same order MUST agree
    sqrtyessame guarantee -- 6 / 6 measured
    cos, sinobserved 6 / 6agreement today, not guaranteed: neither is correctly rounded
    ln5 / 6ln(3.0) differs by exactly 1 ULP: MoonBit 1.0986122886681096, CPython 1.0986122886681098

    Because box_muller_pair uses ln, cos and sin, no random-number DGP in this package can be bit-exact against CPython, and neither can anything routed through BLAS/LAPACK (numpy reduces with pairwise summation; LAPACK blocks its pivots). The check therefore asserts the surface where bit-exactness is guaranteed -- 25 / 25 items and 6 / 6 RNG keys, currently identical -- and prints the rest as deliberately not asserted, so the absence is not mistaken for an oversight. A mutation battery (_verify/_bitexact_mutation_1640.py) confirms the gate discriminates: all four mutations killed, including a truncated and a mis-tiled RNG key.

    #Not covered, so not claimed

    The coverage check is a test-reachability proxy, not instrumented line coverage. There is no dependency-vulnerability scan -- moon update resolves versions, it is not an audit. mutation kills three mutants on one kernel, not a whole-codebase surviving-mutant ledger, and no CI workflow runs it. examples/fuzz/ has no crash-regression corpus, and its seed argument is ignored -- fn main takes no parameters -- so the fuzz check replays one fixed master seed (20260824) three times rather than sweeping seeds. Each invocation is a real property-based run -- 11 surfaces, 300 trials per surface -- so the check repeats that one run, and no CI workflow runs it either. And the two declared moon.mod dependencies -- moonbit-community/sqlite3@0.2.3 and moonbitlang/async@0.22.7 -- are dead: nothing imports them, and dependencies already WARNs about exactly that (2 declared; non-conforming:['moonbit-community/sqlite3@0.2.3']; declared but unreferenced by library code:['moonbit-community/sqlite3@0.2.3', 'moonbitlang/async@0.22.7']) rather than passing quietly. Removing them is an open call, not an oversight. Dead is not the same as harmless, though: the published source of moonbitlang/async@0.22.7 imports moonbitlang/core/async, a core subpackage that older cores do not carry, so the dead pin is what sets the toolchain floor -- see Installation. The sqlite3 pin is not what forces it: its published source imports no moonbitlang/core/async.

    #Honest policy trees (v0.98.0)

    DoubleMLPolicyTree::new(features, orth_signal, depth = 1, honest = false,split_seed = 2024, min_leaf_n = 5) splits the sample when honest is on: policy_tree_build sees only the splitting half, and every reported leaf statistic (leaf_assignment, leaf_signal_mean, leaf_count, leaf_se) is computed on the estimation half. That is the honesty of Athey & Imbens (2016, PNAS 113(27):7353-7360), and it makes their property a property rather than a claim: with the partition held fixed, a leaf value is a plain sample mean, so leaf_se[k] = sd(y_k) / sqrt(n_k) has its usual sampling interpretation. is_honest() reports which regime produced a number, and honest defaults to false so existing callers are byte-identical.

    Two caveats are load-bearing and are documented in-source. Honesty fixes the bias, not the small-leaf variance: Cattaneo, Klusowski & Yu (arXiv:2509.11381) show that CART-type greedy splitting picks highly imbalanced splits with nonvanishing probability and that "sample splitting ... does not remove this limitation", which is why min_leaf_n (default 5) guards on estimation-half leaf counts and unreliable_leaves() names the offenders instead of reporting an untrustworthy leaf_se silently. And a single honest tree spends about half the sample on each of its two jobs -- Wager & Athey (2018, JASA) recover that precision by averaging many honest trees, which this package deliberately does not attempt.

    policy_value_se() is the EXACT standard error of the plain sample mean, not the tempting sum_k (n_k/n)^2 se_k^2: that form assumes independent leaf means, but group means of one sample are negatively correlated, and the independence form collapses to exactly zero when all the variation is between leaves.

    #Project layout

    moonbit_doubleML/ <- the library (moon.mod v0.164.62, 220 .mbt files) moon.pkg <- the package's imports and supported targets ... <- one file per estimator + DGPs + score / nuisance kernels vectorized.mbt <- v0.81.0+ vectorised cross-fit helpers doc/ <- wasm-gc-targeted numbered tutorials 001_introduction/ ... 006_python_check/ examples/ <- 21 driver binaries (all listed in moon.work) main/ <- 12 estimators in 18 printed runs, 20 model fits: 5 also run with n_rep=5, and RDD runs twice (sharp, fuzzy) datasets/ <- 401(k)-style ATE / ATT recovery did_binary/ <- 2-period panel DID did_cs/ <- staggered CS-DID did_cs_binary/ <- staggered CS-DID (binary outcome) did_multi/ <- multi-period DID aggregation did_cross_section/ <- Sant'Anna-Zhao 2020 plpr/, lplr/, apos/, <- single-estimator focused demos cvar/, fuzz/ consumer_demo/ <- library-user pattern (`examples/consumer_demo`) api_server/ <- HTTP service built on `moonbitlang/async` moon.work <- 23-member workspace aggregator (the library, doc/, 21 examples) AGENTS.md <- agent guide for coding agents (MoonBit convention) skills/moonbit_doubleML.md <- agent skill: API surface + anti-patterns

    #Dependency rule

    • Only official moonbitlang/* packages.
    • Non-official packages may only be riantr/* (this repo).
    • Pin to the latest published version (e.g. moonbitlang/async@0.22.7).
    • Consequence: examples/api_server/ builds directly on moonbitlang/async's raw Server API. No third-party HTTP framework is allowed.

    Current state: the rule is not met, by one line. moonbit_doubleML/moon.mod declares two packages, and neither is imported by any .mbt in the library (measured: 0 references each):

    declaredimported by the library?note
    moonbitlang/async@0.22.7noreferenced by nothing in the library: examples/api_server/ imports the same package at the same pin (moonbitlang/async@0.22.7), but no .mbt under moonbit_doubleML/ imports it
    moonbit-community/sqlite3@0.2.3nonot moonbitlang/* -- added in v0.85.0 for DoubleMLPolicyTree memoisation, which now uses an in-memory FitCache

    So the library has no runtime third-party dependency today, while moon.mod carries two dead entries -- one of which does not satisfy the rule above. Deleting both lines is the change that would make this section true.

    #Attribution

    moonbit_doubleML is a port of the upstream DoubleML/doubleml-for-py package (BSD 3-Clause License). Upstream's 19 name-matched estimator classes are re-implemented in pure MoonBit with the same score formulae and variance estimators, as is its RDD implementation (RDFlex upstream, DoubleMLRDD here). DoubleMLPLPR, DoubleMLLPLR and DoubleMLDIDCSBinary are not MoonBit-only -- all three ship upstream. DoubleMLLPLR and DoubleMLDIDCSBinary are compared against upstream's own classes; DoubleMLPLPR's upstream fit is compared against a hand-rolled reference on a different dataset from the port's, so PLPR has no upstream gate. The last candidate for a port-only estimator, DoubleMLDIDCrossSection, is upstream's DoubleMLDIDCS under a different name. One estimator does have no 1:1 upstream class: DoubleMLDIDCS, this port's variant of upstream's multi-period DoubleMLDIDMulti -- see the estimator table and _verify/UPSTREAM_PROVENANCE.md.

    #Differences from upstream doubleml-for-py

    • Native MoonBit package layout, type system, and test organization.
    • Independent implementations of Matrix, linear / logistic regression, stratified K-fold, ChaCha8 PRNG, and Kahan summation in MoonBit; no NumPy / scikit-learn dependency.
    • DoubleMLData / DoubleMLXxx::new().fit() as the canonical MoonBit-idiomatic API, on native / wasm-gc / wasm / js backends (Serverless / Wasm / edge deployments). The library exports no JSON in/out -- the JSON surface is examples/api_server/'s own request/response encoding.
    • Behaviour-level parity check via the 24 Python reference scripts: 23 compare under a per-validator numeric tolerance, and one (validate_bitexact_with_python.py) compares IEEE-754 bit patterns instead. The tolerance tier keeps the port resilient to upstream refactors; the bit-exact tier is where it must not drift at all.
    • Strict dependency rule (see above): only moonbitlang/* official packages -- one declared line does not meet it today (moonbit-community/sqlite3, which nothing imports). The library's runtime supply chain is still moonbitlang/core only.

    #Used By

    • riantr/pyroduct -- downstream consumer that models Ren Yongxiang's MA thesis (Gadamer/Habermas, Shanghai Academy of Social Sciences 2008) plus its appendix as runnable multi-agent state machines. Its dmlref package cross-checks its own from-scratch DoubleML PLR against riantr/moonbit_doubleML: same nuisance (OLS), n = 400, true theta = 1.5, theta delta 0.017 (1.667 vs 1.685) and se delta 0.001 (0.153 vs 0.152). Those figures are pyroduct's own measurement, in pyroduct's dmlref report; this repository does not re-measure them, because the code that produces them is not in this tree. Source lives on gitee.com/ren-yongxiang/pyroduct.
    • examples/api_server/ -- this repo's HTTP service.
    • examples/consumer_demo/ -- minimal end-to-end PLR showing the consumer-side import pattern (moon add riantr/moonbit_doubleML).

    #Development

    ENGINEERING.md is the companion, and it is worth saying what it is: its header is the correction ledger -- one entry per corrected round -- and its body is this README as it stood at v0.164.11, word for word, with the old title line replaced by the heading above it. That body is frozen at v0.164.11 -- it carries the gate table as it stood at that release, so it is a record, not a live view. The current gate commands live in .github/workflows/check.yml and .github/workflows/publish.yml, plus .github/scripts/qa_loop/ (the QA harness the CI job invokes). All of them are in the repository; the registry publishes this one.

    $ moon test --target native --deny-warn Total tests: 1118, passed: 1118, failed: 0.

    #License

    MIT. The upstream package, DoubleML/doubleml-for-py, is BSD 3-Clause; this port is MIT-licensed and credits it (see Attribution above).

    Learner

    pub trait Learner {
    fn fit(Self, Matrix, Array[Double], Array[Double]) -> Self
    fn predict(Self, Matrix) -> Array[Double]
    }

    Trait for any learner that can be fit on (x, y) and predict on a feature matrix. Used by the DML cross-fit helpers and the PLR estimator.

    v0.118.0: fit takes a THIRD argument, sample_weight, matching upstream doubleml's protocol -- its ml_g / ml_m are objects with fit(X, y, sample_weight), so a learner without that parameter could not be a drop-in replacement, and a library that cannot express a weighted fit cannot port the DR-learner.

    An EMPTY weight array means "unweighted". That is the whole backward-compatibility story: every cross-fit helper in this package takes sample_weight? defaulting to [], so all 22 estimators and every existing caller are byte-identical. It also mirrors scikit-learn's sample_weight=None.

    MoonBit traits do NOT support a default method body (measured: adding one with parameters fails with Missing type annotation forthe parameter), so a defaulted fit_weighted is not an option. Each impl dispatches on emptiness itself; the shared helper is w_is_unweighted(w) below rather than a trait default.

    BootstrapMethodError

    pub suberror BootstrapMethodError {
    UnknownMethod(String)
    }

    Error type raised by draw_bootstrap_weights when the requested bootstrap method is not one of the supported options ("normal", "Bayes", "wild"). The payload is the unknown method name, which the caller can use to log or surface a meaningful diagnostic.

    Added in v0.37.0 to convert the previous abort() call into a testable error path. The pre-v0.37.0 panic_bootstrap_invalid_method test only exercised the require check in DoubleMLDIDMulti::bootstrap (which fires before the _ => abort fallback) — the test was silently skipped on native/wasm-gc. The new test draw_bootstrap_weights_raises_unknown_method calls draw_bootstrap_weights directly with an invalid method, exercising the previously-unreachable _ => abort path.

    BracketSignError

    pub suberror BracketSignError {
    UpperSignFailed
    }

    Error type raised by solve_pq when the IPW score at the upper bracket remains non-positive after 20 exponential widens — the score is structurally non-monotonic on the bracket, the quantile is non-monotonic in this data, or q is too close to 1 with sparse treatment.

    Added in v0.42.0 to convert the previous abort() call in solve_pq into a testable error path. The pre-v0.42.0 abort was reachable only via the (private) solve_pq helper; no public test exercised it. The new solve_pq_raises_on_upper_bracket_sign_failure test constructs a pathological DGP/quantile combination and asserts the error fires.

    Note: the pre-v0.42.0 source also had a lower-bracket-sign-failed abort at solve_pq. That abort is dead code: at lo = y_min - margin < y_min, every 1{y <= lo} = 0, so the IPW score treated/m * 0 - q is -q < 0 for all q > 0. The lo_score >= 0.0 check never fires. The dead abort is removed in v0.42.0; the suberror type has only the reachable UpperSignFailed variant.

    CalibrationFittingError

    pub suberror CalibrationFittingError {
    IncompleteCVPartition
    }

    Error type raised by isotonic_calibrate_cv when the provided cv partition does not cover every input index (some input rows are not in any fold's test_idx). This indicates a malformed cv partition passed by the caller.

    Added in v0.38.0 to convert the previous abort() call into a testable error path. The pre-v0.38.0 abort was reachable only via the (formerly private) isotonic_calibrate_cv helper; no public test exercised it. The new isotonic_calibrate_cv_raises_incomplete_partition test constructs a deliberately-malformed cv partition and asserts the error fires.

    ClusterDataError

    pub suberror ClusterDataError {
    MissingUnit(Int)
    }

    Error type raised by build_row_unit_map when a row's unit id is not present in the uniq list (a malformed cluster vector — the cluster ids must form a subset of the unique unit ids). The payload is the missing unit id, which the caller can use to log or surface a meaningful diagnostic.

    Added in v0.36.0 to convert the previous abort() call into a testable error path. The pre-v0.36.0 panic_build_row_unit_map_missing_unit test was silently skipped on native/wasm-gc (MoonBit's panic_* driver skips panic-prefixed tests; see _verify/WHITEBOX_T_REPORT.md).

    DIDDataError

    pub suberror DIDDataError {
    NonBinaryTreatment(Int)
    }

    Error type raised by DoubleMLDIDData::new when the treatment vector d is non-binary. The default port supports only the binary d ∈ {0, 1} convention (only the switchers; the multi-valued {-1, 0, 1} Sant'Anna & Zhao 2020 convention is not implemented). The payload is the index of the first non-binary entry, which the caller can use to log a meaningful diagnostic.

    Added in v0.43.0 to convert the previous abort() call into a testable error path. The pre-v0.43.0 abort was silently skipped on native/wasm-gc via the panic_* driver behavior (see _verify/WHITEBOX_T_REPORT.md). The new did_data_raises_on_non_binary_treatment test constructs a DoubleMLDIDData with a non-binary d entry and asserts the error fires.

    EmptyArrayError

    pub suberror EmptyArrayError

    Error type raised by array_min and array_max when the input array is empty. No payload — the empty array case has no diagnostic detail to carry.

    Added in v0.41.0 to convert the previous abort() calls into testable error paths. The pre-v0.41.0 aborts were reachable only via internal helpers; no public test exercised them. The new array_min_raises_on_empty and array_max_raises_on_empty tests call the helpers directly with [] and assert the errors fire.

    InvalidCalibrationError

    pub suberror InvalidCalibrationError {
    UnknownMethod(String)
    }

    Error type raised by apply_calibration (extracted from PSProcessor::adjust_ps in v0.37.0) when the configured calibration method is not one of the supported options ("none", "isotonic"). The payload is the unknown method name, which the caller can use to log or surface a meaningful diagnostic.

    Added in v0.37.0 to convert the previous abort() call inside adjust_ps into a testable error path. The panic_* test driver limitation had not been observed for this path because no test exercised it; the new test ps_processor_adjust_ps_raises_unknown_method constructs a config directly (bypassing PSProcessorConfig::new's require check) to reach the previously-unreachable abort.

    PSConfigError

    pub suberror PSConfigError {
    InconsistentCVCalibration
    }

    Error type raised by PSProcessorConfig::new when the configuration is internally inconsistent — the only currently-reachable case is cv_calibration = true combined with calibration_method = "none", because CV calibration is only meaningful for the isotonic method. No payload — the call-site (the require checks for clipping/extreme thresholds and calibration_method string) is enough to identify the configuration error.

    Added in v0.44.0 to convert the previous abort() call into a testable error path. The pre-v0.44.0 panic_ps_processor_cv_without_calibration test was silently skipped on native/wasm-gc (MoonBit's panic_* driver skips panic-prefixed tests; see _verify/WHITEBOX_T_REPORT.md). The new ps_processor_config_raises_inconsistent_cv_calibration test calls PSProcessorConfig::new directly with the inconsistent config and asserts the error fires.

    PreconditionError

    pub suberror PreconditionError {
    Violated(SourceLoc)
    }

    Error type reserved for the upcoming conversion of check.mbt::check and check.mbt::require from abort("precondition failed at ...") to a typed raise. The payload is the SourceLoc of the failing call site (auto-injected by #callsite(autofill(loc)) at every call), so the diagnostic message will point at the offending source line.

    Added in v0.47.0 as a planning release. v0.47.0 only declares the suberror type and ships a tiny check_make_violated helper (in check.mbt) that constructs a Violated(loc) for the regression test. The actual check/require → raise PreconditionError conversion is targeted for v0.48.0+ (cascade to all 324 pub functions, expected 1-2 release effort with try/catch/re-abort shims at every call site so the public abort behavior is preserved during the transition).

    VarEstClusterError

    pub suberror VarEstClusterError {
    JTooSmall(Double, Double, Int)
    }

    Error type raised by var_est_cluster when the fold-mean J = mean(psi_deriv) lands below the 1e-6 floor (a defensive guard added in v0.34.0 against divide-by-near-zero inflations of the cluster SE; see the rationale comment in var_est_cluster below). The payload captures the exact (j, g, n_units) triple that triggered the floor so callers can log or surface a meaningful diagnostic.

    Callers that want to preserve the pre-v0.35.0 process-death behavior should match on this variant and re-abort; callers that want to retry or surface the error to downstream consumers should propagate it via ?.

    CART

    pub enum CART {
    Leaf(Double)
    Split(Int, Double, CART, CART)
    } derive(
    Debug
    )

    Immutable CART tree node. Split carries the feature column index, the threshold, and the two child subtrees. Leaf carries the per-leaf mean (the constant prediction for rows that land here).

    CART::to_repr

    CSBinPanelRow

    type CSBinPanelRow derive(
    Debug
    )

    Per-row output of cs_bin_panel_subset. Each row is one observation in the post-subset panel: a (G_indicator, T_indicator) pair, the covariates, and the (still-raw) outcome y.

    ConstantLearner

    pub struct ConstantLearner {
    value : Double
    } derive(
    Debug
    )

    Constant-predictor learner. fit is a no-op (returns self); predict returns a length-x.rows() array of the constant value for every row, ignoring x.

    ConstantLearner::fit

    fn ConstantLearner::fit(self : ConstantLearner, x : Matrix, y : Array[Double]) -> ConstantLearner

    v0.118.0: the body became this inherent method so that ConstantLearner::new(..).fit(x, y) still resolves; the trait method (three-argument) delegates here.

    ConstantLearner::new

    fn ConstantLearner::new(value : Double) -> ConstantLearner

    ConstantLearner::predict

    fn ConstantLearner::predict(self : ConstantLearner, x : Matrix) -> Array[Double]

    DIDAggregationResult

    pub struct DIDAggregationResult {
    theta : Array[Double]
    se : Array[Double]
    agg_names : Array[String]
    } derive(
    Debug
    )

    Aggregation result for a single axis (group, time, or event). theta is the weighted-mean ATT, se is the delta-method SE, agg_names[i] is the human-readable label (e.g. the group value, the time period, or the event-time value).

    DidCsData

    type DidCsData

    Result of the DID CS2021 DGP.

    DidCsData::d_get

    fn DidCsData::d_get(self : DidCsData) -> Array[Double]

    Get the treatment vector.

    DidCsData::g_get

    fn DidCsData::g_get(self : DidCsData) -> Array[Int]

    Get the group (cohort) index.

    DidCsData::id_get

    fn DidCsData::id_get(self : DidCsData) -> Array[Int]

    Get the unit id (within cohort).

    DidCsData::n_groups_get

    fn DidCsData::n_groups_get(self : DidCsData) -> Int

    Get the number of cohorts.

    DidCsData::n_periods_get

    fn DidCsData::n_periods_get(self : DidCsData) -> Int

    Get the number of periods.

    DidCsData::t_get

    fn DidCsData::t_get(self : DidCsData) -> Array[Int]

    Get the time-period index.

    DidCsData::theta_get

    fn DidCsData::theta_get(self : DidCsData) -> Double

    Get the true ATT parameter.

    DidCsData::x_get

    fn DidCsData::x_get(self : DidCsData) -> Matrix

    Get the covariate matrix (panel-level, n_obs x dim_x).

    DidCsData::y_get

    fn DidCsData::y_get(self : DidCsData) -> Array[Double]

    Get the outcome vector.

    DidMultiData

    type DidMultiData

    Result of the DID CS2021 multi-cohort DGP.

    DidMultiData::d_get

    fn DidMultiData::d_get(self : DidMultiData) -> Array[Double]

    DidMultiData::g_get

    fn DidMultiData::g_get(self : DidMultiData) -> Array[Int]

    DidMultiData::id_get

    fn DidMultiData::id_get(self : DidMultiData) -> Array[Int]

    DidMultiData::n_groups_get

    fn DidMultiData::n_groups_get(self : DidMultiData) -> Int

    DidMultiData::n_periods_get

    fn DidMultiData::n_periods_get(self : DidMultiData) -> Int

    DidMultiData::t_get

    fn DidMultiData::t_get(self : DidMultiData) -> Array[Int]

    DidMultiData::theta_get

    fn DidMultiData::theta_get(self : DidMultiData) -> Double

    DidMultiData::x_get

    fn DidMultiData::x_get(self : DidMultiData) -> Matrix

    DidMultiData::y_get

    fn DidMultiData::y_get(self : DidMultiData) -> Array[Double]

    DoubleMLAPO

    pub struct DoubleMLAPO {
    data : DoubleMLData
    treatment_level : Double
    n_folds : Int
    n_rep : Int
    seed : Int
    smpls : Array[Array[Fold]]
    propensity_clip : Double
    ps_processor_config : PSProcessorConfig
    normalize_ipw : Bool
    ml_g : LearnerDispatch
    ml_m : LearnerDispatch
    g_hat : Array[Double]
    m_hat : Array[Double]
    coef : Double
    se : Double
    fitted : Bool
    psi_a : Array[Double]
    psi_b : Array[Double]
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    fit_cache : FitCache
    } derive(
    Debug
    )

    Average potential outcomes for an arbitrary treatment level.

    DoubleMLAPO::bias_corrected_coef

    fn DoubleMLAPO::bias_corrected_coef(self : DoubleMLAPO) -> Double

    v0.91.0+: returns coef UNCHANGED -- a documented no-op, not a bias correction.

    coef is the root of the DML moment f(theta) = E[theta * psi_a + psi_b] (see var_est.mbt), so mean(f(coef)) is identically zero: the estimating function is orthogonal by construction, and that orthogonality IS what makes the estimator consistent. Nothing computable from the fitted scores is a bias estimate for this class of estimator, so this accessor reports the uncorrected point estimate rather than a number that merely looks like a correction.

    (APO's psi_a is the constant -1.)

    v0.79.0 - v0.90.0 returned coef + mean(psi_b - coef * psi_a). That vector is the score at -coef, NOT at coef; since coef = -mean_b / mean_a its mean is mean_b - coef * mean_a = -2 * coef * mean_a, so the accessor returned coef * (1 - 2 * mean(psi_a)) (exactly 3 * coef when mean(psi_a) = -1). That is not a bias estimate. See bias_corrected_theta in sandwich.mbt for the algebra. The method is kept so the API surface stays stable; removing it outright is the obvious follow-up.

    Preconditions: self.fitted.

    DoubleMLAPO::bootstrap

    fn DoubleMLAPO::bootstrap(self : DoubleMLAPO, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLAPO

    v0.61.0+: multiplier bootstrap for DoubleMLAPO. The per-observation influence function is

    psi[i] = theta * psi_a[i] + psi_b[i] = -1 + theta * pb[i]

    where pb[i] = g[i] + treated[i] * (y[i] - g[i]) / m[i] is the IPW-centred potential-outcome score, computed at the fitted coef from the stored g_hat / m_hat. Draws n_rep_boot weight vectors of length n_obs from the chosen multiplier distribution, and returns a fitted model with boot_t_stat[b] = sum_i w[b, i] * psi[i] /(sqrt(n) * se_psi) populated where se_psi = sqrt(mean(psi^2)).

    method_name selects the multiplier distribution:
    • "normal" (default): w[i] ~ N(0, 1).
    • "Bayes": w[i] = exp(1) - 1 (mean 0, var 1).
    • "wild": w[i] = x[i] / sqrt(2) + (y[i]^2 - 1) / 2 with x, y ~ N(0, 1).

    Calling bootstrap requires the model to be fitted; calling on an un-fit model aborts with PreconditionError. The helper is did_bootstrap_t_stat (v0.55.0 extracted from DoubleMLDIDCrossSection::bootstrap); APO is the n_thetas=1 case.

    DoubleMLAPO::clear_cache

    fn DoubleMLAPO::clear_cache(self : DoubleMLAPO) -> DoubleMLAPO

    v0.84.0+: drop the cached nuisances. After this, the next fit() will run the full cross-fit (and repopulate the cache if memoize is still enabled).

    DoubleMLAPO::cluster_sandwich_se

    fn DoubleMLAPO::cluster_sandwich_se(self : DoubleMLAPO, cluster_ids : Array[Int]) -> Double

    v0.89.0+: cluster-robust sandwich standard error for the fitted APO. Routes through cluster_sandwich_variance with the same psi_a / psi / M_inv inputs as the IID sandwich_se path. cluster_ids[i] is the cluster of observation i on the full-sample (not transformed) domain. When the model was fitted on cluster data (data.cluster_vars non-empty) the natural cluster_ids are those very unit ids; otherwise the caller supplies them.

    Preconditions: self.fitted, cluster_ids.length() == psi_a.length().

    DoubleMLAPO::coef

    fn DoubleMLAPO::coef(self : DoubleMLAPO) -> Double

    DoubleMLAPO::confint

    fn DoubleMLAPO::confint(self : DoubleMLAPO) -> (Double, Double)

    DoubleMLAPO::disable_memoize

    fn DoubleMLAPO::disable_memoize(self : DoubleMLAPO) -> DoubleMLAPO

    v0.84.0+: turn off memoization. After this, fit() will not read or write the cache; the existing fit_cache is preserved on the returned struct (call clear_cache() to drop it).

    DoubleMLAPO::enable_memoize

    fn DoubleMLAPO::enable_memoize(self : DoubleMLAPO) -> DoubleMLAPO

    v0.84.0+: turn on memoization. When enabled (and n_rep == 1), the next fit() caches the LAST rep's (g_hat, m_hat,psi_a, psi_b) plus row-to-fold mapping; subsequent fit() calls with the same data fingerprint, fold split, learner configuration, propensity clip, and cluster partition reuse the cached nuisances. The var_est(psi_a, psi_b) -> (coef,se) pipeline still runs fresh on every fit(), so any post-aggregation configuration change always takes effect.

    DoubleMLAPO::fit

    DoubleMLAPO::has_cache

    fn DoubleMLAPO::has_cache(self : DoubleMLAPO) -> Bool

    v0.84.0+: true iff fit_cache holds at least one cached nuisance prediction (i.e. a previous fit() with memoize_enabled = true has populated the cache). Note that has_cache() does NOT verify the cache key matches the current data + learner configuration -- check memoize_enabled if you also need to know whether the next fit() will hit.

    DoubleMLAPO::learner_g

    fn DoubleMLAPO::learner_g(self : DoubleMLAPO) -> LearnerDispatch

    Accessor for the outcome-nuisance learner used by the most recent fit(...) call. v0.60.0+.

    DoubleMLAPO::learner_m

    fn DoubleMLAPO::learner_m(self : DoubleMLAPO) -> LearnerDispatch

    Accessor for the propensity-score learner used by the most recent fit(...) call. v0.60.0+.

    DoubleMLAPO::n_features

    fn DoubleMLAPO::n_features(self : DoubleMLAPO) -> Int

    Number of features (covariate columns).

    DoubleMLAPO::n_obs

    fn DoubleMLAPO::n_obs(self : DoubleMLAPO) -> Int

    DoubleMLAPO::new

    fn DoubleMLAPO::new(data : DoubleMLData, treatment_level? : Double, n_folds? : Int, n_rep? : Int, seed? : Int, propensity_clip? : Double, normalize_ipw? : Bool, ps_processor_config? : PSProcessorConfig?, ml_g? : LearnerDispatch, ml_m? : LearnerDispatch) -> DoubleMLAPO

    DoubleMLAPO::predictions_g

    fn DoubleMLAPO::predictions_g(self : DoubleMLAPO) -> Array[Double]

    DoubleMLAPO::predictions_m

    fn DoubleMLAPO::predictions_m(self : DoubleMLAPO) -> Array[Double]

    DoubleMLAPO::sample_splitting

    fn DoubleMLAPO::sample_splitting(self : DoubleMLAPO) -> SampleSplitting?

    The sample splitting recorded by set_sample_splitting, or None when none was supplied and fit draws its own. Some carries the DERIVED counts next to the folds, so a caller can read back what the estimator actually used rather than inferring it from the constructor arguments it no longer has any say over.

    A Some here does NOT mean the folds were used: on the cluster path fit_cluster draws unit-level folds and ignores them. See set_sample_splitting.

    DoubleMLAPO::sandwich_se

    fn DoubleMLAPO::sandwich_se(self : DoubleMLAPO, kind : SandwichKind) -> Double

    v0.89.0+: Huber-White sandwich standard error for the fitted APO (average potential outcome at treatment_level). Returns sqrt(var) where var comes from the shared sandwich_variance(kind, ...) dispatch in sandwich.mbt (HC0 / HC1 / HC2 / HC3).

    The three inputs are the ones fit(...) already persists for the multiplier bootstrap (see the psi_a / psi_b field docs on DoubleMLAPO):
    • psi_a = self.psi_a -- the potential-outcome score's treatment term, structurally the constant -1 (the potential-outcome score has no treatment-side variation), so mean(psi_a) == -1 and M_inv = [[-1.0]].
    • psi = psi_at(self.coef, self.psi_a, self.psi_b) -- the per-observation influence function at the fitted coef, with psi_b the IPW-centred score g[i] + treated[i] * (y[i] - g[i]) / m[i]. Matches the psi(theta) = theta * psi_a + psi_b form documented on DoubleMLAPO::bootstrap.
    • M_inv = [[1 / mean(psi_a)]] (1x1). Only M_inv[0, 0]^2 enters the variance, so the sign of the (up-to-sign) Jacobian inverse is irrelevant.

    APO has no transformed / subset domain: both the IID path and the v0.65.0 cluster path (fit_cluster) persist length-n_obs IF components, so the variance's n_obs is self.psi_a.length() == self.n_obs().

    Preconditions: self.fitted, mean(psi_a) != 0.

    DoubleMLAPO::se

    fn DoubleMLAPO::se(self : DoubleMLAPO) -> Double

    DoubleMLAPO::sensitivity_analysis

    fn DoubleMLAPO::sensitivity_analysis(self : DoubleMLAPO, cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    DoubleMLAPO::sensitivity_analysis_cluster

    fn DoubleMLAPO::sensitivity_analysis_cluster(self : DoubleMLAPO, cluster_ids? : Array[Int], cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.72.0+: cluster-robust analogue of DoubleMLAPO::sensitivity_analysis. Same residual formula (y - g_hat) and the same psi_a = -1 (constant) as the IID path; only the variance / bias computation is cluster-aware. cluster_ids defaults to DoubleMLData::cluster_vars.

    DoubleMLAPO::sensitivity_nu2_elements

    fn DoubleMLAPO::sensitivity_nu2_elements(self : DoubleMLAPO) -> (Array[Double], Array[Double]) raise

    v0.131.7: the nu2 score element and the Riesz representer for the APO policy score, transcribed from upstream irm/apo.py:371-382.

    Upstream's two layers collapse here as they do for IRM:

    • weights, weights_bar = self._get_weights(). _initialize_weights defaults to np.ones(n_obs) (apo.py inherits it from irm.py:249) and there is no weights_bar key, so weights == weights_bar == 1 (apo.py:234-242). Note APO's _get_weights takes NO m_hat argument -- only IRM's does, and only for ATTE.
    • m_hat_adj = _propensity_score_adjustment(m_hat, treated, normalize_ipw) (apo.py:365-367), which returns m_hat unchanged when normalize_ipw is False. This port HAS the flag (normalize_ipw : Bool, apo.mbt:44) and calls the same helper at PSProcessor::from_config(ps_processor_config) (apo.mbt:320), so the adjusted propensity is available directly rather than needing a new implementation.

    With both weight factors equal to 1:

    m_alpha = 1 / m_hat_adj rr = treated / m_hat_adj nu2 = mean( 2*m_alpha - rr^2 )

    treated[i] = 1{d[i] == treatment_level} (apo.mbt:355), matching upstream's self.treated.

    The default path previously computed mean(psi_a^2), upstream's documented FALLBACK (double_ml.py:1634-1641) applied to the wrong variable. APO's psi_a is the constant -1, so the fallback collapsed nu2 to exactly 1.

    DoubleMLAPO::set_sample_splitting

    fn DoubleMLAPO::set_sample_splitting(self : DoubleMLAPO, smpls : Array[Array[Fold]]) -> DoubleMLAPO

    Record a caller-supplied sample splitting and DERIVE the fold and repetition counts from it. Returns a new DoubleMLAPO; the receiver is unchanged, as everywhere in this package.

    smpls is one entry per repetition, each entry one Fold per fold -- the nested form is the only form, so a single repetition is [f0, f1, f2] wrapped once, i.e. [[f0, f1, f2]].

    The derivation is upstream's, and it is the part that surprises people: set_sample_splitting (doubleml/double_ml_sampling_mixins.py:76) sets n_folds and n_rep FROM the supplied partition, so handing a two-fold split to a model built with n_folds=5 yields a two-fold model. On the returned model n_folds / n_rep are updated to match, and fit uses the supplied folds instead of drawing them.

    Validation, via check_sample_splitting: every repetition carries the same number of folds, and within each repetition the test index sets are disjoint and cover exactly [0, n_obs). A supplied partition that is not a partition aborts rather than quietly producing a cross-fit that leaks across folds.

    Applies to the IID path only

    fit dispatches to fit_cluster when cluster_vars is non-empty, and that branch keeps drawing its own UNIT-level folds (kfold(n_units, self.n_folds, ...), then expanded to rows). This method supplies ROW-level folds, so on the cluster path they are ignored: the splitting is recorded, reported by sample_splitting, and carried across the cluster fit, but it does not change the folds that path uses. That is a real asymmetry and is stated here rather than papered over. Wiring it up would mean a second, unit-indexed splitting and a unit-indexed validation, which check_sample_splitting does not provide; until that exists, use fit on row-level data when you need the split to be honoured.

    Memoization is turned OFF on the returned model regardless of memoize_enabled. The fit cache is keyed on data + learner + cluster hashes with no term for the fold assignment, so caching an externally-split fit could return a DIFFERENT partition's predictions. The fit cache is also cleared here, for the same reason.

    Note that a subsequent fit() on the returned model rebuilds boot_t_stat / n_rep_boot from scratch, so a bootstrap computed before set_sample_splitting is dropped by that fit. That is the package-wide convention, not something this method introduces; call bootstrap(...) again on the fitted model if you need it.

    DoubleMLAPO::tune

    fn DoubleMLAPO::tune(self : DoubleMLAPO, param_set~ : Array[TuneParam], scoring_method? : String, n_folds_tune? : Int, seed? : Int) -> DoubleMLAPO

    v0.65.0+: tune the (ml_g, ml_m) nuisance-learner pair via MSE-on-g_hat cross-fitting. The chosen (learner_g,learner_m) is then re-fit on the FINAL-FIT fold partition (self.n_folds) under DoubleMLAPO::fit. treatment_level is held fixed at self.treatment_level.

    param_set is an Array[TuneParam]; each entry is a (learner_g, learner_m) pair. scoring_method is "MSE" (default), "RMSE", or "NegMSE". Returns a re-fitted DoubleMLAPO with the chosen pair applied.

    DoubleMLAPOS

    pub struct DoubleMLAPOS {
    data : DoubleMLData
    treatment_levels : Array[Double]
    n_folds : Int
    n_rep : Int
    seed : Int
    smpls : Array[Array[Fold]]
    propensity_clip : Double
    ps_processor_config : PSProcessorConfig
    normalize_ipw : Bool
    ml_g : LearnerDispatch
    ml_m : LearnerDispatch
    coefs : Array[Double]
    ses : Array[Double]
    fitted : Bool
    boot_t_stat : Array[Array[Double]]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    fit_cache : FitCache
    psi_b_flat : Array[Double]
    } derive(
    Debug
    )

    Average potential outcomes symmetric across multiple treatment levels. v0.49.0: full upstream parity — treatment_levels validation in new (rejects duplicates and levels not in data.d), the causal_contrast method (level-by-level delta and SE vs a reference level), and the treatment_levels() / n_treatment_levels() / fitted() accessors.

    Each treatment level is fit with the same fold partition (the parent does not currently route a shared partition to the child DoubleMLAPO; each child draws its own folds via kfold. v0.50.0+ plans to wire the parent through a fit_with_splits helper to share one stratified partition, but the v0.49.0 implementation is the v0.50.0 PR target) and the same closed-form LinearRegression learner. The causal_contrast(reference_levels) method then returns the level-by-level difference coefs[i] - coefs[ref] for one or more reference levels, matching the upstream DoubleMLAPOS.causal_contrast semantics.

    DoubleMLAPOS::bias_corrected_coef_at

    fn DoubleMLAPOS::bias_corrected_coef_at(self : DoubleMLAPOS, treatment_index : Int) -> Double

    v0.100.0+: returns coefs[treatment_index] UNCHANGED -- a documented no-op, not a bias correction. Identical in reasoning to DoubleMLAPO::bias_corrected_coef (v0.91.0, the sibling estimator) and to DoubleMLQTE::bias_corrected_coef_at; see DoubleMLPQ::bias_corrected_coef and bias_corrected_theta in sandwich.mbt for the full argument.

    coefs[j] is the root of the DML moment f(theta) = E[theta * psi_a + psi_b] (var_est.mbt), so mean(f(coefs[j])) is identically zero: the estimating function is orthogonal by construction, and that orthogonality IS what makes the estimator consistent. Nothing computable from the fitted scores is a bias estimate for this class of estimator, so this accessor reports the uncorrected point estimate rather than a number that merely looks like a correction.

    The pre-v0.91.0 form coef + mean(psi_b - coef * psi_a) is that vector at -coef, NOT at coef; since coef = -mean_b / mean_a its mean is mean_b - coef * mean_a = -2 * coef * mean_a, so the accessor returned coef * (1 - 2 * mean(psi_a)) -- exactly 3 * coef when mean(psi_a) = -1 (APO's case). That is not a bias estimate.

    The method is per level, matching the rest of the v0.100.0 APOS API.

    Preconditions: self.fitted, 0 <= treatment_index < coefs.length().

    DoubleMLAPOS::boot_method

    fn DoubleMLAPOS::boot_method(self : DoubleMLAPOS) -> String

    DoubleMLAPOS::boot_seed

    fn DoubleMLAPOS::boot_seed(self : DoubleMLAPOS) -> Int

    DoubleMLAPOS::boot_t_stats

    fn DoubleMLAPOS::boot_t_stats(self : DoubleMLAPOS) -> Array[Array[Double]]

    Per-level boot_t_stat accessors (v0.63.0+).

    DoubleMLAPOS::bootstrap

    fn DoubleMLAPOS::bootstrap(self : DoubleMLAPOS, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLAPOS

    Per-level multiplier bootstrap for DoubleMLAPOS. Each treatment level's child DoubleMLAPO is re-fit (deterministic given seed) and its bootstrap(...) invoked; the per-level boot_t_stat arrays are concatenated into a length-n_levels Array[Array[Double]] and also written to self.boot_t_stat.

    method_name selects the multiplier distribution: "normal" (default), "Bayes", "wild" — see DoubleMLAPO::bootstrap. n_rep_boot defaults to 500; seed defaults to 2024.

    DoubleMLAPOS::causal_contrast

    fn DoubleMLAPOS::causal_contrast(self : DoubleMLAPOS, reference_levels : Array[Double]) -> Array[Array[Double]]

    v0.49.0: causal contrasts between the requested treatment levels and the supplied reference level(s). Returns one Array[Double] of length 2 * treatment_levels.length() - 1 per reference level: the ref-level slot is a single 0.0 (its contrast is trivially zero), and every other slot is a (delta, se) pair where delta = coefs[i] - coefs[ref_idx] and se = sqrt(se[i]^2 + se[ref_idx]^2). ref_idx is the position of the reference level in treatment_levels. The layout is interleaved ([0.0, delta_0, se_0, delta_1, se_1, ...] for a 2-level input) rather than a [(level, coef, se), ...] table — see apo_test.mbt::apos_causal_contrast_with_reference for the actual indices.

    The SE of each contrast is computed via the standard var(psi_a) + var(psi_b) - 2*cov(psi_a, psi_b) style approximation; for v0.49.0 we take the conservative sqrt(se_a^2 + se_b^2) route (same as the upstream causal_contrast summary table), which is exact when the per-level psi_a and psi_b are independent across levels (true under stratified kfold with disjoint train indices).

    DoubleMLAPOS::clear_cache

    fn DoubleMLAPOS::clear_cache(self : DoubleMLAPOS) -> DoubleMLAPOS

    v0.84.0+: drop the cached (coefs, ses) arrays. After this, the next fit() will run the per-level loop fresh (and repopulate the cache if memoize is still enabled).

    DoubleMLAPOS::cluster_sandwich_se_at

    fn DoubleMLAPOS::cluster_sandwich_se_at(self : DoubleMLAPOS, treatment_index : Int, cluster_ids : Array[Int]) -> Double

    v0.100.0+: cluster-robust sandwich standard error for treatment level treatment_index of a fitted APOS (Arellano 1987, Cameron-Gelbach-Miller 2011). Routes through cluster_sandwich_variance with the SAME psi_a / psi / M_inv inputs as the IID sandwich_se_at path.

    DoubleMLData carries cluster_vars, so a clustered fit can pass self.data.cluster_vars directly; on the IID constructor path (cluster_vars = []) the caller must supply the grouping variable explicitly -- any clustering the application has: region, site, panel unit. With all-singleton clusters the meat degenerates to sum_i psi[i]^2 and the formula collapses to sandwich_se_at(j, HC0), hence to ses[j] on an IID fit.

    NOT equal to the IID HC0 with real clusters, on two counts: the within-cluster cross terms enter the meat, and the denominator is n_obs (observations) here while a clustered FIT's ses[j] is divided by n_units. This is the same row-level-vs-unit-level distinction QTE documents.

    Preconditions: self.fitted, 0 <= treatment_index < treatment_levels.length(), mean(psi_a) != 0, cluster_ids.length() == n_obs.

    DoubleMLAPOS::coefs

    fn DoubleMLAPOS::coefs(self : DoubleMLAPOS) -> Array[Double]

    DoubleMLAPOS::confint

    fn DoubleMLAPOS::confint(self : DoubleMLAPOS, level? : Double, joint? : Bool) -> Array[(Double, Double)]

    Per-level Wald confidence intervals (coef - z * se, coef + z * se) for DoubleMLAPOS. Returns one (lo, hi) tuple per treatment level, in user-supplied order. level defaults to 0.95 (z = 1.959963984540054 for the standard normal).

    DoubleMLAPOS::disable_memoize

    fn DoubleMLAPOS::disable_memoize(self : DoubleMLAPOS) -> DoubleMLAPOS

    v0.84.0+: turn off memoization. After this, fit() will not read or write the cache; the existing fit_cache is preserved on the returned struct (call clear_cache() to drop it).

    DoubleMLAPOS::enable_memoize

    fn DoubleMLAPOS::enable_memoize(self : DoubleMLAPOS) -> DoubleMLAPOS

    v0.84.0+: turn on memoization. Forwards .enable_memoize() to each child DoubleMLAPO on the next call, and caches the resulting (coefs, ses) arrays at the parent level so a repeated fit() call with identical inputs skips the per-level loop entirely.

    DoubleMLAPOS::fit

    DoubleMLAPOS::fitted

    fn DoubleMLAPOS::fitted(self : DoubleMLAPOS) -> Bool

    v0.49.0: whether fit has been called.

    DoubleMLAPOS::has_cache

    fn DoubleMLAPOS::has_cache(self : DoubleMLAPOS) -> Bool

    v0.84.0+: true iff fit_cache holds at least one cached (coefs, ses) pair (i.e. a previous fit() with memoize_enabled = true has populated the cache). Note that has_cache() does NOT verify the cache key matches the current data + learner configuration -- check memoize_enabled if you also need to know whether the next fit() will hit.

    DoubleMLAPOS::learner_g

    fn DoubleMLAPOS::learner_g(self : DoubleMLAPOS) -> LearnerDispatch

    Accessor for the outcome-nuisance learner used by the most recent fit(...) call. v0.60.0+.

    DoubleMLAPOS::learner_m

    fn DoubleMLAPOS::learner_m(self : DoubleMLAPOS) -> LearnerDispatch

    Accessor for the propensity-score learner used by the most recent fit(...) call. v0.60.0+.

    DoubleMLAPOS::n_rep_boot

    fn DoubleMLAPOS::n_rep_boot(self : DoubleMLAPOS) -> Int

    DoubleMLAPOS::n_treatment_levels

    fn DoubleMLAPOS::n_treatment_levels(self : DoubleMLAPOS) -> Int

    v0.49.0: number of requested treatment levels.

    DoubleMLAPOS::new

    fn DoubleMLAPOS::new(data : DoubleMLData, treatment_levels : Array[Double], n_folds? : Int, n_rep? : Int, seed? : Int, propensity_clip? : Double, normalize_ipw? : Bool, ps_processor_config? : PSProcessorConfig?, ml_g? : LearnerDispatch, ml_m? : LearnerDispatch) -> DoubleMLAPOS

    DoubleMLAPOS::sample_splitting

    fn DoubleMLAPOS::sample_splitting(self : DoubleMLAPOS) -> SampleSplitting?

    The sample splitting recorded by set_sample_splitting, or None when none was supplied. Some carries the DERIVED counts next to the folds. As with DoubleMLAPO::sample_splitting, a Some here does NOT by itself prove the folds were used on the cluster path — see set_sample_splitting.

    DoubleMLAPOS::sandwich_se_at

    fn DoubleMLAPOS::sandwich_se_at(self : DoubleMLAPOS, treatment_index : Int, kind : SandwichKind) -> Double

    v0.100.0+: heteroskedasticity-consistent (Huber-White) sandwich standard error for treatment level treatment_index of a fitted APOS. Routes through the shared sandwich_variance dispatch, so the HC0 / HC1 / HC2 / HC3 relationships are the package-wide ones (see the file header in sandwich.mbt and the identities pinned in expand_v088_test.mbt).

    The three inputs are the ones the child DoubleMLAPO already computed and persisted for its own multiplier bootstrap:
    • psi_a = the regenerated constant -1 row;
    • psi = psi_at(coefs[treatment_index], psi_a, psi_b) -- the per-observation influence function at the fitted coefficient, with psi_b the IPW-centred potential-outcome score g[i] + treated[i] * (y[i] - g[i]) / m[i]. Uses the package-wide psi(theta) = theta * psi_a + psi_b order (sandwich.mbt is the authority, not the psi_a + theta * psi_b phrasing some DID-family comments use);
    • M_inv = [[1 / mean(psi_a)]] = [[-1.0]]; only M_inv[0, 0]^2 enters the variance.

    n_obs is the full sample -- the same n_obs the child divides by in var_est -- and n_params is 1: ONE scalar estimand per treatment level, NOT treatment_levels.length(). The plausible misreading k = n_levels would give sqrt(n / (n - k)) for HC1 and is ruled out in the test.

    On the IID path sandwich_se_at(j, HC0) == ses[j] EXACTLY (see the section comment); on a CLUSTERED fit ses[j] is the unit-level cluster-robust SE and the invariant does not hold -- use cluster_sandwich_se_at(j, self.data.cluster_vars).

    Preconditions: self.fitted, 0 <= treatment_index < treatment_levels.length(), mean(psi_a) != 0.

    DoubleMLAPOS::sensitivity_analysis

    fn DoubleMLAPOS::sensitivity_analysis(self : DoubleMLAPOS, cf_y? : Double, cf_d? : Double) -> Array[SensitivityResult] raise

    v0.68.0+: per-level Cinelli & Hazlett (2020) omitted-variable bias analysis for DoubleMLAPOS. Re-fits a child DoubleMLAPO at each treatment level and delegates to its sensitivity_analysis(...). The per-level SensitivityResult is returned in user-supplied order; cross-level aggregation (e.g. for a joint sensitivity bound) is the caller's responsibility. Mirrors the DoubleMLAPOS::bootstrap pattern (re-fit each child, capture per-level results).

    DoubleMLAPOS::sensitivity_analysis_cluster

    fn DoubleMLAPOS::sensitivity_analysis_cluster(self : DoubleMLAPOS, cluster_ids? : Array[Int], cf_y? : Double, cf_d? : Double) -> Array[SensitivityResult] raise

    v0.74.0+: cluster-robust analogue of DoubleMLAPOS::sensitivity_analysis. Re-fits a child DoubleMLAPO at each treatment level and delegates to its sensitivity_analysis_cluster(...) so the per-cluster sigma2_cluster / nu2_cluster are computed against the cluster-summed residuals / psi_a. The per-level SensitivityResult is returned in user-supplied order; cross-level aggregation (e.g. for a joint cluster-robust sensitivity bound) is the caller's responsibility. Mirrors the IID path (sensitivity_analysis) and the cluster-aware sensitivity_analysis_cluster on DoubleMLAPO.

    cluster_ids defaults to DoubleMLData::cluster_vars.

    DoubleMLAPOS::ses

    fn DoubleMLAPOS::ses(self : DoubleMLAPOS) -> Array[Double]

    DoubleMLAPOS::set_sample_splitting

    fn DoubleMLAPOS::set_sample_splitting(self : DoubleMLAPOS, smpls : Array[Array[Fold]]) -> DoubleMLAPOS

    DoubleMLAPOS::set_sample_splitting — the multi-treatment sibling of DoubleMLAPO::set_sample_splitting, with one structural difference worth stating up front.

    APOS does not cross-fit anything itself. fit builds one child DoubleMLAPO per treatment level and calls child.fit(); the fold draw and the cross-fit both happen inside the child. So recording the splitting on the parent is not sufficient — it has to be PROPAGATED to every child, which fit does by composing the child's own setter (a pure builder, so the composition stays a value). Had this been written as "store it and return self", APOS would have looked like it had the feature and been exactly as inert as the v0.65.0 tune tests.

    The counts are derived exactly as upstream's set_sample_splitting does (doubleml/double_ml_sampling_mixins.py:76): n_folds and n_rep come OUT of the supplied partition, so a three-fold split handed to a model built with n_folds=9 yields a three-fold model.

    The same partition reaches every treatment level's child. That is the intended reading — one splitting for the whole model, not one per level — and it matters numerically: independent splits per level would give each coefs[j] a different nuisance cross-fit.

    The cluster caveat is inherited from the child and is real: on cluster data each child dispatches to its own fit_cluster, which draws UNIT-level folds and ignores these ROW-level ones.

    DoubleMLAPOS::treatment_levels

    fn DoubleMLAPOS::treatment_levels(self : DoubleMLAPOS) -> Array[Double]

    v0.49.0: the requested treatment levels, in user-supplied order.

    DoubleMLAPOS::tune

    fn DoubleMLAPOS::tune(self : DoubleMLAPOS, param_set~ : Array[TuneParam], scoring_method? : String, n_folds_tune? : Int, seed? : Int) -> DoubleMLAPOS

    DoubleMLAPOS::tune - score a grid of (learner_g, learner_m) pairs and re-fit with the winner. APOS is the multi-treatment sibling of DoubleMLAPO and tunes the same two slots, so it routes through the same tune_score_grid core.

    v0.108.0: new. APOS had no tune at all, so it was one of the fourteen estimators that carried a coverage gap against upstream (where tune reaches every estimator through the BaseDML mixin).

    The cluster guard is inherited from APO, which itself only got one in v0.108.0 - cluster-DML tune folds must be drawn over unique units rather than rows, and a row-wise schedule on clustered data produces a plausible-looking score for a wrong cross-fit instead of an error.

    DoubleMLBLP

    pub struct DoubleMLBLP {
    basis : Matrix
    orth_signal : Array[Double]
    cov_type : String
    ml_g : LearnerDispatch
    coef : Array[Double]
    se : Array[Double]
    fitted : Bool
    n_obs : Int
    rss : Double
    var_y : Double
    residuals : Array[Double]
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    fit_cache : FitCache
    } derive(
    Debug
    )

    Best linear predictor of an orthogonal signal on a supplied basis.

    cov_type selects the standard-error convention. Valid values:
    • "HC0" (default): White's heteroskedasticity-consistent sandwich SE — robust to arbitrary residual heteroskedasticity. Matches the upstream doubleml.utils.blp call to statsmodels.OLS(cov_type='HC0').
    • "nonrobust": classic homoskedastic OLS SE (sigma^2 * (X^T X)^{-1} with sigma^2 = RSS / (n - p)), which is only valid under the homogeneous-error assumption.

    REVIEW L5: the field is currently stored on the struct for forward compatibility (post-fit introspection), but is not used outside fit. Construct via DoubleMLBLP::new to validate the value.

    v0.63.0+: ml_g? field accepts a LearnerDispatch. The coef / (X^T X)^{-1} machinery is always the closed-form OLS path (BLP is by definition the OLS projection); the dispatch learner only affects the residual / RSS computation. Defaults to LearnerDispatch::linear_regression() which preserves the v0.62.2 byte-equality behaviour for the standard fit.

    DoubleMLBLP::basis

    fn DoubleMLBLP::basis(self : DoubleMLBLP) -> Matrix

    v0.22.0+: the basis matrix (the BLP's "design matrix"). Shape n_obs x p_features. Used by GainStatsSource::from_blp_cv to refit the BLP on each fold's training subset.

    DoubleMLBLP::bootstrap

    fn DoubleMLBLP::bootstrap(self : DoubleMLBLP, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLBLP

    v0.64.0+: multiplier bootstrap for DoubleMLBLP. BLP is the OLS projection of orth_signal onto the augmented design [1, basis]; per-observation IF is psi[i, j] = M[j, :] @ xa_i * e_i where M = (Xa^T Xa + ridge I)^{-1} and xa_i = [1, basis[i, :]]. se_flat is the per-coefficient SE (HC0 sandwich diagonal under cov_type = "HC0", sqrt(sigma^2 * (X^T X)^{-1}_{jj}) under cov_type = "nonrobust"); the helper skips a coefficient when se[j] = 0. Routes through the shared generic_bootstrap_ols_per_coef helper (see bootstrap_helper.mbt).

    method_name selects the multiplier distribution: "normal" (default), "Bayes", "wild". seed defaults to 2024; n_rep_boot defaults to 500.

    boot_t_stat is a flat [n_rep_boot * (p + 1)] array of t-statistics (row-major by rep, then by coef). Calling on an un-fit model aborts via PreconditionError.

    DoubleMLBLP::clear_cache

    fn DoubleMLBLP::clear_cache(self : DoubleMLBLP) -> DoubleMLBLP

    v0.83.0+: drop any cached OLS projection. Forces the next fit() to recompute from scratch.

    DoubleMLBLP::cluster_hac_se

    fn DoubleMLBLP::cluster_hac_se(self : DoubleMLBLP, cluster_ids : Array[Int]) -> Array[Double]

    v0.97.0+: cluster-robust (Arellano 1987, Cameron-Gelbach-Miller 2011) standard errors for the BLP projection -- the clustered analogue of hac_se(HC0), one SE per coefficient.

    cluster_ids[i] is the 0-based cluster of the i-th row of basis and orth_signal, and cluster_ids.length() must equal n_obs. Cluster indices are 0-based; 1 + max(cluster_ids) is the number of clusters.

    Per-row score for coefficient j, s_ij = m_j(xa_i) * e_i (the BLP HC0 term under a square root, with its sign), aggregated within cluster:

    S_cj = sum_{i in c} s_ij var_j = sum_c S_cj^2 * n_c / (n_c - 1)

    with the (n_c - 1) jackknife correction clipped to 1 for single-observation clusters (the statsmodelscov_type='cluster' convention, and the same clip cluster_sandwich_variance uses). There is NO 1 / n^2 divisor: the shared helper needs one because its moment is a MEAN moment, while this is a sum of squared row scores, exactly like hac_se(HC0).

    With all-singleton clusters the meat collapses to sum_i s_ij^2, i.e. hac_se(HC0) -- to floating-point tolerance, NOT bit-exactly, for two reasons: the per-row square is formed as s_i * s_i here against the m^2 e^2 association in hac_se, and this accumulator is Kahan-compensated (as in cluster_sandwich_variance) against hac_se's plain running sum. Pooled clusters differ.

    DoubleMLBLP has no cluster_vars field, so the user must pass cluster_ids explicitly. Calling on an un-fit model aborts via PreconditionError.

    DoubleMLBLP::coef

    fn DoubleMLBLP::coef(self : DoubleMLBLP) -> Array[Double]

    DoubleMLBLP::confint_joint

    fn DoubleMLBLP::confint_joint(self : DoubleMLBLP, contrast : Matrix, level? : Double) -> Array[(Double, Double)]

    Joint confidence interval for the linear contrast contrast @ coef (length n_contrast), via chi-squared critical value on the Mahalanobis distance.

    (contrast @ (coef - theta))^T @ inv(Omega_contrast) @ (contrast @ (coef - theta)) ~ chi2(n_contrast)

    where Omega_contrast = contrast @ Omega @ contrast^T is the induced covariance. Equivalent to a Bonferroni-style worst-case bound but tighter for low correlation.

    Parameters:
    • contrast: row-major matrix (n_contrast, p + 1) whose rows define the linear functions of coef to interval-estimate.
    • level: confidence level in (0, 1). Default 0.95.

    Returns: array of (low, high) tuples (each row a symmetric interval around contrast @ coef). For a single contrast row, returns a 1-element array. v0.53.0-dev Task 3 / v0.11.4 upstream parity.

    Notes: the upstream joint-CI uses bootstrap to draw the critical value from np.quantile(np.max(np.abs(bootstrap))), which requires the full omega matrix. In our port we approximate the critical value with the chi-squared quantile (1 df per row), and use the diagonal sandwich form of Omega_contrast (contrast[r]^2 @ diag(se^2)) for the variance. This is the standard closed-form chi-squared joint CI when the joint-CI variance is dominated by the diagonal (a conservative approximation for the upstream bootstrap).

    DoubleMLBLP::disable_memoize

    fn DoubleMLBLP::disable_memoize(self : DoubleMLBLP) -> DoubleMLBLP

    v0.83.0+: turn off memoization. Same immutability contract as enable_memoize(). After this, fit() will not read or write the cache; the existing fit_cache is preserved on the returned struct (call clear_cache() to drop it).

    DoubleMLBLP::enable_memoize

    fn DoubleMLBLP::enable_memoize(self : DoubleMLBLP) -> DoubleMLBLP

    v0.83.0+: turn on memoization for subsequent fit() calls. When enabled, fit() will cache the OLS projection (coef, se, residuals, n_obs, rss, var_y) and skip the LinearRegression::fit + sandwich_se path on a repeat call whose basis + orthogonal signal + learner + covariance type are all unchanged. Mirrors the IRM / PLR / CVAR / SSM plumbing.

    Default is OFF. When OFF, every fit() call runs the full OLS projection and the cache is neither read nor written, so v0.82.0 callers see byte-identical output.

    DoubleMLBLP::fit

    DoubleMLBLP::hac_se

    fn DoubleMLBLP::hac_se(self : DoubleMLBLP, kind : SandwichKind) -> Array[Double]

    v0.97.0+: heteroskedasticity-consistent (Huber-White) standard errors for the BLP projection, in the HC0 / HC1 / HC2 / HC3 family. Returns a length-n_params() vector -- one SE per coefficient, intercept at index 0 -- mirroring coef and se, which are both that length.

    This is NOT sandwich_se. Read the section comment above ("WHY BLP DOES NOT REUSE sandwich_se") for the algebra: BLP's meat is sum_i ( (M[j,:] . xa_i)^2 * e_i^2 ) with a full p1 x p1 normal inverse and no 1 / n^2, where the shared DML helper is a scalar-Jacobian MEAN-moment sandwich. The SandwichKind enum is reused -- it is the package's shared vocabulary for the HC family -- but the arithmetic behind each variant is the projection one.

    The invariant that proves the wiring: on a cov_type = "HC0" fit, se IS the HC0 standard error, so hac_se(HC0) == se holds BIT-IDENTICALLY, elementwise. It is NOT claimed on a cov_type = "nonrobust" fit, whose se is the homoskedastic sigma^2 (X'X)^-1 form.

    HC2 / HC3 divide each term by 1 - h_i (HC2) or (1 - h_i)^2 (HC3) using the OLS hat diagonal from leverage(). If any h_i leaves [0, 1) the divisor would be non-positive, which means the projection is rank-deficient. This ABORTS rather than clipping: a clip is what silently broke identities in v0.93 / v0.94, and for a leverage in [0, 1) no correction should ever fire. See blp_hac_require_df for why the df check has to run first.

    DoubleMLBLP::has_cache

    fn DoubleMLBLP::has_cache(self : DoubleMLBLP) -> Bool

    v0.83.0+: true iff fit_cache holds at least one cached observation (i.e. at least one prior fit() call with memoize_enabled = true has populated the cache). Note that the cache may still be stale relative to the current basis / learner configuration -- check memoize_enabled before assuming a cache hit.

    DoubleMLBLP::learner_g

    fn DoubleMLBLP::learner_g(self : DoubleMLBLP) -> LearnerDispatch

    v0.153.0: the outcome learner (ml_g) recorded at construction and used by fit when no explicit argument is given. DoubleMLBLP stores the single slot it has -- there is no ml_m, since the BLP policy score has no propensity term.

    DoubleMLBLP::leverage

    fn DoubleMLBLP::leverage(self : DoubleMLBLP) -> Array[Double]

    v0.97.0+: the OLS hat-matrix diagonal of the BLP design, the same quantity hac_se HC2 / HC3 divide by. Length n_obs.

    X^a (X'X + ridge I)^-1 X^{a'} is a projection plus a ridge-order perturbation, so every entry lies in [0, 1) and the entries sum to the RANK of the augmented design -- the trace of a projection is its rank -- which is n_params() for a full-rank basis and LESS for a rank-deficient one (a constant or duplicated basis column), always up to the ridge term. expand_v097_test.mbt pins the trace against the rank and the [0, 1) bound.

    Recomputed from the persisted basis on every call: BLP is a single closed-form OLS projection, so there is nothing to persist for it and nothing in the FitCache to extend.

    DoubleMLBLP::n_obs

    fn DoubleMLBLP::n_obs(self : DoubleMLBLP) -> Int

    v0.19.0+: sample size used by the BLP fit.

    DoubleMLBLP::n_params

    fn DoubleMLBLP::n_params(self : DoubleMLBLP) -> Int

    v0.97.0+: the number of coefficients the BLP projection estimates, basis.cols() + 1. LinearRegression::fit augments the stored basis with an intercept column, so this is coef.length() and se.length() on a fitted model, with the intercept at index 0.

    This is the k of the HC1 finite-sample correction n / (n - k) in hac_se(HC1), and the same p the cov_type = "nonrobust" branch uses for RSS / (n - p). Read it from here rather than assuming basis.cols(): the two differ by the intercept.

    Available before fit (it is a property of the design, not of the fit), mirroring DoubleMLRDD::n_local_params.

    DoubleMLBLP::new

    fn DoubleMLBLP::new(basis : Matrix, orth_signal : Array[Double], cov_type? : String, ml_g? : LearnerDispatch) -> DoubleMLBLP

    DoubleMLBLP::orth_signal

    fn DoubleMLBLP::orth_signal(self : DoubleMLBLP) -> Array[Double]

    v0.22.0+: the orthogonal signal array (the BLP's "outcome" variable). Length n_obs. Used by GainStatsSource::from_blp_cv to compute the cross-fit residual variance.

    DoubleMLBLP::predictions

    fn DoubleMLBLP::predictions(self : DoubleMLBLP) -> Array[Double]

    Fitted values basis_aug @ coef for each observation, length n_obs. Matches the upstream DoubleMLBLP.predictions / predict semantic — the orthogonal-signal prediction under the BLP coefficient vector.

    Note: coef has length p_basis + 1 because LinearRegression::fit adds an intercept column to basis. We reconstruct that column (all-1.0) on the fly to keep the stored self.basis unchanged.

    DoubleMLBLP::rss

    fn DoubleMLBLP::rss(self : DoubleMLBLP) -> Double

    v0.19.0+: residual sum of squares from the BLP fit. Equals sum_i (orth_signal[i] - basis[i] @ coef)^2.

    DoubleMLBLP::se

    fn DoubleMLBLP::se(self : DoubleMLBLP) -> Array[Double]

    DoubleMLBLP::sensitivity_analysis

    fn DoubleMLBLP::sensitivity_analysis(self : DoubleMLBLP, cf_y? : Double, cf_d? : Double) -> Array[SensitivityResult] raise

    v0.69.0+: per-coefficient sensitivity analysis for DoubleMLBLP.

    BLP is the closed-form OLS projection of orth_signal onto the augmented design Xa = [1, basis] (intercept + basis columns). Per-observation influence-function rows for coefficient j are

    psi_a[j][i] = M[j, :] @ xa_i

    where M = (Xa^T Xa + ridge I)^{-1} is the OLS precision matrix and xa_i is the augmented row i. The full IF for coef j decomposes as psi[i, j] = psi_a[j][i] * residuals[i] (matches the v0.64.0 bootstrap IF rows used by generic_bootstrap_ols_per_coef).

    Sensitivity for each coef follows the shared irm_style_sensitivity decomposition with:
    • theta = coef[j]
    • residuals = self.residuals (the OLS residuals from fit)
    • psi_a = psi_a[j]
    • cf_y / cf_d default to 0.05 (matching the rest of the v0.66.0-onward sensitivity family).

    Returns an Array[SensitivityResult] of length coef.length() (= n_features + 1, including the intercept at index 0). Calling on an un-fit model aborts via PreconditionError.

    DoubleMLBLP::sensitivity_analysis_cluster

    fn DoubleMLBLP::sensitivity_analysis_cluster(self : DoubleMLBLP, cluster_ids : Array[Int], cf_y? : Double, cf_d? : Double) -> Array[SensitivityResult] raise

    v0.74.0+: cluster-robust analogue of DoubleMLBLP::sensitivity_analysis. Same residual (self.residuals) and same per-coef psi_a_j (the M[j, :] @ xa_i Riesz-representer rows from the OLS precision matrix) as the IID path; only the variance / bias computation is cluster-aware. The augmented design xa and the precision xtx_inv are recomputed identically so the per-coef psi_a_j rows match the bootstrap IF rows exactly.

    DoubleMLBLP has no data field (just basis + orth_signal); the user must pass cluster_ids explicitly. cluster_ids.length() must equal self.basis.rows() (= self.orth_signal.length()).

    Returns an Array[SensitivityResult] of length self.coef.length() (= n_features + 1, including the intercept at index 0). Calling on an un-fit model aborts via PreconditionError.

    DoubleMLBLP::var_y

    fn DoubleMLBLP::var_y(self : DoubleMLBLP) -> Double

    v0.19.0+: variance of the orthogonal signal (the BLP's "outcome" variable). Computed as a population variance (divisor n, not n - 1).

    DoubleMLBinaryData

    pub struct DoubleMLBinaryData {
    x : Matrix
    y : Array[Double]
    d : Array[Double]
    } derive(
    Debug
    )

    Double / debiased machine learning for the partially logistic regression model (upstream doubleml.plm.DoubleMLLPLR, Liu, Zhang, Zhou 2021):

    Y = expit(D * theta_0 + r_0(X)), Y in {0, 1}

    The treatment D may be binary or continuous. The model uses a double cross-fit so the auxiliary regression t_0(X) = E[W | X] (where W = logit(M_0)) can be estimated with inner-fold OOF predictions without leaking information from the outer test set.

    Two scores are supported, exactly as upstream's SCORE FORMULAS:
    • "nuisance_space": psi_hat * (y*exp(-theta*D)*d_tilde -d_tilde*(1-Y)*exp(r_hat)), upstream plm/lplr.py:522-524. The starting beta is computed per fold, one per fold, from the inner predictions.
    • "instrument": the score itself is upstream's instrument-type form (Y - expit(theta*D + r_hat)) * (D - m_hat), with the derivative upstream gives at plm/lplr.py:536-538. The starting beta is still per-fold.

    v0.105.0: the two SCORE FORMULAS used to be inert. score was validated and stored but never read, so both strings returned the nuisance_space answer bit for bit; instrument now produces a genuinely different estimate.

    WHAT IS NOT UPSTREAM, and is easy to assume otherwise: upstream also CONDITIONS WHAT ml_m IS FITTED ON, per score (plm/lplr.py:244-264) -- Y = 0 subsamples for nuisance_space, M*(1-M) sample weights for instrument. That is implemented on neither branch here; m_pred is aliased to a_pred, unconditioned and unweighted. See the m_pred = a_pred block in fit for the full measurement and why it is held off.

    DoubleMLBinaryData::new

    fn DoubleMLBinaryData::new(x : Matrix, y : Array[Double], d : Array[Double]) -> DoubleMLBinaryData

    DoubleMLCVAR

    pub struct DoubleMLCVAR {
    data : DoubleMLData
    treatment : Double
    quantile : Double
    n_folds : Int
    n_rep : Int
    seed : Int
    smpls : Array[Array[Fold]]
    propensity_clip : Double
    ps_processor_config : PSProcessorConfig
    normalize_ipw : Bool
    ml_g : LearnerDispatch
    ml_m : LearnerDispatch
    g_hat : Array[Double]
    m_hat : Array[Double]
    coef : Double
    se : Double
    fitted : Bool
    psi_a : Array[Double]
    psi_b : Array[Double]
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    fit_cache : FitCache
    } derive(
    Debug
    )

    Conditional Value at Risk for a binary potential outcome, following the Kallus, Mao & Uehara (2024) "Removing Hidden Confounding by Supervised Gating" estimator (the upstream doubleml.irm.cvar.DoubleMLCVAR).

    The estimator solves the IPW score mean(1{d==treatment} / m(X) * 1{y <= theta} - quantile) = 0 per outer fold (with a per-fold preliminary cross-fit of m on the train side) to get a per-fold ipw_est[i], averages these for pq_est, and uses the cross-fitted (g, m) nuisances to evaluate the DML influence function psi_a = -1, psi_b = 1{d==treatment} * (g_target - g_hat) / m_hat + g_hat where g_target = max(pq_est, (y - q*pq_est) / (1-q)). The point estimate and SE come from the shared var_est(psi_a,psi_b) helper.

    v0.50.0: full upstream parity. The pre-v0.50.0 simplified version (which lived in quantile.mbt::DoubleMLCVAR and computed the CVaR via a single solve_pq call + a "max" target trick) has been removed; the canonical CVaR estimator is this struct.

    DoubleMLCVAR::bias_corrected_coef

    fn DoubleMLCVAR::bias_corrected_coef(self : DoubleMLCVAR) -> Double

    v0.91.0+: returns coef UNCHANGED -- a documented no-op, not a bias correction.

    coef is the root of the DML moment f(theta) = E[theta * psi_a + psi_b] (see var_est.mbt), so mean(f(coef)) is identically zero: the estimating function is orthogonal by construction, and that orthogonality IS what makes the estimator consistent. Nothing computable from the fitted scores is a bias estimate for this class of estimator, so this accessor reports the uncorrected point estimate rather than a number that merely looks like a correction.

    (CVAR's psi_a is the constant -1.)

    v0.79.0 - v0.90.0 returned coef + mean(psi_b - coef * psi_a). That vector is the score at -coef, NOT at coef; since coef = -mean_b / mean_a its mean is mean_b - coef * mean_a = -2 * coef * mean_a, so the accessor returned coef * (1 - 2 * mean(psi_a)) (exactly 3 * coef when mean(psi_a) = -1). That is not a bias estimate. See bias_corrected_theta in sandwich.mbt for the algebra. The method is kept so the API surface stays stable; removing it outright is the obvious follow-up.

    Preconditions: self.fitted.

    DoubleMLCVAR::bootstrap

    fn DoubleMLCVAR::bootstrap(self : DoubleMLCVAR, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLCVAR

    v0.75.0+: multiplier bootstrap for DoubleMLCVAR. The per-observation influence function is

    psi[i] = theta * psi_a[i] + psi_b[i] = -1 + theta * psi_b[i]

    where psi_b[i] = 1{d==treatment} * (g_target - g_hat) /m_hat + g_hat is computed at the fitted coef from the last rep's cross-fitted nuisances (g_hat, m_hat) and g_target = max(coef, (y - q*coef) / (1 - q)). psi_a is the constant -1 vector. Same IRM-style IF shape as DoubleMLIRM (constant derivative + offset score); the score-form IF identical to the v0.71.0 DoubleMLCVAR::sensitivity_analysis psi_a = -1 decomposition.

    method_name selects the multiplier distribution: "normal" (default), "Bayes", "wild"; seed defaults to 2024; n_rep_boot defaults to 500.

    Calling on an un-fit model aborts via PreconditionError. Returns a new DoubleMLCVAR with boot_t_stat / boot_method / n_rep_boot / boot_seed populated.

    DoubleMLCVAR::clear_cache

    fn DoubleMLCVAR::clear_cache(self : DoubleMLCVAR) -> DoubleMLCVAR

    v0.83.0+: drop any cached nuisance predictions, fold assignment, and ipw_vec. Forces the next fit() to recompute from scratch.

    DoubleMLCVAR::cluster_sandwich_se

    fn DoubleMLCVAR::cluster_sandwich_se(self : DoubleMLCVAR, cluster_ids : Array[Int]) -> Double

    v0.86.0+: cluster-robust sandwich standard error for the fitted CVAR. Routes through cluster_sandwich_variance with the same psi_a / psi / M_inv inputs as the IID sandwich_se path.

    Preconditions: self.fitted, cluster_ids.length() == n_obs.

    DoubleMLCVAR::coef

    fn DoubleMLCVAR::coef(self : DoubleMLCVAR) -> Double

    Point estimate (the upper-tail conditional mean of Y(treatment)).

    DoubleMLCVAR::confint

    fn DoubleMLCVAR::confint(self : DoubleMLCVAR) -> (Double, Double)

    95% Wald confidence interval (coef - 1.96 * se, coef + 1.96 * se).

    DoubleMLCVAR::disable_memoize

    fn DoubleMLCVAR::disable_memoize(self : DoubleMLCVAR) -> DoubleMLCVAR

    v0.83.0+: turn off memoization. Same immutability contract as enable_memoize(). After this, fit() will not read or write the cache; the existing fit_cache is preserved on the returned struct (call clear_cache() to drop it).

    DoubleMLCVAR::enable_memoize

    fn DoubleMLCVAR::enable_memoize(self : DoubleMLCVAR) -> DoubleMLCVAR

    v0.83.0+: turn on memoization for subsequent fit() calls. When enabled, fit() will cache the LAST rep's per-fold nuisance predictions (g_hat, m_final), the per-fold ipw_vec (needed to recompute pq_est on a cache hit), and the fold assignment; on a repeat call whose data + learner fingerprint + fold split is identical, the entire per-fold inner crossfit is skipped and the cached values feed the post-fold psi_a / psi_b / coef / se pipeline.

    enable_memoize() is honored only when n_rep == 1; for n_rep > 1 the per-rep cross-fit must run each time (the cache would otherwise need to thread n_rep independent per-rep nuisance arrays, which the FitCache layout does not accommodate).

    Default is OFF. When OFF, every fit() call runs the full per-fold inner crossfit and the cache is neither read nor written, so v0.82.0 callers see byte-identical output.

    DoubleMLCVAR::fit

    v0.50.0: fit the DoubleMLCVAR estimator. Implements the upstream _nuisance_est flow:
    1. For each rep r, draw n_folds outer folds with kfold(n, self.n_folds, self.seed + r).
    2. For each outer fold, run the inner cross-fit (see cvar_inner_crossfit) to get per-fold (g_hat,m_hat, ipw_est).
    3. After all folds, clip m_hat to [clip, 1-clip], optionally normalize the IPW weights, and (if treatment == 0) flip 1 - m_hat.
    4. Compute pq_est = mean(ipw_vec) and the final psi_a, psi_b with g_target = max(pq_est, (y - q*pq_est) / (1-q)).
    5. var_est(psi_a, psi_b) gives the per-rep (theta, se); aggregate across reps with aggregate_coef_se.

    DoubleMLCVAR::fitted

    fn DoubleMLCVAR::fitted(self : DoubleMLCVAR) -> Bool

    v0.50.0: True iff fit has been called.

    DoubleMLCVAR::has_cache

    fn DoubleMLCVAR::has_cache(self : DoubleMLCVAR) -> Bool

    v0.83.0+: true iff fit_cache holds at least one cached observation (i.e. at least one prior fit() call with memoize_enabled = true has populated the cache). Note that the cache may still be stale relative to the current data + learner configuration -- check memoize_enabled before assuming a cache hit.

    DoubleMLCVAR::learner_g

    fn DoubleMLCVAR::learner_g(self : DoubleMLCVAR) -> LearnerDispatch

    Accessor for the outcome-quantile-nuisance learner used by the most recent fit(...) call. v0.60.0+.

    DoubleMLCVAR::learner_m

    fn DoubleMLCVAR::learner_m(self : DoubleMLCVAR) -> LearnerDispatch

    Accessor for the propensity-score learner used by the most recent fit(...) call. v0.60.0+.

    DoubleMLCVAR::n_features

    fn DoubleMLCVAR::n_features(self : DoubleMLCVAR) -> Int

    Number of features (covariate columns).

    DoubleMLCVAR::n_obs

    fn DoubleMLCVAR::n_obs(self : DoubleMLCVAR) -> Int

    Number of observations.

    DoubleMLCVAR::new

    fn DoubleMLCVAR::new(data : DoubleMLData, treatment? : Double, quantile? : Double, n_folds? : Int, n_rep? : Int, seed? : Int, propensity_clip? : Double, ps_processor_config? : PSProcessorConfig?, normalize_ipw? : Bool, ml_g? : LearnerDispatch, ml_m? : LearnerDispatch) -> DoubleMLCVAR

    Construct a DoubleMLCVAR estimator.

    Parameters mirror the upstream DoubleMLCVAR.__init__:
    • treatment : binary potential outcome to target (0 or 1; default 1)
    • quantile : upper-tail level q of the conditional value at risk (strictly in (0, 1); default 0.5)
    • n_folds : number of outer / inner folds (default 2, matching the rest of the package's IRM family)
    • n_rep : number of sample-splitting repetitions (default 1)
    • seed : PRNG seed for the outer fold partition (default 3141)
    • propensity_clip: lower / upper clip bound for the propensity m (strictly in (0, 0.5); default 1e-6)
    • normalize_ipw : if true, normalize the IPW weights so they sum to n within each treatment group, matching the upstream default (default true).

    DoubleMLCVAR::predictions_g

    fn DoubleMLCVAR::predictions_g(self : DoubleMLCVAR) -> Array[Double]

    v0.50.0: cross-fitted g nuisance predictions (length n_obs). Only meaningful after fit.

    DoubleMLCVAR::predictions_m

    fn DoubleMLCVAR::predictions_m(self : DoubleMLCVAR) -> Array[Double]

    v0.50.0: cross-fitted m (propensity) nuisance predictions (length n_obs). Values are already clipped to [propensity_clip, 1 - propensity_clip]. If treatment == 0, the values are flipped to 1 - m (the symmetric treatment swap from the upstream API). Only meaningful after fit.

    DoubleMLCVAR::sample_splitting

    fn DoubleMLCVAR::sample_splitting(self : DoubleMLCVAR) -> SampleSplitting?

    The sample splitting recorded by set_sample_splitting, or None when none was supplied and fit draws its own. Some carries the DERIVED counts next to the folds, so a caller can read back what the estimator actually used rather than inferring it from the constructor arguments it no longer has any say over.

    On CVaR this reports the OUTER splitting only. The preliminary per-fold propensity cross-fit inside cvar_inner_crossfit is drawn internally and is not represented here - see set_sample_splitting for why.

    DoubleMLCVAR::sandwich_se

    fn DoubleMLCVAR::sandwich_se(self : DoubleMLCVAR, kind : SandwichKind) -> Double

    v0.86.0+: Huber-White sandwich standard error for the fitted CVAR. Returns sqrt(var) where var comes from the shared sandwich_variance(kind, ...) dispatch in sandwich.mbt (HC0 / HC1 / HC2 / HC3).

    The three inputs are the ones fit(...) already persists for the multiplier bootstrap (see the psi_a / psi_b field docs on DoubleMLCVAR):
    • psi_a = self.psi_a -- the constant -1 IRM-style Riesz representer, so mean(psi_a) = -1 and M_inv = -1.
    • psi = psi_at(self.coef, self.psi_a, self.psi_b) -- the per-observation influence function evaluated at the fitted coef, where psi_b carries the IPW weighting: 1{d == treatment} * (g_target - g_hat) / m_hat + g_hat with g_target = max(coef, (y - q * coef) / (1 - q)). Same psi_at score order as IRM / PLR.
    • M_inv = [[1 / mean(psi_a)]] (1x1). Only M_inv[0, 0]^2 enters the variance, so the sign of the (up-to-sign) Jacobian inverse is irrelevant.

    Preconditions: self.fitted, mean(psi_a) != 0.

    DoubleMLCVAR::se

    fn DoubleMLCVAR::se(self : DoubleMLCVAR) -> Double

    Standard error (DML influence-function SE; see var_est).

    DoubleMLCVAR::sensitivity_analysis

    fn DoubleMLCVAR::sensitivity_analysis(self : DoubleMLCVAR, cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.71.0: sensitivity analysis on DoubleMLCVAR. CVaR's DML influence function is the IRM-style form documented in the struct-level comment:

    psi_a[i] = -1 (constant) psi_b[i] = 1{d[i] == treatment} * (g_target - g_hat[i]) / m_hat[i] + g_hat[i]

    where g_target = max(coef, (y - q*coef) / (1 - q)) and q = self.quantile. The constant psi_a = -1 and the residual y - g_hat let us reuse the shared irm_style_sensitivity helper (see sensitivity.mbt).

    v0.157.0: the previous wording here ended "...and are passed through to the result for upstream parity". That was wrong, and measurement replaced it.

    • cf_y / cf_d ARE stored, so a caller can read back what was asked for -- but they reach NO computation. Measured across cf = 0.00 / 0.03 / 0.05 / 0.10 / 0.20: rv, max_bias, sigma2 and nu2 are all bit-identical (delta = 0 on every field). Only the stored cf_y/cf_d round-trip.
    • Upstream uses cf to set the WIDTH of the theta band (measured there: +/-6.88 SE at cf=0.20). This port's SensitivityResult (sensitivity.mbt:534) has no band, no CI and no rva, so it STRUCTURALLY cannot carry the quantity cf moves upstream. That is the real sense in which there is no parity here, and it is not fixable by plumbing.
    • The default is 0.05, where upstream's is 0.03 at 17 of its 21 estimator classes. So even the stored value diverges.

    Evidence: _verify/PARITY_COMMENTS_1570.md, _verify/_cvar_cf_1570.txt. (The premise of this whole block -- constant psi_a -- is confirmed: nu2 comes back as exactly 1.)

    DoubleMLCVAR::sensitivity_analysis_cluster

    fn DoubleMLCVAR::sensitivity_analysis_cluster(self : DoubleMLCVAR, cluster_ids? : Array[Int], cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.74.0+: cluster-robust analogue of DoubleMLCVAR::sensitivity_analysis. Same outcome residual formula (y - g_hat) and same psi_a = -1 (constant) as the IID path; only the variance / bias computation is cluster-aware (sigma2_cluster and nu2_cluster are the G / n_clusters sums of squared cluster sums).

    cluster_ids defaults to DoubleMLData::cluster_vars.

    DoubleMLCVAR::set_sample_splitting

    fn DoubleMLCVAR::set_sample_splitting(self : DoubleMLCVAR, smpls : Array[Array[Fold]]) -> DoubleMLCVAR

    Record a caller-supplied sample splitting and DERIVE the fold and repetition counts from it. Returns a new DoubleMLCVAR; the receiver is unchanged, as everywhere in this package.

    smpls is one entry per repetition, each entry one Fold per fold -- the nested form is the only form, so a single repetition is [f0, f1, f2] wrapped once, i.e. [[f0, f1, f2]].

    The derivation is upstream's, and it is the part that surprises people: set_sample_splitting (doubleml/double_ml_sampling_mixins.py:76) sets n_folds and n_rep FROM the supplied partition, so handing a two-fold split to a model built with n_folds=5 yields a two-fold model. On the returned model n_folds / n_rep are updated to match, and fit uses the supplied folds instead of drawing them.

    Validation, via check_sample_splitting: every repetition carries the same number of folds, and within each repetition the test index sets are disjoint and cover exactly [0, n_obs). A supplied partition that is not a partition aborts rather than quietly producing a cross-fit that leaks across folds.

    What this splitting does and does not replace

    CVaR has TWO fold sets, not one, and only the outer one is replaced:

    • The OUTER folds (kfold(n, self.n_folds, self.seed + r), driven per repetition by fit) ARE taken from smpls.

    • The PRELIMINARY fold set stays drawn. Inside cvar_inner_crossfit, each outer training fold is first split 50/50 by stratified_half_split into (train_1, train_2), and a stratified n_folds-fold cross-fit of the preliminary propensity runs over train_1 alone.

    That second set cannot be taken from smpls, and the reason is structural rather than a shortcut: its index space is the train_1 SUBSET of rows, reached through a per-fold kfold_stratified(train_1.length(), slice_vector(d, train_1), ...) whose fold lengths vary with the outer fold, while smpls is a partition of [0, n). Substituting it would need a second, differently-shaped splitting threaded through the free function's signature, plus a way to reconcile an arbitrary caller partition with a per-fold subset - and any mismatch there would break the propensity cross-fit inside one outer fold. So the preliminary set keeps being drawn, seeded as before. The consequence worth knowing: a fully externally-split CVaR still differs from an un-split one even when both partitions coincide, because its preliminary propensity cross-fit is still redrawn. That is stated here rather than left to be discovered by a test that compares estimates.

    Memoization is turned OFF on the returned model regardless of memoize_enabled. The fit cache is keyed on data + learner + cluster hashes with no term for the fold assignment, so caching an externally-split fit could return a DIFFERENT partition's predictions. The fit cache is also cleared here, for the same reason.

    Existing bootstrap state

    fit rebuilds boot_t_stat / boot_method / n_rep_boot / boot_seed from scratch on every call, so the fit that a caller makes next on the returned model DROPS any bootstrap the model was carrying. tune ends in such a fit, which makes this easy to hit by accident: set a splitting on a bootstrapped model, tune it, and the bootstrap is gone with no error. This method does not change that behaviour and does not clear the bootstrap itself (it returns ..self, so any bootstrap survives the call) - it is a property of fit, shared with every estimator in this package, recorded here because CVaR's tune makes it reachable in one step. Call bootstrap(...) again on the fitted model if you need it.

    DoubleMLCVAR::tune

    fn DoubleMLCVAR::tune(self : DoubleMLCVAR, param_set~ : Array[TuneParam], scoring_method? : String, n_folds_tune? : Int, seed? : Int) -> DoubleMLCVAR

    DoubleMLCVAR::tune - score a grid of (learner_g,learner_m) pairs and re-fit with the winner.

    Slot semantics: CVAR is a propensity-first family, so the first TuneParam slot is the treatment / propensity learner E[g|d,x] and the second is the outcome learner E[m|x]. The first field is still named learner_l (the field names are fixed by the partially-linear family); build candidates with TuneParam::for_treatment(learner_g, learner_m) so the call site carries the slot's role.

    v0.108.0: new. CVAR had no tune at all, so it was one of the estimators carrying a coverage gap against upstream, where tune reaches every estimator through the BaseDML mixin. It routes through the shared tune_score_grid core in tune.mbt - fold draw, cross-fit, scoring and the argmin/argmax selection all live there.

    CVAR-specific caveats:

    • The re-fit is self.fit(ml_g=..., ml_m=...), which reads quantile, treatment, ps_processor, n_folds, n_rep / seed and the memoize flag from self. Nothing is carried across by hand, and the tune-time folds are discarded - the winner is re-cross-fitted under self.n_folds.
    • DoubleMLCVAR::fit clears the bootstrap fields back to boot_t_stat: [] / boot_method: "" / n_rep_boot: 0 / boot_seed: 0 on every call. So calling tune on a model that already carries a bootstrap drops that bootstrap state
      • you have to re-run bootstrap on the returned model. That is fit's pre-existing behaviour, not something tune adds, but it is visible here because tune is a second way to reach fit.
    • The score is MSE of the first-slot learner cross-fitted against the outcome y, not against the treatment d, so it is a shortlisting proxy and not a direct measure of propensity quality. Same convention as the other propensity-first ::tune methods.

    The cluster guard IS present here, and unlike the DID* siblings it is reachable: CVAR's data is a DoubleMLData, which does carry cluster_vars and does expose is_cluster_data(). Cluster-DML tune folds must be drawn over unique units rather than rows - a row-wise fold schedule on clustered data splits a unit across the train/test boundary and produces a plausible-looking score for a wrong cross-fit rather than an error, which is exactly the silent mis-scoring that the v0.108.0 APO fix closed on the other side of the family. Aborting here is the correct behaviour.

    DoubleMLDID

    pub struct DoubleMLDID {
    data : DoubleMLDIDData
    n_folds : Int
    n_rep : Int
    seed : Int
    smpls : Array[Array[Fold]]
    propensity_clip : Double
    ps_processor_config : PSProcessorConfig
    score : String
    in_sample_normalization : Bool
    ml_g : LearnerDispatch
    ml_m : LearnerDispatch
    strata : Array[Int]
    g0_hat : Array[Double]
    g1_hat : Array[Double]
    m_hat : Array[Double]
    coef : Double
    se : Double
    psi_a : Array[Double]
    psi_b : Array[Double]
    fitted : Bool
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    fit_cache : FitCache
    } derive(
    Debug
    )

    Double / debiased machine learning estimator for the difference in differences (DID) model with panel data and binary treatment d ∈ {0, 1}, following Sant'Anna and Zhao (2020).

    The reduced-form outcome equation is

    Y_post = g_0(0, X) + D * theta + U_post, E[U | D, X] = 0 Y_pre = g_0(0, X) + U_pre, E[U_pre | X] = 0

    or, in first differences,

    dY = Y_post - Y_pre = g_1(1, X) - g_0(0, X) + D * theta + (U_post - U_pre)

    We form cross-fitted nuisance predictions

    g0(X) = E[Y | D = 0, X] (trained on D = 0) g1(X) = E[Y | D = 1, X] (trained on D = 1) m(X) = P(D = 1 | X) (trained on all obs; observational only, clipped to [eps, 1 - eps])

    and use the observational DID score (the most general one):

    resid_d0 = Y - g0 p_hat = mean(D) weight_psi_a = D / p_hat weight_resid = (D - m) / (p_hat * (1 - m)) psi_b = (D - m)/(p_hat (1 - m)) * (Y - g0) [the g1 term cancels in ATT] psi_a = -D / p_hat psi(theta) = theta * psi_a + psi_b

    Note: in the upstream code, when D = 1 is the only informative group, the ATT-style psi_b simplifies to psi_b = weight_resid_d0 * resid_d0 because psi_b_1 (the g1-based term) is zero under the ATT weighting. The port follows that simplification.

    Point estimate and variance

    theta_hat = -mean(psi_b) / mean(psi_a) J = mean(psi_a) gamma = mean(psi(theta_hat)^2) sigma2 = gamma / (J^2 * n) se = sqrt(sigma2).

    The experimental score (score = "experimental") and the in-sample-normalisation variant (in_sample_normalization = true) are supported as of v0.8.0; they are required by DoubleMLDIDBinary's preprocessing wrapper. The staggered-DID variant (DoubleMLDIDCS) is still not implemented in this port.

    DoubleMLDID::bias_corrected_coef

    fn DoubleMLDID::bias_corrected_coef(self : DoubleMLDID) -> Double

    v0.91.0+: returns coef UNCHANGED -- a documented no-op, not a bias correction.

    coef is the root of the DML moment f(theta) = E[theta * psi_a + psi_b] (see var_est.mbt), so mean(f(coef)) is identically zero: the estimating function is orthogonal by construction, and that orthogonality IS what makes the estimator consistent. Nothing computable from the fitted scores is a bias estimate for this class of estimator, so this accessor reports the uncorrected point estimate rather than a number that merely looks like a correction.

    v0.79.0 - v0.90.0 returned coef + mean(psi_b - coef * psi_a). That vector is the score at -coef, NOT at coef; since coef = -mean_b / mean_a its mean is mean_b - coef * mean_a = -2 * coef * mean_a, so the accessor returned coef * (1 - 2 * mean(psi_a)) (exactly 3 * coef when mean(psi_a) = -1). That is not a bias estimate. See bias_corrected_theta in sandwich.mbt for the algebra. The method is kept so the API surface stays stable; removing it outright is the obvious follow-up.

    Preconditions: self.fitted.

    DoubleMLDID::bootstrap

    fn DoubleMLDID::bootstrap(self : DoubleMLDID, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLDID

    v0.64.0+: multiplier bootstrap for DoubleMLDID. The per-observation influence function is

    psi[i] = theta * psi_a[i] + psi_b[i]

    where psi_a[i] = -d[i] / p_hat (or -1 for the experimental score) and psi_b[i] is the per-observation ATT score, both populated by fit(...) from the last rep's cross-fitted nuisances. Routes through the shared generic_bootstrap_t_stat helper (see bootstrap_helper.mbt).

    method_name selects the multiplier distribution: "normal" (default), "Bayes", "wild". seed defaults to 2024; n_rep_boot defaults to 500.

    Calling on an un-fit model aborts via PreconditionError.

    DoubleMLDID::clear_cache

    fn DoubleMLDID::clear_cache(self : DoubleMLDID) -> DoubleMLDID

    v0.82.0+: drop any cached nuisance predictions and fold assignment.

    DoubleMLDID::cluster_sandwich_se

    fn DoubleMLDID::cluster_sandwich_se(self : DoubleMLDID, cluster_ids : Array[Int]) -> Double

    v0.86.0+: cluster-robust sandwich standard error for the fitted DID. Routes through cluster_sandwich_variance with the same psi_a / psi / M_inv inputs as the IID sandwich_se path. DoubleMLDIDData carries no cluster_vars, so the caller must supply cluster_ids explicitly (typically the DID unit / panel id).

    Preconditions: self.fitted, cluster_ids.length() == n_obs.

    DoubleMLDID::coef

    fn DoubleMLDID::coef(self : DoubleMLDID) -> Double

    DoubleMLDID::confint

    fn DoubleMLDID::confint(self : DoubleMLDID, joint? : Bool, level? : Double) -> (Double, Double)

    v0.67.0+: joint is a no-op for single-theta estimators; accepted for API parity.

    DoubleMLDID::disable_memoize

    fn DoubleMLDID::disable_memoize(self : DoubleMLDID) -> DoubleMLDID

    v0.82.0+: turn off memoization.

    DoubleMLDID::enable_memoize

    fn DoubleMLDID::enable_memoize(self : DoubleMLDID) -> DoubleMLDID

    v0.82.0+: turn on memoization for subsequent fit() calls.

    DoubleMLDID::fit

    Run the DID estimation.

    DoubleMLDID::has_cache

    fn DoubleMLDID::has_cache(self : DoubleMLDID) -> Bool

    v0.82.0+: true iff fit_cache holds at least one cached observation.

    DoubleMLDID::learner_g

    fn DoubleMLDID::learner_g(self : DoubleMLDID) -> LearnerDispatch

    v0.153.0: the outcome learner (ml_g) recorded at construction and used by fit when no explicit argument is given. DoubleMLDID stored the pair since v0.60.0 but, unlike ten sibling estimators, never exposed it, so a fitted model could not report which learners produced it.

    DoubleMLDID::learner_m

    fn DoubleMLDID::learner_m(self : DoubleMLDID) -> LearnerDispatch

    v0.153.0: the propensity learner (ml_m) recorded at construction. See learner_g.

    DoubleMLDID::n_obs

    fn DoubleMLDID::n_obs(self : DoubleMLDID) -> Int

    DoubleMLDID::new

    fn DoubleMLDID::new(data : DoubleMLDIDData, n_folds? : Int, n_rep? : Int, seed? : Int, propensity_clip? : Double, ps_processor? : PSProcessor, ps_processor_config? : PSProcessorConfig?, score? : String, in_sample_normalization? : Bool, strata? : Array[Int], ml_g? : LearnerDispatch, ml_m? : LearnerDispatch) -> DoubleMLDID

    DoubleMLDID::predictions_g0

    fn DoubleMLDID::predictions_g0(self : DoubleMLDID) -> Array[Double]

    DoubleMLDID::predictions_g1

    fn DoubleMLDID::predictions_g1(self : DoubleMLDID) -> Array[Double]

    DoubleMLDID::predictions_m

    fn DoubleMLDID::predictions_m(self : DoubleMLDID) -> Array[Double]

    DoubleMLDID::sample_splitting

    fn DoubleMLDID::sample_splitting(self : DoubleMLDID) -> SampleSplitting?

    The sample splitting recorded by set_sample_splitting, or None when none was supplied and fit draws its own. Some carries the DERIVED counts next to the folds, so a caller can read back what the estimator actually used rather than inferring it from the constructor arguments it no longer has any say over.

    DoubleMLDID::sandwich_se

    fn DoubleMLDID::sandwich_se(self : DoubleMLDID, kind : SandwichKind) -> Double

    v0.86.0+: Huber-White sandwich standard error for the fitted DID. Returns sqrt(var) where var comes from the shared sandwich_variance(kind, ...) dispatch in sandwich.mbt (HC0 / HC1 / HC2 / HC3).

    The three inputs are the ones fit(...) already persists for the multiplier bootstrap (see the psi_a / psi_b field docs on DoubleMLDID):
    • psi_a = self.psi_a -- the ATT-style score's treatment term (-d / p_hat for the observational score, -1 for the experimental score, or -d / mean(d) under in-sample normalization). mean(psi_a) = -1 by construction, so M_inv = -1.
    • psi = psi_at(self.coef, self.psi_a, self.psi_b) -- the per-observation influence function evaluated at the fitted coef, where psi_b is the ATT outcome score. Matches the psi(theta) = theta * psi_a + psi_b form documented on DoubleMLDID::bootstrap.
    • M_inv = [[1 / mean(psi_a)]] (1x1). Only M_inv[0, 0]^2 enters the variance, so the sign of the (up-to-sign) Jacobian inverse is irrelevant.

    Preconditions: self.fitted, mean(psi_a) != 0.

    DoubleMLDID::se

    fn DoubleMLDID::se(self : DoubleMLDID) -> Double

    DoubleMLDID::sensitivity_analysis

    fn DoubleMLDID::sensitivity_analysis(self : DoubleMLDID, cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.66.0+: Cinelli & Hazlett (2020) omitted-variable bias analysis. Outcome residual is y - g0_hat - (g1_hat - g0_hat) * d; the Riesz-representer variance follows upstream's PRIMARY formula nu2 = mean(2 * m_alpha - rr^2) (did/did.py:352) rather than its fallback; see DoubleMLDID::sensitivity_nu2_elements.

    DoubleMLDID::sensitivity_analysis_cluster

    fn DoubleMLDID::sensitivity_analysis_cluster(self : DoubleMLDID, cluster_ids : Array[Int], cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.72.0+: cluster-robust analogue of DoubleMLDID::sensitivity_analysis. Same DID-style residual form (y - g0 - (g1 - g0) * d) and the same psi_a as the IID path; only the variance / bias computation is cluster-aware. DoubleMLDIDData has no cluster_vars field (the DID model itself doesn't fit a cluster path), so the user must pass cluster_ids explicitly. cluster_ids.length() must equal self.data.n_obs().

    DoubleMLDID::sensitivity_nu2_elements

    fn DoubleMLDID::sensitivity_nu2_elements(self : DoubleMLDID) -> (Array[Double], Array[Double]) raise

    v0.131.6: the nu2 score element and the Riesz representer for the DID ATT score, transcribed from upstream did/did.py:332-353.

    p_hat = mean(d) propensity_weight_d0 = m_hat / (1 - m_hat) score == "observational", in_sample_normalization: weight_d0 = (1 - d) * propensity_weight_d0 m_alpha = (d / p_hat) * (1/p_hat + propensity_weight_d0 / mean(weight_d0)) rr = d / p_hat - weight_d0 / mean(weight_d0) score == "observational", not in_sample_normalization: m_alpha = (d / p_hat^2) * (1 + propensity_weight_d0) rr = d / p_hat - ((1 - d) / p_hat) * propensity_weight_d0 score == "experimental": (identical with and without the flag) m_alpha = 1/p_hat + 1/(1 - p_hat) -- a CONSTANT array rr = d / p_hat - (1 - d)/(1 - p_hat) nu2_score_element = 2 * m_alpha - rr^2 nu2 = mean(nu2_score_element)

    The default (observational, in_sample_normalization = false) branch is the one this port's default arguments select, and it is the branch that used to be wrong here: the shared irm_style_sensitivity helper computes nu2 = mean(psi_a^2), which is upstream's documented FALLBACK (double_ml.py:1634-1641), applied to the wrong variable on top of that.

    DoubleMLDIDBinary shares this method deliberately. Upstream's did/did_binary.py:764-777 is the SAME formula; the two implementations differ only in the array sources (the subset's y/d and id-aligned predictions) and in a n_ids / n_obs_subset scaling applied to psi_sigma2 / psi_nu2 / riesz_rep -- but NOT to sigma2 / nu2 themselves. Those three scaled arrays feed only psi_max_bias, which every caller in this port discards via _, so the single shared path reproduces both estimators' reported sigma2 and nu2 exactly.

    Guarded denominators follow the convention used elsewhere in this package: the degenerate case maps to 0 rather than propagating a non-finite value.

    DoubleMLDID::set_sample_splitting

    fn DoubleMLDID::set_sample_splitting(self : DoubleMLDID, smpls : Array[Array[Fold]]) -> DoubleMLDID

    Record a caller-supplied sample splitting and DERIVE the fold and repetition counts from it. Returns a new DoubleMLDID; the receiver is unchanged, as everywhere in this package.

    smpls is one entry per repetition, each entry one Fold per fold -- the nested form is the only form, so a single repetition is [f0, f1, f2] wrapped once, i.e. [[f0, f1, f2]].

    The derivation is upstream's, and it is the part that surprises people: set_sample_splitting (doubleml/double_ml_sampling_mixins.py:76) sets n_folds and n_rep FROM the supplied partition, so handing a two-fold split to a model built with n_folds=5 yields a two-fold model. On the returned model n_folds / n_rep are updated to match, and fit uses the supplied folds instead of drawing them.

    Validation, via check_sample_splitting: every repetition carries the same number of folds, and within each repetition the test index sets are disjoint and cover exactly [0, n_obs). A supplied partition that is not a partition aborts rather than quietly producing a cross-fit that leaks across folds.

    Interaction with strata

    DID picks between two fold strategies: stratified_kfold when strata has length n_obs, plain kfold otherwise. An external splitting REPLACES BOTH. strata is then not consulted by fit at all, so a supplied partition is used verbatim and the usual guarantee that each fold balances the (G, T) cells no longer holds -- balance is then whatever the caller's partition happens to provide. This is the intended reading of "use these folds", but it is the one case where supplying a splitting changes something other than the fold boundaries, so it is called out here rather than left to be discovered.

    Memoization is turned OFF on the returned model regardless of memoize_enabled. The fit cache is keyed on data + learner + cluster hashes with no term for the fold assignment, so caching an externally-split fit could return a DIFFERENT partition's predictions. The fit cache is also cleared here, for the same reason.

    Note that a subsequent fit() on the returned model rebuilds boot_t_stat / n_rep_boot from scratch, so a bootstrap computed before set_sample_splitting is dropped by that fit. That is the package-wide convention, not something this method introduces; call bootstrap(...) again on the fitted model if you need it.

    DoubleMLDID::tune

    fn DoubleMLDID::tune(self : DoubleMLDID, param_set~ : Array[TuneParam], scoring_method? : String, n_folds_tune? : Int, seed? : Int) -> DoubleMLDID

    DoubleMLDID::tune - score a grid of nuisance-learner combinations and re-fit the estimator with the winner.

    Slots

    Tunes the two DID nuisance slots in the propensity-first sense documented on TuneParam (see the slot-semantics table there): the FIRST slot is the treatment / propensity learner E[g | x], the SECOND is the outcome learner E[m0 + d * m1 | x]. The first slot is stored on the field named learner_l; that field name is not a statement about which learner it holds, and always has been learner_l. Build each grid row with TuneParam::for_treatment(learner_g, learner_m) so the call site carries the role rather than leaving a reader to infer it from a field called learner_l.

    Routing

    The fold draw, the scoring and the selection rule all go through the shared tune_score_grid core in tune.mbt; this method adds no numerics of its own. Only the first slot is scored: the winning learner_l is then paired with the same grid row's learner_m for the re-fit under the FINAL-FIT fold schedule (self.n_folds).

    v0.108.0: new. DoubleMLDID had no tune at all, which was a coverage gap against upstream, where tune reaches every estimator through the BaseDML mixin.

    Caveats found while reading the fit path

    • n is NOT taken from self.n_obs(). The core derives it from self.data.y.length(), which is what the n_obs-less estimators in this package need. On DID the two agree: DoubleMLDIDData::new requires x.nrows == y.length and n_obs is x.rows().
    • fit exposes no tune_result parameter, so the per-candidate score vector is NOT retained on the returned estimator. This is the one thing not carried over from DoubleMLPLR::tune, which stashes a TuneResult. Recorded here rather than dropped silently.
    • fit cross-fits n_rep times, re-seeding per repetition (self.seed + r) and averaging the nuisance vectors, and it stratifies on self.strata when strata are present. The tune score is a SINGLE unstratified cross-fit, so it reflects one draw rather than the rep-averaged nuisance the final fit actually uses. tune forwards no n_rep / strata knob: both stay on self.

    No cluster guard

    require(!self.data.is_cluster_data()) is deliberately ABSENT here, unlike on DoubleMLAPO::tune. Not an oversight: DoubleMLDIDData is {x, y, d}, defines no is_cluster_data(), and carries no cluster_vars - cluster ids reach DID as an explicit argument to DoubleMLDID::cluster_sandwich_se(cluster_ids) at standard-error time instead. There is no cluster state on the data container for a guard to read, so a guard here could never fire.

    Stated so the absence is not read as an endorsement: cluster-aware tuning is not ENFORCED on DID, and it is not implemented either. Tune folds are drawn over rows, where a correct cluster-DML tune needs folds over unique units. Use DoubleMLDID::fit(ml_g=..., ml_m=...) with hand-picked candidates on the cluster path until a unit-wise fold schedule lands.

    DoubleMLDIDBinary

    pub struct DoubleMLDIDBinary {
    data : DoubleMLDIDBinaryData
    g_value : Int
    t_value_pre : Int
    t_value_eval : Int
    control_group : String
    anticipation_periods : Int
    n_folds : Int
    n_rep : Int
    seed : Int
    propensity_clip : Double
    ps_processor_config : PSProcessorConfig
    score : String
    in_sample_normalization : Bool
    ml_g : LearnerDispatch
    ml_m : LearnerDispatch
    eval_idx : Array[Int]
    inner : DoubleMLDID
    fitted : Bool
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    } derive(
    Debug
    )

    Binary DID model (Sant'Anna & Zhao 2020, §4.3) for panel data with binary treatment in terms of the (group, time) combination. Supports the two score variants "observational" (default, IPW-style) and "experimental" (A/B-test-style, requires independent treatment assignment), and the two weighting conventions "in_sample_normalization = true" (divide by sample mean) and false (divide by p_hat = mean(d)). The default (observational, false) matches the byte-equality of the pre-0.8.0 DoubleMLDID port on the canonical DGP.

    v0.10.0 additions (corresponds to upstream DoubleMLDIDCSBinary):
    • the propensity processor was split out of the bare propensity_clip argument, so the clipping threshold applied inside the score denominator is configurable independently of the inner cross-fit's numerical-safety clip. v0.127.0 promotes it to a full ps_processor_config (upstream's shape), stored concrete and forwarded verbatim to the inner DoubleMLDID, which applies it at upstream's single adjust_ps site (did_binary.py:537).
    • fit builds the wide-format strata G_indicator + 2 * t_indicator (matching upstream self._strata) and passes it to DoubleMLDID::new(strata=...), switching the inner sample-splitting to stratified_kfold. Each fold then balances the four (G, T) cells.

    The model is a thin wrapper around DoubleMLDID: it preprocesses the long-format panel into the wide-format DID dataset, then dispatches to DoubleMLDID::fit. The DML point estimate is the ATT (average treatment effect on the treated) for the chosen (g_value, t_value_pre, t_value_eval) triple.

    DoubleMLDIDBinary::bias_corrected_coef

    fn DoubleMLDIDBinary::bias_corrected_coef(self : DoubleMLDIDBinary) -> Double

    v0.91.0+: returns the inner DoubleMLDID::bias_corrected_coef unchanged, i.e. the uncorrected coef on the post-subset wide-format sample -- a documented no-op, not a bias correction. See DoubleMLDID::bias_corrected_coef for why there is nothing to correct.

    Preconditions: self.fitted.

    DoubleMLDIDBinary::bootstrap

    fn DoubleMLDIDBinary::bootstrap(self : DoubleMLDIDBinary, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLDIDBinary

    v0.64.0+: multiplier bootstrap for DoubleMLDIDBinary. Delegates to the inner DoubleMLDID::bootstrap(...) (the wide-format ATT sub-model). The returned boot_t_stat is the inner's t-statistic array — same meaning, same shape, same RNG (the inner is re-bootstrapped on each call so the long-format row mapping in eval_idx is preserved).

    method_name / n_rep_boot / seed are passed through to the inner call. Calling on an un-fit model aborts via PreconditionError.

    DoubleMLDIDBinary::clear_cache

    v0.82.0+: drop the inner cache (no-op on the wrapper itself).

    DoubleMLDIDBinary::cluster_sandwich_se

    fn DoubleMLDIDBinary::cluster_sandwich_se(self : DoubleMLDIDBinary, cluster_ids : Array[Int]) -> Double

    v0.89.0+: cluster-robust sandwich standard error for the fitted binary DID. Forwarded to the inner DoubleMLDID::cluster_sandwich_se, which routes through cluster_sandwich_variance with the inner's psi_a / psi / M_inv.

    cluster_ids is on the POST-SUBSET wide-format indexing (n_obs_subset() rows, one per retained unit), typically the unit id of the cell's panel.

    Preconditions: self.fitted, cluster_ids.length() == self.n_obs_subset().

    DoubleMLDIDBinary::coef

    fn DoubleMLDIDBinary::coef(self : DoubleMLDIDBinary) -> Double

    Point estimate (ATT) for the chosen (g_value, t_value_pre,t_value_eval) triple.

    DoubleMLDIDBinary::confint

    fn DoubleMLDIDBinary::confint(self : DoubleMLDIDBinary, joint? : Bool, level? : Double) -> (Double, Double)

    95% Wald-style confidence interval. v0.67.0+: joint is a no-op for single-theta estimators; delegates to the inner DoubleMLDID::confint.

    DoubleMLDIDBinary::disable_memoize

    v0.82.0+: turn off memoization.

    DoubleMLDIDBinary::enable_memoize

    v0.82.0+: turn on memoization for subsequent fit() calls. The flag is forwarded to the inner DoubleMLDID so the wide-format cross-fit honours the cache.

    DoubleMLDIDBinary::fit

    Run the binary DID estimation. Three steps:
    1. Preprocess the long-format panel into the wide-format DID dataset (preprocess_did_binary).
    2. Build a DoubleMLDIDData from the wide-format arrays.
    3. Fit a DoubleMLDID on the wide-format data with the chosen score and in_sample_normalization.

    The preprocessing keeps only units observed in both t_value_pre and t_value_eval, drops units with neither the G_indicator = (g == g_value) nor the C_indicator set, and uses the earlier period's covariates as the regressors.

    DoubleMLDIDBinary::has_cache

    fn DoubleMLDIDBinary::has_cache(self : DoubleMLDIDBinary) -> Bool

    v0.82.0+: true iff the inner DoubleMLDID cache holds at least one cached observation.

    DoubleMLDIDBinary::inner_psi_a

    fn DoubleMLDIDBinary::inner_psi_a(self : DoubleMLDIDBinary) -> Array[Double]

    v0.15.0+: per-observation psi_a on the cell's wide-format data (the inner DoubleMLDID's psi_a field). Length equals n_obs_subset() (the cell's wide-format panel size). Used by the multiplier bootstrap in DoubleMLDIDMulti::bootstrap to map wide-format psi back to the full long-format panel.

    DoubleMLDIDBinary::inner_psi_b

    fn DoubleMLDIDBinary::inner_psi_b(self : DoubleMLDIDBinary) -> Array[Double]

    v0.15.0+: per-observation psi_b on the cell's wide-format data. See inner_psi_a for details.

    DoubleMLDIDBinary::learner_g

    v0.153.0: the outcome learner (ml_g) recorded at construction, used by fit when no explicit argument is given. Reports the DEFAULT, not necessarily the learner of the current fit: an explicit fit(ml_g = ...) overrides it for that call only and is not recorded.

    DoubleMLDIDBinary::learner_m

    v0.153.0: the propensity learner (ml_m) recorded at construction. See learner_g for the same default-vs-current-fit caveat.

    DoubleMLDIDBinary::n_features

    fn DoubleMLDIDBinary::n_features(self : DoubleMLDIDBinary) -> Int

    Number of features (matches data.n_features()).

    DoubleMLDIDBinary::n_obs_subset

    fn DoubleMLDIDBinary::n_obs_subset(self : DoubleMLDIDBinary) -> Int

    Number of units in the wide-format subset (i.e. observed in both t_value_pre and t_value_eval and assigned to either G or C).

    DoubleMLDIDBinary::new

    fn DoubleMLDIDBinary::new(data : DoubleMLDIDBinaryData, g_value : Int, t_value_pre : Int, t_value_eval : Int, control_group? : String, anticipation_periods? : Int, n_folds? : Int, n_rep? : Int, seed? : Int, propensity_clip? : Double, ps_processor? : PSProcessor, ps_processor_config? : PSProcessorConfig?, score? : String, in_sample_normalization? : Bool, ml_g? : LearnerDispatch, ml_m? : LearnerDispatch) -> DoubleMLDIDBinary

    DoubleMLDIDBinary::predictions_g0

    fn DoubleMLDIDBinary::predictions_g0(self : DoubleMLDIDBinary) -> Array[Double]

    Cross-fitted control outcome predictions g_0(X) = E[Y | D = 0, X].

    DoubleMLDIDBinary::predictions_g1

    fn DoubleMLDIDBinary::predictions_g1(self : DoubleMLDIDBinary) -> Array[Double]

    Cross-fitted treated outcome predictions g_1(X) = E[Y | D = 1, X].

    DoubleMLDIDBinary::predictions_m

    fn DoubleMLDIDBinary::predictions_m(self : DoubleMLDIDBinary) -> Array[Double]

    Cross-fitted propensity predictions on the wide-format subset.

    DoubleMLDIDBinary::psi_a_long

    fn DoubleMLDIDBinary::psi_a_long(self : DoubleMLDIDBinary) -> Array[Double]

    v0.15.0+: per-observation influence function component psi_a mapped from the cell's wide-format data back to the long-format panel. Length equals data.n_obs() (the long-format panel). For long-format rows that are not in the cell's wide-format subset, the value is 0.0. The influence function psi = psi_a + theta * psi_b is used by the multiplier bootstrap in DoubleMLDIDMulti::bootstrap.

    DoubleMLDIDBinary::psi_b_long

    fn DoubleMLDIDBinary::psi_b_long(self : DoubleMLDIDBinary) -> Array[Double]

    v0.15.0+: per-observation influence function component psi_b mapped from the cell's wide-format data back to the long-format panel. See psi_a_long for details.

    DoubleMLDIDBinary::sandwich_se

    fn DoubleMLDIDBinary::sandwich_se(self : DoubleMLDIDBinary, kind : SandwichKind) -> Double

    v0.89.0+: Huber-White sandwich standard error for the fitted binary DID. Pure forwarder: the wrapper holds the whole fitted inner DoubleMLDID and that estimator already implements the v0.86.0 sandwich_se API, so the three methods are delegated rather than recomputed. The same applies to the DoubleMLDIDCSBinary / DoubleMLDID::sandwich_se contract (same psi_a / psi / M_inv construction, same shared sandwich_variance(kind, ...) dispatch in sandwich.mbt).

    The inner DoubleMLDID owns the IF components, so the variance's n_obs is the POST-SUBSET wide-format panel width self.n_obs_subset() -- NOT self.data.n_obs() (the long-format panel) and NOT the length of psi_a_long(). psi_a_long() maps the inner psi back to the long panel and zero-fills rows outside the cell, so feeding it here (or passing cluster_ids of long-panel length) is wrong.

    Preconditions: self.fitted.

    DoubleMLDIDBinary::se

    fn DoubleMLDIDBinary::se(self : DoubleMLDIDBinary) -> Double

    Standard error of the ATT point estimate.

    DoubleMLDIDBinary::sensitivity_analysis

    fn DoubleMLDIDBinary::sensitivity_analysis(self : DoubleMLDIDBinary, cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.66.0+: Cinelli & Hazlett (2020) omitted-variable bias analysis. Delegates to the inner DoubleMLDID::sensitivity_analysis on the wide-format ATT sub-model; the long-format row mapping in eval_idx is preserved (the residual is computed on the inner's row space).

    DoubleMLDIDBinary::sensitivity_analysis_cluster

    fn DoubleMLDIDBinary::sensitivity_analysis_cluster(self : DoubleMLDIDBinary, cluster_ids : Array[Int], cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.72.0+: cluster-robust analogue of DoubleMLDIDBinary::sensitivity_analysis. Delegates to the inner DoubleMLDID::sensitivity_analysis_cluster on the wide-format ATT sub-model. cluster_ids must have the same length as the wide-format subset (n_obs_subset, i.e. inner.data.n_obs()); the long-format row mapping in eval_idx is preserved. Pass an empty cluster_ids (the default) to abort via the inner precondition (no per-row cluster mapping is implied by the long-format panel).

    DoubleMLDIDBinary::tune

    fn DoubleMLDIDBinary::tune(self : DoubleMLDIDBinary, param_set~ : Array[TuneParam], scoring_method? : String, n_folds_tune? : Int, seed? : Int) -> DoubleMLDIDBinary

    DoubleMLDIDBinary::tune - score a grid of nuisance-learner combinations and re-fit the estimator with the winner.

    Slots

    Same two slots as DoubleMLDID::tune, in the propensity-first sense documented on TuneParam (see its slot-semantics table): FIRST slot is the treatment / propensity learner E[g | x], SECOND is the outcome learner E[m0 + d * m1 | x]. The first slot lives on the field named learner_l - that name is not a claim about which learner it holds. Use TuneParam::for_treatment(learner_g, learner_m) so the call site carries the role.

    Routing

    The fold draw, the scoring and the selection rule all go through the shared tune_score_grid core in tune.mbt; this method adds no numerics of its own. Only the first slot is scored, and the winning learner_l is paired with the same grid row's learner_m for the re-fit.

    v0.108.0: new. DoubleMLDIDBinary had no tune at all, which was a coverage gap against upstream, where tune reaches every estimator through the BaseDML mixin.

    Caveats found while reading the fit path

    • ROW SET MISMATCH, and it is the substantive one. fit first runs preprocess_did_binary and then rebuilds a wide, post-subset panel restricted to the four (G_indicator, T_indicator) cells; the final cross-fit runs on THAT data, stratified on G_indicator + 2 * t_indicator (falling back to plain kfold when a stratum is too small). tune_score_grid scores against self.data.x / self.data.y, i.e. the FULL long-format panel, not the wide post-subset rows the fit actually uses. So a candidate is ranked on strictly more rows than it is later cross-fitted on. This is a known gap, not an endorsement: the ranking is still a legitimate OOF score of E[y | x], but it is not scored on the estimator's own estimation sample.
    • fit exposes no tune_result parameter, so the per-candidate score vector is not retained on the returned estimator (same as on DoubleMLDID::tune, and unlike DoubleMLPLR::tune which stores a TuneResult). Recorded rather than dropped silently.
    • n comes from self.data.y.length() via the core, not from self.n_obs_subset(). The latter is the post-subset count, so using it here would have been the wrong denominator for a full-panel score.

    No cluster guard

    require(!self.data.is_cluster_data()) is deliberately ABSENT. DoubleMLDIDBinaryData is {x, y, d, t, g, id} and defines no is_cluster_data(). It does carry id (the panel unit id), but cluster ids reach this estimator as an explicit argument to DoubleMLDIDBinary::cluster_sandwich_se(cluster_ids) rather than as data-container state, so a guard reading self.data could never fire. Adding the method here would have meant inventing a cluster flag to guard on, which is out of scope for this change.

    Consequence, stated so the absence is not read as an endorsement: unit-aware tuning is neither enforced nor implemented for this estimator. Tune folds are row-wise.

    DoubleMLDIDBinaryData

    pub struct DoubleMLDIDBinaryData {
    x : Matrix
    y : Array[Double]
    d : Array[Double]
    t : Array[Int]
    g : Array[Int]
    id : Array[Int]
    } derive(
    Debug
    )

    Panel data container for the binary DID model. Stores long-format panel observations: each row is (unit, time, y, d, x_1, ...,x_p). t_col and id_col identify the time and unit indices. g_col is the unit's treatment-group index (the period of first treatment; equal to never_treated_value for never-treated units). All arrays are length n_obs_total = n_units * n_periods.

    The fit step reshapes this long-format data into a wide-format DID dataset: for each unit observed in both t_value_pre and t_value_eval, we construct y_diff = y_post - y_pre, the G_indicator = (g == g_value), the C_indicator (never-treated or not-yet-treated per control_group), and the covariates from the earlier period. The wide-format dataset is then passed to DoubleMLDID for the standard DML cross-fit.

    DoubleMLDIDBinaryData::n_features

    fn DoubleMLDIDBinaryData::n_features(self : DoubleMLDIDBinaryData) -> Int

    DoubleMLDIDBinaryData::n_obs

    DoubleMLDIDBinaryData::new

    fn DoubleMLDIDBinaryData::new(x : Matrix, y : Array[Double], d : Array[Double], t : Array[Int], g : Array[Int], id : Array[Int]) -> DoubleMLDIDBinaryData

    DoubleMLDIDCS

    pub struct DoubleMLDIDCS {
    data : DoubleMLDIDCSData
    control_group : String
    anticipation_periods : Int
    n_folds : Int
    n_rep : Int
    seed : Int
    propensity_clip : Double
    ps_processor_config : PSProcessorConfig
    in_sample_normalization : Bool
    coef_matrix : Array[Double]
    se_matrix : Array[Double]
    psi_matrix : Array[Double]
    psi_a_matrix : Array[Double]
    residuals_matrix : Array[Double]
    cell_psi_a : Array[Array[Double]]
    cell_psi_b : Array[Array[Double]]
    m_hat_long : Array[Double]
    panel_folds : Array[Fold]
    g_hat_d0t0_long : Array[Double]
    g_hat_d0t1_long : Array[Double]
    g_hat_d1t0_long : Array[Double]
    g_hat_d1t1_long : Array[Double]
    sigma2_panel : Double
    nu2_panel : Double
    psi_sigma2_long : Array[Double]
    psi_nu2_long : Array[Double]
    riesz_rep_long : Array[Double]
    n_groups : Int
    n_periods : Int
    fitted : Bool
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    ml_g : LearnerDispatch
    ml_m : LearnerDispatch
    } derive(
    Debug
    )

    Callaway-Sant'Anna (2021) staggered DID model. Iterates over every (g, t_pre, t_eval) triple where g is a treatment group and t_eval is strictly after g, runs a DoubleMLDIDBinary on the long-format panel restricted to the never-treated control cohort, and stores the per-(g, t) ATT estimate, SE, and 95% CI.

    Simplifications vs. upstream:
    • Binary treatment {0, 1} only (the {-1, 0, 1} multi-valued d convention is not supported here; use DoubleMLDIDBinary with control_group = "not_yet_treated" for the staggered case).
    • Default control group is "never_treated". "not_yet_treated" is supported but not-yet-treated units are not "switched in" to be controls in subsequent periods (we always use the never-treated sentinel cohort as the single control).
    • Score is fixed to observational; in-sample normalisation is false (matches the DoubleMLDID default). Callers can pass in_sample_normalization = true to switch to the Sant'Anna & Zhao (2020) eq. 4.3 form.
    • No sensitivity analysis, no tune_optuna, no aggregation beyond the per-(g, t) output.

    DoubleMLDIDCS::bias_corrected_coef_at

    fn DoubleMLDIDCS::bias_corrected_coef_at(self : DoubleMLDIDCS, group_idx : Int, period_idx : Int) -> Double

    v0.100.0+: returns coef_at(group_idx, period_idx) UNCHANGED -- a documented no-op, not a bias correction. Identical in reasoning to DoubleMLAPO::bias_corrected_coef (v0.91.0), DoubleMLAPOS::bias_corrected_coef_at (v0.100.0) and DoubleMLQTE::bias_corrected_coef_at; see DoubleMLPQ::bias_corrected_coef and bias_corrected_theta in sandwich.mbt for the full argument.

    coef_at(g, t) is the child's root of the DML moment f(theta) = E[theta * psi_a + psi_b] (var_est.mbt), so mean(f(coef_at(g, t))) is identically zero: the estimating function is orthogonal by construction, and that orthogonality IS what makes the estimator consistent. Nothing computable from the fitted scores is a bias estimate for this class of estimator, so this accessor reports the uncorrected point estimate rather than a number that merely looks like a correction.

    The pre-v0.91.0 form coef + mean(psi_b - coef * psi_a) is that vector at -coef, NOT at coef; since coef = -mean_b / mean_a its mean is mean_b - coef * mean_a = -2 * coef * mean_a, so the accessor returned coef * (1 - 2 * mean(psi_a)) -- exactly 3 * coef when mean(psi_a) = -1, which is exactly this score's case for every cell. That is not a bias estimate.

    Unlike sandwich_se_at, an unestimated cell does NOT abort here: the answer is the identity on coef_at, and coef_at reports 0.0 for such a cell, so 0.0 is the consistent answer rather than a misleading one.

    The method is per cell, matching the rest of the v0.100.0 DIDCS API.

    Preconditions: self.fitted, 0 <= group_idx < n_groups, 0 <= period_idx < n_periods.

    DoubleMLDIDCS::bootstrap

    fn DoubleMLDIDCS::bootstrap(self : DoubleMLDIDCS, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLDIDCS

    v0.64.0+: multiplier bootstrap for DoubleMLDIDCS. For each (g, t) cell that has a non-zero SE, materialises the per-cell IF row (psi_matrix[(gi * n_periods + pi) *n_obs + i_long]) into a flat [n_cells, n_obs] psi matrix and calls the shared generic_bootstrap_psi_matrix helper. boot_t_stat is a flat [n_rep_boot * n_cells] array, row-major by rep, then by cell — the same layout as DoubleMLDIDMulti::boot_t_stat. Pre-treatment or empty cells (se_matrix[k] == 0) are zeroed out by the helper.

    method_name selects the multiplier distribution: "normal" (default), "Bayes", "wild". seed defaults to 2024; n_rep_boot defaults to 500.

    Calling on an un-fit model aborts via PreconditionError.

    DoubleMLDIDCS::clear_cache

    fn DoubleMLDIDCS::clear_cache(self : DoubleMLDIDCS) -> DoubleMLDIDCS

    v0.82.0+: drop any cached nuisance predictions across all per-cell inner models. No-op on an un-fit wrapper.

    DoubleMLDIDCS::cluster_sandwich_se_at

    fn DoubleMLDIDCS::cluster_sandwich_se_at(self : DoubleMLDIDCS, group_idx : Int, period_idx : Int, cluster_ids : Array[Int]) -> Double

    v0.100.0+: cluster-robust sandwich standard error for the (g, t) cell of a fitted CS-DID (Arellano 1987, Cameron-Gelbach-Miller 2011). Routes through cluster_sandwich_variance with the SAME psi_a / psi / M_inv inputs as the IID sandwich_se_at path, and the same per-cell n_wide row set.

    DoubleMLDIDCSData has no cluster_vars field (the CS-DID estimator itself fits no cluster path), so the caller must supply cluster_ids explicitly. The ids are PER CELL AND PER CELL ROW, not per long-format panel row: cluster_ids.length() must equal this cell's cell_psi_a[g * n_periods + t].length(), i.e. the child's n_wide. For a (g, t) cell that is one entry per unit observed in both the pre and the eval period, so the panel data.id (length n_units * n_periods, long format) is the WRONG array to pass; slice the cell's rows first, or build the ids from the same (g in {G, C}, t in {pre, eval}) rule the cell loop uses. Cluster indices are 0-based and 1 + max(cluster_ids) is the number of clusters. For a DID the natural grouping is the panel unit.

    NOT equal to the IID HC0 once clusters hold more than one row, and the reason is the MEAT, not the denominator: cluster_sandwich_variance sums S_c = (sum_{i in c}psi[i])^2 per cluster, so the within-cluster cross terms enter, and each cluster carries a per-cluster jackknife factor n_c / (n_c - 1) (clipped to 1 for a singleton cluster). The divisor is the same n_wide^2 as HC0, and all rows of the cell are the same rows. With ALL-SINGLETON clusters the meat degenerates to sum_i psi[i]^2, the jackknife factors are all 1, and the formula collapses to sandwich_se_at(g, t, HC0) exactly -- which is the property expand_v100_didcs_test.mbt pins.

    This is the ROW-level cluster variance. A clustered FIT's se_at in this package is divided by n_units (panel units), not by the row count, so cluster_sandwich_se_at is not a drop-in for a cluster-robust se_at; the DIDCS fit path takes no clustering at all, so there is no clustered se_at to disagree with here.

    Preconditions: self.fitted, valid indices, the cell was actually estimated, mean(psi_a) != 0, cluster_ids.length() == n_wide, all cluster_ids[i] >= 0.

    DoubleMLDIDCS::coef_at

    fn DoubleMLDIDCS::coef_at(self : DoubleMLDIDCS, group_idx : Int, period_idx : Int) -> Double

    Per-(g, t) ATT estimate (row-major indexing). 0.0 if the (g, t) cell is empty (e.g. t_eval ≤ g for the chosen group).

    DoubleMLDIDCS::confint

    fn DoubleMLDIDCS::confint(self : DoubleMLDIDCS, joint? : Bool, level? : Double) -> Array[(Double, Double)]

    When joint = false (default), uses the Wald-style theta ± 1.96 * se interval. When joint = true, uses the bootstrap: theta ± critical_value * se where critical_value is the (1 - alpha) quantile of max_k |boot_t_stat[b, k]| over bootstrap replications b (the joint critical value). Requires bootstrap() to have been called.

    DoubleMLDIDCS::disable_memoize

    fn DoubleMLDIDCS::disable_memoize(self : DoubleMLDIDCS) -> DoubleMLDIDCS

    v0.82.0+: turn off memoization.

    DoubleMLDIDCS::enable_memoize

    fn DoubleMLDIDCS::enable_memoize(self : DoubleMLDIDCS) -> DoubleMLDIDCS

    v0.82.0+: turn on memoization for subsequent fit() calls. The flag is forwarded to every per-cell DoubleMLDIDBinary fit.

    DoubleMLDIDCS::fit

    Run the CS-DID estimation: for every (g, t_eval) triple with t_eval > g, restrict the panel to the never-treated cohort plus the units with g == g_value, run a DoubleMLDIDBinary on the restricted long-format data with t_value_pre = g and t_value_eval = t_eval, and store the resulting ATT and SE.

    The (g, t_eval) combinations are visited in row-major order (groups ascending, periods ascending). Cells with t_eval <= g are left at the default 0.0 (the CS-DID convention is "no pre-treatment estimate" for such cells; downstream aggregation layers can drop them via the nan-aware aggregator).

    DoubleMLDIDCS::group_at

    fn DoubleMLDIDCS::group_at(self : DoubleMLDIDCS, group_idx : Int) -> Int

    Group value at row index i (sorted ascending).

    DoubleMLDIDCS::has_cache

    fn DoubleMLDIDCS::has_cache(self : DoubleMLDIDCS) -> Bool

    v0.82.0+: true iff the memoize flag is set.

    DoubleMLDIDCS::learner_g

    v0.153.0: the outcome learner (ml_g) recorded at construction and used by fit when no explicit argument is given. Reports the DEFAULT, not necessarily the learner of the current fit: an explicit fit(ml_g = ...) overrides it for that call only and is not recorded.

    DoubleMLDIDCS::learner_m

    v0.153.0: the propensity learner (ml_m) recorded at construction. See learner_g for the same default-vs-current-fit caveat.

    DoubleMLDIDCS::n_groups

    fn DoubleMLDIDCS::n_groups(self : DoubleMLDIDCS) -> Int

    Number of groups (excluding the never-treated sentinel).

    DoubleMLDIDCS::n_periods

    fn DoubleMLDIDCS::n_periods(self : DoubleMLDIDCS) -> Int

    Number of distinct time periods.

    DoubleMLDIDCS::new

    fn DoubleMLDIDCS::new(data : DoubleMLDIDCSData, control_group? : String, anticipation_periods? : Int, n_folds? : Int, n_rep? : Int, seed? : Int, propensity_clip? : Double, ps_processor? : PSProcessor, ps_processor_config? : PSProcessorConfig?, in_sample_normalization? : Bool, ml_g? : LearnerDispatch, ml_m? : LearnerDispatch) -> DoubleMLDIDCS

    DoubleMLDIDCS::period_at

    fn DoubleMLDIDCS::period_at(self : DoubleMLDIDCS, period_idx : Int) -> Int

    Time value at column index t (sorted ascending).

    DoubleMLDIDCS::predictions_g_d0_t0

    fn DoubleMLDIDCS::predictions_g_d0_t0(self : DoubleMLDIDCS) -> Array[Double]

    E[Y | D = 0, T = 0, X], cross-fitted over the whole panel. Length n_obs. The conventions above apply to all four; they are documented on this one.

    DoubleMLDIDCS::predictions_g_d0_t1

    fn DoubleMLDIDCS::predictions_g_d0_t1(self : DoubleMLDIDCS) -> Array[Double]

    E[Y | D = 0, T = 1, X], cross-fitted over the whole panel. Length n_obs. See DoubleMLDIDCS::predictions_g_d0_t0 for the shared conventions.

    DoubleMLDIDCS::predictions_g_d1_t0

    fn DoubleMLDIDCS::predictions_g_d1_t0(self : DoubleMLDIDCS) -> Array[Double]

    E[Y | D = 1, T = 0, X], cross-fitted over the whole panel. Length n_obs. See DoubleMLDIDCS::predictions_g_d0_t0 for the shared conventions. Structurally EMPTY on the canonical 2-period fixture -- see convention 3.

    DoubleMLDIDCS::predictions_g_d1_t1

    fn DoubleMLDIDCS::predictions_g_d1_t1(self : DoubleMLDIDCS) -> Array[Double]

    E[Y | D = 1, T = 1, X], cross-fitted over the whole panel. Length n_obs. See DoubleMLDIDCS::predictions_g_d0_t0 for the shared conventions.

    DoubleMLDIDCS::predictions_m

    fn DoubleMLDIDCS::predictions_m(self : DoubleMLDIDCS) -> Array[Double]

    Cross-fitted group propensity m_hat = E[D | X] on the LONG-format panel. v0.146.0+ (stage 1a of the did_cs sensitivity migration).

    Empty until fit. Length n_obs -- the LONG panel, i.e. one entry per unit-period row, not per unit.

    WHY IT EXISTS. Upstream's did_cs sensitivity decomposition needs this on the full panel: propensity_weight_d0 = m_hat / (1 - m_hat) (did_cs.py:470), which feeds m_alpha and hence nu2 = mean(2*m_alpha -rr^2) (did_cs.py:527-528). Until now the port could not produce it: each (g, t) cell delegates to a child DoubleMLDIDBinary restricted to that cell's two cohorts and two periods, so its propensity is a different object, and DoubleMLDIDCS exposed no prediction accessor either.

    NOT YET CONSUMED. This release only persists and exposes the nuisance. sensitivity_analysis still routes through the legacy irm_style_sensitivity, so no reported number changes in v0.146.0 -- which is asserted by GATE 5 in expand_v146_test.mbt. The nu2 formula port that consumes it is a later stage, and it additionally needs the four (d, t) outcome nuisances that this stage does not build.

    DoubleMLDIDCS::sandwich_se_at

    fn DoubleMLDIDCS::sandwich_se_at(self : DoubleMLDIDCS, group_idx : Int, period_idx : Int, kind : SandwichKind) -> Double

    v0.100.0+: heteroskedasticity-consistent (Huber-White) sandwich standard error for the (g, t) cell of a fitted CS-DID. Routes through the shared sandwich_variance dispatch, so the HC0 / HC1 / HC2 / HC3 relationships are the package-wide ones (see the file header in sandwich.mbt and the identities pinned in expand_v088_test.mbt and expand_v100_didcs_test.mbt).

    The three inputs are the ones the child DoubleMLDIDBinary already computed and persisted for its own multiplier bootstrap:
    • psi_a = the child's wide-format psi_a row, i.e. the treatment-weight term -d / p_hat;
    • psi = psi_at(coef_at(g, t), psi_a, psi_b) -- the per-observation influence function at the fitted cell coefficient, in the package-wide psi(theta) = theta * psi_a + psi_b order. This is the order var_est uses, and it is the OPPOSITE of the psi_a + theta * psi_b order the long-format psi_matrix uses -- see the section comment above;
    • M_inv = [[1 / mean(psi_a)]], which is [[-1.0]] here (only M_inv[0, 0]^2 enters the variance).

    n_obs is the cell's n_wide -- the child's own wide-format row count, the same n its var_est divided by -- and n_params is 1: ONE scalar estimand (this cell's ATT), NOT n_groups and NOT the number of visited cells. The plausible misreading k = n_groups would give sqrt(n / (n - k)) for HC1 and is ruled out in the test.

    coef_at(g, t) IS the child's stored coef, the same number var_est solved for, so on the IID path

    sandwich_se_at(g, t, HC0) == se_at(g, t)

    holds BIT-IDENTICALLY (measured difference 0.0; see the section comment and expand_v100_didcs_test.mbt).

    Preconditions: self.fitted, 0 <= group_idx < n_groups, 0 <= period_idx < n_periods, the cell was actually estimated, mean(psi_a) != 0, and n_obs > n_params for HC1 / HC2 / HC3.

    DoubleMLDIDCS::se_at

    fn DoubleMLDIDCS::se_at(self : DoubleMLDIDCS, group_idx : Int, period_idx : Int) -> Double

    Per-(g, t) ATT standard error.

    DoubleMLDIDCS::sensitivity_analysis

    fn DoubleMLDIDCS::sensitivity_analysis(self : DoubleMLDIDCS, cf_y? : Double, cf_d? : Double) -> Array[SensitivityResult] raise

    default. Calling on an un-fit model aborts via PreconditionError.

    DoubleMLDIDCS::sensitivity_analysis_cluster

    fn DoubleMLDIDCS::sensitivity_analysis_cluster(self : DoubleMLDIDCS, cluster_ids : Array[Int], cf_y? : Double, cf_d? : Double) -> Array[SensitivityResult] raise

    v0.73.0+: cluster-robust analogue of DoubleMLDIDCS::sensitivity_analysis. Same per-cell ATT-form residual y - g_d0_hat - (g_d1_hat - g_d0_hat) *d and the same per-cell psi_a (the Riesz-representer component) as the IID path; only the variance / bias computation is cluster-aware (see irm_style_sensitivity_cluster_multi and irm_style_sensitivity_cluster in sensitivity.mbt).

    DoubleMLDIDCSData has no cluster_vars field (the CS-DID estimator itself does not fit a cluster path), so the user must pass cluster_ids explicitly. cluster_ids.length() must equal self.data.n_obs() (the long-format panel length). Cluster indices are 0-based; 1 + max(cluster_ids) is the number of clusters. All rows in the same cluster share an id.

    Cells with se_matrix[k] == 0 (pre-treatment / no observed evaluation period / empty panel subset) return a zeroed SensitivityResult from the inner irm_style_sensitivity_cluster pass.

    Returns an Array[SensitivityResult] of length n_groups * n_periods in row-major (gi, pi) order.

    DoubleMLDIDCS::sensitivity_folds

    fn DoubleMLDIDCS::sensitivity_folds(self : DoubleMLDIDCS) -> Array[Fold]

    The panel-wide cross-fitting folds backing predictions_m. v0.146.0+. Exposed so the nuisance is reproducible and its stratification is inspectable rather than a hidden detail of fit.

    DoubleMLDIDCS::sensitivity_nu2

    fn DoubleMLDIDCS::sensitivity_nu2(self : DoubleMLDIDCS) -> Double

    Upstream's nu2 (did_cs.py:527-528):

    nu2 = mean(2*m_alpha - rr^2)

    where m_alpha and rr are the Riesz quantities from doubleml/did/did_cs.py:466-497. Both formulas verified bit-exact against a running upstream 0.11.4: on a 2x2 panel upstream reports nu2 = 18.253043736106648 and sigma2 = 256.4070590464714, and this transcription reproduces both to the last digit (_verify/_oracle_v1482_nu2_gap.py).

    PANEL-LEVEL, like sensitivity_sigma2.

    MAY BE NaN, AND THAT IS CORRECT -- on a 2-period panel. The in_sample_normalization = true branch divides by mean(d1t0), which is 0.0 on the canonical 2-period fixture because nobody is treated in the pre-period -- the (d=1, t=0) cell is structurally empty. Upstream's arithmetic on the same input produces the same Inf/NaN, and no fallback is substituted, because a quiet replacement number would be indistinguishable from a correct one.

    On a MULTI-PERIOD panel this accessor is NOT correct, and does not merely go NaN -- it returns a large negative value (measured -112652.99) built from a negative denominator. See the v0.154.0 RESTRICTION note on sensitivity_sigma2, which governs all five sensitivity_* accessors. This paragraph's "that is correct" claim holds ONLY for 2-period panels.

    Which branch runs is self.in_sample_normalization, whose port default (false) differs from upstream's (true).

    0.0 before fit.

    DoubleMLDIDCS::sensitivity_psi_nu2

    fn DoubleMLDIDCS::sensitivity_psi_nu2(self : DoubleMLDIDCS) -> Array[Double]

    Per-row psi_nu2 = (2*m_alpha - rr^2) - nu2. As with psi_sigma2, upstream stores the DEVIATION from the scalar (did_cs.py:529), so this array has mean exactly zero and sensitivity_nu2 is NOT its mean -- recovering the element itself needs psi_nu2[i] + nu2. Length n_obs; empty before fit.

    v0.154.0: 2-PERIOD PANELS ONLY. See the RESTRICTION note on sensitivity_sigma2.

    DoubleMLDIDCS::sensitivity_psi_sigma2

    fn DoubleMLDIDCS::sensitivity_psi_sigma2(self : DoubleMLDIDCS) -> Array[Double]

    Per-row psi_sigma2 = (y - g_hat)^2 - sigma2. Upstream's convention is the DEVIATION from the scalar (did_cs.py:464), so this array has mean exactly zero -- it is not the raw element. Length n_obs; empty before fit.

    v0.154.0: 2-PERIOD PANELS ONLY. See the RESTRICTION note on sensitivity_sigma2 -- on a multi-period panel every row with t >= 2 is discarded from the g-functions this deviation is built from.

    DoubleMLDIDCS::sensitivity_riesz_rep

    fn DoubleMLDIDCS::sensitivity_riesz_rep(self : DoubleMLDIDCS) -> Array[Double]

    Per-row Riesz representer rr. Length n_obs; empty before fit.

    v0.154.0: 2-PERIOD PANELS ONLY. See the RESTRICTION note on sensitivity_sigma2 -- rr is built from the same mean(d * (1 - t)) denominator that goes negative on a multi-period panel.

    DoubleMLDIDCS::sensitivity_sigma2

    fn DoubleMLDIDCS::sensitivity_sigma2(self : DoubleMLDIDCS) -> Double

    Upstream's sigma2 (did_cs.py:462-463):

    sigma2 = mean((y - g_hat)^2)

    PANEL-LEVEL, not per cell. Upstream's _sensitivity_element_est reads self._dml_data in its entirety and its manual oracle fit_did_cs(y, x, d, t, ...) takes no group argument at all, so there is one sigma2 for the whole panel -- unlike sensitivity_analysis, which returns one SensitivityResult per (group, period) cell.

    This does NOT change what sensitivity_analysis reports; that path still uses irm_style_sensitivity over the DML score element. The two disagree by construction and both are exposed.

    v0.154.0 RESTRICTION -- THIS PATH IS 2-PERIOD PANELS ONLY. All five sensitivity_* accessors assume the treatment variable t is a BINARY post-treatment indicator taking values {0, 1}. They are correct only when the panel's period labels are exactly [0, 1], which is the canonical make_did_cs_CS2021 fixture.

    On a MULTI-PERIOD panel they are wrong, in two independent ways, both measured (_verify/PORT_VS_UPSTREAM_DEFAULTS_1540.md):

    1. The four g-function condition masks are built hardcoded to period labels 0 and 1 (did_cs.mbt, the cond_d0_t0 .. cond_d1_t1 loop), so every row with t >= 2 is silently discarded from all four g_hat_dXtY nuisances. On the 4-period fixture that is 800 of 1600 rows -- exactly half, matching the v0.147.0 cell-occupancy census.
    2. t is then used as a 0/1 INDICATOR, so 1 - t is negative for t >= 2. That makes mean(d * (1 - t)) negative -- measured -0.5 on the 4-period fixture -- which is a denominator, not a frequency.

    Consequence: on a multi-period panel these accessors return a number computed from half the rows with a malformed indicator. It is not NaN, so nothing signals the problem. The ATT path is unaffected and needs no caveat; see GATE 4 in expand_v154b_test.mbt.

    No guard is raised today: adding one changes reported values, so it is scoped as its own change rather than slipped in here. Until then, treat a multi-period sigma2 / nu2 as NOT IMPLEMENTED. Five tripwires in expand_v154b_test.mbt pin the current defective behaviour -- invert them, do not delete them, when this is fixed.

    0.0 before fit.

    DoubleMLDIDCS::tune

    fn DoubleMLDIDCS::tune(self : DoubleMLDIDCS, param_set~ : Array[TuneParam], scoring_method? : String, n_folds_tune? : Int, seed? : Int) -> DoubleMLDIDCS

    DoubleMLDIDCS::tune - score a grid of nuisance-learner combinations and re-fit the estimator with the winner.

    Slots

    Tunes the two DID nuisance slots in the propensity-first sense documented on TuneParam (see its slot-semantics table): FIRST slot is the treatment / propensity learner E[g | x], SECOND is the outcome learner E[m0 + d * m1 | x]. The first slot lives on the field named learner_l - that name is not a claim about which learner it holds. Build rows with TuneParam::for_treatment(learner_g, learner_m) so the call site carries the role.

    Routing

    The fold draw, the scoring and the selection rule all go through the shared tune_score_grid core in tune.mbt; this method adds no numerics of its own. Only the first slot is scored, and the winning learner_l is paired with the same grid row's learner_m for the re-fit.

    v0.108.0: new. DoubleMLDIDCS had no tune at all, which was a coverage gap against upstream, where tune reaches every estimator through the BaseDML mixin.

    Caveats found while reading the fit path

    • This is the estimator the core's y.length() design exists for: DoubleMLDIDCS exposes NO n_obs() (its only size accessors are n_groups and n_periods). A core keyed on self.n_obs() could not have served it without pushing a new accessor onto a public type purely to serve a helper. The score is therefore over the long-format panel, data.y.length() rows.
    • fit takes only (ml_g, ml_m) as tunables. It then builds a per-(group, period) child DoubleMLDIDBinary and forwards ml_g~ / ml_m~ into the child's fit. The score="observational" and in_sample_normalization=self.in_sample_normalization settings on that child are real arguments of the fit path, but they are NOT DoubleMLDIDCS::fit parameters - fit reads them off self and passes them down. tune therefore has nothing to forward here, and a caller who needs a different DML score or normalization on the tuned model must set it on the estimator before calling tune, since the winning re-fit is self.fit(...) and inherits self's values.
    • ROW SET MISMATCH. fit cross-fits each cell on that cell's wide 2-period sub-panel, whereas tune_score_grid scores against the full long-format data.x / data.y. Candidates are ranked over more rows than they are later cross-fitted on. Known gap, not an endorsement.
    • fit exposes no tune_result parameter, so the per-candidate score vector is not retained on the returned estimator (as on DoubleMLDID::tune, and unlike DoubleMLPLR::tune which stores a TuneResult). Recorded rather than dropped silently.

    No cluster guard

    require(!self.data.is_cluster_data()) is deliberately ABSENT. DoubleMLDIDCSData is {x, y, d, t, id, g, groups, times} and defines no is_cluster_data(); it does carry id, the panel unit id, but cluster ids are passed explicitly to DoubleMLDIDCS::cluster_sandwich_se_at(group_idx, period_idx, cluster_ids) rather than held as guard-readable container state, so a guard on self.data could never fire. Adding the method here would have meant inventing a cluster flag to guard on, which is out of scope for this change.

    The honest consequence, and the reason this one is worth reading twice: DIDCS is a repeated-unit panel estimator and its tune folds are drawn over ROWS (unit-periods), not over unique units, so a single unit's own rows can land on both sides of a fold. The absence of the guard is a statement that the guard is not implementable today, NOT that row-wise folds are correct on this data. Unit-wise tune folds remain an open gap.

    DoubleMLDIDCSBinary

    pub struct DoubleMLDIDCSBinary {
    data : DoubleMLDIDCSData
    g_value : Int
    t_value_pre : Int
    t_value_eval : Int
    control_group : String
    anticipation_periods : Int
    n_folds : Int
    n_rep : Int
    seed : Int
    propensity_clip : Double
    ps_processor_config : PSProcessorConfig
    score : String
    in_sample_normalization : Bool
    coef : Double
    se : Double
    psi_a : Array[Double]
    psi_b : Array[Double]
    g_d0_t0 : Array[Double]
    g_d0_t1 : Array[Double]
    g_d1_t0 : Array[Double]
    g_d1_t1 : Array[Double]
    m_hat : Array[Double]
    subset_y : Array[Double]
    subset_g : Array[Double]
    subset_t : Array[Double]
    n_obs_subset : Int
    n_g_subset : Int
    n_c_subset : Int
    fitted : Bool
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    ml_g : LearnerDispatch
    ml_m : LearnerDispatch
    } derive(
    Debug
    )

    v0.51.0: Callaway-Sant'Anna (2021) DID with binary (group, time) outcomes. Estimates the ATT(g_value, t_value_eval) for a specific (g_value, t_value_pre, t_value_eval) triple via the Sant'Anna-Zhao (2020) binary-outcome DML score. Mirrors the upstream DoubleMLDIDCSBinary (Python 0.11.4) with the v0.51.0 simplifications listed in the file-level docstring.

    DoubleMLDIDCSBinary::bias_corrected_coef

    fn DoubleMLDIDCSBinary::bias_corrected_coef(self : DoubleMLDIDCSBinary) -> Double

    v0.91.0+: returns coef UNCHANGED -- a documented no-op, not a bias correction.

    coef is the root of the DML moment f(theta) = E[theta * psi_a + psi_b] (see var_est.mbt), so mean(f(coef)) is identically zero: the estimating function is orthogonal by construction, and that orthogonality IS what makes the estimator consistent. Nothing computable from the fitted scores is a bias estimate for this class of estimator, so this accessor reports the uncorrected point estimate rather than a number that merely looks like a correction.

    v0.79.0 - v0.90.0 returned coef + mean(psi_b - coef * psi_a). That vector is the score at -coef, NOT at coef; since coef = -mean_b / mean_a its mean is mean_b - coef * mean_a = -2 * coef * mean_a, so the accessor returned coef * (1 - 2 * mean(psi_a)) (exactly 3 * coef when mean(psi_a) = -1). That is not a bias estimate. See bias_corrected_theta in sandwich.mbt for the algebra. The method is kept so the API surface stays stable; removing it outright is the obvious follow-up.

    Preconditions: self.fitted.

    DoubleMLDIDCSBinary::bootstrap

    fn DoubleMLDIDCSBinary::bootstrap(self : DoubleMLDIDCSBinary, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLDIDCSBinary

    v0.64.0+: multiplier bootstrap for DoubleMLDIDCSBinary. The per-observation influence function is

    psi[i] = theta * psi_a[i] + psi_b[i]

    where psi_a[i] and psi_b[i] are the per-row ATT-score elements (computed in fit on the post-subset panel). Routes through the shared generic_bootstrap_t_stat helper (see bootstrap_helper.mbt).

    method_name selects the multiplier distribution: "normal" (default), "Bayes", "wild". seed defaults to 2024; n_rep_boot defaults to 500.

    Calling on an un-fit model aborts via PreconditionError.

    DoubleMLDIDCSBinary::clear_cache

    v0.82.0+: drop any cached nuisance predictions. No-op on an un-fit wrapper.

    DoubleMLDIDCSBinary::cluster_sandwich_se

    fn DoubleMLDIDCSBinary::cluster_sandwich_se(self : DoubleMLDIDCSBinary, cluster_ids : Array[Int]) -> Double

    v0.87.0+: cluster-robust sandwich standard error for the fitted binary CS-DID. Routes through cluster_sandwich_variance with the same psi_a / psi / M_inv inputs as the IID sandwich_se path. DoubleMLDIDCSData has no cluster_vars field, so the user must pass cluster_ids explicitly -- typically the panel unit id, which is the natural cluster for a DID.

    Preconditions: self.fitted, cluster_ids.length() == psi_a.length() (the post-subset count).

    DoubleMLDIDCSBinary::coef

    fn DoubleMLDIDCSBinary::coef(self : DoubleMLDIDCSBinary) -> Double

    v0.51.0: ATT estimate (point estimate) for the chosen (g_value, t_value_pre, t_value_eval) triple.

    DoubleMLDIDCSBinary::confint

    fn DoubleMLDIDCSBinary::confint(self : DoubleMLDIDCSBinary, joint? : Bool, level? : Double) -> (Double, Double)

    v0.51.0: 95% Wald-style confidence interval. v0.67.0+: joint is a no-op for single-theta estimators.

    DoubleMLDIDCSBinary::disable_memoize

    v0.82.0+: turn off memoization.

    DoubleMLDIDCSBinary::enable_memoize

    v0.82.0+: turn on memoization for subsequent fit() calls. The flag is currently informational -- the CS Binary cross-fit uses cs_bin_crossfit_nuisance, which runs n_rep reps internally, so a per-rep cache is not applicable. Forwarded for uniformity with the rest of the DID family.

    DoubleMLDIDCSBinary::fit

    v0.51.0: run the CS Binary estimation. Three steps:
    1. Subset the panel to the 4 (G_indicator, T_indicator) cells.
    2. Cross-fit the 4 g-functions and the propensity using kfold_stratified on G_indicator + 2 * T_indicator.
    3. Compute psi_a, psi_b via the observational Sant'Anna-Zhao score, and derive the ATT and SE via the shared var_est(psi_a, psi_b) helper.

    DoubleMLDIDCSBinary::fitted

    fn DoubleMLDIDCSBinary::fitted(self : DoubleMLDIDCSBinary) -> Bool

    v0.51.0: true after fit has been called, false otherwise.

    DoubleMLDIDCSBinary::g_value

    fn DoubleMLDIDCSBinary::g_value(self : DoubleMLDIDCSBinary) -> Int

    v0.51.0: the g_value constructor argument (the treated group in the (g, t) DID setup).

    DoubleMLDIDCSBinary::has_cache

    fn DoubleMLDIDCSBinary::has_cache(self : DoubleMLDIDCSBinary) -> Bool

    v0.82.0+: true iff the memoize flag is set.

    DoubleMLDIDCSBinary::learner_g

    v0.153.0: the outcome learner (ml_g) recorded at construction and used by fit when no explicit argument is given. Reports the DEFAULT, not necessarily the learner of the current fit: an explicit fit(ml_g = ...) overrides it for that call only and is not recorded.

    DoubleMLDIDCSBinary::learner_m

    v0.153.0: the propensity learner (ml_m) recorded at construction. See learner_g for the same default-vs-current-fit caveat.

    DoubleMLDIDCSBinary::n_c_subset

    fn DoubleMLDIDCSBinary::n_c_subset(self : DoubleMLDIDCSBinary) -> Int

    v0.51.0: number of control (C_indicator = 1) rows in the post-subset panel.

    DoubleMLDIDCSBinary::n_g_subset

    fn DoubleMLDIDCSBinary::n_g_subset(self : DoubleMLDIDCSBinary) -> Int

    v0.51.0: number of treated (G_indicator = 1) rows in the post-subset panel.

    DoubleMLDIDCSBinary::n_obs

    fn DoubleMLDIDCSBinary::n_obs(self : DoubleMLDIDCSBinary) -> Int

    v0.51.0: number of observations in the post-subset panel (i.e. the effective sample size for the SE). This is the post-subset count, NOT the full panel n_obs. Matches the upstream DoubleMLDIDCSBinary.n_obs_subset attribute.

    DoubleMLDIDCSBinary::n_obs_panel

    fn DoubleMLDIDCSBinary::n_obs_panel(self : DoubleMLDIDCSBinary) -> Int

    v0.51.0: total number of observations in the original (pre-subset) panel.

    DoubleMLDIDCSBinary::new

    fn DoubleMLDIDCSBinary::new(data : DoubleMLDIDCSData, g_value : Int, t_value_pre : Int, t_value_eval : Int, control_group? : String, anticipation_periods? : Int, n_folds? : Int, n_rep? : Int, seed? : Int, propensity_clip? : Double, ps_processor? : PSProcessor, ps_processor_config? : PSProcessorConfig?, score? : String, in_sample_normalization? : Bool, ml_g? : LearnerDispatch, ml_m? : LearnerDispatch) -> DoubleMLDIDCSBinary

    v0.51.0: construct a DoubleMLDIDCSBinary estimator. Validates the inputs and stores them on the struct; no estimation happens until fit is called. The score argument is restricted to "observational" for v0.51.0 (experimental is a v0.52.0+ target).

    DoubleMLDIDCSBinary::predictions_g_d0_t0

    fn DoubleMLDIDCSBinary::predictions_g_d0_t0(self : DoubleMLDIDCSBinary) -> Array[Double]

    v0.51.0: cross-fitted nuisance predictions g_d0_t0 (control × pre). Length n_obs_subset().

    DoubleMLDIDCSBinary::predictions_g_d0_t1

    fn DoubleMLDIDCSBinary::predictions_g_d0_t1(self : DoubleMLDIDCSBinary) -> Array[Double]

    v0.51.0: cross-fitted nuisance predictions g_d0_t1 (control × eval).

    DoubleMLDIDCSBinary::predictions_g_d1_t0

    fn DoubleMLDIDCSBinary::predictions_g_d1_t0(self : DoubleMLDIDCSBinary) -> Array[Double]

    v0.51.0: cross-fitted nuisance predictions g_d1_t0 (treated × pre).

    DoubleMLDIDCSBinary::predictions_g_d1_t1

    fn DoubleMLDIDCSBinary::predictions_g_d1_t1(self : DoubleMLDIDCSBinary) -> Array[Double]

    v0.51.0: cross-fitted nuisance predictions g_d1_t1 (treated × eval).

    DoubleMLDIDCSBinary::predictions_m

    fn DoubleMLDIDCSBinary::predictions_m(self : DoubleMLDIDCSBinary) -> Array[Double]

    v0.51.0: cross-fitted propensity predictions m(X) = E[G_indicator | X]. Clipped to [propensity_clip, 1 - propensity_clip].

    DoubleMLDIDCSBinary::psi_a

    fn DoubleMLDIDCSBinary::psi_a(self : DoubleMLDIDCSBinary) -> Array[Double]

    v0.51.0: per-observation psi_a from the CS Binary score. Length n_obs_subset().

    DoubleMLDIDCSBinary::psi_b

    fn DoubleMLDIDCSBinary::psi_b(self : DoubleMLDIDCSBinary) -> Array[Double]

    v0.51.0: per-observation psi_b from the CS Binary score. Length n_obs_subset().

    DoubleMLDIDCSBinary::sandwich_se

    fn DoubleMLDIDCSBinary::sandwich_se(self : DoubleMLDIDCSBinary, kind : SandwichKind) -> Double

    v0.87.0+: Huber-White sandwich standard error for the fitted binary CS-DID. Returns sqrt(var) where var comes from the shared sandwich_variance(kind, ...) dispatch in sandwich.mbt (HC0 / HC1 / HC2 / HC3), the same dispatch DoubleMLDID / DoubleMLIIVM / DoubleMLCVAR use.

    The three inputs are the ones fit(...) already persists for the multiplier bootstrap (see the psi_a / psi_b field docs on DoubleMLDIDCSBinary):
    • psi_a = self.psi_a -- the negated ATT weight (-d / (m * l) under the observational score, or the in-sample-normalized -d / mean(d)). Both are non-positive, so mean(psi_a) <= 0 and exactly -1 under in-sample normalization.
    • psi = psi_at(self.coef, self.psi_a, self.psi_b) -- the per-observation influence function at the fitted coef, matching the psi[i] = psi_a[i] +theta * psi_b[i] form documented on DoubleMLDIDCSBinary::bootstrap.
    • M_inv = [[1 / mean(psi_a)]] (1x1). Only M_inv[0, 0]^2 enters the variance, so the sign of the (up-to-sign) Jacobian inverse is irrelevant.

    The variance's n_obs is self.psi_a.length(), i.e. the POST-SUBSET panel width (self.n_obs() / n_obs_subset), not the full pre-subset panel width (self.n_obs_panel()). cluster_ids must therefore be supplied on the same post-subset indexing.

    Preconditions: self.fitted, mean(psi_a) != 0.

    DoubleMLDIDCSBinary::se

    fn DoubleMLDIDCSBinary::se(self : DoubleMLDIDCSBinary) -> Double

    v0.51.0: standard error of the ATT estimate.

    DoubleMLDIDCSBinary::sensitivity_analysis

    fn DoubleMLDIDCSBinary::sensitivity_analysis(self : DoubleMLDIDCSBinary, cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.66.0+: Cinelli & Hazlett (2020) omitted-variable bias analysis. Routes through the shared irm_style_sensitivity helper with upstream's residual vector (see cs_bin_sensitivity_residuals).

    v0.130.0 FIXES the defect v0.129.0 recorded. The old body was

    let d = self.data.d residuals[i] = self.data.y[i] - g00[i] - (g10[i] - g00[i]) * d[i]

    which is wrong twice over, and both halves were load-bearing:
    1. WRONG VARIABLE. self.data.d is the per-period treatment. Every other use of "d" in this estimator -- psi_a, the propensity, the conditional-g split -- is G (did_cs_binary.py:472), and upstream's sensitivity reads d = self._g_data_subset (:847).
    2. WRONG ROWS. self.data is the full panel; the loop runs over subset positions. MEASURED on the staggered fixture: 240 of the 720 rows read had t == 1 -- a period the subset never contains, and the period in which y carries the treatment effect. So sigma2 was inflated by construction.

    irm_style_sensitivity requires residuals to be element-wise aligned with psi_a; its require(n == psi_a.length()) passed only because both happened to be length 720, which is exactly how the misalignment hid.

    DoubleMLDIDCSBinary::sensitivity_analysis_cluster

    fn DoubleMLDIDCSBinary::sensitivity_analysis_cluster(self : DoubleMLDIDCSBinary, cluster_ids : Array[Int], cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.72.0+: cluster-robust analogue of DoubleMLDIDCSBinary::sensitivity_analysis. Same residual vector and the same psi_a as the IID path (both come from cs_bin_sensitivity_residuals, so the two cannot drift apart); only the variance / bias computation is cluster-aware. DoubleMLDIDCSData has no cluster_vars field, so cluster_ids must be passed explicitly with length matching self.n_obs() (the post-subset count).

    DoubleMLDIDCSBinary::t_value_eval

    fn DoubleMLDIDCSBinary::t_value_eval(self : DoubleMLDIDCSBinary) -> Int

    v0.51.0: the t_value_eval constructor argument (the evaluation period).

    DoubleMLDIDCSBinary::t_value_pre

    fn DoubleMLDIDCSBinary::t_value_pre(self : DoubleMLDIDCSBinary) -> Int

    v0.51.0: the t_value_pre constructor argument (the baseline pre-treatment period).

    DoubleMLDIDCSBinary::tune

    fn DoubleMLDIDCSBinary::tune(self : DoubleMLDIDCSBinary, param_set~ : Array[TuneParam], scoring_method? : String, n_folds_tune? : Int, seed? : Int) -> DoubleMLDIDCSBinary

    DoubleMLDIDCSBinary::tune - score a grid of nuisance-learner combinations and re-fit the estimator with the winner.

    Slots

    Tunes the two DID nuisance slots in the propensity-first sense documented on TuneParam (see its slot-semantics table): FIRST slot is the treatment / propensity learner E[g | x], SECOND is the outcome learner E[m0 + d * m1 | x]. The first slot lives on the field named learner_l - that name is not a claim about which learner it holds. Build rows with TuneParam::for_treatment(learner_g, learner_m) so the call site carries the role.

    Routing

    The fold draw, the scoring and the selection rule all go through the shared tune_score_grid core in tune.mbt; this method adds no numerics of its own. Only the first slot is scored, and the winning learner_l is paired with the same grid row's learner_m for the re-fit under the FINAL-FIT fold schedule (self.n_folds / self.seed).

    v0.108.0: new. DoubleMLDIDCSBinary had no tune at all, which was a coverage gap against upstream, where tune reaches every estimator through the BaseDML mixin.

    Caveats found while reading the fit path

    • This estimator SHARES DoubleMLDIDCSData with DoubleMLDIDCS, so the same data container and the same row set feed both tune families. n therefore comes from self.data.y.length() via the core, which is the FULL panel. That is deliberately NOT self.n_obs(): on this type n_obs() returns n_obs_subset, the POST-subset count, which is a different and smaller number. Using the estimator accessor here would have scored a full-panel cross-fit against a subset denominator.
    • ROW SET MISMATCH, and the stratification asymmetry with it. fit runs cs_bin_panel_subset to restrict the panel to the four (G_indicator, T_indicator) cells and then cross-fits on that post-subset panel using kfold_stratified(n_sub, strata, self.n_folds, self.seed) on the key G_indicator + 2 * T_indicator, so each fold balances the (G, T) cells. tune_score_grid instead draws plain row-wise kfold folds over the full long-format data.x / data.y, with no strata. So candidates are ranked on strictly more rows than they are later cross-fitted on, and under a fold schedule that does not balance the DID cells. Both are known gaps, not endorsements.
    • fit exposes no tune_result parameter, so the per-candidate score vector is not retained on the returned estimator (as on DoubleMLDID::tune, and unlike DoubleMLPLR::tune which stores a TuneResult). Recorded rather than dropped silently.

    No cluster guard

    require(!self.data.is_cluster_data()) is deliberately ABSENT. The DoubleMLDIDCSData it shares with DoubleMLDIDCS defines no is_cluster_data(); it does carry id, the panel unit id, but cluster ids are passed explicitly to DoubleMLDIDCSBinary::cluster_sandwich_se(cluster_ids) rather than held as guard-readable container state, so a guard on self.data could never fire. Adding the method here would have meant inventing a cluster flag to guard on, which is out of scope for this change.

    The honest consequence, as on DoubleMLDIDCS: this is a repeated-unit panel estimator whose tune folds are drawn over ROWS, not unique units, and a unit's own rows can land on both sides of a fold. The missing guard records that it is not implementable today, not that row-wise folds are correct here. Unit-wise tune folds remain open.

    DoubleMLDIDCSData

    pub struct DoubleMLDIDCSData {
    x : Matrix
    y : Array[Double]
    d : Array[Double]
    t : Array[Int]
    id : Array[Int]
    g : Array[Int]
    groups : Array[Int]
    times : Array[Int]
    } derive(
    Debug
    )

    Data container for the Callaway-Sant'Anna (CS) DID model with multi-period panel data and binary treatment. The treatment d is the change in treatment status (binary {0, 1} under the simplified CS-DID port; the upstream package also supports {-1, 0, 1} for "switchers" via the control_group parameter, which is out of scope here). t is the time index (length n_periods); each unit is observed in every period (n_obs =n_units * n_periods rows).

    The fit step iterates over the distinct treatment groups g and the evaluation periods t, runs a DoubleMLDIDBinary for each (g, t_pre, t_eval) triple on the long-format panel, and returns the per-(g, t) ATT estimates as a flat array (row-major, length n_groups * n_periods).

    DoubleMLDIDCSData::new

    fn DoubleMLDIDCSData::new(x : Matrix, y : Array[Double], d : Array[Double], t : Array[Int], id : Array[Int], g : Array[Int]) -> DoubleMLDIDCSData

    DoubleMLDIDCrossSection

    pub struct DoubleMLDIDCrossSection {
    data : DoubleMLDIDCrossSectionData
    n_folds : Int
    n_rep : Int
    seed : Int
    score : String
    in_sample_normalization : Bool
    propensity_clip : Double
    ps_processor_config : PSProcessorConfig
    ml_g : LearnerDispatch
    ml_m : LearnerDispatch
    coef : Double
    se : Double
    psi_a : Array[Double]
    psi_b : Array[Double]
    g_d0_t0 : Array[Double]
    g_d0_t1 : Array[Double]
    g_d1_t0 : Array[Double]
    g_d1_t1 : Array[Double]
    m_hat : Array[Double]
    fitted : Bool
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    } derive(
    Debug
    )

    v0.20.0+: Cross-section DID model with 4 g-functions and 1 propensity function. The score function matches the upstream doubleml.DoubleMLDIDCS._score_elements algorithm.

    score selects the score convention:
    • "observational" (default): the 2x2 DID setting where treatment assignment may be confounded by covariates. Uses the doubly-robust form with propensity reweighting.
    • "experimental": an A/B-test setting where treatment is independent of pre-treatment covariates. The propensity m collapses to a constant and the score simplifies.

    in_sample_normalization selects the in-sample vs out-of-sample normalization:
    • false (default): the canonical Sant'Anna-Zhao form, with weight_psi_a = d / p_hat.
    • true: in-sample normalization weight_psi_a = d / mean(d).

    DoubleMLDIDCrossSection::bias_corrected_coef

    fn DoubleMLDIDCrossSection::bias_corrected_coef(self : DoubleMLDIDCrossSection) -> Double

    v0.91.0+: returns coef UNCHANGED -- a documented no-op, not a bias correction.

    v0.102.0: the score is psi = theta * psi_a + psi_b and coef = -mean(psi_b) / mean(psi_a), so the score is an orthogonal moment score whose derivative in theta is mean(psi_a) -- a non-zero constant here. Note which branch produces it: with the default in_sample_normalization = false the observational weight is d / p_hat with p_hat = mean(d), so mean(psi_a) = -1 exactly; the in-sample-normalized branch weights by d / mean(d) and lands on the same -1. (The experimental score instead uses a constant weight_psi_a = 1, giving mean(psi_a) = -1 by construction too.) That is the same situation as every other var_est estimator in the package, and for the same reason: bias_corrected_theta is provably the identity for an orthogonal score, so nothing computable from the fitted scores is a bias estimate for this class of estimator. This accessor reports the uncorrected point estimate rather than a number that merely looks like a correction.

    (v0.91.0 - v0.101.0 gave a different reason for the same return value: it described this estimator as a PROJECTION (argmin_theta) fit whose psi was "a residual, not an orthogonal score". That description matched neither the upstream DoubleMLDIDCS nor, after the v0.102.0 fit correction, this estimator.)

    v0.79.0 - v0.90.0 returned coef + mean(psi_b - coef * psi_a), the score at -coef. The result was not a bias estimate. See bias_corrected_theta in sandwich.mbt for the algebra. The method is kept so the API surface stays stable; removing it outright is the obvious follow-up.

    Preconditions: self.fitted.

    DoubleMLDIDCrossSection::bootstrap

    fn DoubleMLDIDCrossSection::bootstrap(self : DoubleMLDIDCrossSection, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLDIDCrossSection

    v0.21.0+: multiplier bootstrap. Draws n_rep_boot weight vectors of length n_obs from the chosen multiplier distribution, computes boot_t_stat[b] = sum_i w[b, i] * psi[i] /(sqrt(n) * se) where psi[i] = theta * psi_a[i] + psi_b[i] is the per-observation influence function, and returns a fitted model with boot_t_stat populated.

    method_name selects the multiplier distribution:
    • "normal" (default): w[i] ~ N(0, 1). Matches the upstream bootstrap(method="normal") default.
    • "Bayes": w[i] = exp(1) - 1 (mean 0, var 1).
    • "wild": w[i] = x[i] / sqrt(2) + (y[i]^2 - 1) /2 with x, y ~ N(0, 1). Robust to heteroskedasticity in the influence-function residuals.

    The bootstrap populates self.boot_t_stat and is required for confint(joint=true).

    DoubleMLDIDCrossSection::clear_cache

    v0.82.0+: drop any cached nuisance predictions. No-op on an un-fit wrapper.

    DoubleMLDIDCrossSection::cluster_sandwich_se

    fn DoubleMLDIDCrossSection::cluster_sandwich_se(self : DoubleMLDIDCrossSection, cluster_ids : Array[Int]) -> Double

    v0.87.0+: cluster-robust sandwich standard error for the fitted cross-section DID. Routes through cluster_sandwich_variance with the same psi_a / psi / M_inv inputs as the IID sandwich_se path. DoubleMLDIDCrossSectionData has no cluster_vars field, so the user must pass cluster_ids explicitly. Cluster indices are 0-based; 1 + max(cluster_ids) is the number of clusters.

    Preconditions: self.fitted, cluster_ids.length() == psi_a.length().

    DoubleMLDIDCrossSection::coef

    ATT estimate from the cross-section DID fit.

    DoubleMLDIDCrossSection::confint

    fn DoubleMLDIDCrossSection::confint(self : DoubleMLDIDCrossSection, joint? : Bool, level? : Double) -> (Double, Double)

    v0.20.0+ (extended in v0.21.0): confidence interval for the ATT.

    When joint = false (default), uses the Wald-style theta +/- 1.96 * se interval (or the level-th quantile of the standard normal, scaled to the requested level).

    When joint = true, uses the multiplier bootstrap (must call bootstrap() first). The critical value is the empirical (1 + level) / 2 quantile of |boot_t_stat|, which is wider than the pointwise critical value (more conservative; matches the joint-CI convention for a scalar parameter).

    level is the confidence level (default 0.95).

    DoubleMLDIDCrossSection::disable_memoize

    v0.82.0+: turn off memoization.

    DoubleMLDIDCrossSection::enable_memoize

    v0.82.0+: turn on memoization. Forwarded for uniformity; the cross-section DID uses an internal crossfit_nuisance call so the flag is informational.

    DoubleMLDIDCrossSection::fit

    v0.20.0+: fit the cross-section DID model. Runs cross-fit nuisance estimation (4 g-functions + 1 propensity), constructs the psi_a / psi_b score, and returns the ATT and HC0 SE.

    DoubleMLDIDCrossSection::has_cache

    fn DoubleMLDIDCrossSection::has_cache(self : DoubleMLDIDCrossSection) -> Bool

    v0.82.0+: true iff the memoize flag is set.

    DoubleMLDIDCrossSection::learner_g

    Accessor for the outcome-nuisance learner used by the most recent fit(...) call. v0.60.0+.

    DoubleMLDIDCrossSection::learner_m

    Accessor for the propensity-score learner used by the most recent fit(...) call. v0.60.0+.

    DoubleMLDIDCrossSection::new

    fn DoubleMLDIDCrossSection::new(data : DoubleMLDIDCrossSectionData, n_folds? : Int, n_rep? : Int, seed? : Int, score? : String, in_sample_normalization? : Bool, propensity_clip? : Double, ps_processor? : PSProcessor, ps_processor_config? : PSProcessorConfig?, ml_g? : LearnerDispatch, ml_m? : LearnerDispatch) -> DoubleMLDIDCrossSection

    DoubleMLDIDCrossSection::predictions_g_d0_t0

    fn DoubleMLDIDCrossSection::predictions_g_d0_t0(self : DoubleMLDIDCrossSection) -> Array[Double]

    v0.20.0+: nuisance predictions g(0, 0) (control, pre-period). Length n_obs.

    DoubleMLDIDCrossSection::predictions_g_d0_t1

    fn DoubleMLDIDCrossSection::predictions_g_d0_t1(self : DoubleMLDIDCrossSection) -> Array[Double]

    v0.20.0+: nuisance predictions g(0, 1) (control, post-period). Length n_obs.

    DoubleMLDIDCrossSection::predictions_g_d1_t0

    fn DoubleMLDIDCrossSection::predictions_g_d1_t0(self : DoubleMLDIDCrossSection) -> Array[Double]

    v0.20.0+: nuisance predictions g(1, 0) (treated, pre-period). Length n_obs.

    DoubleMLDIDCrossSection::predictions_g_d1_t1

    fn DoubleMLDIDCrossSection::predictions_g_d1_t1(self : DoubleMLDIDCrossSection) -> Array[Double]

    v0.20.0+: nuisance predictions g(1, 1) (treated, post-period). Length n_obs.

    DoubleMLDIDCrossSection::predictions_m

    fn DoubleMLDIDCrossSection::predictions_m(self : DoubleMLDIDCrossSection) -> Array[Double]

    v0.20.0+: propensity predictions m(x) = E[D=1 | X]. Length n_obs. Clipped to [propensity_clip, 1 -propensity_clip] after the cross-fit prediction averaging.

    DoubleMLDIDCrossSection::psi_a

    v0.20.0+: per-observation psi_a from the cross-section DID score. Length n_obs. Throws if the model hasn't been fit.

    DoubleMLDIDCrossSection::psi_b

    v0.20.0+: per-observation psi_b from the cross-section DID score. Length n_obs. Throws if the model hasn't been fit.

    DoubleMLDIDCrossSection::sandwich_se

    fn DoubleMLDIDCrossSection::sandwich_se(self : DoubleMLDIDCrossSection, kind : SandwichKind) -> Double

    v0.87.0+: Huber-White sandwich standard error for the fitted cross-section DID. Returns sqrt(var) where var comes from the shared sandwich_variance(kind, ...) dispatch in sandwich.mbt (HC0 / HC1 / HC2 / HC3), the same dispatch DoubleMLDID / DoubleMLIIVM / DoubleMLCVAR use.

    The three inputs are the ones fit(...) already persists for the multiplier bootstrap (see the psi_a / psi_b field docs on DoubleMLDIDCrossSection):
    • psi_a = self.psi_a -- the negated ATT weight, -weight_psi_a, where weight_psi_a is d / (m * l) (observational), d / m (experimental), or the in-sample-normalized variant d / mean(d). Every variant is a non-negative weight, so mean(psi_a) <= 0 and, under in-sample normalization, exactly -1.
    • psi = psi_at(self.coef, self.psi_a, self.psi_b) -- the per-observation influence function at the fitted coef, the shared helper fit / bootstrap / the other 19 sandwich_se methods use.
    • M_inv = [[1 / mean(psi_a)]] (1x1). This is 1 / J with J = mean(psi_a) = dE[psi] / d theta, the Jacobian inverse of the score psi = theta * psi_a + psi_b.

    v0.102.0: through v0.101.0 this method used psi[i] = psi_a[i] + coef * psi_b[i] and carried a comment block declaring that its M_inv was "not 1 / mean(psi_a) in any principled sense (the argmin has vanishing first derivative)". That reasoning described a projection (argmin_theta) fit that did not match the upstream estimator, and the formula it quoted for se was not the one fit computed either. With fit now on the shared var_est path the score order is the family's, M_inv = 1 / mean(psi_a) is the principled value rather than a placeholder, and sandwich_se(hc0) equals se() to the bit -- the same invariant the other 19 estimators already satisfy. See CHANGELOG v0.102.0 for the measurements.

    The variance's n_obs is self.psi_a.length() (the length fit(...) persists, equal to self.data.n_obs()).

    Preconditions: self.fitted, mean(psi_a) != 0.

    DoubleMLDIDCrossSection::se

    Standard error of the ATT estimate (HC0 sandwich).

    DoubleMLDIDCrossSection::sensitivity_analysis

    fn DoubleMLDIDCrossSection::sensitivity_analysis(self : DoubleMLDIDCrossSection, cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.70.0+: Cinelli & Hazlett (2020) omitted-variable bias analysis for the cross-section DID model (Sant'Anna & Zhao 2020). Single-theta IRM-style decomposition: the outcome residual is the ATT form y - g_d0_t0_hat - (g_d1_t0_hat - g_d0_t0_hat) * d on the cross-section sample (matches the v0.66.0 DoubleMLDIDCSBinary::sensitivity_analysis convention extended with the 4-g nuisance predictions this estimator carries); the per-observation Riesz-representer is the psi_a already persisted by fit (drives the multiplier bootstrap IF rows). Routes through the shared irm_style_sensitivity helper.

    cf_y / cf_d default to 0.05 matching the rest of the v0.66.0-onward sensitivity family. Calling on an un-fit model aborts via PreconditionError.

    DoubleMLDIDCrossSection::sensitivity_analysis_cluster

    fn DoubleMLDIDCrossSection::sensitivity_analysis_cluster(self : DoubleMLDIDCrossSection, cluster_ids : Array[Int], cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.73.0+: cluster-robust analogue of DoubleMLDIDCrossSection::sensitivity_analysis. Same cross-section ATT-form residual y - g_d0_t0_hat - (g_d1_t0_hat - g_d0_t0_hat) * d and the same psi_a as the IID path; only the variance / bias computation is cluster-aware (see irm_style_sensitivity_cluster in sensitivity.mbt).

    DoubleMLDIDCrossSectionData has no cluster_vars field, so the user must pass cluster_ids explicitly. cluster_ids.length() must equal self.data.n_obs() (the cross-section sample length). Cluster indices are 0-based; 1 + max(cluster_ids) is the number of clusters.

    DoubleMLDIDCrossSection::tune

    fn DoubleMLDIDCrossSection::tune(self : DoubleMLDIDCrossSection, param_set~ : Array[TuneParam], scoring_method? : String, n_folds_tune? : Int, seed? : Int) -> DoubleMLDIDCrossSection

    DoubleMLDIDCrossSection::tune - score a grid of (learner_g, learner_m) pairs and re-fit with the winner.

    Slot semantics: this is a propensity-first family, so the first TuneParam slot is the treatment / propensity learner E[g|d,x] and the second is the outcome learner. The first field is still named learner_l (the names are fixed by the partially-linear family and do not change with it); build candidates with TuneParam::for_treatment(learner_g,learner_m) so the call site carries the slot's role instead of leaving a reader to infer it from a field called learner_l.

    v0.108.0: new. DIDCrossSection had no tune at all, so it was one of the estimators carrying a coverage gap against upstream, where tune reaches every estimator through the BaseDML mixin. It routes through the shared tune_score_grid core in tune.mbt - fold draw, cross-fit, scoring and the argmin/argmax selection all live there - rather than re-implementing the loop a ninth time.

    The re-fit is self.fit(ml_g=..., ml_m=...). fit reads n_folds, n_rep, seed, propensity_clip and ps_processor from self and re-applies its own final-fit fold schedule, so nothing else is carried across by hand and no bootstrap state is dropped (fit itself re-applies boot_t_stat / boot_method / n_rep_boot / boot_seed). The grid's candidate cross-fits are NOT reused for the final fit - the winner's nuisances are re-cross-fitted from scratch under self.n_folds, same as every other ::tune.

    Caveat on what the score means: it is MSE of the first-slot learner cross-fitted against the OUTCOME y, not against the treatment d. fit actually builds 4 g-functions g(d,t,x) plus 1 propensity m(x) from these two learners, and the grid never observes the per-cell nuisance quality or the propensity error, so a candidate can win on outcome fit and still be the worse propensity model. This is the same convention the other propensity-first ::tune methods (APO / APOS / IRM / IIVM) use; read the grid as a shortlist, not a per-cell optimum.

    There is no cluster guard here, deliberately. Unlike DoubleMLData / DoubleMLIIVMData / DoubleMLPLIVData, DoubleMLDIDCrossSectionData has no cluster_vars field and no is_cluster_data() method at all, so clustered-inference data cannot be represented in this type in the first place. Writing the guard would not compile, and adding the method is outside this change. This is not the v0.108.0 APO asymmetry (a guard missing where the data type has one) - the accessors genuinely do not exist here.

    DoubleMLDIDCrossSectionData

    pub struct DoubleMLDIDCrossSectionData {
    x : Matrix
    y : Array[Double]
    d : Array[Double]
    t : Array[Int]
    name : String
    } derive(
    Debug
    )

    Data container for the cross-section DID model (Sant'Anna & Zhao 2020, "repeated cross-sections" variant). Each unit has ONE observation, with covariates x, outcome y, binary treatment d (in {0, 1}), and binary post-period indicator t (in {0, 1}). The total sample size is n.

    Unlike the panel DID, there is no id column (cross-section = each unit is observed at most once) and no g column (no group structure -- the "treated" group is just the d == 1 cohort and the "control" group is the d == 0 cohort). The model fits 4 g-functions g(d, t, x) = E[Y | D=d, T=t, X] for the 4 (d, t) combinations, plus 1 propensity function m(x) = E[D=1 | X], and constructs the ATT score function from these nuisance predictions.

    DoubleMLDIDCrossSectionData::n_features

    Number of features in the cross-section DID data (excluding the intercept, which is added inside the learner).

    DoubleMLDIDCrossSectionData::n_obs

    Sample size of the cross-section DID data.

    DoubleMLDIDCrossSectionData::new

    fn DoubleMLDIDCrossSectionData::new(x : Matrix, y : Array[Double], d : Array[Double], t : Array[Int], name? : String) -> DoubleMLDIDCrossSectionData

    DoubleMLDIDData

    pub struct DoubleMLDIDData {
    x : Matrix
    y : Array[Double]
    d : Array[Double]
    } derive(
    Debug
    )

    Data container for DoubleMLDID. Uses panel data with two time periods. The treatment d is the change in treatment status between the post-period and the pre-period (so d ∈ {-1, 0, 1} for never-treated/always-treated/switchers under the Sant'Anna & Zhao (2020) convention). The default port supports binary d ∈ {0, 1} (only the switchers).

    DoubleMLDIDData::n_features

    fn DoubleMLDIDData::n_features(self : DoubleMLDIDData) -> Int

    DoubleMLDIDData::n_obs

    fn DoubleMLDIDData::n_obs(self : DoubleMLDIDData) -> Int

    DoubleMLDIDData::new

    fn DoubleMLDIDData::new(x : Matrix, y : Array[Double], d : Array[Double]) -> DoubleMLDIDData raise DIDDataError

    Returns DoubleMLDIDData raise DIDDataError: the v0.43.0 conversion replaces the previous abort() call with raise DIDDataError::NonBinaryTreatment(i) so the non-binary-d path becomes directly testable. Callers that want the pre-v0.43.0 process-death behavior should catch the error and re-abort (this is what DoubleMLDIDBinaryData::new does); callers that want to surface the error to downstream consumers should propagate via ?. The require checks on x.nrows against y.length and d.length are unchanged and still abort the process (they are central require checks; refactoring them is out of scope for this surgical release).

    DoubleMLDIDMulti

    pub struct DoubleMLDIDMulti {
    data : DoubleMLDIDCSData
    gt_combinations : Array[(Int, Int, Int)]
    control_group : String
    anticipation_periods : Int
    n_folds : Int
    n_rep : Int
    seed : Int
    ps_processor : PSProcessor
    in_sample_normalization : Bool
    ml_g : LearnerDispatch
    ml_m : LearnerDispatch
    group_sizes : Array[Int]
    inner : DoubleMLDIDCS
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    fitted : Bool
    memoize_enabled : Bool
    } derive(
    Debug
    )

    DoubleMLDIDMulti is a thin top-level wrapper over DoubleMLDIDCS that adds:

    1. A gt_combinations selector. Each combination is a (g_value, t_value_pre, t_value_eval) triple. The convenience keyword "standard" expands to "every post-treatment (g, t) with t_pre = g" (the default Callaway-Sant'Anna staggered set). "all" additionally includes pre-treatment cells for the event-study profile. "universal" is the same as "all" for the panel case (a cross-section-only setting in upstream is not ported; see the "Notes" section in CHANGELOG.md).
    2. aggregate_group, aggregate_time, aggregate_event methods that wrap the matching helpers in did_aggregation.mbt.

    DoubleMLDIDMulti::fit reuses DoubleMLDIDCS::fit to compute the per-(g, t) ATT matrix (and SE matrix), then hands the matrices to the aggregation helpers. The internal DoubleMLDIDCS instance is the canonical per-(g, t) estimator; DoubleMLDIDMulti adds the gt_combinations filter and the aggregation API on top.

    DoubleMLDIDMulti::aggregate_event

    Aggregate by event time e = t - g. Returns a DIDAggregationResult with one entry per unique event time.

    DoubleMLDIDMulti::aggregate_group

    Aggregate by group. Returns a DIDAggregationResult with one entry per group.

    DoubleMLDIDMulti::aggregate_time

    Aggregate by time period. Returns a DIDAggregationResult with one entry per period.

    DoubleMLDIDMulti::bias_corrected_coef_at_idx

    fn DoubleMLDIDMulti::bias_corrected_coef_at_idx(self : DoubleMLDIDMulti, idx : Int) -> Double

    v0.100.0+: coef_at_idx(idx) UNCHANGED -- a documented no-op, not a bias correction. Identical in reasoning to DoubleMLDIDCS::bias_corrected_coef_at and the rest of the family; see DoubleMLPQ::bias_corrected_coef in sandwich.mbt for the full argument. The child's ATT is the root of the DML moment f(theta) = E[theta * psi_a + psi_b], so mean(f(coef_at)) is identically zero: the estimating function is orthogonal by construction, and that orthogonality is exactly what makes the estimator consistent. Nothing computable from the fitted scores is a bias estimate for this class of estimator, so this accessor reports the uncorrected point estimate rather than a number that merely looks like a correction. The pre-v0.91.0 form coef + mean(psi_b - coef * psi_a) is that vector at -coef, NOT at coef; with coef = -mean_b / mean_a its mean is -2 * coef * mean(psi_a), so it returned coef * (1 - 2 * mean(psi_a)) -- exactly 3 * coef when mean(psi_a) = -1, which is this score's case for every cell.

    A genuine difference from sandwich_se_at_idx: a DEGENERATE combination does NOT abort here. The answer is the identity on coef_at_idx, and coef_at_idx reports 0.0 for an unestimated cell, so 0.0 is the consistent answer rather than a misleading one. 0.0 is also why this accessor is safe to call across a full sweep while the sandwich pair is not.

    Preconditions: self.fitted, 0 <= idx < gt_combinations.length(), and gt_combinations[idx] maps to an inner (gi, pi).

    DoubleMLDIDMulti::bootstrap

    fn DoubleMLDIDMulti::bootstrap(self : DoubleMLDIDMulti, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLDIDMulti

    v0.15.0+: multiplier bootstrap for joint confidence intervals. Draws n_rep_boot weight vectors from the chosen multiplier distribution and computes boot_t_stat[b, k] = sum_i w[b, i] * psi_k[i] / (sqrt(n) *se_k) for each bootstrap replication b and each (g, t) cell k. The joint confidence interval uses the empirical 95th percentile of max_k |boot_t_stat[b, k]| as the critical value; the per-cell Wald CI uses 1.96.

    method_name selects the multiplier distribution:
    • "normal": w[i] ~ N(0, 1) (default; matches the upstream bootstrap(method="normal") default).
    • "Bayes": w[i] = exp(1) - 1 (mean 0, var 1).
    • "wild": w[i] = x[i] / sqrt(2) + (y[i]^2 - 1) / 2 with x, y ~ N(0, 1). Robust to heteroskedasticity.

    seed controls the chacha8 RNG used to draw the weights (default 2024; matches the upstream numpy default of np.random.seed(2024) for the first upstream test).

    The bootstrap populates self.boot_t_stat and is required for confint(joint=true).

    DoubleMLDIDMulti::clear_cache

    v0.82.0+: drop any cached nuisance predictions. No-op on an un-fit wrapper.

    DoubleMLDIDMulti::cluster_sandwich_se_at_idx

    fn DoubleMLDIDMulti::cluster_sandwich_se_at_idx(self : DoubleMLDIDMulti, idx : Int, cluster_ids : Array[Int]) -> Double

    v0.100.0+: cluster-robust sandwich standard error (Arellano 1987, Cameron-Gelbach-Miller 2011) for the combination at row-major index idx. Same pure forward as sandwich_se_at_idx: the inner cell is resolved and self.inner.cluster_sandwich_se_at(gi, pi, cluster_ids) is returned unchanged.

    DoubleMLDIDCSData has no cluster_vars field, so there is still no default cluster and the caller must supply cluster_ids. They are PER CELL ROW, not per long-format panel row: cluster_ids.length() must equal THAT cell's n_wide, i.e. one entry per unit observed in both the pre and the eval period. The long-format panel id (length n_units * n_periods) is the WRONG array to pass for a cell whose n_wide is smaller, and because the mapping is per index, an idx-independent array of the wrong length fails at whichever index it is passed to. For a DID the natural grouping is the panel unit.

    Why this is not se_at_idx with a different flavour: the difference is the MEAT, not the denominator. cluster_sandwich_variance divides by the cell's own n_wide -- the same divisor HC0 uses -- but sums S_c = (sum_{i in c}psi[i])^2 per cluster, so the within-cluster cross terms enter and each cluster carries a jackknife factor n_c / (n_c - 1). With all-singleton clusters the meat collapses to sum_ipsi[i]^2 and the result is exactly sandwich_se_at_idx(idx, HC0); with real clusters it is larger. (It is also not a drop-in for a cluster-robust se_at: that is a different, row-level estimator which this DIDCS fit path does not compute.)

    Aborts at a degenerate combination for the same reason sandwich_se_at_idx does -- the inner refuses an unestimated cell, and the wrapper forwards that rather than papering over it.

    Preconditions: self.fitted, 0 <= idx < gt_combinations.length(), the combination maps to an estimated inner cell with mean(psi_a) != 0, cluster_ids.length() == n_wide, all cluster_ids[i] >= 0.

    DoubleMLDIDMulti::coef_at_idx

    fn DoubleMLDIDMulti::coef_at_idx(self : DoubleMLDIDMulti, idx : Int) -> Double

    The inner per-(g, t) ATT at row-major index idx (matching the canonical gt_combinations[i] ordering).

    DoubleMLDIDMulti::confint

    fn DoubleMLDIDMulti::confint(self : DoubleMLDIDMulti, joint? : Bool, level? : Double) -> Array[(Double, Double)]

    v0.15.0+: confidence interval for the per-(g, t) ATT. When joint = false (default), uses the Wald-style theta +/- 1.96 * se interval. When joint = true, uses the bootstrap: theta +/- critical_value * se where critical_value is the 95th percentile of max_k |boot_t_stat[b, k]| across bootstrap replications b. Joint CIs are wider (more conservative) and require bootstrap() to be called first.

    level is the confidence level (default 0.95).

    DoubleMLDIDMulti::disable_memoize

    fn DoubleMLDIDMulti::disable_memoize(self : DoubleMLDIDMulti) -> DoubleMLDIDMulti

    v0.82.0+: turn off memoization.

    DoubleMLDIDMulti::enable_memoize

    fn DoubleMLDIDMulti::enable_memoize(self : DoubleMLDIDMulti) -> DoubleMLDIDMulti

    v0.82.0+: turn on memoization for subsequent fit() calls. The flag is forwarded to the inner DoubleMLDIDCS.

    DoubleMLDIDMulti::fit

    Run the per-(g, t) cross-fits and store the per-cell ATT matrix for downstream aggregation. The actual per-cell fitting is delegated to DoubleMLDIDCS::fit, which already iterates over every (g, t) cell.

    DoubleMLDIDMulti::has_cache

    fn DoubleMLDIDMulti::has_cache(self : DoubleMLDIDMulti) -> Bool

    v0.82.0+: true iff the memoize flag is set.

    DoubleMLDIDMulti::learner_g

    Accessor for the outcome-nuisance learner forwarded to the inner DoubleMLDIDCS on the most recent fit(...) call. v0.60.0+.

    DoubleMLDIDMulti::learner_m

    Accessor for the propensity-score learner forwarded to the inner DoubleMLDIDCS on the most recent fit(...) call. v0.60.0+.

    DoubleMLDIDMulti::n_combinations

    fn DoubleMLDIDMulti::n_combinations(self : DoubleMLDIDMulti) -> Int

    Number of (g, t_pre, t_eval) triples.

    DoubleMLDIDMulti::new

    fn DoubleMLDIDMulti::new(data : DoubleMLDIDCSData, gt_combinations? : Array[(Int, Int, Int)], gt_combinations_keyword? : String, control_group? : String, anticipation_periods? : Int, n_folds? : Int, n_rep? : Int, seed? : Int, ps_processor? : PSProcessor, in_sample_normalization? : Bool, ml_g? : LearnerDispatch, ml_m? : LearnerDispatch) -> DoubleMLDIDMulti

    Construct a DoubleMLDIDMulti.

    gt_combinations may be either an Array[(Int, Int, Int)] of explicit (g_value, t_value_pre, t_value_eval) triples, or one of the keywords:

    • "standard": every (g, t) with t > g and t_pre = g (the default Callaway-Sant'Anna staggered set).
    • "all": every (g, t) in the (groups x periods) grid.
    • "universal": same as "all" for the panel case (upstream's universal is only meaningful for repeated cross sections, which this port does not implement).

    DoubleMLDIDMulti::p_adjust

    fn DoubleMLDIDMulti::p_adjust(self : DoubleMLDIDMulti, method_name? : String) -> Array[Double]

    v0.16.0+: multiple-testing p-value adjustment for the per-(g, t) ATTs. Returns an Array[Double] of adjusted p-values (length n_combinations).

    Methods:
    • "romano-wolf" (default): the stepdown bootstrap procedure from Romano & Wolf (2005). For each cell k, sorted by descending |t_k|, compute p_k = mean_b [max_j > k |boot_t_stat[b, j]| >=|t_k|]. Then enforce monotonicity: p_corrected[k] = max(p_k, p_corrected[k - 1]) (in sorted order). Requires bootstrap() to have been called first.
    • "holm": Holm-Bonferroni stepdown (no bootstrap required). Sort unadjusted p-values ascending; for each k, p_corrected[k] = max((n - k) * p_sorted[k],p_corrected[k - 1]), then re-sort to original order.
    • "bonferroni": p_corrected[k] = n * p_k, clipped to 1.0. No bootstrap required.

    The p-values are computed from the Wald-style t-statistics (theta / se per cell) via the two-sided normal approximation.

    DoubleMLDIDMulti::p_values

    fn DoubleMLDIDMulti::p_values(self : DoubleMLDIDMulti) -> Array[Double]

    v0.16.0+: per-cell unadjusted p-values for H0:theta = 0 (two-sided, normal approximation). Length n_combinations. pval[k] = 2 * (1 - norm.cdf(|t_k|)). Uses the standard-normal survival function on the Wald-style t-statistics from t_stats().

    The implementation uses Abramowitz & Stegun (1964) formula 7.1.26 for the normal CDF (max absolute error ~7.5e-8). MoonBit's @math does not expose erfc, so we approximate norm.cdf directly.

    DoubleMLDIDMulti::sandwich_se_at_idx

    fn DoubleMLDIDMulti::sandwich_se_at_idx(self : DoubleMLDIDMulti, idx : Int, kind : SandwichKind) -> Double

    v0.100.0+: heteroskedasticity-consistent (Huber-White) sandwich standard error for the combination at row-major index idx (the same (g, t_pre, t_eval) triple ordering as coef_at_idx and se_at_idx). The per-cell analogue of the DID family's joint sandwich_se: this wrapper estimates no scalar of its own, so the natural index is the one it already exposes, the combination index.

    DoubleMLDIDMulti persists NO per-cell score state -- only group_sizes and boot_t_stat -- so this method is a pure FORWARD. The triple is mapped to the inner (gi, pi) and the answer is self.inner.sandwich_se_at(gi, pi, kind) returned unchanged, with no arithmetic in between. Hence

    sandwich_se_at_idx(idx, kind) == inner.sandwich_se_at(gi, pi, kind)

    bit for bit, and on the IID path

    sandwich_se_at_idx(idx, HC0) == se_at_idx(idx)

    holds for the reason it holds one level down: the inner's HC0 was MEASURED equal to its own se_at on every non-degenerate cell (abs_diff exactly 0.0), because var_est and sandwich_variance_hc0 run the same op sequence over the same Kahan sum of the same products in the same index order and M_inv[0, 0]^2 == 1.0 exactly (the DID score's psi_a[i] = -d[i] / p_hat with p_hat = mean(d) gives mean(psi_a) == -1). The wrapper adds no n_params and no second estimate, so nothing about that identity is disturbed here.

    The one thing the wrapper does add is COVERAGE. gt_combinations may name a combination the inner never estimated: "all" and "universal" emit the pre-treatment placebos (g, t_pre = g, t_eval < g), and the CS-DID fit only estimates t_eval > g, so those map to an EMPTY inner cell. There this method ABORTS, by forwarding the inner's refusal: the inner rejects an unestimated cell rather than return a misleading 0.0 off an empty score row. That is not smoothed over. A caller sweeping every index must skip the degenerate combinations itself, exactly as it must for the inner API -- and se_at_idx at the same index returns 0.0 rather than aborting, so the two accessors are NOT interchangeable over a full sweep.

    Preconditions: self.fitted, 0 <= idx < gt_combinations.length(), gt_combinations[idx] maps to an inner (gi, pi), that cell was actually estimated, mean(psi_a) != 0, and n_obs > n_params for HC1 / HC2 / HC3.

    DoubleMLDIDMulti::se_at_idx

    fn DoubleMLDIDMulti::se_at_idx(self : DoubleMLDIDMulti, idx : Int) -> Double

    The inner per-(g, t) SE at row-major index idx.

    DoubleMLDIDMulti::sensitivity_analysis

    fn DoubleMLDIDMulti::sensitivity_analysis(self : DoubleMLDIDMulti, cf_y? : Double, cf_d? : Double) -> Array[SensitivityResult] raise

    v0.70.0+: per-(g, t) Cinelli & Hazlett (2020) omitted-variable bias analysis for DoubleMLDIDMulti. Delegates to DoubleMLDIDCS::sensitivity_analysis for the full n_groups * n_periods per-cell SensitivityResult array, then filters down to the cells selected by gt_combinations (i.e. the same cells used by coef_at_idx / se_at_idx).

    Each selected (g, t) cell's result carries the ATT-form residual y - g_d0_hat - (g_d1_hat - g_d0_hat) *d on the long-format panel (persisted by DoubleMLDIDCS::fit in psi_a_matrix / residuals_matrix) and the matching per-cell Riesz representer. Routes through the shared irm_style_sensitivity helper (see sensitivity.mbt).

    Cells with no fitted estimate (se_matrix[k] <= 0) return a zeroed SensitivityResult from the inner pass; the filtering preserves that contract.

    Returns an Array[SensitivityResult] of length gt_combinations.length(). Calling on an un-fit model aborts via PreconditionError.

    DoubleMLDIDMulti::sensitivity_analysis_cluster

    fn DoubleMLDIDMulti::sensitivity_analysis_cluster(self : DoubleMLDIDMulti, cluster_ids : Array[Int], cf_y? : Double, cf_d? : Double) -> Array[SensitivityResult] raise

    v0.73.0+: cluster-robust analogue of DoubleMLDIDMulti::sensitivity_analysis. Delegates to the inner DoubleMLDIDCS::sensitivity_analysis_cluster (which carries the per-cell ATT-form residual and per-cell psi_a from psi_a_matrix / residuals_matrix) and then filters down to the gt_combinations selected cells (same lookup as coef_at_idx / se_at_idx).

    DoubleMLDIDMulti's data struct (DoubleMLDIDCSData) has no cluster_vars field, so the user must pass cluster_ids explicitly. cluster_ids.length() must equal self.data.n_obs() (the long-format panel length).

    Cells with no fitted estimate (inner.se_matrix[k] <= 0) return a zeroed SensitivityResult from the inner pass; the filtering preserves that contract.

    Returns an Array[SensitivityResult] of length gt_combinations.length().

    DoubleMLDIDMulti::t_stats

    fn DoubleMLDIDMulti::t_stats(self : DoubleMLDIDMulti) -> Array[Double]

    v0.16.0+: per-cell t-statistics theta / se (length n_combinations). The Wald-style t-statistic matches the upstream all_t_stats[:, i_rep] (per repetition, but v0.15.0 is n_rep = 1 only). The Romano-Wolf stepdown p-adjustment in p_adjust consumes these t-statistics. Returns 0.0 for cells where se_k = 0 (pre-treatment / missing cells).

    DoubleMLDIDMulti::tune

    fn DoubleMLDIDMulti::tune(self : DoubleMLDIDMulti, param_set~ : Array[TuneParam], scoring_method? : String, n_folds_tune? : Int, seed? : Int) -> DoubleMLDIDMulti

    DoubleMLDIDMulti::tune - score a grid of (learner_g,learner_m) pairs and re-fit the per-cell DID model with the winner.

    Slot semantics: propensity-first family, same as DoubleMLDIDCrossSection::tune and the other DID* estimators. The first TuneParam slot is the treatment / propensity learner, the second is the outcome learner, and the first field is still named learner_l because the field names are fixed by the partially-linear family. Use TuneParam::for_treatment(learner_g, learner_m) so the call site states the slot's role.

    v0.108.0: new. DIDMulti had no tune at all, so it was one of the estimators carrying a coverage gap against upstream, where tune reaches every estimator through the BaseDML mixin. It routes through the shared tune_score_grid core in tune.mbt, same as every other ::tune.

    What tune forwards, and what it does NOT touch:

    • Forwarded: ml_g / ml_m from the winning TuneParam, i.e. the first two arguments of fit.
    • Carried over from self implicitly: everything else, because DoubleMLDIDMulti::fit takes ONLY ml_g and ml_m and rebuilds the model with { ..self, inner,ml_g, ml_m, fitted: true }. In particular the per-(g,t) cell grid survives untouched: gt_combinations (and its gt_combinations_keyword spelling) is a DoubleMLDIDMulti::new argument, NOT a fit argument, so there is no cell list for tune to plumb through and no way for it to silently narrow the cell set. The fold schedule, n_rep / seed and the memoize flag likewise never appear in the tune -> fit call: the memoize forwarding and the two-stage inner refit (pre- and post-memoize) are fit's own business.
    • Dropped: nothing. The only state the tune stage produces is the fold draw and the candidate scores, and those are discarded by design - the winner is re-cross-fitted from scratch under the final-fit fold schedule rather than reusing the tune-time predictions.

    Same scoring caveat as the sibling: the score is MSE of the first-slot learner cross-fitted against the outcome y, not against d, so it is a shortlisting proxy rather than a per-cell nuisance optimum.

    No cluster guard, deliberately: DoubleMLDIDCSData has no cluster_vars field and no is_cluster_data() method, so there is nothing to guard and the call would not compile. The data type's id field is a panel unit id used for aggregation, not a cluster-var accessor.

    DoubleMLData

    pub struct DoubleMLData {
    x : Matrix
    y : Array[Double]
    d : Array[Double]
    cluster_vars : Array[Int]
    z : Array[Double]
    } derive(
    Debug
    )

    Container for the data consumed by a DML model. Mirrors the subset of doubleml.DoubleMLData that the PLR model needs: a feature matrix x, an outcome vector y, and a (possibly vector) treatment vector d. Multi-column treatment is currently treated as a single column vector in the port (the public DoubleMLPLR API takes a single treatment, matching the generate_data_simple example).

    When cluster_vars is non-empty, the model routes through the clustered DML path: folds are drawn over the unique unit ids in cluster_vars (not over individual rows), the causal parameter is the fold-weighted ratio of cluster score sums, and the variance is the unit-level cluster-robust estimator (_var_est's one-cluster-variable branch). Each row must carry exactly one cluster id; the length of cluster_vars is n_obs. This mirrors the upstream DoubleMLData(cluster_cols=) API in 0.11.x and is the path DoubleMLClusterData (the pre-0.11 backward-compat shim) used to take.

    DoubleMLData::is_cluster_data

    fn DoubleMLData::is_cluster_data(self : DoubleMLData) -> Bool

    True iff the data is set up for clustered inference (a non-empty cluster_vars vector was passed to new).

    DoubleMLData::is_instrument_data

    fn DoubleMLData::is_instrument_data(self : DoubleMLData) -> Bool

    True iff the data is set up for IV-type DML (a non-empty z vector was passed to new). The IV-type score on DoubleMLPLR::fit(score="IV-type") requires this; calling fit with score="IV-type" and no instrument aborts.

    DoubleMLData::n_cluster_vars

    fn DoubleMLData::n_cluster_vars(self : DoubleMLData) -> Int

    Length of the cluster_vars vector (0 when not clustered).

    DoubleMLData::n_features

    fn DoubleMLData::n_features(self : DoubleMLData) -> Int

    Number of features (columns of X).

    DoubleMLData::n_obs

    fn DoubleMLData::n_obs(self : DoubleMLData) -> Int

    Number of observations in the data.

    DoubleMLData::new

    fn DoubleMLData::new(x : Matrix, y : Array[Double], d : Array[Double], cluster_vars? : Array[Int], z? : Array[Double]) -> DoubleMLData

    Build a DoubleMLData from an n x p feature matrix, an outcome vector of length n and a treatment vector of length n. Pass a non-empty cluster_vars to enable the clustered DML path; pass [] (the default) for the standard row-level path.

    DoubleMLData::z

    fn DoubleMLData::z(self : DoubleMLData) -> Array[Double]

    v0.55.0: instrument vector Z (length n_obs) for the IV-type DML score on DoubleMLPLR. Returns an empty array when no instrument was passed to new.

    DoubleMLIIVM

    pub struct DoubleMLIIVM {
    data : DoubleMLIIVMData
    n_folds : Int
    n_rep : Int
    seed : Int
    smpls : Array[Array[Fold]]
    propensity_clip : Double
    ps_processor_config : PSProcessorConfig
    ml_g : LearnerDispatch
    ml_m : LearnerDispatch
    ml_r : LearnerDispatch
    g0_hat : Array[Double]
    g1_hat : Array[Double]
    m_hat : Array[Double]
    r0_hat : Array[Double]
    r1_hat : Array[Double]
    coef : Double
    se : Double
    fitted : Bool
    psi_a : Array[Double]
    psi_b : Array[Double]
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    fit_cache : FitCache
    } derive(
    Debug
    )

    Double / debiased machine learning estimator for the interactive IV regression model (IIVM) of Chernozhukov et al. (2018) with the LATE score, identifying the Local Average Treatment Effect on the "compliers":

    Y = theta * D + g_0(D, X) + U, E[U | D, X] = 0 D = m_0(X, Z) + V, E[V | X, Z] = 0

    where the binary instrument Z satisfies the relevance and exclusion restrictions. Five cross-fitted nuisance functions are needed (each estimated out-of-fold via K-fold):

    g0(X) = E[Y | Z = 0, X] (trained only on Z = 0) g1(X) = E[Y | Z = 1, X] (trained only on Z = 1) m(X) = E[Z | X] (trained on all obs, then clipped to [eps, 1 - eps]) r0(X) = E[D | Z = 0, X] (trained only on Z = 0) r1(X) = E[D | Z = 1, X] (trained only on Z = 1)

    Residuals:

    u_hat0 = Y - g0, u_hat1 = Y - g1 w_hat0 = D - r0, w_hat1 = D - r1

    LATE score:

    psi_b = (g1 - g0) + Z u_hat1 / m - (1 - Z) u_hat0 / (1 - m) psi_a = -(r1 - r0) - Z w_hat1 / m + (1 - Z) w_hat0 / (1 - m) psi(theta) = theta * psi_a + psi_b

    Point estimate and variance (same _var_est formula as the other DML models):

    theta_hat = -mean(psi_b) / mean(psi_a) J = mean(psi_a) gamma = mean(psi(theta_hat)^2) sigma2 = gamma / (J^2 * n) se = sqrt(sigma2).

    DoubleMLIIVM::bias_corrected_coef

    fn DoubleMLIIVM::bias_corrected_coef(self : DoubleMLIIVM) -> Double

    v0.91.0+: returns coef UNCHANGED -- a documented no-op, not a bias correction.

    coef is the root of the DML moment f(theta) = E[theta * psi_a + psi_b] (see var_est.mbt), so mean(f(coef)) is identically zero: the estimating function is orthogonal by construction, and that orthogonality IS what makes the estimator consistent. Nothing computable from the fitted scores is a bias estimate for this class of estimator, so this accessor reports the uncorrected point estimate rather than a number that merely looks like a correction.

    v0.79.0 - v0.90.0 returned coef + mean(psi_b - coef * psi_a). That vector is the score at -coef, NOT at coef; since coef = -mean_b / mean_a its mean is mean_b - coef * mean_a = -2 * coef * mean_a, so the accessor returned coef * (1 - 2 * mean(psi_a)) (exactly 3 * coef when mean(psi_a) = -1). That is not a bias estimate. See bias_corrected_theta in sandwich.mbt for the algebra. The method is kept so the API surface stays stable; removing it outright is the obvious follow-up.

    Preconditions: self.fitted.

    DoubleMLIIVM::bootstrap

    fn DoubleMLIIVM::bootstrap(self : DoubleMLIIVM, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLIIVM

    v0.61.0+: multiplier bootstrap for DoubleMLIIVM. The per-observation influence function is

    psi[i] = theta * psi_a[i] + psi_b[i]

    where psi_a and psi_b are the LATE score elements (defined in the module doc) computed at the fitted coef from the last rep's cross-fitted nuisances g0_hat / g1_hat / m_hat / r0_hat / r1_hat. Draws n_rep_boot weight vectors of length n_obs from the chosen multiplier distribution, and returns a fitted model with boot_t_stat[b] = sum_i w[b, i] * psi[i] /(sqrt(n) * se_psi) populated where se_psi = sqrt(mean(psi^2)).

    method_name selects the multiplier distribution:
    • "normal" (default): w[i] ~ N(0, 1).
    • "Bayes": w[i] = exp(1) - 1 (mean 0, var 1).
    • "wild": w[i] = x[i] / sqrt(2) + (y[i]^2 - 1) / 2 with x, y ~ N(0, 1).

    Calling bootstrap requires the model to be fitted; calling on an un-fit model aborts with PreconditionError. The helper is did_bootstrap_t_stat (v0.55.0 extracted from DoubleMLDIDCrossSection::bootstrap); IIVM is the n_thetas=1 case.

    DoubleMLIIVM::clear_cache

    fn DoubleMLIIVM::clear_cache(self : DoubleMLIIVM) -> DoubleMLIIVM

    v0.82.0+: drop any cached nuisance predictions and fold assignment.

    DoubleMLIIVM::cluster_sandwich_se

    fn DoubleMLIIVM::cluster_sandwich_se(self : DoubleMLIIVM, cluster_ids : Array[Int]) -> Double

    v0.86.0+: cluster-robust sandwich standard error for the fitted IIVM. Routes through cluster_sandwich_variance with the same psi_a / psi / M_inv inputs as the IID sandwich_se path.

    Preconditions: self.fitted, cluster_ids.length() == n_obs.

    DoubleMLIIVM::coef

    fn DoubleMLIIVM::coef(self : DoubleMLIIVM) -> Double

    DoubleMLIIVM::confint

    fn DoubleMLIIVM::confint(self : DoubleMLIIVM, joint? : Bool, level? : Double) -> (Double, Double)

    v0.67.0+: joint is a no-op for single-theta estimators; accepted for API parity.

    DoubleMLIIVM::disable_memoize

    fn DoubleMLIIVM::disable_memoize(self : DoubleMLIIVM) -> DoubleMLIIVM

    v0.82.0+: turn off memoization. Same immutability contract as enable_memoize(). After this, fit() will not read or write the cache; the existing fit_cache is preserved on the returned struct (call clear_cache() to drop it).

    DoubleMLIIVM::enable_memoize

    fn DoubleMLIIVM::enable_memoize(self : DoubleMLIIVM) -> DoubleMLIIVM

    v0.82.0+: turn on memoization for subsequent fit() calls. When enabled, fit() will cache the per-observation nuisance predictions (g0_hat, g1_hat, m_hat, r0_hat, r1_hat) and the fold partition and skip the cross-fit on a repeat call whose data + learner fingerprint is unchanged. Returns a new DoubleMLIIVM with the flag set (the struct is immutable; the cache itself is populated by the next fit() call).

    DoubleMLIIVM::fit

    fn DoubleMLIIVM::fit(self : DoubleMLIIVM, ml_g? : LearnerDispatch, ml_m? : LearnerDispatch, ml_r? : LearnerDispatch, max_attempts? : Int) -> DoubleMLIIVM

    Run the IIVM estimation.

    Per-repetition behaviour: each repetition r cross-fits the g0 / g1 / m / r0 / r1 nuisances from its own folds (seed self.seed + r), computes its own (theta_r, se_r) from the LATE score, and the two arrays are then aggregated by aggregate_coef_se (median of thetas, then SE from the median of (theta_r + 1.96 * se_r)). For n_rep == 1 the aggregator returns the single (theta_1, se_1) exactly, so the byte-equality with the previous "average then estimate" implementation is preserved. The predictions_g0 / g1 / m / r0 / r1 accessors return the nuisances from the last repetition (the conventional choice in upstream doubleml), not a cross-rep average.

    DoubleMLIIVM::has_cache

    fn DoubleMLIIVM::has_cache(self : DoubleMLIIVM) -> Bool

    v0.82.0+: true iff fit_cache holds at least one cached observation.

    DoubleMLIIVM::learner_g

    fn DoubleMLIIVM::learner_g(self : DoubleMLIIVM) -> LearnerDispatch

    v0.153.0: the outcome learner (ml_g) recorded at construction and used by fit when no explicit argument is given. DoubleMLIIVM stored all three slots since v0.60.0 but, unlike ten sibling estimators, never exposed them.

    DoubleMLIIVM::learner_m

    fn DoubleMLIIVM::learner_m(self : DoubleMLIIVM) -> LearnerDispatch

    v0.153.0: the treatment-propensity learner (ml_m) recorded at construction. See learner_g.

    DoubleMLIIVM::learner_r

    fn DoubleMLIIVM::learner_r(self : DoubleMLIIVM) -> LearnerDispatch

    v0.153.0: the selection-propensity learner (ml_r) recorded at construction. DoubleMLIIVM is the only estimator in the package with an ml_r slot; v0.137.0 classified this score as carrying a reciprocal in both directions, which the measurement then refuted -- it measured harmless.

    DoubleMLIIVM::n_obs

    fn DoubleMLIIVM::n_obs(self : DoubleMLIIVM) -> Int

    DoubleMLIIVM::new

    fn DoubleMLIIVM::new(data : DoubleMLIIVMData, n_folds? : Int, n_rep? : Int, seed? : Int, propensity_clip? : Double, ps_processor_config? : PSProcessorConfig?, ml_g? : LearnerDispatch, ml_m? : LearnerDispatch, ml_r? : LearnerDispatch) -> DoubleMLIIVM

    DoubleMLIIVM::predictions_g0

    fn DoubleMLIIVM::predictions_g0(self : DoubleMLIIVM) -> Array[Double]

    DoubleMLIIVM::predictions_g1

    fn DoubleMLIIVM::predictions_g1(self : DoubleMLIIVM) -> Array[Double]

    DoubleMLIIVM::predictions_m

    fn DoubleMLIIVM::predictions_m(self : DoubleMLIIVM) -> Array[Double]

    DoubleMLIIVM::predictions_r0

    fn DoubleMLIIVM::predictions_r0(self : DoubleMLIIVM) -> Array[Double]

    DoubleMLIIVM::predictions_r1

    fn DoubleMLIIVM::predictions_r1(self : DoubleMLIIVM) -> Array[Double]

    DoubleMLIIVM::sample_splitting

    fn DoubleMLIIVM::sample_splitting(self : DoubleMLIIVM) -> SampleSplitting?

    The sample splitting recorded by set_sample_splitting, or None when none was supplied and fit draws its own. Some carries the DERIVED counts next to the folds, so a caller can read back what the estimator actually used rather than inferring it from the constructor arguments it no longer has any say over.

    DoubleMLIIVM::sandwich_se

    fn DoubleMLIIVM::sandwich_se(self : DoubleMLIIVM, kind : SandwichKind) -> Double

    v0.86.0+: Huber-White sandwich standard error for the fitted IIVM. Returns sqrt(var) where var comes from the shared sandwich_variance(kind, ...) dispatch in sandwich.mbt (HC0 / HC1 / HC2 / HC3).

    The three inputs are the ones fit(...) already persists for the multiplier bootstrap (see the psi_a / psi_b field docs on DoubleMLIIVM):
    • psi_a = self.psi_a -- the IIVM LATE residualized-treatment score (-(r1 - r0) - Z * w1 / m + (1 - Z) * w0 / (1 - m)).
    • psi = psi_at(self.coef, self.psi_a, self.psi_b) -- the per-observation influence function evaluated at the fitted coef, where psi_b is the residualized-outcome score ((g1 - g0) + Z * u1 / m - (1 - Z) * u0 / (1 - m)). Same psi_at score order as IRM / PLR.
    • M_inv = [[1 / mean(psi_a)]] (1x1). Only M_inv[0, 0]^2 enters the variance, so the sign of the (up-to-sign) Jacobian inverse is irrelevant.

    Preconditions: self.fitted, mean(psi_a) != 0.

    DoubleMLIIVM::se

    fn DoubleMLIIVM::se(self : DoubleMLIIVM) -> Double

    DoubleMLIIVM::sensitivity_analysis

    fn DoubleMLIIVM::sensitivity_analysis(self : DoubleMLIIVM, cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.66.0+: Cinelli & Hazlett (2020) omitted-variable bias analysis. Outcome residual is y - g0_hat - (g1_hat - g0_hat) * d; the Riesz-representer variance is mean(psi_a^2) where psi_a = -(r1 - r0) - Z * w1/m + (1-Z) * w0/(1-m) for the LATE score. Routes through the shared irm_style_sensitivity helper.

    DoubleMLIIVM::sensitivity_analysis_cluster

    fn DoubleMLIIVM::sensitivity_analysis_cluster(self : DoubleMLIIVM, cluster_ids? : Array[Int], cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.72.0+: cluster-robust analogue of DoubleMLIIVM::sensitivity_analysis. Same DID-style residual form (y - g0 - (g1 - g0) * d) and the same psi_a = -(r1 - r0) - Z * w1/m + (1 - Z) * w0/(1 - m) (LATE score) as the IID path; only the variance / bias computation is cluster-aware. cluster_ids defaults to DoubleMLIIVMData::cluster_vars.

    DoubleMLIIVM::set_sample_splitting

    fn DoubleMLIIVM::set_sample_splitting(self : DoubleMLIIVM, smpls : Array[Array[Fold]]) -> DoubleMLIIVM

    Record a caller-supplied sample splitting and DERIVE the fold and repetition counts from it. Returns a new DoubleMLIIVM; the receiver is unchanged, as everywhere in this package.

    smpls is one entry per repetition, each entry one Fold per fold -- the nested form is the only form, so a single repetition is [f0, f1, f2] wrapped once, i.e. [[f0, f1, f2]].

    The derivation is upstream's, and it is the part that surprises people: set_sample_splitting (doubleml/double_ml_sampling_mixins.py:76) sets n_folds and n_rep FROM the supplied partition, so handing a two-fold split to a model built with n_folds=5 yields a two-fold model. On the returned model n_folds / n_rep are updated to match, and fit uses the supplied folds instead of drawing them.

    Validation, via check_sample_splitting: every repetition carries the same number of folds, and within each repetition the test index sets are disjoint and cover exactly [0, n_obs). A supplied partition that is not a partition aborts rather than quietly producing a cross-fit that leaks across folds.

    Memoization: fit will not read or write the fit cache once an external splitting is recorded. The cache key is built from the data, learner and cluster hashes and has no term for the fold assignment, so two different supplied partitions would collide and the second fit would silently return the first one's predictions. The memoize_enabled flag is carried through unchanged; it is the !external term in fit that refuses the cache. The cache is also CLEARED here, so a re-fit under a new splitting cannot resurrect an entry written under the old one.

    Cluster path: an externally supplied splitting applies to the ROW-level path only. fit_cluster draws UNIT-level folds over the unique cluster ids and expands them to rows, so a supplied row-level partition is not consulted there and a clustered fit keeps drawing its own unit-level folds. Making the cluster path honour external splits is a separate decision and out of scope here; the field is carried across so the row-level path resumes the supplied splitting on a later non-cluster fit.

    The one-fold "no sample splitting" case needs no special handling: a single Fold whose train and test both cover everything is a valid partition with folds = 1, which is what upstream detects and reports.

    DoubleMLIIVM::tune

    fn DoubleMLIIVM::tune(self : DoubleMLIIVM, param_set~ : Array[TuneParam], scoring_method? : String, n_folds_tune? : Int, seed? : Int) -> DoubleMLIIVM

    v0.65.0+: tune the (ml_g, ml_m) nuisance-learner pair via MSE-on-g_hat cross-fitting (matches DoubleMLPLR::tune's MSE-on-l_hat scoring convention). ml_r (the instrument propensity) is held fixed at self.ml_r for both the tune stage and the re-fit. The chosen (learner_g, learner_m) is then re-fit on the FINAL-FIT fold partition (self.n_folds) under DoubleMLIIVM::fit. Cluster-DML is not supported in tune.

    param_set is an Array[TuneParam]; each entry is a (learner_g, learner_m) pair. scoring_method is "MSE" (default), "RMSE", or "NegMSE". Returns a re-fitted DoubleMLIIVM with the chosen pair applied.

    DoubleMLIIVMData

    pub struct DoubleMLIIVMData {
    x : Matrix
    y : Array[Double]
    d : Array[Double]
    z : Array[Double]
    cluster_vars : Array[Int]
    } derive(
    Debug
    )

    Data container for DoubleMLIIVM. Same shape as DoubleMLData but adds a single instrumental variable z. The treatment d and the instrument z are both binary.

    DoubleMLIIVMData::is_cluster_data

    fn DoubleMLIIVMData::is_cluster_data(self : DoubleMLIIVMData) -> Bool

    True iff the data is set up for clustered inference (a non-empty cluster_vars vector was passed to new).

    DoubleMLIIVMData::n_cluster_vars

    fn DoubleMLIIVMData::n_cluster_vars(self : DoubleMLIIVMData) -> Int

    Length of the cluster_vars vector (0 when not clustered).

    DoubleMLIIVMData::n_features

    fn DoubleMLIIVMData::n_features(self : DoubleMLIIVMData) -> Int

    DoubleMLIIVMData::n_obs

    fn DoubleMLIIVMData::n_obs(self : DoubleMLIIVMData) -> Int

    DoubleMLIIVMData::new

    fn DoubleMLIIVMData::new(x : Matrix, y : Array[Double], d : Array[Double], z : Array[Double], cluster_vars? : Array[Int]) -> DoubleMLIIVMData

    DoubleMLIRM

    pub struct DoubleMLIRM {
    data : DoubleMLData
    n_folds : Int
    n_rep : Int
    seed : Int
    smpls : Array[Array[Fold]]
    propensity_clip : Double
    ps_processor_config : PSProcessorConfig
    ml_g : LearnerDispatch
    ml_m : LearnerDispatch
    g0_hat : Array[Double]
    g1_hat : Array[Double]
    m_hat : Array[Double]
    m_raw : Array[Double]
    coef : Double
    se : Double
    fitted : Bool
    psi_a : Array[Double]
    psi_b : Array[Double]
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    fit_cache : FitCache
    } derive(
    Debug
    )

    Double / debiased machine learning estimator for the interactive regression model (IRM) of Chernozhukov et al. (2018) with the Average Treatment Effect (ATE) score:

    Y = g_0(D, X) + U, E[U | D, X] = 0 D = m_0(X) + V, E[V | X] = 0

    and the ATE orthogonal signal

    g0(X) = E[Y | D=0, X] g1(X) = E[Y | D=1, X] m(X) = P(D=1 | X) (the propensity score) u0 = Y - g0(X) u1 = Y - g1(X) psi_b = (g1 - g0) + (D u1 / m - (1 - D) u0 / (1 - m)) psi_a = -1 psi(theta) = theta * psi_a + psi_b

    with point estimate

    theta_hat = -mean(psi_b) / mean(psi_a) = mean(psi_b)

    and variance (same _var_est formula as DoubleMLPLR):

    J = mean(psi_a) = -1 gamma = mean(psi(theta_hat)^2) sigma2 = gamma / (J^2 * n) se = sqrt(sigma2)

    The cross-fitting scheme trains g0 only on observations with D = 0 and g1 only on observations with D = 1 (the test folds still cover the full observation set), matching doubleml.utils._estimation._get_cond_smpls in the upstream package. The propensity score is clipped to [propensity_clip, 1 - propensity_clip] before being used in the score, guarding against near-zero or near-one values.

    DoubleMLIRM::bias_corrected_coef

    fn DoubleMLIRM::bias_corrected_coef(self : DoubleMLIRM) -> Double

    v0.91.0+: returns coef UNCHANGED -- a documented no-op, not a bias correction.

    coef is the root of the DML moment f(theta) = E[theta * psi_a + psi_b] (see var_est.mbt), so mean(f(coef)) is identically zero: the estimating function is orthogonal by construction, and that orthogonality IS what makes the estimator consistent. Nothing computable from the fitted scores is a bias estimate for this class of estimator, so this accessor reports the uncorrected point estimate rather than a number that merely looks like a correction.

    (IRM's psi_a is the constant -1.)

    v0.79.0 - v0.90.0 returned coef + mean(psi_b - coef * psi_a). That vector is the score at -coef, NOT at coef; since coef = -mean_b / mean_a its mean is mean_b - coef * mean_a = -2 * coef * mean_a, so the accessor returned coef * (1 - 2 * mean(psi_a)) (exactly 3 * coef when mean(psi_a) = -1). That is not a bias estimate. See bias_corrected_theta in sandwich.mbt for the algebra. The method is kept so the API surface stays stable; removing it outright is the obvious follow-up.

    Preconditions: self.fitted.

    DoubleMLIRM::bootstrap

    fn DoubleMLIRM::bootstrap(self : DoubleMLIRM, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLIRM

    v0.61.0+: multiplier bootstrap for DoubleMLIRM. The per-observation influence function is

    psi[i] = theta * psi_a[i] + psi_b[i] = -1 + theta * psi_b[i]

    where psi_b[i] = (g1-g0)[i] + (D*u1/m - (1-D)*u0/(1-m))[i] is computed at the fitted coef from the last rep's cross-fitted nuisances g0_hat / g1_hat / m_hat. Draws n_rep_boot weight vectors of length n_obs from the chosen multiplier distribution, and returns a fitted model with boot_t_stat[b] = sum_i w[b, i] * psi[i] /(sqrt(n) * se_psi) populated where se_psi = sqrt(mean(psi^2)).

    method_name selects the multiplier distribution:
    • "normal" (default): w[i] ~ N(0, 1).
    • "Bayes": w[i] = exp(1) - 1 (mean 0, var 1).
    • "wild": w[i] = x[i] / sqrt(2) + (y[i]^2 - 1) / 2 with x, y ~ N(0, 1).

    Calling bootstrap requires the model to be fitted; calling on an un-fit model aborts with PreconditionError. The helper is did_bootstrap_t_stat (v0.55.0 extracted from DoubleMLDIDCrossSection::bootstrap); IRM is the n_thetas=1 case.

    DoubleMLIRM::clear_cache

    fn DoubleMLIRM::clear_cache(self : DoubleMLIRM) -> DoubleMLIRM

    v0.80.0+: drop any cached nuisance predictions and fold assignment. Useful when the caller wants to free memory or force the next fit() to recompute from scratch (e.g. after mutating a learner in place that the cache key does not detect).

    DoubleMLIRM::cluster_sandwich_se

    fn DoubleMLIRM::cluster_sandwich_se(self : DoubleMLIRM, cluster_ids : Array[Int]) -> Double

    v0.79.0+: cluster-robust sandwich standard error for the fitted IRM. Routes through cluster_sandwich_variance in sandwich.mbt with M_inv = [[1 / mean(psi_a)]] (matching the IID path's Jacobian inverse).

    Preconditions: self.fitted, cluster_ids.length() == n_obs.

    DoubleMLIRM::coef

    fn DoubleMLIRM::coef(self : DoubleMLIRM) -> Double

    DoubleMLIRM::confint

    fn DoubleMLIRM::confint(self : DoubleMLIRM, joint? : Bool, level? : Double) -> (Double, Double)

    v0.67.0+: joint is a no-op for single-theta estimators (the joint CI equals the Wald CI); accepted for API parity with the multi-theta estimators.

    DoubleMLIRM::disable_memoize

    fn DoubleMLIRM::disable_memoize(self : DoubleMLIRM) -> DoubleMLIRM

    v0.80.0+: turn off memoization. Same immutability contract as enable_memoize(). After this, fit() will not read or write the cache; the existing fit_cache is preserved on the returned struct (call clear_cache() to drop it).

    DoubleMLIRM::enable_memoize

    fn DoubleMLIRM::enable_memoize(self : DoubleMLIRM) -> DoubleMLIRM

    v0.80.0+: turn on memoization for subsequent fit() calls. When enabled, fit() will cache the per-observation nuisance predictions and the fold partition and skip the cross_fit_irm(...) step on a repeat call whose data + learner fingerprint is unchanged. Returns a new DoubleMLIRM with the flag set (the struct is immutable; the cache itself is populated by the next fit() call).

    Default is OFF. When OFF, every fit() call runs the full cross-fit and the cache is neither read nor written, so v0.79.0 callers see byte-identical output.

    DoubleMLIRM::fit

    fn DoubleMLIRM::fit(self : DoubleMLIRM, ml_g? : LearnerDispatch, ml_m? : LearnerDispatch, max_attempts? : Int) -> DoubleMLIRM

    Run the IRM estimation. The default learners are closed-form LinearRegression instances for both the outcome nuisance (ml_g) and the propensity score (ml_m).

    Per-repetition behaviour: each repetition r cross-fits the g0 / g1 / m nuisances from its own folds (seed self.seed + r), computes its own (theta_r, se_r) from the ATE score, and the two arrays are then aggregated by aggregate_coef_se (median of thetas, then SE from the median of (theta_r + 1.96 * se_r)). For n_rep == 1 the aggregator returns the single (theta_1, se_1) exactly, so the byte-equality with the previous "average then estimate" implementation is preserved. The predictions_g0 / g1 / m accessors return the nuisances from the last repetition (the conventional choice in upstream doubleml), not a cross-rep average.

    When self.data carries a non-empty cluster_vars vector, the estimator routes through the clustered DML path: folds partition whole units (rows of one cluster id stay on the same side of every split), the ATE is the fold-weighted ratio of cluster score sums, and the SE is unit-level cluster-robust.

    DoubleMLIRM::has_cache

    fn DoubleMLIRM::has_cache(self : DoubleMLIRM) -> Bool

    v0.80.0+: true iff fit_cache holds at least one cached observation (i.e. at least one prior fit() call with memoize_enabled = true has populated the cache). Note that the cache may still be stale relative to the current data + learner configuration -- check memoize_enabled before assuming a cache hit.

    DoubleMLIRM::learner_g

    fn DoubleMLIRM::learner_g(self : DoubleMLIRM) -> LearnerDispatch

    Accessor for the outcome-nuisance learner used by the most recent fit(...) / fit_cluster(...) call. v0.59.0+.

    DoubleMLIRM::learner_m

    fn DoubleMLIRM::learner_m(self : DoubleMLIRM) -> LearnerDispatch

    Accessor for the propensity-score learner used by the most recent fit(...) / fit_cluster(...) call. v0.59.0+.

    DoubleMLIRM::n_features

    fn DoubleMLIRM::n_features(self : DoubleMLIRM) -> Int

    Number of features (covariate columns).

    DoubleMLIRM::n_obs

    fn DoubleMLIRM::n_obs(self : DoubleMLIRM) -> Int

    DoubleMLIRM::new

    fn DoubleMLIRM::new(data : DoubleMLData, n_folds? : Int, n_rep? : Int, seed? : Int, propensity_clip? : Double, ps_processor_config? : PSProcessorConfig?, ml_g? : LearnerDispatch, ml_m? : LearnerDispatch) -> DoubleMLIRM

    DoubleMLIRM::predictions_g0

    fn DoubleMLIRM::predictions_g0(self : DoubleMLIRM) -> Array[Double]

    DoubleMLIRM::predictions_g1

    fn DoubleMLIRM::predictions_g1(self : DoubleMLIRM) -> Array[Double]

    DoubleMLIRM::predictions_m

    fn DoubleMLIRM::predictions_m(self : DoubleMLIRM) -> Array[Double]

    DoubleMLIRM::propensity_score_raw

    fn DoubleMLIRM::propensity_score_raw(self : DoubleMLIRM) -> Array[Double]

    Raw (pre-clipping) propensity scores, length n_obs. v0.53.0-dev Task 4: mirrors upstream feat "retain raw IRM propensity scores" so callers can inspect the un-clipped predictions without re-fitting.

    DoubleMLIRM::sample_splitting

    fn DoubleMLIRM::sample_splitting(self : DoubleMLIRM) -> SampleSplitting?

    The sample splitting recorded by set_sample_splitting, or None when none was supplied and fit draws its own. Some carries the DERIVED counts next to the folds, so a caller can read back what the estimator actually used rather than inferring it from the constructor arguments it no longer has any say over.

    DoubleMLIRM::sandwich_se

    fn DoubleMLIRM::sandwich_se(self : DoubleMLIRM, kind : SandwichKind) -> Double

    v0.79.0+: Huber-White sandwich standard error for the fitted IRM. Returns sqrt(var_xx) where var_xx is computed by the sandwich_variance_xx free function in sandwich.mbt (HC0 / HC1 / HC2 / HC3). The Jacobian inverse M_inv = [[1 / mean(psi_a)]] is built from the stored psi_a (which is [-1, -1, ..., -1] for the IRM ATE score, so M_inv = [[-1.0]] always — the mean(psi_a) is -1 by construction).

    Preconditions: self.fitted.

    DoubleMLIRM::se

    fn DoubleMLIRM::se(self : DoubleMLIRM) -> Double

    DoubleMLIRM::sensitivity_analysis

    fn DoubleMLIRM::sensitivity_analysis(self : DoubleMLIRM, cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    DoubleMLIRM::sensitivity_analysis_cluster

    fn DoubleMLIRM::sensitivity_analysis_cluster(self : DoubleMLIRM, cluster_ids? : Array[Int], cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.72.0+: cluster-robust analogue of DoubleMLIRM::sensitivity_analysis. Same DID-style residual form (y - g0 - (g1 - g0) * d) and the same psi_a = -1 (constant) as the IID path; only the variance / bias computation is cluster-aware. cluster_ids defaults to DoubleMLData::cluster_vars.

    DoubleMLIRM::sensitivity_nu2_elements

    fn DoubleMLIRM::sensitivity_nu2_elements(self : DoubleMLIRM) -> (Array[Double], Array[Double]) raise

    v0.131.7: the nu2 score element and the Riesz representer for the IRM ATE score, transcribed from upstream irm/irm.py:412-423.

    Upstream computes it through two layers that both COLLAPSE here:

    • weights, weights_bar = self._get_weights(m_hat=m_hat_adj). self._weights["weights"] defaults to np.ones(n_obs) (irm.py:249) and this port exposes no user-supplied weights, so weights == weights_bar == 1 on both the ATE branch (irm.py:258-263) and -- via the absent weights_bar key -- identically. The ATTE branch (irm.py:265-272) does not apply: the port is ATE-only (Score (ATE, weights=1, weights_bar=1), irm.mbt:602).

    • m_hat_adj = _propensity_score_adjustment(m_hat, d, normalize_ipw) returns m_hat unchanged when normalize_ipw is False. That is upstream's default (irm.py:138) and it is exactly why this port's DoubleMLIRM carries no normalize_ipw field. So m_hat_adj == m_hat.

    What is left, with both weight factors equal to 1:

    m_alpha = 1/m_hat + 1/(1 - m_hat) rr = d/m_hat - (1 - d)/(1 - m_hat) nu2 = mean( 2*m_alpha - rr^2 )

    The default path previously computed mean(psi_a^2), which is upstream's documented FALLBACK (double_ml.py:1634-1641) applied to the wrong variable. Note psi_a here is -1/mean(weights) == -1, a CONSTANT (irm.py:392), so the fallback reduced nu2 to exactly 1.

    DoubleMLIRM::set_sample_splitting

    fn DoubleMLIRM::set_sample_splitting(self : DoubleMLIRM, smpls : Array[Array[Fold]]) -> DoubleMLIRM

    Record a caller-supplied sample splitting and DERIVE the fold and repetition counts from it. Returns a new DoubleMLIRM; the receiver is unchanged, as everywhere in this package.

    smpls is one entry per repetition, each entry one Fold per fold -- the nested form is the only form, so a single repetition is [f0, f1, f2] wrapped once, i.e. [[f0, f1, f2]].

    The derivation is upstream's, and it is the part that surprises people: set_sample_splitting (doubleml/double_ml_sampling_mixins.py:76) sets n_folds and n_rep FROM the supplied partition, so handing a two-fold split to a model built with n_folds=5 yields a two-fold model. On the returned model n_folds / n_rep are updated to match, and fit uses the supplied folds instead of drawing them.

    Validation, via check_sample_splitting: every repetition carries the same number of folds, and within each repetition the test index sets are disjoint and cover exactly [0, n_obs). A supplied partition that is not a partition aborts rather than quietly producing a cross-fit that leaks across folds.

    Memoization: fit will not read or write the fit cache once an external splitting is recorded. The cache key is built from the data, learner and cluster hashes and has no term for the fold assignment, so two different supplied partitions would collide and the second fit would silently return the first one's predictions. The memoize_enabled flag is carried through unchanged; it is the !external term in fit that refuses the cache. The cache is also CLEARED here, so a re-fit under a new splitting cannot resurrect an entry written under the old one.

    Cluster path: an externally supplied splitting applies to the ROW-level path only. fit_cluster draws UNIT-level folds over the unique cluster ids and expands them to rows, so a supplied row-level partition is not consulted there and a clustered fit keeps drawing its own unit-level folds. Making the cluster path honour external splits is a separate decision and out of scope here; the field is carried across so the row-level path resumes the supplied splitting on a later non-cluster fit.

    The one-fold "no sample splitting" case needs no special handling: a single Fold whose train and test both cover everything is a valid partition with folds = 1, which is what upstream detects and reports.

    DoubleMLIRM::tune

    fn DoubleMLIRM::tune(self : DoubleMLIRM, param_set~ : Array[TuneParam], scoring_method? : String, n_folds_tune? : Int, seed? : Int) -> DoubleMLIRM

    v0.65.0+: tune the (ml_g, ml_m) nuisance-learner pair via MSE-on-g_hat cross-fitting (matches DoubleMLPLR::tune's MSE-on-l_hat scoring convention; see tune.mbt §4.1). The chosen (learner_g, learner_m) is then re-fit on the FINAL-FIT fold partition (self.n_folds) under DoubleMLIRM::fit. Cluster-DML is not supported in tune (mirrors the PLR behaviour — tune requires !self.data.is_cluster_data()).

    param_set is an Array[TuneParam]; each entry is a (learner_g, learner_m) pair. scoring_method is "MSE" (default), "RMSE", or "NegMSE". Returns a re-fitted DoubleMLIRM with the chosen learners applied. The chosen pair is visible via ml_g / ml_m on the returned model (no tune_result field is persisted — that audit field is reserved for PLR-style estimators).

    DoubleMLLPLR

    pub struct DoubleMLLPLR {
    data : DoubleMLBinaryData
    score : String
    n_folds : Int
    n_folds_inner : Int
    n_rep : Int
    seed : Int
    smpls : Array[Array[Fold]]
    ml_g : LearnerDispatch
    ml_m : LearnerDispatch
    coef_ : Double
    se_ : Double
    r_hat : Array[Double]
    m_hat : Array[Double]
    a_hat : Array[Double]
    fitted : Bool
    fit_warnings : Array[String]
    psi_a : Array[Double]
    psi_b : Array[Double]
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    fit_cache : FitCache
    } derive(
    Debug
    )

    Model: Y = expit(D * theta + r_0(X)). Binary outcomes, mixed treatment type. Wraps a single-treatment LPLR with closed-form logistic regression learners (LogisticRegression for ml_M and ml_m, LinearRegression for ml_t). The repository keeps one estimator per data; multi-treatment support is out of scope here.

    DoubleMLLPLR::bias_corrected_coef

    fn DoubleMLLPLR::bias_corrected_coef(self : DoubleMLLPLR) -> Double

    v0.92.0+: returns coef UNCHANGED -- a documented no-op, not a bias correction. Identical in reasoning to the twelve bias_corrected_coef methods added in v0.86.0 - v0.91.0; see DoubleMLIRM::bias_corrected_coef and bias_corrected_theta in sandwich.mbt for the full argument.

    coef is the root of the DML moment f(theta) = E[theta * psi_a + psi_b] in var_est.mbt's convention -- for LPLR, psi_a is the score DERIVATIVE and psi_b the score OFFSET -- so mean(f(coef)) is identically zero: the estimating function is orthogonal by construction, and that orthogonality IS what makes the estimator consistent. Nothing computable from the fitted scores is a bias estimate for this class of estimator, so this accessor reports the uncorrected point estimate rather than a number that merely looks like a correction.

    Preconditions: self.fitted.

    DoubleMLLPLR::bootstrap

    fn DoubleMLLPLR::bootstrap(self : DoubleMLLPLR, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLLPLR

    v0.75.0+: multiplier bootstrap for DoubleMLLPLR. The per-observation influence function (raw score at the fitted coef_) is

    psi[i] = coef * sc.psi_deriv[i] + (sc.psi[i] - coef * sc.psi_deriv[i]) = sc.psi[i]

    NOTE the argument order below. LPLR persists its IF components in the INVERTED (offset, slope) order relative to every other estimator in the package: self.psi_a is the OFFSET at theta_hat (sc.psi - theta_hat * sc.psi_deriv) and self.psi_b is the SLOPE (sc.psi_deriv, the actual d/dtheta term). psi_at(coef, psi_a, psi_b) expects (coefficient, offset), so LPLR passes (self.psi_b,self.psi_a) -- slope as psi_a, offset as psi_b. That recovers psi_at(coef, sc.psi_deriv, sc.psi - coef *sc.psi_deriv) = sc.psi[i], the raw score at the fitted theta.

    v0.90.0 makes this explicit. v0.75.0 - v0.89.0 called the shared helper with the arguments the other way round plus the old (swapped) score order, and the two wrongs cancelled; the arithmetic above shows the cancellation is exact, so the numeric output is unchanged by v0.90.0. Routing through psi_at means the cancellation is no longer load-bearing.

    The bootstrap draws n_rep_boot weight vectors of length n_obs from the chosen multiplier distribution, and stores boot_t_stat[b] = sum_i w[b, i] * psi[i] /(sqrt(n) * se_psi) where se_psi = sqrt(mean(psi^2)).

    method_name selects the multiplier distribution: "normal" (default), "Bayes", "wild"; seed defaults to 2024; n_rep_boot defaults to 500.

    Calling on an un-fit model aborts via PreconditionError. Returns a new DoubleMLLPLR with boot_t_stat / boot_method / n_rep_boot / boot_seed populated.

    DoubleMLLPLR::clear_cache

    fn DoubleMLLPLR::clear_cache(self : DoubleMLLPLR) -> DoubleMLLPLR

    v0.83.0+: drop any cached nuisance predictions and fold assignment. Forces the next fit() to recompute from scratch.

    DoubleMLLPLR::cluster_sandwich_se

    fn DoubleMLLPLR::cluster_sandwich_se(self : DoubleMLLPLR, cluster_ids : Array[Int]) -> Double

    v0.92.0+: cluster-robust sandwich standard error for the fitted LPLR (Arellano 1987, Cameron-Gelbach-Miller 2011). Routes through cluster_sandwich_variance with the SAME swapped psi and M_inv inputs as the IID sandwich_se path -- see that method's doc for why LPLR's influence-function components are stored inverted.

    DoubleMLBinaryData carries no cluster_vars, so the caller must supply cluster_ids explicitly (any grouping variable the application has: region, site, panel unit). With all-singleton clusters the meat degenerates to sum_i psi[i]^2 and the formula collapses to sandwich_se(HC0), hence to se().

    Preconditions: self.fitted, cluster_ids.length() == psi_b.length().

    DoubleMLLPLR::coef

    fn DoubleMLLPLR::coef(self : DoubleMLLPLR) -> Double

    DoubleMLLPLR::confint

    fn DoubleMLLPLR::confint(self : DoubleMLLPLR) -> (Double, Double)

    DoubleMLLPLR::disable_memoize

    fn DoubleMLLPLR::disable_memoize(self : DoubleMLLPLR) -> DoubleMLLPLR

    v0.83.0+: turn off memoization. Same immutability contract as enable_memoize(). After this, fit() will not read or write the cache; the existing fit_cache is preserved on the returned struct (call clear_cache() to drop it).

    DoubleMLLPLR::enable_memoize

    fn DoubleMLLPLR::enable_memoize(self : DoubleMLLPLR) -> DoubleMLLPLR

    v0.83.0+: turn on memoization for subsequent fit() calls. When enabled, fit() will cache the LAST rep's per-fold nuisance predictions (r_hat, m_hat, a_hat) and the fold assignment; on a repeat call whose data + learner fingerprint + fold split is identical, the entire per-fold crossfit is skipped and the cached values feed the Newton / score / SE pipeline.

    enable_memoize() is honored only when n_rep == 1; for n_rep > 1 the per-rep cross-fit must run each time (the cache would otherwise need to thread n_rep independent per-rep nuisance arrays, which the FitCache layout does not accommodate).

    Default is OFF. When OFF, every fit() call runs the full cross-fit and the cache is neither read nor written, so v0.82.0 callers see byte-identical output.

    DoubleMLLPLR::fit

    Fit the LPLR estimator. Mirrors the upstream DoubleMLLPLR._nuisance_est / _est_causal_pars / _se_causal_pars flow:

    1. Outer cross-fit ml_M on (d, x) -> Y; the same outer folds are also used for the inner re-split. ml_M is a LogisticRegression so its predict returns the probability of Y = 1.
    2. Double cross-fit ml_a (also LogisticRegression for binary D) on x -> D to obtain inner-fold OOF propensity predictions per outer fold.
    3. Build per-fold targets W_inner from ml_M INNER-OOF predictions (clipped to [1e-8, 1 - 1e-8], then logit) -- upstream's M_hat["preds_inner"][i][train] (plm/lplr.py:318); cross-fit ml_t (a LinearRegression) on x -> W_inner to get t_hat.
    4. Per fold, compute beta_f from inner W and (d - a_inner), and write it onto that fold's TEST rows (beta[test] = b_f, :323). Average across rows for the Newton starting value (:326).
    5. ml_m supplies d_tilde = d - m_hat. Upstream fits it as a separate learner, restricted to the Y = 0 rows under score="nuisance_space"; this port aliases m_hat = a_hat (see the m_pred = a_pred comment in the body).
    6. Build the score at any theta from r_i = t_hat_i - beta_i * a_hat_i -- beta_i is that ROW's value, not a shared scalar (plm/lplr.py:345); no theta in r; see lplr_score_at for both upstream formulas -- they differ, and that difference is what score selects.
    7. Newton iteration with mean(psi) and mean(psi_deriv).
    8. Variance via the standard linear-score path (var_est(psi_a, psi_b) with psi_a = psi_deriv, psi_b = psi - theta * psi_deriv); the LPLR score is not linear in theta but is exactly the theta * psi_a +psi_b form at the converged theta with psi_a =psi_deriv(theta), psi_b = psi(theta) - theta *psi_deriv(theta), so the same machinery applies.

    LPLR is not cluster data; var_est runs the row-level path.

    DoubleMLLPLR::has_cache

    fn DoubleMLLPLR::has_cache(self : DoubleMLLPLR) -> Bool

    v0.83.0+: true iff fit_cache holds at least one cached observation (i.e. at least one prior fit() call with memoize_enabled = true has populated the cache). Note that the cache may still be stale relative to the current data + learner configuration -- check memoize_enabled before assuming a cache hit.

    DoubleMLLPLR::learner_g

    fn DoubleMLLPLR::learner_g(self : DoubleMLLPLR) -> LearnerDispatch

    Accessor for the outcome-nuisance learner used by the most recent fit(...) call. v0.60.0+.

    DoubleMLLPLR::learner_m

    fn DoubleMLLPLR::learner_m(self : DoubleMLLPLR) -> LearnerDispatch

    Accessor for the propensity-score learner used by the most recent fit(...) call. v0.60.0+.

    DoubleMLLPLR::new

    fn DoubleMLLPLR::new(data : DoubleMLBinaryData, score? : String, n_folds? : Int, n_folds_inner? : Int, n_rep? : Int, seed? : Int, ml_g? : LearnerDispatch, ml_m? : LearnerDispatch) -> DoubleMLLPLR

    DoubleMLLPLR::predictions_a

    fn DoubleMLLPLR::predictions_a(self : DoubleMLLPLR) -> Array[Double]

    a_hat (E[D | X] propensity used in d_tilde) from the last repetition. In LPLR, m_hat == a_hat (a single nuisance regressor feeds both roles), but the field is preserved for parity with upstream's separate ml_m / ml_a learners.

    DoubleMLLPLR::predictions_m

    fn DoubleMLLPLR::predictions_m(self : DoubleMLLPLR) -> Array[Double]

    m_hat (E[D | X], outer cross-fit, "a_hat" in upstream) from the last repetition. Length n_obs.

    DoubleMLLPLR::predictions_t

    fn DoubleMLLPLR::predictions_t(self : DoubleMLLPLR) -> Array[Double]

    t_hat (E[W | X]) from the last repetition. Length n_obs.

    DoubleMLLPLR::sample_splitting

    fn DoubleMLLPLR::sample_splitting(self : DoubleMLLPLR) -> SampleSplitting?

    The sample splitting recorded by set_sample_splitting, or None when none was supplied and fit draws its own. Some carries the DERIVED counts next to the folds, so a caller can read back what the estimator actually used rather than inferring it from the constructor arguments it no longer has any say over.

    DoubleMLLPLR::sandwich_se

    fn DoubleMLLPLR::sandwich_se(self : DoubleMLLPLR, kind : SandwichKind) -> Double

    v0.92.0+: Huber-White sandwich standard error for the fitted LPLR, routed through the shared sandwich_variance(kind, ...) dispatch in sandwich.mbt.

    THE INVERSION -- READ BEFORE CHANGING THE ARGUMENT ORDER

    DoubleMLLPLR persists its influence-function components inverted relative to every other estimator in the package. The internal LplrScore struct (see lplr_score_at) carries psi -- the score itself, which is the OFFSET in the f(theta) = theta * deriv + offset linearisation -- and psi_deriv -- the derivative of the score w.r.t. theta, i.e. the COEFFICIENT. fit persists them as

    self.psi_a = sc.psi - theta_hat * sc.psi_deriv (OFFSET) self.psi_b = sc.psi_deriv (DERIVATIVE)

    so the field names are the mirror image of the package convention (psi_a = coefficient row, psi_b = offset). var_est.mbt -- the reference, unchanged -- is fed (sc.psi_deriv, sc.psi - theta_hat * sc.psi_deriv), i.e. the tuple in package order, and its J = mean(psi_a) is therefore mean(psi_deriv). Two consequences, and both are load-bearing:

    1. The score must be evaluated with the arrays SWAPPED: psi_at(coef, self.psi_b, self.psi_a), which recovers theta_hat * sc.psi_deriv + (sc.psi - theta_hat *sc.psi_deriv) = sc.psi, the raw score at the fitted theta. This is exactly the argument order its bootstrap call site has used since v0.90.0 (see DoubleMLLPLR::bootstrap), so the two paths cannot drift apart.

    2. M_inv must be [[1 / mean(self.psi_b)]] -- mean(psi_deriv), the true Jacobian. v0.87.0 built M_inv from mean(self.psi_a), which is mean(sc.psi - theta_hat * sc.psi_deriv): a catastrophic-cancellation residual, not a derivative. It is ~60x smaller in magnitude here and its sign is not even stable, so the resulting HC0 was inflated by roughly 60x and HC2 / HC3 hit the 1e-10 degenerate-leverage clip (6.4e10). LPLR was skipped in v0.87.0 and again in v0.90.0 for this reason.

    With both corrections in place the payoff invariant holds, as it does for the other 12 estimators:

    sandwich_se(HC0) == se()

    to floating-point tolerance. se() is var_est over the same (psi_deriv, offset) tuple, i.e. sqrt(mean(psi(theta_hat)^2) / (mean(psi_deriv)^2 * n)), which is algebraically M_inv[0,0]^2 * sum_i psi[i]^2 / n / n -- the v0.91.0 accumulator, evaluated at the same point.

    The three inputs are the ones fit already persists for the multiplier bootstrap:
    • psi_a (the length-n array sandwich_variance only reads for its length precondition) is the DERIVATIVE row self.psi_b;
    • psi = psi_at(coef, self.psi_b, self.psi_a);
    • M_inv = [[1 / mean(self.psi_b)]] (1x1). Only M_inv[0, 0]^2 enters the variance, so the sign of the (up-to-sign) Jacobian inverse is irrelevant.

    n_obs is self.psi_b.length(): LPLR has no transformed or subset domain, so the persisted sample is the full self.data.n_obs().

    Preconditions: self.fitted, mean(psi_b) != 0.

    DoubleMLLPLR::se

    fn DoubleMLLPLR::se(self : DoubleMLLPLR) -> Double

    DoubleMLLPLR::sensitivity_analysis

    fn DoubleMLLPLR::sensitivity_analysis(self : DoubleMLLPLR, cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.70.0+: Cinelli & Hazlett (2020) omitted-variable bias analysis for DoubleMLLPLR (Liu-Zhang-Zhou 2021 partially logistic regression). Single-theta IRM-style decomposition:

    • Outcome residual: residuals[i] = y[i] - t_pred[i], where t_pred is the cross-fitted E[Y | D, X] nuisance persisted by fit (also surfaced via predictions_t). Same outcome-nuisance convention as the v0.66.0 DoubleMLPLR::sensitivity_analysis.

    • Per-observation Riesz representer psi_a[i]: the LPLR ATE IF denominator psi_a[i] = -d[i] * (d[i] - a_hat[i]) where a_hat is the outer cross-fitted propensity E[D | X] from predictions_a. The exact LPLR score derivative (psi_deriv(theta)) depends on the preliminary linear coefficient beta_start which the struct does not persist; the simplified -d * (d - a_hat) form captures the same IRM-style "treatment interacted with treatment-propensity residual" structure used by DoubleMLIRM for the binary-ATE score and is the convention the C&H sensitivity formula expects.

    Routes through the shared irm_style_sensitivity helper (see sensitivity.mbt). cf_y / cf_d default to 0.05 matching the rest of the v0.66.0-onward sensitivity family. Calling on an un-fit model aborts via PreconditionError.


    v0.144.0: DOCUMENTED DEVIATION -- UPSTREAM RAISES NOT IMPLEMENTED.

    This is the strongest of the three. Verified against upstream doubleml-0.11.4: plm/lplr.py sets self._sensitivity_implemented = False and its _sensitivity_element_est body is literally raise NotImplementedError(). Upstream does not merely decline to compute an LPLR sensitivity analysis -- reaching for the elements raises. This port returns a result anyway, kept for API compatibility, and it must be read as PORT-DEFINED.

    Note this is a DIFFERENT issue from the solver's discarded convergence flag (let _ = converged, further down in fit, tracked separately in v0.145.0). One concerns the sensitivity API surface; the other concerns a coefficient computed at a non-solution. Both are real, and fixing either does not address the other.

    mean(psi_a^2) below uses psi_a = -d * (d - a_hat), the simplified LPLR IF denominator, which is NOT upstream's Riesz representer. The nu2 here is not comparable to DoubleMLPLR's upstream-aligned 1 / mean(v^2).

    DoubleMLLPLR::sensitivity_analysis_cluster

    fn DoubleMLLPLR::sensitivity_analysis_cluster(self : DoubleMLLPLR, cluster_ids : Array[Int], cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.73.0+: cluster-robust analogue of DoubleMLLPLR::sensitivity_analysis. Same outcome residual y - t_pred and the same per-observation Riesz representer psi_a[i] = -d[i] * (d[i] -a_hat[i]) as the IID path; only the variance / bias computation is cluster-aware (see irm_style_sensitivity_cluster in sensitivity.mbt).

    DoubleMLBinaryData has no cluster_vars field, so the user must pass cluster_ids explicitly. cluster_ids.length() must equal self.data.n_obs().

    DoubleMLLPLR::set_sample_splitting

    fn DoubleMLLPLR::set_sample_splitting(self : DoubleMLLPLR, smpls : Array[Array[Fold]]) -> DoubleMLLPLR

    Record a caller-supplied sample splitting and DERIVE the fold and repetition counts from it. Returns a new DoubleMLLPLR; the receiver is unchanged, as everywhere in this package.

    smpls is one entry per repetition, each entry one Fold per fold -- the nested form is the only form, so a single repetition is [f0, f1, f2] wrapped once, i.e. [[f0, f1, f2]].

    The derivation is upstream's, and it is the part that surprises people: set_sample_splitting (doubleml/double_ml_sampling_mixins.py:76) sets n_folds and n_rep FROM the supplied partition, so handing a two-fold split to a model built with n_folds=5 yields a two-fold model. On the returned model n_folds / n_rep are updated to match, and fit uses the supplied folds instead of drawing them.

    Validation, via check_sample_splitting: every repetition carries the same number of folds, and within each repetition the test index sets are disjoint and cover exactly [0, n_obs). A supplied partition that is not a partition aborts rather than quietly producing a cross-fit that leaks across folds.

    Memoization: fit will not read or write the fit cache once an external splitting is recorded. The cache key is built from the data and learner hashes and has no term for the fold assignment, so two different supplied partitions would collide and the second fit would silently return the first one's predictions. The memoize_enabled flag is carried through unchanged; it is the !external term in fit that refuses the cache. The cache is also CLEARED here, so a re-fit under a new splitting cannot resurrect an entry written under the old one.

    Scope: an externally supplied splitting replaces the OUTER partition only. LPLR nests a second, inner cross-fit of n_folds_inner folds behind the preliminary Newton start (drawn at self.seed + r * 1000 + 7) and that inner split is still drawn internally, so it is NOT covered by this method. LPLR has no cluster path at all: DoubleMLBinaryData exposes no is_cluster_data() and fit runs the row-level variance path, so there is no unit-level draw to worry about either.

    The one-fold "no sample splitting" case needs no special handling: a single Fold whose train and test both cover everything is a valid partition with folds = 1, which is what upstream detects and reports.

    DoubleMLLPLR::tune

    fn DoubleMLLPLR::tune(self : DoubleMLLPLR, param_set~ : Array[TuneParam], scoring_method? : String, n_folds_tune? : Int, seed? : Int) -> DoubleMLLPLR

    Tune the (ml_g, ml_m) nuisance-learner pair via MSE-on-l_hat cross-fitting. The winning pair is re-fit on the FINAL-FIT fold partition (self.n_folds) under DoubleMLLPLR::fit; the tune-time cross-fit is not reused. scoring_method is "MSE" (default), "RMSE" or "NegMSE"; n_folds_tune defaults to 5 and seed to 3141. Returns a re-fitted DoubleMLLPLR.

    Slot semantics: LPLR is a partially linear outcome family, so the FIRST TuneParam slot is the OUTCOME learner and the second is the nuisance / propensity learner. Build the grid with TuneParam::for_outcome. Concretely the first slot becomes ml_g (routed by fit to the ml_t W-regressor slot) and the second becomes ml_m (routed to the binary-classification slots). This is worth stating because the ml_g field name reads as a propensity name -- see the learner_g / learner_m accessors, which document ml_g as the outcome-nuisance learner.

    v0.108.0: new. LPLR had no tune at all, so it was one of the estimators carrying a coverage gap against upstream, where tune reaches every estimator through the BaseDML mixin. The fold draw, the scoring loop and the argmin/argmax selection route through the shared tune_score_grid core. LPLR exposes no n_obs(), which is exactly why the core takes its observation count from y.length() rather than from an accessor.

    n_folds_inner (the per-fold inner cross-fit count behind the preliminary Newton start) is NOT a fit parameter, so there is nothing for this method to forward and nothing it can drop: fit reads self.n_folds_inner off the struct, validates it in new, and re-persists it on the returned model. The re-fit therefore uses the tuned model's own inner fold count. The grid scoring does not use n_folds_inner at all -- it uses n_folds_tune -- so changing n_folds_inner cannot change which candidate wins, only the estimate produced afterwards.

    No cluster guard: DoubleMLBinaryData exposes no is_cluster_data(), and fit states that LPLR is not cluster data and runs the row-level variance path. There is no clustered path here to mis-handle, so the guard would be unreachable at best; the method does not add the method or the guard.

    DoubleMLLPLR::warnings

    fn DoubleMLLPLR::warnings(self : DoubleMLLPLR) -> Array[String]

    Diagnostics from the most recent fit(...) call. v0.145.0+.

    THE WARNING CONVENTION, since this package has none.

    Until this release the package had no output channel of any kind -- no println, no stderr -- and that is deliberate: a numerical library that writes to the console makes its test output unreadable and its behaviour untestable. It also meant that when the LPLR Newton solver failed to reach a solution, fit discarded the flag (let _ = converged) and returned a coefficient and standard error computed at a non-solution anyway. Upstream warns here; this port had nowhere to.

    So warnings are RETURNED, not emitted. The caller asks:

    let model = DoubleMLLPLR::new(data).fit()
    for w in model.warnings() {
    println(w) // the CALLER decides whether to print
    }

    That keeps the library silent, keeps the condition observable, and keeps it testable -- a gate can assert that a degenerate design produces a warning and a healthy one does not.

    ONE ENTRY PER FAILED REPETITION, and the text names WHICH failure, because the three are different problems:

    stop_reasonmeaning
    degenerate_derivative|d psi / d theta| < 1e-300 -- the Jacobian vanished, so the Newton direction is undefined
    divergedthe iterate passed 1e6 and was abandoned
    exhausted_step_budgetall 50 damped-Newton steps were used without meeting the 1e-9 step tolerance

    A non-empty result means coef() and se() are not an estimate and its standard error. Note that se() is computed as sqrt(gamma / (j^2 * n)) with j = mean(psi_deriv), so a non-solution point can yield a deceptively SMALL standard error rather than a conspicuously large one -- the failure does not look like a failure.

    DoubleMLLPQ

    pub struct DoubleMLLPQ {
    data : DoubleMLLPQData
    treatment : Double
    quantile : Double
    n_folds : Int
    seed : Int
    propensity_clip : Double
    ps_processor_config : PSProcessorConfig
    coef : Double
    se : Double
    fitted : Bool
    predictions_g0 : Array[Double]
    predictions_g1 : Array[Double]
    predictions_m : Array[Double]
    psi : Array[Double]
    psi_a : Array[Double]
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    fit_cache : FitCache
    } derive(
    Debug
    )

    DoubleMLLPQ::bias_corrected_coef

    fn DoubleMLLPQ::bias_corrected_coef(self : DoubleMLLPQ) -> Double

    v0.93.0+: returns coef UNCHANGED -- a documented no-op, not a bias correction. Identical in reasoning to the thirteen bias_corrected_coef methods added in v0.86.0 - v0.92.0; see DoubleMLIRM::bias_corrected_coef and bias_corrected_theta in sandwich.mbt for the full argument.

    coef is the bisection root of the LPQ quantile moment mean(psi_ipw(theta)) = 0. That estimating function is orthogonal at its root by construction -- and that orthogonality IS what makes the estimator consistent -- so no correction built from the fitted scores is a bias estimate for this class of estimator. This accessor therefore reports the uncorrected point estimate rather than a number that merely looks like a correction.

    The pre-v0.91.0 form coef + mean(psi_b - coef * psi_a) is algebraically 3 * coef for a constant-psi_a estimator and is not a bias estimate for ANY of them; the v0.91.0 argument applies here unchanged.

    Preconditions: self.fitted.

    DoubleMLLPQ::bootstrap

    fn DoubleMLLPQ::bootstrap(self : DoubleMLLPQ, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLLPQ

    v0.64.0+: multiplier bootstrap for DoubleMLLPQ. The per-observation influence function psi is the centered score at the bisection root (mean 0, se_psi =sqrt(mean(psi^2)) is the bootstrap denominator). Routes through the shared generic_bootstrap_single_psi helper (see bootstrap_helper.mbt).

    method_name selects the multiplier distribution: "normal" (default), "Bayes", "wild". seed defaults to 2024; n_rep_boot defaults to 500.

    Calling on an un-fit model aborts via PreconditionError.

    DoubleMLLPQ::clear_cache

    fn DoubleMLLPQ::clear_cache(self : DoubleMLLPQ) -> DoubleMLLPQ

    v0.82.0+: drop any cached nuisance predictions.

    DoubleMLLPQ::cluster_sandwich_se

    fn DoubleMLLPQ::cluster_sandwich_se(self : DoubleMLLPQ, cluster_ids : Array[Int]) -> Double

    v0.93.0+: cluster-robust sandwich standard error for the fitted LPQ (Arellano 1987, Cameron-Gelbach-Miller 2011). Routes through cluster_sandwich_variance with the SAME self.psi and M_inv inputs as the IID sandwich_se path -- see the section comment above for why those are not the ordinary (psi_at(...),1/mean(psi_a)) pair.

    DoubleMLLPQData carries no cluster_vars, so the caller must supply cluster_ids explicitly (any grouping variable the application has: region, site, panel unit). With all-singleton clusters the meat degenerates to sum_i psi[i]^2 and the formula collapses to sandwich_se(HC0), hence to se().

    Preconditions: self.fitted, |psi_a[0]| >= 1e-12, cluster_ids.length() == psi.length().

    DoubleMLLPQ::coef

    fn DoubleMLLPQ::coef(self : DoubleMLLPQ) -> Double

    DoubleMLLPQ::confint

    fn DoubleMLLPQ::confint(self : DoubleMLLPQ, joint? : Bool, level? : Double) -> (Double, Double)

    95% Wald confidence interval (z = 1.959963984540054). Matches the DoubleMLLPLR::confint idiom byte-for-byte. v0.67.0+: joint is a no-op for single-theta estimators.

    DoubleMLLPQ::disable_memoize

    fn DoubleMLLPQ::disable_memoize(self : DoubleMLLPQ) -> DoubleMLLPQ

    v0.82.0+: turn off memoization.

    DoubleMLLPQ::enable_memoize

    fn DoubleMLLPQ::enable_memoize(self : DoubleMLLPQ) -> DoubleMLLPQ

    v0.82.0+: turn on memoization for subsequent fit() calls.

    DoubleMLLPQ::fit

    DoubleMLLPQ::has_cache

    fn DoubleMLLPQ::has_cache(self : DoubleMLLPQ) -> Bool

    v0.82.0+: true iff fit_cache holds at least one cached observation.

    DoubleMLLPQ::n_features

    fn DoubleMLLPQ::n_features(self : DoubleMLLPQ) -> Int

    Number of features (covariate columns).

    DoubleMLLPQ::n_obs

    fn DoubleMLLPQ::n_obs(self : DoubleMLLPQ) -> Int

    Number of observations.

    DoubleMLLPQ::new

    fn DoubleMLLPQ::new(data : DoubleMLLPQData, treatment? : Double, quantile? : Double, n_folds? : Int, seed? : Int, propensity_clip? : Double, ps_processor_config? : PSProcessorConfig?) -> DoubleMLLPQ

    DoubleMLLPQ::predictions_g0

    fn DoubleMLLPQ::predictions_g0(self : DoubleMLLPQ) -> Array[Double]

    Cross-fitted outcome nuisance for Z=0 (length n_obs). v0.53.0-dev: matches upstream DoubleMLLPQ.predictions["g0"].

    DoubleMLLPQ::predictions_g1

    fn DoubleMLLPQ::predictions_g1(self : DoubleMLLPQ) -> Array[Double]

    Cross-fitted outcome nuisance for Z=1 (length n_obs). v0.53.0-dev: matches upstream DoubleMLLPQ.predictions["g1"].

    DoubleMLLPQ::predictions_m

    fn DoubleMLLPQ::predictions_m(self : DoubleMLLPQ) -> Array[Double]

    Cross-fitted treatment nuisance (propensity score, length n_obs). v0.53.0-dev: matches upstream DoubleMLLPQ.predictions["m"].

    DoubleMLLPQ::sandwich_se

    fn DoubleMLLPQ::sandwich_se(self : DoubleMLLPQ, kind : SandwichKind) -> Double

    v0.93.0+: heteroskedasticity-consistent (Huber-White) sandwich standard error for the fitted LPQ. Routes through the shared sandwich_variance dispatch, so the HC0 / HC1 / HC2 / HC3 relationships are the package-wide ones (see the file header in sandwich.mbt and the identities pinned in expand_v088_test.mbt).

    The two inputs are NOT the usual (psi_at(...), 1/mean(psi_a)) pair, and the deviation is deliberate -- see the section comment above. self.psi is used AS the score (it is already evaluated at coef; there is no psi_b to reconstruct it from, and psi_at would evaluate a different function whose root is not coef), and the Jacobian is the persisted data-dependent deriv in self.psi_a[0], NOT the constant -1.

    n_obs is self.psi.length(), the full sample: LPQ has no transformed or subset domain.

    Preconditions: self.fitted, |psi_a[0]| >= 1e-12.

    DoubleMLLPQ::se

    fn DoubleMLLPQ::se(self : DoubleMLLPQ) -> Double

    DoubleMLLPQ::sensitivity_analysis

    fn DoubleMLLPQ::sensitivity_analysis(self : DoubleMLLPQ, cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.67.0+: Cinelli & Hazlett (2020) omitted-variable bias analysis for the LPQ (Local Quantile) estimator. The IF psi is centered (mean 0 at the bisection root); nu2 = mean(psi^2) and sigma2 = Var(y). Routes through the shared single_psi_sensitivity helper (see sensitivity.mbt).

    DoubleMLLPQ::sensitivity_analysis_cluster

    fn DoubleMLLPQ::sensitivity_analysis_cluster(self : DoubleMLLPQ, cluster_ids : Array[Int], cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.74.0+: cluster-robust analogue of DoubleMLLPQ::sensitivity_analysis. The IID path uses the centered-IF formulation (sigma2 = Var(y), nu2 = mean(psi^2)); we replicate that here by routing through irm_style_sensitivity_cluster with residuals = y - mean(y) (so mean(residuals^2) =Var(y)) and psi_a = psi (so mean(psi_a^2) =mean(psi^2)); the IRM-style helper's per-obs C&H max_bias is identical to single_psi_sensitivity's in this case. Only the variance / bias computation is cluster-aware (sigma2_cluster and nu2_cluster are the G / n_clusters sums of squared cluster sums).

    DoubleMLLPQData has no cluster_vars field, so the user must pass cluster_ids explicitly. cluster_ids.length() must equal self.data.n_obs(). Cluster indices are 0-based; 1 + max(cluster_ids) is the number of clusters.

    DoubleMLLPQData

    pub struct DoubleMLLPQData {
    x : Matrix
    y : Array[Double]
    d : Array[Double]
    z : Array[Double]
    } derive(
    Debug
    )

    DoubleMLLPQData::new

    fn DoubleMLLPQData::new(x : Matrix, y : Array[Double], d : Array[Double], z : Array[Double]) -> DoubleMLLPQData

    DoubleMLPLIV

    pub struct DoubleMLPLIV {
    data : DoubleMLPLIVData
    n_folds : Int
    n_rep : Int
    seed : Int
    smpls : Array[Array[Fold]]
    learner : LearnerDispatch
    l_hat : Array[Double]
    r_hat : Array[Double]
    m_hat : Array[Double]
    coef : Double
    se : Double
    fitted : Bool
    psi_a : Array[Double]
    psi_b : Array[Double]
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    fit_cache : FitCache
    } derive(
    Debug
    )

    Double / debiased machine learning estimator for the partially linear IV regression model (PLIV) of Chernozhukov et al. (2018) with the partialling out score:

    Y = D * theta_0 + g_0(X) + zeta, E[zeta | D, X] = 0 D = m_0(X) + V, E[V | X] = 0 Z = ell_0(X) + xi, E[xi | X] = 0, Cov(Z, V) != 0 (relevance)

    with the partialling out (single-instrument) score

    l_hat = E_hat[Y | X] r_hat = E_hat[D | X] m_hat = E_hat[Z | X] u_hat = Y - l_hat w_hat = D - r_hat v_hat = Z - m_hat psi_a = -w_hat * v_hat psi_b = v_hat * u_hat psi(theta) = theta * psi_a + psi_b

    with point estimate and variance

    theta_hat = -mean(psi_b) / mean(psi_a) = mean(v_hat * u_hat) / mean(w_hat * v_hat) J = mean(psi_a) gamma = mean(psi(theta_hat)^2) sigma2 = gamma / (J^2 * n) se = sqrt(sigma2).

    The port supports only a single instrument and the partialling out score (the IV-type score, which would need an additional ml_g learner, is not implemented). All three nuisance functions are estimated with the same closed-form LinearRegression learner.

    DoubleMLPLIV::bias_corrected_coef

    fn DoubleMLPLIV::bias_corrected_coef(self : DoubleMLPLIV) -> Double

    v0.91.0+: returns coef UNCHANGED -- a documented no-op, not a bias correction.

    coef is the root of the DML moment f(theta) = E[theta * psi_a + psi_b] (see var_est.mbt), so mean(f(coef)) is identically zero: the estimating function is orthogonal by construction, and that orthogonality IS what makes the estimator consistent. Nothing computable from the fitted scores is a bias estimate for this class of estimator, so this accessor reports the uncorrected point estimate rather than a number that merely looks like a correction.

    v0.79.0 - v0.90.0 returned coef + mean(psi_b - coef * psi_a). That vector is the score at -coef, NOT at coef; since coef = -mean_b / mean_a its mean is mean_b - coef * mean_a = -2 * coef * mean_a, so the accessor returned coef * (1 - 2 * mean(psi_a)) (exactly 3 * coef when mean(psi_a) = -1). That is not a bias estimate. See bias_corrected_theta in sandwich.mbt for the algebra. The method is kept so the API surface stays stable; removing it outright is the obvious follow-up.

    Preconditions: self.fitted.

    DoubleMLPLIV::bootstrap

    fn DoubleMLPLIV::bootstrap(self : DoubleMLPLIV, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLPLIV

    v0.61.0+: multiplier bootstrap for DoubleMLPLIV. The per-observation influence function is

    psi[i] = theta * psi_a[i] + psi_b[i] = -wv + theta * vu

    where w = d - r_hat, v = z - m_hat, u = y - l_hat are computed at the fitted coef from the last rep's cross-fitted nuisances l_hat / r_hat / m_hat. Draws n_rep_boot weight vectors of length n_obs from the chosen multiplier distribution, and returns a fitted model with boot_t_stat[b] = sum_i w[b, i] * psi[i] /(sqrt(n) * se_psi) populated where se_psi = sqrt(mean(psi^2)).

    method_name selects the multiplier distribution:
    • "normal" (default): w[i] ~ N(0, 1).
    • "Bayes": w[i] = exp(1) - 1 (mean 0, var 1).
    • "wild": w[i] = x[i] / sqrt(2) + (y[i]^2 - 1) / 2 with x, y ~ N(0, 1).

    Calling bootstrap requires the model to be fitted; calling on an un-fit model aborts with PreconditionError. The helper is did_bootstrap_t_stat (v0.55.0 extracted from DoubleMLDIDCrossSection::bootstrap); PLIV is the n_thetas=1 case.

    DoubleMLPLIV::clear_cache

    fn DoubleMLPLIV::clear_cache(self : DoubleMLPLIV) -> DoubleMLPLIV

    v0.82.0+: drop any cached nuisance predictions and fold assignment.

    DoubleMLPLIV::cluster_sandwich_se

    fn DoubleMLPLIV::cluster_sandwich_se(self : DoubleMLPLIV, cluster_ids : Array[Int]) -> Double

    v0.86.0+: cluster-robust sandwich standard error for the fitted PLIV. Routes through cluster_sandwich_variance with the same psi_a / psi / M_inv inputs as the IID sandwich_se path.

    Preconditions: self.fitted, cluster_ids.length() == n_obs.

    DoubleMLPLIV::coef

    fn DoubleMLPLIV::coef(self : DoubleMLPLIV) -> Double

    DoubleMLPLIV::confint

    fn DoubleMLPLIV::confint(self : DoubleMLPLIV, joint? : Bool, level? : Double) -> (Double, Double)

    v0.67.0+: joint is a no-op for single-theta estimators; accepted for API parity.

    DoubleMLPLIV::disable_memoize

    fn DoubleMLPLIV::disable_memoize(self : DoubleMLPLIV) -> DoubleMLPLIV

    v0.82.0+: turn off memoization.

    DoubleMLPLIV::enable_memoize

    fn DoubleMLPLIV::enable_memoize(self : DoubleMLPLIV) -> DoubleMLPLIV

    v0.82.0+: turn on memoization for subsequent fit() calls. Returns a new DoubleMLPLIV with the flag set (the struct is immutable; the cache itself is populated by the next fit() call).

    DoubleMLPLIV::fit

    fn DoubleMLPLIV::fit(self : DoubleMLPLIV, learner? : LearnerDispatch, max_attempts? : Int) -> DoubleMLPLIV

    Run the PLIV estimation. The default learner is a closed-form LinearRegression; a different Learner can be supplied for experiments. The result is stored on the object and the object is returned for chaining.

    Per-repetition behaviour: each repetition r cross-fits the l / r / m nuisances from its own folds (seed self.seed + r), computes its own (theta_r, se_r) from the partialling-out single-instrument score, and the two arrays are then aggregated by aggregate_coef_se (median of thetas, then SE from the median of (theta_r + 1.96 * se_r)). For n_rep == 1 the aggregator returns the single (theta_1, se_1) exactly, so the byte-equality with the previous "average then estimate" implementation is preserved. The predictions_l / r / m accessors return the nuisances from the last repetition (the conventional choice in upstream doubleml), not a cross-rep average.

    DoubleMLPLIV::has_cache

    fn DoubleMLPLIV::has_cache(self : DoubleMLPLIV) -> Bool

    v0.82.0+: true iff fit_cache holds at least one cached observation.

    DoubleMLPLIV::n_obs

    fn DoubleMLPLIV::n_obs(self : DoubleMLPLIV) -> Int

    DoubleMLPLIV::new

    fn DoubleMLPLIV::new(data : DoubleMLPLIVData, n_folds? : Int, n_rep? : Int, seed? : Int, learner? : LearnerDispatch) -> DoubleMLPLIV

    DoubleMLPLIV::predictions_l

    fn DoubleMLPLIV::predictions_l(self : DoubleMLPLIV) -> Array[Double]

    DoubleMLPLIV::predictions_m

    fn DoubleMLPLIV::predictions_m(self : DoubleMLPLIV) -> Array[Double]

    DoubleMLPLIV::predictions_r

    fn DoubleMLPLIV::predictions_r(self : DoubleMLPLIV) -> Array[Double]

    DoubleMLPLIV::sample_splitting

    fn DoubleMLPLIV::sample_splitting(self : DoubleMLPLIV) -> SampleSplitting?

    The sample splitting recorded by set_sample_splitting, or None when none was supplied and fit draws its own. Some carries the DERIVED counts next to the folds, so a caller can read back what the estimator actually used rather than inferring it from the constructor arguments it no longer has any say over.

    DoubleMLPLIV::sandwich_se

    fn DoubleMLPLIV::sandwich_se(self : DoubleMLPLIV, kind : SandwichKind) -> Double

    v0.86.0+: Huber-White sandwich standard error for the fitted PLIV. Returns sqrt(var) where var comes from the shared sandwich_variance(kind, ...) dispatch in sandwich.mbt (HC0 / HC1 / HC2 / HC3).

    The three inputs are the ones fit(...) already persists for the multiplier bootstrap (see the psi_a / psi_b field docs on DoubleMLPLIV):
    • psi_a = self.psi_a -- the partialling-out treatment score -w_hat * v_hat with w_hat = d - r_hat, v_hat = z - m_hat.
    • psi = psi_at(self.coef, self.psi_a, self.psi_b) -- the per-observation influence function evaluated at the fitted coef, where psi_b = v_hat * u_hat is the partialling-out outcome score with u_hat = y - l_hat. Same psi_at score order as IRM / PLR.
    • M_inv = [[1 / mean(psi_a)]] (1x1). Only M_inv[0, 0]^2 enters the variance, so the sign of the (up-to-sign) Jacobian inverse is irrelevant.

    Preconditions: self.fitted, mean(psi_a) != 0.

    DoubleMLPLIV::se

    fn DoubleMLPLIV::se(self : DoubleMLPLIV) -> Double

    DoubleMLPLIV::sensitivity_analysis

    fn DoubleMLPLIV::sensitivity_analysis(self : DoubleMLPLIV, cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.66.0+: Cinelli & Hazlett (2020) omitted-variable bias analysis. Outcome residual is y - l_hat; the Riesz-representer variance is mean(psi_a^2) where psi_a = -w * v for the partialling-out IV score (w = d - r_hat, v = z - m_hat). Routes through the shared irm_style_sensitivity helper.


    v0.144.0: DOCUMENTED DEVIATION -- UPSTREAM DOES NOT IMPLEMENT THIS.

    Verified against upstream doubleml-0.11.4: DoubleML.sensitivity_analysis is guarded by if self._sensitivity_implemented:, whose base default is False, and plm/pliv.py never sets it. DoubleMLPLIV._sensitivity_element_est is pass. So upstream REFUSES this analysis for PLIV, while this port returns a number. There is therefore no upstream formula to conform to, and no correct-by-construction value this function could be changed to.

    The port keeps the result because it is a working IRM-style decomposition and callers depend on it, but it must be read as a PORT-DEFINED quantity. In particular mean(psi_a^2) with psi_a = -w * v is the square of the DML SCORE ELEMENT, not the C&H Riesz representer -- the same conflation that DoubleMLPLR carried until v0.144.0 corrected it. Do not treat the nu2 here as comparable to DoubleMLPLR's, which is now upstream's 1 / mean(v^2).

    Sibling cases, same upstream verdict: DoubleMLPLPR (_sensitivity_implemented = False, _sensitivity_element_est is pass) and DoubleMLLPLR (_sensitivity_implemented = False, and _sensitivity_element_est raise NotImplementedError()). DoubleMLPLR is the only one of the four upstream implements.

    DoubleMLPLIV::sensitivity_analysis_cluster

    fn DoubleMLPLIV::sensitivity_analysis_cluster(self : DoubleMLPLIV, cluster_ids? : Array[Int], cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.72.0+: cluster-robust analogue of DoubleMLPLIV::sensitivity_analysis. Same residual formula (y - l_hat) and the same psi_a = -w * v (partialling-out IV score) as the IID path; only the variance / bias computation is cluster-aware. cluster_ids defaults to DoubleMLData::cluster_vars.

    DoubleMLPLIV::set_sample_splitting

    fn DoubleMLPLIV::set_sample_splitting(self : DoubleMLPLIV, smpls : Array[Array[Fold]]) -> DoubleMLPLIV

    Record a caller-supplied sample splitting and DERIVE the fold and repetition counts from it. Returns a new DoubleMLPLIV; the receiver is unchanged, as everywhere in this package.

    smpls is one entry per repetition, each entry one Fold per fold -- the nested form is the only form, so a single repetition is [f0, f1, f2] wrapped once, i.e. [[f0, f1, f2]].

    The derivation is upstream's, and it is the part that surprises people: set_sample_splitting (doubleml/double_ml_sampling_mixins.py:76) sets n_folds and n_rep FROM the supplied partition, so handing a two-fold split to a model built with n_folds=5 yields a two-fold model. On the returned model n_folds / n_rep are updated to match, and fit uses the supplied folds instead of drawing them.

    Validation, via check_sample_splitting: every repetition carries the same number of folds, and within each repetition the test index sets are disjoint and cover exactly [0, n_obs). A supplied partition that is not a partition aborts rather than quietly producing a cross-fit that leaks across folds.

    Memoization: fit will not read or write the fit cache once an external splitting is recorded. The cache key is built from the data, learner and cluster hashes and has no term for the fold assignment, so two different supplied partitions would collide and the second fit would silently return the first one's predictions. The memoize_enabled flag is carried through unchanged; it is the !external term in fit that refuses the cache. The cache is also CLEARED here, so a re-fit under a new splitting cannot resurrect an entry written under the old one.

    Cluster path: an externally supplied splitting applies to the ROW-level path only. fit_cluster draws UNIT-level folds over the unique cluster ids and expands them to rows, so a supplied row-level partition is not consulted there and a clustered fit keeps drawing its own unit-level folds. Making the cluster path honour external splits is a separate decision and out of scope here; the field is carried across so the row-level path resumes the supplied splitting on a later non-cluster fit.

    The one-fold "no sample splitting" case needs no special handling: a single Fold whose train and test both cover everything is a valid partition with folds = 1, which is what upstream detects and reports.

    DoubleMLPLIV::tune

    fn DoubleMLPLIV::tune(self : DoubleMLPLIV, param_set~ : Array[LearnerDispatch], scoring_method? : String, n_folds_tune? : Int, seed? : Int) -> DoubleMLPLIV

    v0.65.0+: tune the single nuisance learner (used for all three nuisances l / r / m) via MSE-on-l_hat cross-fitting (matches DoubleMLPLR::tune's MSE-on-l_hat scoring convention; see tune.mbt §4.1). The chosen learner is then re-fit on the FINAL-FIT fold partition (self.n_folds) under DoubleMLPLIV::fit. Cluster-DML is not supported in tune (mirrors the PLR behaviour — tune requires !self.data.is_cluster_data()).

    param_set is an Array[LearnerDispatch] (each entry is a candidate nuisance learner; PLIV has only one nuisance slot so the TuneParam wrapper is unnecessary). Returns a re-fitted DoubleMLPLIV with the chosen learner applied via the learner field. scoring_method is "MSE" (default), "RMSE", or "NegMSE".

    DoubleMLPLIVData

    pub struct DoubleMLPLIVData {
    x : Matrix
    y : Array[Double]
    d : Array[Double]
    z : Array[Double]
    cluster_vars : Array[Int]
    } derive(
    Debug
    )

    Data container for DoubleMLPLIV. In addition to the covariates x, the outcome y and the treatment d, PLIV needs an instrumental variable z. The port supports a single instrument (1-D array) — the multi-instrument case is not implemented.

    DoubleMLPLIVData::is_cluster_data

    fn DoubleMLPLIVData::is_cluster_data(self : DoubleMLPLIVData) -> Bool

    True iff the data is set up for clustered inference (a non-empty cluster_vars vector was passed to DoubleMLPLIVData::new).

    DoubleMLPLIVData::n_cluster_vars

    fn DoubleMLPLIVData::n_cluster_vars(self : DoubleMLPLIVData) -> Int

    Length of the cluster_vars vector (0 when not clustered).

    DoubleMLPLIVData::n_features

    fn DoubleMLPLIVData::n_features(self : DoubleMLPLIVData) -> Int

    Number of features.

    DoubleMLPLIVData::n_obs

    fn DoubleMLPLIVData::n_obs(self : DoubleMLPLIVData) -> Int

    Number of observations.

    DoubleMLPLIVData::new

    fn DoubleMLPLIVData::new(x : Matrix, y : Array[Double], d : Array[Double], z : Array[Double], cluster_vars? : Array[Int]) -> DoubleMLPLIVData

    Build a DoubleMLPLIVData from an n x p feature matrix, an outcome vector of length n, a treatment vector of length n and an instrument vector of length n.

    DoubleMLPLPR

    pub struct DoubleMLPLPR {
    panel : DoubleMLPanelData
    approach : String
    score : String
    n_folds : Int
    n_rep : Int
    seed : Int
    learner : LearnerDispatch
    coef_ : Double
    se_ : Double
    l_hat : Array[Double]
    m_hat : Array[Double]
    fitted : Bool
    psi_a : Array[Double]
    psi_b : Array[Double]
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    fit_cache : FitCache
    } derive(
    Debug
    )

    DoubleMLPLPR model. See the struct docs on DoubleMLPanelData and transform_panel for the four approaches. Scores: "partialling out" (default) or "IV-type" (fits an extra g-nuisance on y - theta_initial * d exactly like upstream).

    DoubleMLPLPR::bias_corrected_coef

    fn DoubleMLPLPR::bias_corrected_coef(self : DoubleMLPLPR) -> Double

    v0.91.0+: returns coef UNCHANGED -- a documented no-op, not a bias correction.

    coef is the root of the DML moment f(theta) = E[theta * psi_a + psi_b] (see var_est.mbt), so mean(f(coef)) is identically zero: the estimating function is orthogonal by construction, and that orthogonality IS what makes the estimator consistent. Nothing computable from the fitted scores is a bias estimate for this class of estimator, so this accessor reports the uncorrected point estimate rather than a number that merely looks like a correction.

    v0.79.0 - v0.90.0 returned coef + mean(psi_b - coef * psi_a). That vector is the score at -coef, NOT at coef; since coef = -mean_b / mean_a its mean is mean_b - coef * mean_a = -2 * coef * mean_a, so the accessor returned coef * (1 - 2 * mean(psi_a)) (exactly 3 * coef when mean(psi_a) = -1). That is not a bias estimate. See bias_corrected_theta in sandwich.mbt for the algebra. The method is kept so the API surface stays stable; removing it outright is the obvious follow-up.

    Preconditions: self.fitted.

    DoubleMLPLPR::bootstrap

    fn DoubleMLPLPR::bootstrap(self : DoubleMLPLPR, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLPLPR

    v0.75.0+: multiplier bootstrap for DoubleMLPLPR. The per-observation influence function is

    psi[i] = theta * psi_a[i] + psi_b[i]

    where psi_a[i] (PO: -v_hat[i]^2; IV-type: -v_hat[i] * d[i]) and psi_b[i] (PO: v_hat[i] * u_hat[i]; IV-type: v_hat[i] * (y[i] - g_pred[i])) are populated by fit(...) from the LAST rep's cross-fitted nuisances on the TRANSFORMED-domain sample. Note that this is an IID bootstrap (multipliers drawn independently of transform_panel's clustering); the cluster-aware variance comes from the var_est_cluster call inside fit(...), not from the multiplier weights.

    method_name selects the multiplier distribution: "normal" (default), "Bayes", "wild"; seed defaults to 2024; n_rep_boot defaults to 500.

    Calling on an un-fit model aborts via PreconditionError. Returns a new DoubleMLPLPR with boot_t_stat / boot_method / n_rep_boot / boot_seed populated.

    DoubleMLPLPR::clear_cache

    fn DoubleMLPLPR::clear_cache(self : DoubleMLPLPR) -> DoubleMLPLPR

    v0.83.0+: drop any cached nuisance predictions and fold assignment. Forces the next fit() to recompute from scratch.

    DoubleMLPLPR::cluster_sandwich_se

    fn DoubleMLPLPR::cluster_sandwich_se(self : DoubleMLPLPR, cluster_ids : Array[Int]) -> Double

    v0.87.0+: cluster-robust sandwich standard error for the fitted PLPR. Routes through cluster_sandwich_variance with the same psi_a / psi / M_inv inputs as the IID sandwich_se path. DoubleMLPanelData carries no cluster_vars field, so the user must pass cluster_ids explicitly (typically the panel unit id).

    Note: PLPR's own se is already unit-clustered (it uses the fold-level cluster sums); this method exposes the generic cluster-robust sandwich on the same sample so the two can be compared on a common footing.

    Preconditions: self.fitted, cluster_ids.length() == psi_a.length().

    DoubleMLPLPR::coef

    fn DoubleMLPLPR::coef(self : DoubleMLPLPR) -> Double

    DoubleMLPLPR::confint

    fn DoubleMLPLPR::confint(self : DoubleMLPLPR) -> (Double, Double)

    DoubleMLPLPR::disable_memoize

    fn DoubleMLPLPR::disable_memoize(self : DoubleMLPLPR) -> DoubleMLPLPR

    v0.83.0+: turn off memoization. Same immutability contract as enable_memoize(). After this, fit() will not read or write the cache; the existing fit_cache is preserved on the returned struct (call clear_cache() to drop it).

    DoubleMLPLPR::enable_memoize

    fn DoubleMLPLPR::enable_memoize(self : DoubleMLPLPR) -> DoubleMLPLPR

    v0.83.0+: turn on memoization for subsequent fit() calls. When enabled, fit() will cache the LAST rep's cross- fitted (l_hat, m_hat) and the row-to-fold mapping; on a repeat call whose panel fingerprint + fold split + learner + approach + score is identical, the entire per-fold crossfit is skipped and the cached values feed the cluster-robust score / SE pipeline.

    enable_memoize() is honored only when n_rep == 1; for n_rep > 1 the per-rep cross-fit must run each time (the cache would otherwise need to thread n_rep independent per-rep nuisance arrays, which the FitCache layout does not accommodate).

    Default is OFF. When OFF, every fit() call runs the full cross-fit and the cache is neither read nor written, so v0.82.0 callers see byte-identical output.

    DoubleMLPLPR::fit

    fn DoubleMLPLPR::fit(self : DoubleMLPLPR, learner? : LearnerDispatch, max_attempts? : Int) -> DoubleMLPLPR

    Fit the DML estimator. Runs the standard cross-fit PO or IV-type score on the transformed data, including upstream's cre_general post-hoc m_hat adjustment and the clustered inference path (unit-level folds, fold-weighted coefficient, cluster-robust SE).

    DoubleMLPLPR::has_cache

    fn DoubleMLPLPR::has_cache(self : DoubleMLPLPR) -> Bool

    v0.83.0+: true iff fit_cache holds at least one cached observation (i.e. at least one prior fit() call with memoize_enabled = true has populated the cache). Note that the cache may still be stale relative to the current panel + learner configuration -- check memoize_enabled before assuming a cache hit.

    DoubleMLPLPR::new

    fn DoubleMLPLPR::new(panel : DoubleMLPanelData, approach? : String, score? : String, n_folds? : Int, n_rep? : Int, seed? : Int, learner? : LearnerDispatch) -> DoubleMLPLPR

    DoubleMLPLPR::predictions_l

    fn DoubleMLPLPR::predictions_l(self : DoubleMLPLPR) -> Array[Double]

    Cross-fitted E[Y | X'] from the last repetition.

    DoubleMLPLPR::predictions_m

    fn DoubleMLPLPR::predictions_m(self : DoubleMLPLPR) -> Array[Double]

    Cross-fitted E[D | X'] (after any cre adjustment) from the last repetition.

    DoubleMLPLPR::sandwich_se

    fn DoubleMLPLPR::sandwich_se(self : DoubleMLPLPR, kind : SandwichKind) -> Double

    v0.87.0+: Huber-White sandwich standard error for the fitted PLPR. Returns sqrt(var) where var comes from the shared sandwich_variance(kind, ...) dispatch in sandwich.mbt (HC0 / HC1 / HC2 / HC3), the same dispatch DoubleMLDID / DoubleMLIIVM / DoubleMLCVAR use.

    The three inputs are the ones fit(...) already persists for the multiplier bootstrap (see the psi_a / psi_b field docs on DoubleMLPLPR):
    • psi_a = self.psi_a -- the score derivative in theta (partialling-out: -v_hat[i]^2; IV-type: -v_hat[i] * d[i]). Under the default PO score every element is <= 0, so mean(psi_a) <= 0.
    • psi = psi_at(self.coef_, self.psi_a, self.psi_b) -- the per-observation influence function at the fitted coef, matching the psi[i] = psi_a[i] +theta * psi_b[i] form documented on DoubleMLPLPR::bootstrap.
    • M_inv = [[1 / mean(psi_a)]] (1x1). Only M_inv[0, 0]^2 enters the variance, so the sign of the (up-to-sign) Jacobian inverse is irrelevant.

    Note the sample length: psi_a / psi_b live on the TRANSFORMED-domain sample, so the variance's n_obs is self.psi_a.length() (= self.l_hat.length()), which equals self.data.n_obs() for the untransformed approaches and can differ once an fd_exact / within_transform approach changes the row set. The variance's n_obs therefore follows psi_a, never the raw panel width.

    Preconditions: self.fitted, mean(psi_a) != 0.

    DoubleMLPLPR::se

    fn DoubleMLPLPR::se(self : DoubleMLPLPR) -> Double

    DoubleMLPLPR::sensitivity_analysis

    fn DoubleMLPLPR::sensitivity_analysis(self : DoubleMLPLPR, cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.70.0+: Cinelli & Hazlett (2020) omitted-variable bias analysis for DoubleMLPLPR (Clarke & Polselli 2025 panel partialling-out / IV-type). Single-theta IRM-style decomposition: outcome residual is y - l_hat (the cross-fitted outcome nuisance from the last rep; the same convention used by the v0.66.0 DoubleMLPLR::sensitivity_analysis); the per-observation Riesz representer psi_a is the score derivative w.r.t. theta, recomputed on-the-fly from the stored (d, l_hat, m_hat) to avoid growing the struct shape:

    • "partialling out" score (default): psi_a[i] = -v_hat[i] * v_hat[i] where v_hat[i] = d[i] - m_hat[i].
    • "IV-type" score: psi_a[i] = -v_hat[i] * d[i]

    (matches the per-iteration psi_a definitions used by est_coef_cluster / var_est_cluster inside fit).

    The score branch is selected from self.score so the sensitivity decomposition stays consistent with the score actually used to fit the model.

    cf_y / cf_d default to 0.05 matching the rest of the v0.66.0-onward sensitivity family. Calling on an un-fit model aborts via PreconditionError.


    v0.144.0: DOCUMENTED DEVIATION -- UPSTREAM EXPLICITLY REFUSES THIS.

    Verified against upstream doubleml-0.11.4: plm/plpr.py sets self._sensitivity_implemented = False and its _sensitivity_element_est body is pass. Upstream's DoubleML.sensitivity_analysis is guarded on that flag and therefore does not perform a PLPR sensitivity analysis at all. There is no upstream formula to conform to.

    This port returns a result regardless, kept for API compatibility. Read it as PORT-DEFINED. mean(psi_a^2) below uses psi_a = -v_hat^2 (the DML score element) where the C&H construction wants the Riesz representer -- the same conflation DoubleMLPLR carried until v0.144.0 corrected it, and so the nu2 here is NOT comparable to DoubleMLPLR's upstream-aligned 1 / mean(v^2). No gate asserts a value for PLPR, because there is no value to assert.

    DoubleMLPLPR::sensitivity_analysis_cluster

    fn DoubleMLPLPR::sensitivity_analysis_cluster(self : DoubleMLPLPR, cluster_ids : Array[Int], cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.73.0+: cluster-robust analogue of DoubleMLPLPR::sensitivity_analysis. Same partialling-out / IV-type residual form y - l_hat and the same per-observation Riesz representer (PO: -v_hat^2; IV-type: -v_hat * d) as the IID path; only the variance / bias computation is cluster-aware (see irm_style_sensitivity_cluster in sensitivity.mbt).

    cluster_ids MUST be in the TRANSFORMED domain (length self.l_hat.length()), not the raw panel length (self.panel.y.length()). plpr's fit() applies transform_panel to the raw panel -- for example, fd_exact drops the first period -- and l_hat / m_hat are indexed against the transformed cross- section. The user must pre-drop rows from cluster_ids matching transform_panel's drop logic (e.g., drop rows where t == 0 for fd_exact on a 0-indexed time grid). The DGP is balanced enough that dropping by (t == 0) works in practice.

    DoubleMLPanelData has no cluster_vars field, so the user must pass cluster_ids explicitly.

    DoubleMLPLPR::tune

    fn DoubleMLPLPR::tune(self : DoubleMLPLPR, param_set~ : Array[LearnerDispatch], scoring_method? : String, n_folds_tune? : Int, seed? : Int) -> DoubleMLPLPR

    Tune the single nuisance learner via MSE-on-l_hat cross-fitting. The winning learner is re-fit on the FINAL-FIT fold partition (self.n_folds) under DoubleMLPLPR::fit; the tune-time cross-fit is not reused. scoring_method is "MSE" (default), "RMSE" or "NegMSE"; n_folds_tune defaults to 5 and seed to 3141. Returns a re-fitted DoubleMLPLPR.

    Grid shape: param_set is a bare Array[LearnerDispatch], NOT an Array[TuneParam]. PLPR is a one-slot estimator, so a two-learner TuneParam would be a wrapper around a single value, and upstream's one-slot estimators use the bare array (same shape as DoubleMLPLIV::tune). PLPR is outcome-first: the candidates are outcome learners E[y|x], so there is no slot role to disambiguate and no for_outcome / for_treatment factory to reach for.

    v0.108.0: new. PLPR had no tune at all, so it was one of the estimators carrying a coverage gap against upstream, where tune reaches every estimator through the BaseDML mixin. The fold draw, the scoring loop and the argmin/argmax selection route through the shared tune_score_grid core, which is keyed on the learner array precisely so both the two-slot and the one-slot grid shapes can share it. PLPR exposes no n_obs(), which is why the core derives the observation count from y.length().

    max_attempts is NOT forwarded. It is a fit parameter with no corresponding struct field, so there is no self.max_attempts to read; the re-fit gets fit's default of 1 retry. A caller who needs the numerical-retry path must call fit(learner = ..., max_attempts = k) explicitly after tuning, rather than expecting tune to preserve it.

    Two mismatches between the tune-time cross-fit and the estimation path, stated here because a guard cannot fix them and a caller choosing learners needs to know:

    1. Fold granularity. tune_score_grid draws a ROW-WISE kfold schedule, while fit always runs the clustered DML path with folds drawn over whole UNITS (unique_units(tf.id)). For a panel this is the same row-vs-unit hazard the cluster guard exists to block in the other estimators, except that PLPR is unconditionally clustered, so there is no non-clustered case to admit and no guard could do useful work.
    2. Domain. The grid scores candidates against the RAW panel (self.panel.x / self.panel.y), while fit estimates on the TRANSFORMED cross-section produced by transform_panel (fd_exact first-differences and drops rows, wg_approx within-transforms). The ranking is a proxy measured on the raw domain, not on the domain the estimate is computed in.

    No cluster guard: DoubleMLPanelData has no cluster_vars field and exposes no is_cluster_data(), so the guard has nothing to call. The method does not add the method.

    DoubleMLPLR

    pub struct DoubleMLPLR {
    data : DoubleMLData
    learner_l : LearnerDispatch
    learner_m : LearnerDispatch
    n_folds : Int
    n_rep : Int
    seed : Int
    smpls : Array[Array[Fold]]
    l_hat : Array[Double]
    m_hat : Array[Double]
    coef : Double
    se : Double
    fitted : Bool
    psi_a : Array[Double]
    psi_b : Array[Double]
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    tune_result : TuneResult?
    memoize_enabled : Bool
    fit_cache : FitCache
    } derive(
    Debug
    )

    Double / debiased machine learning estimator for the partially linear regression model

    Y = D * theta_0 + g_0(X) + zeta, E[zeta | D, X] = 0 D = m_0(X) + V, E[V | X] = 0

    with the partialling out score

    psi_a(theta) = -(D - m_hat)^2, psi_b(theta) = (D - m_hat) * (Y - l_hat), psi(theta) = theta * psi_a + psi_b

    where l_hat = E_hat[Y | X] and m_hat = E_hat[D | X] are obtained from a LinearRegression learner (or any other Learner) trained out-of-fold via K-fold cross-fitting.

    The point estimate is

    theta_hat = -mean(psi_b) / mean(psi_a) = mean((D - m_hat)(Y - l_hat)) / mean((D - m_hat)^2).

    The variance is estimated following doubleml.utils._estimation._var_est (non-cluster case):

    J = mean(psi_a) # expected derivative of psi w.r.t. theta gamma = mean(psi(theta_hat)^2) sigma2 = gamma / (J^2 * n) se = sqrt(sigma2).

    The implementation supports only the partialling out score and a single treatment. It is intentionally minimal — see the README for the matrix of features covered relative to the upstream package.

    DoubleMLPLR::bias_corrected_coef

    fn DoubleMLPLR::bias_corrected_coef(self : DoubleMLPLR) -> Double

    v0.91.0+: returns coef UNCHANGED -- a documented no-op, not a bias correction.

    coef is the root of the DML moment f(theta) = E[theta * psi_a + psi_b] (see var_est.mbt), so mean(f(coef)) is identically zero: the estimating function is orthogonal by construction, and that orthogonality IS what makes the estimator consistent. Nothing computable from the fitted scores is a bias estimate for this class of estimator, so this accessor reports the uncorrected point estimate rather than a number that merely looks like a correction.

    v0.79.0 - v0.90.0 returned coef + mean(psi_b - coef * psi_a). That vector is the score at -coef, NOT at coef; since coef = -mean_b / mean_a its mean is mean_b - coef * mean_a = -2 * coef * mean_a, so the accessor returned coef * (1 - 2 * mean(psi_a)) (exactly 3 * coef when mean(psi_a) = -1). That is not a bias estimate. See bias_corrected_theta in sandwich.mbt for the algebra. The method is kept so the API surface stays stable; removing it outright is the obvious follow-up.

    Preconditions: self.fitted.

    DoubleMLPLR::bootstrap

    fn DoubleMLPLR::bootstrap(self : DoubleMLPLR, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLPLR

    v0.61.0+: multiplier bootstrap for DoubleMLPLR. The per-observation influence function is

    psi[i] = theta * psi_a[i] + psi_b[i]

    (computed at the fitted coef from the last rep's cross-fitted nuisances l_hat / m_hat). Draws n_rep_boot weight vectors of length n_obs from the chosen multiplier distribution, and returns a fitted model with boot_t_stat[b] = sum_i w[b, i] * psi[i] /(sqrt(n) * se_psi) populated where se_psi = sqrt(mean(psi^2)).

    method_name selects the multiplier distribution:
    • "normal" (default): w[i] ~ N(0, 1). Matches the upstream bootstrap(method="normal") default.
    • "Bayes": w[i] = exp(1) - 1 (mean 0, var 1).
    • "wild": w[i] = x[i] / sqrt(2) + (y[i]^2 - 1) / 2 with x, y ~ N(0, 1). Robust to heteroskedasticity.

    Calling bootstrap requires the model to be fitted; calling on an un-fit model aborts with PreconditionError. The helper is did_bootstrap_t_stat (v0.55.0 extracted from DoubleMLDIDCrossSection::bootstrap); PLR is the n_thetas=1 case with psi[i] = psi_at(coef, psi_a, psi_b)[i].

    DoubleMLPLR::clear_cache

    fn DoubleMLPLR::clear_cache(self : DoubleMLPLR) -> DoubleMLPLR

    v0.82.0+: drop any cached nuisance predictions and fold assignment. Useful when the caller wants to free memory or force the next fit() to recompute from scratch.

    DoubleMLPLR::cluster_sandwich_se

    fn DoubleMLPLR::cluster_sandwich_se(self : DoubleMLPLR, cluster_ids : Array[Int]) -> Double

    v0.79.0+: cluster-robust sandwich standard error for the fitted PLR. Same shape as DoubleMLIRM::cluster_sandwich_se; routes through cluster_sandwich_variance with the per-observation PLR psi_a (-v_hat^2) and the per-observation IF psi[i] = psi_at(coef, psi_a, psi_b)[i].

    Preconditions: self.fitted, cluster_ids.length() == n_obs.

    DoubleMLPLR::coef

    fn DoubleMLPLR::coef(self : DoubleMLPLR) -> Double

    Fitted causal parameter.

    DoubleMLPLR::confint

    fn DoubleMLPLR::confint(self : DoubleMLPLR, joint? : Bool, level? : Double) -> (Double, Double)

    95% Wald-style confidence interval [coef - 1.96*se, coef + 1.96*se]. v0.67.0+: joint is a no-op for single-theta estimators (the joint CI equals the Wald CI for a single parameter); accepted for API parity with the multi-theta estimators (APOS / QTE / DIDCS) and the IRM-style cluster path.

    DoubleMLPLR::disable_memoize

    fn DoubleMLPLR::disable_memoize(self : DoubleMLPLR) -> DoubleMLPLR

    v0.82.0+: turn off memoization. Same immutability contract as enable_memoize(). After this, fit() will not read or write the cache; the existing fit_cache is preserved on the returned struct (call clear_cache() to drop it).

    DoubleMLPLR::enable_memoize

    fn DoubleMLPLR::enable_memoize(self : DoubleMLPLR) -> DoubleMLPLR

    v0.82.0+: turn on memoization for subsequent fit() calls. When enabled, fit() will cache the per-observation nuisance predictions and the fold partition and skip the cross-fit nuisance fit on a repeat call whose data + learner fingerprint is unchanged. Returns a new DoubleMLPLR with the flag set (the struct is immutable; the cache itself is populated by the next fit() call).

    Default is OFF. When OFF, every fit() call runs the full cross-fit and the cache is neither read nor written, so v0.81.0 callers see byte-identical output.

    DoubleMLPLR::fit

    fn DoubleMLPLR::fit(self : DoubleMLPLR, learner_l? : LearnerDispatch, learner_m? : LearnerDispatch, max_attempts? : Int, score? : String, tune_result? : TuneResult?) -> DoubleMLPLR

    DoubleMLPLR::has_cache

    fn DoubleMLPLR::has_cache(self : DoubleMLPLR) -> Bool

    v0.82.0+: true iff fit_cache holds at least one cached observation (i.e. at least one prior fit() call with memoize_enabled = true has populated the cache). Note that the cache may still be stale relative to the current data + learner configuration -- check memoize_enabled before assuming a cache hit.

    DoubleMLPLR::n_features

    fn DoubleMLPLR::n_features(self : DoubleMLPLR) -> Int

    Number of features (covariate columns).

    DoubleMLPLR::n_obs

    fn DoubleMLPLR::n_obs(self : DoubleMLPLR) -> Int

    Number of observations.

    DoubleMLPLR::new

    fn DoubleMLPLR::new(data : DoubleMLData, learner_l? : LearnerDispatch, learner_m? : LearnerDispatch, n_folds? : Int, n_rep? : Int, seed? : Int) -> DoubleMLPLR

    DoubleMLPLR::predictions_l

    fn DoubleMLPLR::predictions_l(self : DoubleMLPLR) -> Array[Double]

    Cross-fitted nuisance predictions for the outcome (length n).

    DoubleMLPLR::predictions_m

    fn DoubleMLPLR::predictions_m(self : DoubleMLPLR) -> Array[Double]

    Cross-fitted nuisance predictions for the treatment (length n).

    DoubleMLPLR::sample_splitting

    fn DoubleMLPLR::sample_splitting(self : DoubleMLPLR) -> SampleSplitting?

    The sample splitting recorded by set_sample_splitting, or None when none was supplied and fit draws its own. Some carries the DERIVED counts next to the folds, so a caller can read back what the estimator actually used rather than inferring it from the constructor arguments it no longer has any say over.

    DoubleMLPLR::sandwich_se

    fn DoubleMLPLR::sandwich_se(self : DoubleMLPLR, kind : SandwichKind) -> Double

    v0.79.0+: Huber-White sandwich standard error for the fitted PLR. Same shape as DoubleMLIRM::sandwich_se but operating on the PLR partialling-out score psi_a[i] = -v_hat[i]^2, psi_b[i] = v_hat[i] *u_hat[i]. M_inv = [[1 / mean(psi_a)]]. The sandwich_variance_xx free function in sandwich.mbt does the per-observation squared-score accumulation.

    Preconditions: self.fitted.

    DoubleMLPLR::se

    fn DoubleMLPLR::se(self : DoubleMLPLR) -> Double

    Standard error of the causal parameter, computed via the DML variance formula.

    DoubleMLPLR::sensitivity_analysis

    fn DoubleMLPLR::sensitivity_analysis(self : DoubleMLPLR, cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.66.0+: Cinelli & Hazlett (2020) omitted-variable bias analysis.

    v0.144.0 -- CORRECTED. This used to report nu2 = mean(v^4) and sigma2 = mean((y - l_hat)^2). Both were wrong, and not by a constant factor.

    The old call passed self.psi_a to irm_style_sensitivity, which squares its third argument (sensitivity.mbt:42). But the DML score's psi_a is -v^2 (plr.mbt:369), so the reported baseline was the FOURTH moment mean((-v^2)^2) = mean(v^4) -- a different functional form, not a differently-scaled version of the intended quantity. The Riesz representer is a different object from the score element, which is exactly why irm_style_sensitivity_from_elements was split out in v0.131.0; PLR never migrated off the legacy helper.

    Upstream plm/plr.py:277-293 defines: treatment_residual = d - m_hat (= v) nu2 = 1.0 / mean(v^2) (a SCALAR) rr = treatment_residual * nu2 sigma2 = mean((y - l_hat - theta * v)^2) (centred by theta*v)

    Measured on a seeded confounded design (n = 500, seed 20261) before the fix: mean(v^4) = 0.0765 against upstream's 1/mean(v^2) = 4.609, a factor of 60.24 that moves with the data (it is 1/(mean(v^2)*mean(v^4)), not a units convention), and sigma2 0.776 against 0.337. rv was therefore not the Cinelli-Hazlett robustness value at all.

    WHY sensitivity_from_variance_baselines AND NOT _from_elements. Upstream also builds a per-observation psi_nu2 = nu2 - v^2 * nu2^2, whose mean is EXACTLY zero by construction (mean(v^2) * nu2^2 == nu2). Feeding that to irm_style_sensitivity_from_elements would make its nu2 come out as 0 and route PLR through the nu2 <= 0 fallback branch -- the right number reached by the branch reserved for a degenerate case. The faithful transcription of a scalar nu2 under a contract that takes a per-observation score element is the scalar itself; the Riesz representer is still passed as v * nu2 in spirit but is unobservable (see sensitivity_from_variance_baselines).

    cf_y / cf_d are the confounding-strength upper bounds (defaults 0.05) and are passed through to the result for upstream parity.

    DoubleMLPLR::sensitivity_analysis_cluster

    fn DoubleMLPLR::sensitivity_analysis_cluster(self : DoubleMLPLR, cluster_ids? : Array[Int], cf_y? : Double, cf_d? : Double) -> SensitivityResult raise

    v0.72.0+: cluster-robust analogue of DoubleMLPLR::sensitivity_analysis.

    v0.144.0 -- CORRECTED, with a scope caveat that matters. Upstream's core package has NO sensitivity_analysis_cluster method at all (verified against doubleml-0.11.4: the only sensitivity entry point is DoubleML.sensitivity_analysis), so this is a port-only extension and there is no upstream cluster formula to match. What is fixed here is the same defect as the IID path: the per-observation definitions feeding the cluster aggregation are now upstream's.

    The cluster analogue of upstream's nu2 = 1 / mean(v^2) is the reciprocal of the cluster-robust second-moment baseline, 1 / mean_c (sum_{i in c} v_i)^2, and sigma2 aggregates the SAME theta-centred residual the IID path uses. cluster_ids defaults to DoubleMLData::cluster_vars.

    DoubleMLPLR::set_sample_splitting

    fn DoubleMLPLR::set_sample_splitting(self : DoubleMLPLR, smpls : Array[Array[Fold]]) -> DoubleMLPLR

    Record a caller-supplied sample splitting and DERIVE the fold and repetition counts from it. Returns a new DoubleMLPLR; the receiver is unchanged, as everywhere in this package.

    smpls is one entry per repetition, each entry one Fold per fold -- the nested form is the only form, so a single repetition is [f0, f1, f2] wrapped once, i.e. [[f0, f1, f2]].

    The derivation is upstream's, and it is the part that surprises people: set_sample_splitting (doubleml/double_ml_sampling_mixins.py:76) sets n_folds and n_rep FROM the supplied partition, so handing a two-fold split to a model built with n_folds=5 yields a two-fold model. On the returned model n_folds / n_rep are updated to match, and fit uses the supplied folds instead of drawing them.

    Validation, via check_sample_splitting: every repetition carries the same number of folds, and within each repetition the test index sets are disjoint and cover exactly [0, n_obs). A supplied partition that is not a partition aborts rather than quietly producing a cross-fit that leaks across folds.

    Memoization is switched OFF for the external path, and the fit cache is cleared here. Two separate things, and an earlier draft of this comment conflated them: the returned model still carries memoize_enabled = true (the struct spread preserves it), and what actually prevents caching is the && !external term inside fit. The net effect is the same -- an externally-split fit never reads or writes the cache -- but "the model is switched off" would have been false, and a reader checking memoize_enabled would conclude the opposite. The cache key is built from data + learner + cluster hashes and has no term for the fold assignment, so honouring a cache entry here could return a DIFFERENT partition's predictions. The clear is required for the same reason: an entry written under the previous splitting would otherwise outlive it.

    The one-fold "no sample splitting" case needs no special handling: a single Fold whose train and test both cover everything is a valid partition with folds = 1, which is what upstream detects and reports.

    DoubleMLPLR::tune

    fn DoubleMLPLR::tune(self : DoubleMLPLR, param_set~ : Array[TuneParam], scoring_method? : String, n_folds_tune? : Int, seed? : Int, score? : String) -> DoubleMLPLR

    DoubleMLPLR::tune — score a grid of nuisance-learner combinations and re-fit the model with the winner.

    Algorithm (TUNE_DESIGN.md §4):

    1. Draw a fresh fold schedule folds_tune via kfold(n, n_folds_tune, seed). The tune-time folds are deliberately independent of the final-fit self.n_folds to avoid information leakage — the final DML estimate uses its own fold schedule for cross-fitting, so sharing tune and fit folds would leak l_hat quality into the model-selection step.
    2. For each candidate c in param_set:
      • l_hat_c = cross_fit_predict_dispatch(c.learner_l,x, y, folds_tune)
      • score_c = tune_score_outcome(y, l_hat_c, scoring)
      • on a learner-level exception, set score_c = +Inf (TUNE_DESIGN.md §7: keep tuning, the argmin rule automatically excludes divergent candidates).
    3. c* = argmin_c score_c (lower-is-better for MSE / RMSE, higher-is-better for NegMSE — NegMSE is converted to its lower-is-better form internally).
    4. Re-fit the DML model with learner_l = c*.learner_l,learner_m = c*.learner_m using the final-fit fold schedule (self.n_folds). The tuned nuisance predictions from step 1 are NOT reused — each re-fit produces its own OOF cross-fit under self.n_folds.
    5. Return the re-fitted DoubleMLPLR.

    Edge cases (TUNE_DESIGN.md §7):
    • param_set.length() == 0 -> abort with a descriptive message.
    • param_set.length() == 1 -> skip the scoring loop, re-fit with the single candidate directly (faster).
    • n_folds_tune > n_obs -> abort via the existing kfold precondition cascade.
    • seed not set -> defaults to 3141 for reproducibility.
    • scoring_method not in known set -> abort via TuneScoring::parse.

    score (the DML score: "partialling-out" / "iv-type") is forwarded to the re-fit step unchanged — tune() does not affect the DML score itself, only the nuisance learners.

    Cluster-data (self.data.is_cluster_data()) is not supported in v0.58.0 — cluster-aware tuning needs a different fold schedule (kfold on unique units) and would inflate this method beyond a single release. Use DoubleMLPLR::fit(learner_l = best_l, learner_m = best_m) directly on the cluster-DML path with hand-picked candidates until v0.59.0+ lands cluster-aware tune.

    DoubleMLPLR::tune_result

    fn DoubleMLPLR::tune_result(self : DoubleMLPLR) -> TuneResult?

    Accessor for the tune_result populated by DoubleMLPLR::tune(...) (v0.58.0+). Returns None for models built via DoubleMLPLR::new(...) or re-fit via DoubleMLPLR::fit(...) (a re-fit discards the prior tune history because the nuisance learners may have changed).

    Inspect the returned TuneResult to see which (learner_l,learner_m) combination won under the chosen scoring rule, what the best score was, and the per-candidate score vector (in param_set order).

    DoubleMLPQ

    pub struct DoubleMLPQ {
    data : DoubleMLData
    treatment : Double
    quantile : Double
    n_folds : Int
    seed : Int
    smpls : Array[Array[Fold]]
    propensity_clip : Double
    ps_processor_config : PSProcessorConfig
    ml_l : LearnerDispatch
    ml_m : LearnerDispatch
    coef : Double
    se : Double
    fitted : Bool
    psi : Array[Double]
    psi_a : Array[Double]
    boot_t_stat : Array[Double]
    boot_method : String
    n_rep_boot : Int
    boot_seed : Int
    memoize_enabled : Bool
    fit_cache : FitCache
    } derive(
    Debug
    )

    DoubleMLPQ::bias_corrected_coef

    fn DoubleMLPQ::bias_corrected_coef(self : DoubleMLPQ) -> Double

    v0.94.0+: returns coef UNCHANGED -- a documented no-op, not a bias correction. Identical in reasoning to the fourteen bias_corrected_coef methods added in v0.86.0 - v0.93.0; see DoubleMLIRM::bias_corrected_coef and bias_corrected_theta in sandwich.mbt for the full argument.

    coef is the bisection root of the PQ quantile moment mean(psi(theta)) = 0. That estimating function is orthogonal at its root by construction -- and that orthogonality IS what makes the estimator consistent -- so no correction built from the fitted scores is a bias estimate for this class of estimator. This accessor therefore reports the uncorrected point estimate rather than a number that merely looks like a correction.

    The pre-v0.91.0 form coef + mean(psi_b - coef * psi_a) is algebraically 3 * coef for a constant-psi_a estimator and is not a bias estimate for ANY of them; the v0.91.0 argument applies here unchanged.

    Preconditions: self.fitted.

    DoubleMLPQ::bootstrap

    fn DoubleMLPQ::bootstrap(self : DoubleMLPQ, method_name? : String, n_rep_boot? : Int, seed? : Int) -> DoubleMLPQ

    v0.64.0+: multiplier bootstrap for DoubleMLPQ. The per-observation influence function psi is the centered IPW quantile score at the bisection root (mean 0, se_psi = sqrt(mean(psi^2)) is the bootstrap denominator). Routes through the shared generic_bootstrap_single_psi helper (see bootstrap_helper.mbt).

    method_name selects the multiplier distribution: "normal" (default), "Bayes", "wild". seed defaults to 2024; n_rep_boot defaults to 500.

    Calling on an un-fit model aborts via PreconditionError.

    DoubleMLPQ::clear_cache

    fn DoubleMLPQ::clear_cache(self : DoubleMLPQ) -> DoubleMLPQ

    v0.84.0+: drop the cached solve_pq(...) outputs. After this, the next fit() will run the full solve_pq (and repopulate the cache if memoize is still enabled).

    DoubleMLPQ::cluster_sandwich_se

    fn DoubleMLPQ::cluster_sandwich_se(self : DoubleMLPQ, cluster_ids : Array[Int]) -> Double

    v0.94.0+: cluster-robust sandwich standard error for the fitted PQ (Arellano 1987, Cameron-Gelbach-Miller 2011). Routes through cluster_sandwich_variance with the SAME self.psi and M_inv inputs as the IID sandwich_se path -- see the section comment above for why those are not the ordinary (psi_at(...),1/mean(psi_a)) pair.

    DoubleMLData carries cluster_vars, so a clustered fit can pass self.data.cluster_vars directly; on the IID constructor path (cluster_vars = []) the caller must supply the grouping variable explicitly -- any clustering the application has: region, site, panel unit. With all-singleton clusters the meat degenerates to sum_i psi[i]^2 and the formula collapses to sandwich_se(HC0), hence to se() on an IID fit.

    Preconditions: self.fitted, |psi_a[0]| >= 1e-12, cluster_ids.length() == psi.length().

    DoubleMLPQ::coef

    fn DoubleMLPQ::coef(self : DoubleMLPQ) -> Double

    DoubleMLPQ::confint

    fn DoubleMLPQ::confint(self : DoubleMLPQ, joint? : Bool, level? : Double) -> (Double, Double)

    v0.67.0+: joint is a no-op for single-theta estimators; accepted for API parity.

    DoubleMLPQ::disable_memoize

    fn DoubleMLPQ::disable_memoize(self : DoubleMLPQ) -> DoubleMLPQ

    v0.84.0+: turn off memoization. After this, fit() will not read or write the cache; the existing fit_cache is preserved on the returned struct (call clear_cache() to drop it).

    DoubleMLPQ::enable_memoize