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.122.0
    License
    MIT
    Last updated
    29 days ago
    Downloads
    2K

    #moonbit_doubleML · Double / Debiased Machine Learning in MoonBit

    A pure-MoonBit port of the doubleml-for-py Python package — the Python ecosystem's most mature Double / Debiased Machine Learning implementation — covering all 19 models in upstream plus 3 MoonBit-specific extras (DoubleMLPLPR for static panel data, DoubleMLLPLR for binary outcomes, DoubleMLDIDCSBinary for binary-outcome CS-DID).

    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 a unified DoubleMLXxx::new(data, n_folds, n_rep, seed).fit() API across all 22 estimators, robust variance estimation, propensity-score processing, multiple-testing correction, and a reproducible validation pipeline (23 / 23 Python reference scripts PASS) — on native, wasm, wasm-gc, and js backends under moon test --deny-warn.

    #Status

    ItemValue
    Repositoryhttps://github.com/riantr/moonbit_doubleML
    Authorriantr
    LicenseMIT (port of upstream doubleml-for-py, BSD-3-Clause)
    moon.mod version0.115.0
    Source layoutflat, moonbit_doubleML/ (the library)
    .mbt file count180 in the library (87 production + 93 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 --deny-warn
    Tests (native / wasm / js)849 / 849
    Tests (wasm-gc)855 / 855 (lib 849 + 6 doc tutorials)
    Python cross-checks23 / 23 PASS (validate_*_with_python.py)
    Memoize + vectorize coverage22 / 22 estimators
    Cache read-path audit13 estimators have a hit-vs-fresh assertion; 5 of those 13 additionally carry a corruption probe (IRM, PLR, CVAR, BLP, PQ) since v0.99.0. A corruption probe writes a known-wrong value into one cached slot and requires the reported estimate to move, so a dead cache-read path fails the suite. A hit-vs-fresh assertion alone does not: the fresh recompute is deterministic, so replaying nothing and replaying correctly are indistinguishable to it.
    Joint covarianceDoubleMLQTE::joint_covariance(kind) / cluster_joint_covariance(cluster_ids) since v0.101.0. The quantile estimates share observations, so their influence functions are correlated and the per-quantile sandwich_se_at cannot answer any question posed jointly over two levels. Measured off-diagonal correlations on the v0.101.0 DGP: +0.076, -0.265, +0.124; a two-level contrast's variance is 1.265x the one an independence assumption predicts, and clustering can flip the SIGN of an off-diagonal term. The diagonal is bit-identical to the variance ses[j] is the square root of.
    Sandwich variance coverage19 / 22 estimators (sandwich_se + cluster_sandwich_se + bias_corrected_coef, the last a documented no-op since v0.91.0; DoubleMLQTE exposes the per-quantile sandwich_se_at(j, kind) / cluster_sandwich_se_at(j, cluster_ids) / bias_corrected_coef_at(j) form, and as of v0.100.0 so do the three multi-estimand estimators: DoubleMLAPOS::sandwich_se_at(level, kind), DoubleMLDIDCS::sandwich_se_at(group, period, kind), and DoubleMLDIDMulti::sandwich_se_at_idx(idx, kind)). Not covered: DoubleMLRDD and DoubleMLBLP (projection / local-regression families -- they take the separate hac_se API added in v0.96.0 / v0.97.0) and DoubleMLPolicyTree (honest-split inference, no persisted IF components)
    HTTP serviceexamples/api_server/ — hand-rolled on moonbitlang/async, no third-party framework

    #Features

    Pure-MoonBit, all-4-backends port of doubleml-for-py — 22 DoubleML* estimators (DoubleMLPLR, DoubleMLIRM, DoubleMLPLIV, DoubleMLIIVM, DoubleMLDID, DoubleMLDIDBinary, DoubleMLDIDCS, DoubleMLDIDCSBinary, DoubleMLDIDMulti, DoubleMLDIDCrossSection, DoubleMLSSM, DoubleMLAPO, DoubleMLAPOS, DoubleMLPQ, DoubleMLQTE, DoubleMLLPQ, DoubleMLLPLR, DoubleMLCVAR, DoubleMLRDD, DoubleMLBLP, DoubleMLPLPR, DoubleMLPolicyTree) in 17 source files. The 19 marked (upstream) mirror the upstream doubleml-for-py API; the 3 marked (extra) are MoonBit-specific additions for static-panel PLR, partially-logistic regression, and binary-outcome CS-DID.

    Unified API surface — every estimator follows the same DoubleMLXxx::new(data, n_folds, n_rep, seed).fit() shape and returns the same .coef() / .se() / .confint() / .bootstrap() accessors. No per-estimator interface drift.

    v0.85.0 memoization + vectorization complete (22 / 22) — closes the memoize + vectorize expand on DoubleMLPolicyTree, the last estimator without the API. With this, all 22 estimators expose enable_memoize / disable_memoize / clear_cache / has_cache. (The v0.84.0 note below still listed "2 small DID variants" as pending; those DID variants already carried the API as of v0.82.0, so DoubleMLPolicyTree was in fact the only remaining gap.)

    DoubleMLPolicyTree is a deterministic policy learner, not a cross-fitted nuisance-regression estimator: it has no n_folds, no n_rep, and no fit_cluster. Its cache therefore holds the fitted tree structure plus the per-leaf statistics rather than per-fold nuisance predictions, reusing the FitCache slots as a shape-compatible container (fold_ids = leaf_assignment, predictions[0] = leaf_signal_mean, predictions[3] = leaf_count, n_folds = n_leaves as a partition-count analogue, fold_split_seed = depth as the structural fingerprint). PolicyTreeNode is a recursive sum type with no Clone derive, so the tree is flat-encoded into a fixed-width 5-slots-per-node pre-order Array[Double] and rebuilt on a cache hit. A hit skips both policy_tree_build (the dominant O(n * p * nodes) cost, which allocates a fresh Matrix per node) and the O(n * depth) leaf-walk loop. The per-leaf mean is computed with vector_divide (eps-guarded denominator), and sensitivity_analysis's per-observation residual is computed with a single vector_subtract over a gathered per-row leaf mean instead of one scalar subtract per row per leaf.

    Also in v0.85.0: adds the moonbit-community/sqlite3@0.2.3 dependency (with a moonbitlang/async@0.20.3 pin) and the matching async 0.22.4 header-map type fix in examples/api_server.

    v0.84.0 memoization + vectorization expand — extends the v0.83.0 layer to five more estimators: DoubleMLAPOS, DoubleMLAPO, DoubleMLPQ, DoubleMLQTE, and DoubleMLRDD. Each gains the standard enable_memoize / disable_memoize / clear_cache / has_cache API. DoubleMLAPO (cache stores LAST-rep g_hat / m_hat / psi_a / psi_b; cache-hit path re-runs var_est from cached values), DoubleMLAPOS (parent-level (coefs, ses) cache plus enable_memoize() forwarding to each child DoubleMLAPO), DoubleMLPQ (cache stores (theta, deriv, psi); cache-hit skips the entire solve_pq -- propensity cross-fit + bisection + 3x outcome cross-fits), DoubleMLQTE (cache stores per-quantile per- treatment (theta1, psi1, deriv1, theta0, psi0,deriv0); cache-hit skips the 2 * n_quantiles solve_pq loop), and DoubleMLRDD (no-fold estimator: cache stores the entire (coef, se,n_local, residuals, psi_a) tuple under a (data, cutoff, bandwidth, fuzzy, cov_type, ml_g) key; cache-hit skips all four rdd_side calls). Per-fold residual loops in each are rewritten in terms of the vectorized.mbt helpers (vector_subtract, vector_scale, vector_divide, vector_multiply, vector_add). Coverage: 20 of 22 estimators now carry memoize + vectorize. Remaining 2 small DID variants are queued for v0.85.

    v0.83.0 memoization + vectorization expand — extends the v0.82.0 layer to five additional estimators: DoubleMLCVAR, DoubleMLSSM, DoubleMLBLP, DoubleMLPLPR, and DoubleMLLPLR. Each gains the standard enable_memoize / disable_memoize / clear_cache / has_cache API; the per-fold residual loops in cvar.mbt / cvar_inner_crossfit, ssm.mbt's MAR IPW psi_a / psi_b, blp_policy.mbt's residual / RSS computation, plpr.mbt's v_hat / u_hat / y_resid subtractions, and lplr.mbt's psi_b residual computation are now written in terms of the vectorized.mbt helpers (vector_subtract, vector_scale, vector_divide, vector_multiply, vector_add). Coverage: 15 of 22 estimators now have memoize + vectorize. Remaining 7 estimators (RDD, PQ, QTE, APOS, APO, plus 2 small DID variants) were queued for v0.84.

    v0.82.0 memoization + vectorization expand (partial) — extends the v0.80.0 enable_memoize() / disable_memoize() / clear_cache() / has_cache() API and the v0.81.0 vector_subtract / vector_add / vector_scale / matrix_predict helpers to nine additional estimators: DoubleMLPLR, DoubleMLIIVM, DoubleMLPLIV, DoubleMLDID, DoubleMLDIDBinary, DoubleMLDIDCS, DoubleMLDIDCSBinary, DoubleMLDIDMulti, DoubleMLDIDCrossSection, and DoubleMLLPQ. The FitCache struct was extended to support n_rep > 1 and the cluster path via a cluster_ids_hash field; vectorized.mbt gained vector_multiply and vector_divide (eps=1e-10 clamp on denominator). Coverage: 10 of 22 estimators now have memoize + vectorize. Remaining 7 estimators (RDD, PQ, QTE, CVAR, SSM, BLP, LPLR, PLPR, APOS, APO, plus 2 small DID variants) were queued for v0.83.

    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.

    Propensity-score processor (PSProcessor) — clipping_threshold clipping, isotonic (PAVA) calibration, K-fold cross-validated (CV) calibration. Plugs directly into DoubleMLIRM / DoubleMLIIVM / DoubleMLDID and the rest of the IPW-based models.

    Robust variance & inference — heteroskedasticity-consistent (HC) standard errors, cluster-robust variance, multiplier bootstrap confidence intervals, joint CIs, and Romano-Wolf multiple-testing p-value adjustment. Reused via the bootstrap.mbt helper extracted in v0.55.0. See #Sandwich variance for the exact HC contract.

    Cross-estimator joint sensitivity (v0.77.0+) — the joint_sensitivity(inputs, alpha) helper in sensitivity.mbt takes K >= 2 per-estimator summaries (name, coef, se,sigma_sq, rho, cf_y, cf_d) and emits Bonferroni-corrected joint CIs ([min(per_estimator_lower), max(per_estimator_upper)]) plus the joint RV / RV_q (min(per_estimator_rv) / min(per_estimator_rv_q)). Closes Cinelli & Hazlett (2020) §3.6 for the multi-estimator setting — when the same hypothesis is estimated by two or more estimators, the joint CI controls the family-wise error rate across the bundle.

    Coverage by class:

    • Observational / quasi-experimental: DoubleMLDID, DoubleMLDIDBinary, DoubleMLDIDCS, DoubleMLDIDCSBinary, DoubleMLDIDMulti, DoubleMLDIDCrossSection, DoubleMLRDD, DoubleMLSSM.
    • Strategy & distributional: DoubleMLAPO / DoubleMLAPOS, DoubleMLPQ, DoubleMLQTE, DoubleMLLPQ, DoubleMLCVAR, DoubleMLBLP, DoubleMLPolicyTree.

    Reproducible DGPs + Python reference validation — 23 Python scripts (validate_*_with_python.py) drive 23 DGPs (plr_CCDDHNR, plr_turrell, plr_confounded, irm_discrete, irm_heterogeneous, irm_confounded, iivm, pliv / pliv_cluster, SSM, simple_rdd, DID SZ2020 / CS2021, etc.) and check within-tolerance equivalence against the upstream Python outputs. CI greps the trailing PASS line from each script.

    Docs & demos — 6 doc/<NNN_…>/ tutorials targeting wasm-gc, plus 14 examples/<bin>/ driver binaries (all listed in moon.work), of which examples/api_server/ is an HTTP service built directly on moonbitlang/async@0.20.3 — no third-party HTTP framework is pulled in.

    Strict dependency hygiene — the library imports only moonbitlang/* official packages. moon.mod additionally declares moonbit-community/sqlite3@0.2.3 (added v0.85.0) so consumers can reach a persistence backend through moon add; no .mbt file in the library imports it yet. Non-official deps otherwise restricted to riantr/* (this repo). Reproducible builds, minimal supply-chain surface.

    Learner injection via LearnerDispatch — every estimator's new() / fit() accept ml_g / ml_m / ml_l / ml_r typed optionals. Default is LearnerDispatch::linear_regression() (OLS); v0.62.0+ also accepts LearnerDispatch::logistic_regression(LR) for LPLR's binary-classification slots. Built-in learners: LinearRegression, ConstantLearner, NoopLearner, RFLearner (Breiman 2001 regression), GBLearner (Friedman 2001 regression). RFLearner and GBLearner now reach the 5 specialised internals — DoubleMLDIDCrossSection::crossfit_nuisance, DoubleMLDIDCSBinary::cs_bin_crossfit_nuisance, DoubleMLPQ::solve_pq / DoubleMLQTE::solve_pq, DoubleMLCVAR::cvar_inner_crossfit, and DoubleMLLPLR::cross_fit_predict_dispatch (binary classifier slots) / DoubleMLRDD::rdd_side (kernel-weighted OLS for ml_g = LinearRegression, unweighted fallback for other learners). Defaults preserve v0.61.0 byte-equality; non-default overrides change the IF and the coef.

    #Quick Start

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

    #Library Use

    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().

    #Examples

    14 examples/<bin>/ directories in moon.work. 13 run end-to-end on synthetic DGPs: 12 are CLI-style numeric demos (print true-vs-estimated θ and a 95 % CI); the 13th — examples/api_server/ — is an HTTP service. The 14th — examples/consumer_demo/ — is the library-user pattern that mirrors what an external moon add riantr/moonbit_doubleML consumer would write.

    DriverModelDGPTrue θ
    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=5000, 9 controls1.5
    examples/did_binaryDoubleMLDIDBinary2-period panel DID, 400 units1.0
    examples/did_csDoubleMLDIDCSStaggered CS-DID, 4 cohorts × 4 periods1.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/plpr, examples/lplrDoubleMLPLPR / DoubleMLLPLRStatic-panel PLR / partially logistic regression1.0
    examples/clusterDoubleMLPLR / DoubleMLPLIVCluster-robust SEs (row / var_est_cluster / cluster_sandwich_variance) reported at 1x and 4x the units, plus the all-singleton control that must reproduce se()1.0
    examples/ssmDoubleMLSSMMAR-selection SSM at two seeds x two sample sizes, printing se() and sandwich_se(HC0) side by side — the two must be bit-identical for a var_est-shaped estimator1.0
    examples/apos, examples/cvarDoubleMLAPOS / DoubleMLCVARAPO policy score / CVaR1.0
    examples/fuzzwrappersRandom-property fuzz harness across 12 surfacesn/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:

    $ 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/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 --port 4000 (see examples/api_server/README.md for the full curl recipe). The service is built directly on moonbitlang/async@0.20.3 — no third-party HTTP framework is pulled in.

    #Models

    22 estimators (DoubleML* structs) in 22 files (one struct per file, plus the supporting DGPs and score / nuisance kernels in 160 .mbt files total: 87 production + 73 test), all reachable through the same DoubleMLXxx::new(...).fit() interface. The 19 marked (upstream) mirror the upstream doubleml-for-py API surface; the 3 (extra) rows are MoonBit additions for static-panel PLR, partially-logistic regression, and binary-outcome CS-DID:

    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)
    DoubleMLDIDCSBinaryobservationalCS-DID with binary outcome (extra)
    DoubleMLDIDMultiobservationalmulti-period DID with group-time ATT aggregation (upstream)
    DoubleMLDIDCrossSectionobservationalSant'Anna-Zhao 2020 cross-section DID (upstream)
    DoubleMLSSMMARsample selection (missing-at-random) (upstream)
    DoubleMLAPOpolicy scoreaverage prescriptive effect (upstream)
    DoubleMLAPOSpolicy scoreAPO with stratified treatment (upstream)
    DoubleMLPQquantilepotential quantile (upstream)
    DoubleMLQTEquantilequantile treatment effect (upstream)
    DoubleMLLPQlocal polynomiallocal potential quantile (upstream)
    DoubleMLLPLRnuisance_space (default) / instrumentpartially logistic regression, Liu-Zhang-Zhou 2021 (extra). The two scores are upstream's two distinct formulas (doubleml/plm/lplr.py:521-540), both implemented since v0.105.0; before that the score argument was validated and then never read, so both names returned the same answer.
    DoubleMLCVARCVaRconditional value-at-risk (upstream)
    DoubleMLRDDobservationalregression discontinuity (upstream)
    DoubleMLBLPIVbest linear predictor of treatment effect (upstream)
    DoubleMLPLPRpartialling-outpartially linear panel regression, Clarke-Polselli 2025 (extra)
    DoubleMLPolicyTreepolicypolicy tree (upstream)

    #Tuning

    tune(param_set~, ...) scores a caller-supplied grid of nuisance-learner combinations by cross-fitting the FIRST slot against the outcome, keeps the winner, and re-fits with it. The scoring loop, the fold draw and the argmin/argmax selection live in one shared place (tune_score_grid in tune.mbt); the per-estimator method is a thin wrapper that extracts its own data fields and calls its own fit.

    19 of the 22 estimators expose tune: DoubleMLPLR · DoubleMLPLIV · DoubleMLLPLR · DoubleMLPLPR · DoubleMLDID · DoubleMLDIDCS · DoubleMLDIDCSBinary · DoubleMLDIDCrossSection · DoubleMLDIDMulti · DoubleMLDIDBinary · DoubleMLIRM · DoubleMLIIVM · DoubleMLAPO · DoubleMLAPOS · DoubleMLSSM · DoubleMLCVAR · DoubleMLPQ · DoubleMLQTE · DoubleMLRDD

    The remaining 3 are structural, not pending. DoubleMLLPQ and DoubleMLPolicyTree take no learner at all -- their fit is fit(self) -- so there is nothing to tune. DoubleMLBLP fits demand characteristics rather than a nuisance, and upstream tunes it over a different quantity than a grid of learners describes.

    What the grid is NOT: upstream's is a per-learner HYPERPARAMETER grid (param_grid_func + _create_study + DMLOptunaResult, an Optuna study). This is a flat list of learner PAIRINGS. The coverage is comparable; the search spaces are not. See the v0.108.0 entry in CHANGELOG.md.

    #Sample splitting

    set_sample_splitting(smpls) records a caller-supplied partition and derives n_folds and n_rep from it, exactly as upstream's SampleSplittingMixin.set_sample_splitting does -- a two-fold split handed to a model built with n_folds = 5 produces a two-fold model. sample_splitting() reads the derived counts back, or None when no splitting was supplied.

    12 of the 22 estimators expose it: DoubleMLPLR · DoubleMLPLIV · DoubleMLLPLR · DoubleMLDID · DoubleMLIRM · DoubleMLIIVM · DoubleMLAPO · DoubleMLAPOS · DoubleMLSSM · DoubleMLCVAR · DoubleMLPQ · DoubleMLQTE

    The other 10 are not pending work, and two of the reasons are worth stating because they are easy to mistake for oversights:

    • The DID cell family (DIDCS, DIDCSBinary, DIDCrossSection, DIDMulti) and DIDBinary cross-fit nothing directly -- they build per-cell child estimators. Propagating a partition there is a different mechanism from the row-level one used here, and a partition has to mean something coherent ACROSS cells.
    • PLPR is unconditionally unit-clustered: its folds are unit-level on a transformed cross-section, so a row-level partition is the wrong shape. Upstream takes all_smpls_cluster alongside all_smpls for exactly this case; porting the cluster half is its own decision.
    • RDD and BLP never call kfold at all -- RDD is a local-polynomial estimator with no cross-fitting, and BLP fits demand characteristics.

    On any estimator, an externally supplied splitting applies to the ROW-LEVEL path only. Every cluster path keeps drawing unit-level folds; this is documented per method rather than enforced, because honouring an external splitting there needs a unit-indexed splitting and a unit-indexed validator, which check_sample_splitting is not.

    #RDD kernel and bandwidth

    DoubleMLRDD takes a kernel (RDDKernel: Triangular (default), Normal, Uniform, Epanechnikov, Quadratic; accepted case-insensitively by RDDKernel::parse, and an unknown name ABORTS rather than silently falling back). Only three of the five are rdrobust kernels -- Triangular (default), Uniform and Epanechnikov. Normal and Quadratic are extensions of this port, not upstream options; v0.110.0's comment claimed otherwise and v0.115.0 corrected it against rdrobust 2.2's documentation. Before v0.110.0 the kernel was hardcoded to triangular in both weight sites and the bandwidth had to be supplied by the caller.

    #The two bandwidths

    optimal_bandwidth() implements the MSE-optimal procedure of Cattaneo, Calonico & Tchetgen (2020) -- the one rdrobust exposes through bwselect. The pilot is silverman_bandwidth of the RUNNING VARIABLE (never of the outcome), so the search grid is dimensionless and the answer does not change with the units x is measured in.

    optimal_bias_bandwidth() (v0.115.0) is the CCT second bandwidth b. It exists because bwselect = "CCT" -- rdrobust's default -- computes BOTH h and b, and this package had only the first. They are different numbers because they minimise different functions: a local polynomial of degree j has leading bias O(h^(j+1)), so the j-order MSE criterion carries a b^(2(j+1)) variance term, and rdrobust uses p = 1 for the point estimate and q = 2 for the bias. Measured on the package's own nonlinear fixture, b / h = 0.907.

    #The bias-correction identity

    The correction is not a separate estimator. Substituting the definition of the bias into tau_bc = tau_cl - bias, the conventional terms cancel:

    tau_bc_s = xi_p(h)_s - [xi_p(h)_s - xi_q(b)_s] = xi_q(b)_s

    so tau_bc is exactly the difference of the q-order limit estimates at b. That is why no joint covariance across the two bandwidths is needed, and it is checkable from outside: tau_bc_collapsed() computes the right-hand side and the two agree exactly.

    #What is checkable from outside, and why that matters

    bandwidth_mse(h, nnmatch?, order?), bandwidth_variance_term(h, ...) and bandwidth_sigma4(nnmatch?, order?) are PUBLIC on purpose. At h = h_pilot the bias term is identically zero, so bandwidth_mse(h_pilot) == bandwidth_sigma4() / n exactly. Without those accessors a gate could only verify that the search minimised its own criterion, not the criterion itself -- deleting the variance term left everything green. bandwidth_variance_term exists because hardcoding the exponent to b^4 also left everything green: the search still minimised whatever it was handed. Doubling the bandwidth must multiply it by 16 at order 1 and 64 at order 2.

    Sigma^4 uses rdrobust's nearest-neighbour matching (vce = "nn", nnmatch = 3), pairing each left residual with its nnmatch nearest right neighbours by running-variable distance.

    #What is NOT here, and is not implied

    The bias-corrected POINT estimate is implemented; the bias-corrected ROBUST variance is not. rdrobust's procedure (iii) is "bias- corrected estimates with robust standard errors", and its default robust estimator is vce = "nn" -- the same nearest-neighbour matching this port implements for the CRITERION but not for the VARIANCE. tau_bc_se() returns the homoskedastic / HC0 variance the package already had, applied to the q-order fits. It is a standard error for the bias-corrected estimator, not rdrobust's robust one.

    Consequently coef() / se() are UNCHANGED and bias correction is opt-in: procedure (ii) alone under-covers, which is the entire reason procedure (iii) exists.

    Also still open: the point estimate remains local-LINEAR in u (p = 1, matching rdrobust), while the bias-correction fit is local-QUADRATIC (q = 2, also matching). The bandwidth grid is 50 points, not rdrobust's 100. Recorded in the v0.110.0 / v0.113.0 / v0.115.0 entries in CHANGELOG.md.

    #Sandwich variance

    sandwich.mbt implements the Huber-White family (sandwich_variance_hc0 / _hc1 / _hc2 / _hc3, the sandwich_variance(kind, ...) dispatch, and cluster_sandwich_variance). 16 of the 22 estimators are wired up. 15 expose the no-index triple sandwich_se(kind) / cluster_sandwich_se(cluster_ids) / bias_corrected_coef():

    DoubleMLPLR · DoubleMLIRM · DoubleMLPLIV · DoubleMLIIVM · DoubleMLDID · DoubleMLDIDBinary · DoubleMLDIDCrossSection · DoubleMLDIDCSBinary · DoubleMLSSM · DoubleMLAPO · DoubleMLPLPR · DoubleMLCVAR · DoubleMLLPLR · DoubleMLLPQ · DoubleMLPQ

    The sixteenth, DoubleMLQTE, is a per-quantile estimator (one scalar estimand per entry in the user-supplied quantiles array), so its three methods take the quantile index -- sandwich_se_at(j, kind) / cluster_sandwich_se_at(j, cluster_ids) / bias_corrected_coef_at(j). No joint cross-quantile covariance is implied or computed; see the v0.95.0 entry in CHANGELOG.md for why its M_inv is [[1.0]] rather than 1 / deriv.

    The remaining 6 are deliberately not wired up, each for a structural reason rather than a pending task. DoubleMLAPOS, DoubleMLDIDCS and DoubleMLDIDMulti are documented in the v0.89.0 entry below (no own scores, or a per-cell score matrix that does not carry the sample width the HC identities need). DoubleMLBLP / DoubleMLPolicyTree do not persist the (psi_a, psi_b) influence-function pair the formulas are written against. DoubleMLRDD does persist a psi_a, but it is the intercept Riesz-representer row for the sensitivity decomposition on the bandwidth-restricted sample (length n_local), with no psi_b counterpart, and its own se comes from the WLS / White form (cov_type), not from var_est — giving it a sandwich SE is score-field design work, not a wiring change.

    As of v0.96.0 DoubleMLRDD and as of v0.97.0 DoubleMLBLP take the other route: each exposes its OWN hac_se(kind) / cluster_hac_se(cluster_ids) plus leverage(), and neither gets sandwich_se. The reason is algebraic, not bookkeeping. BLP is an OLS projection of an orthogonal signal onto basis, so its HC0 meat is sum_i ((M[j,:] . xa_i)^2 * e_i^2) over the intercept-augmented design [1, basis], with a full p1 x p1 normal inverse, one row per coefficient, and no 1 / n^2; the shared helper is a scalar-Jacobian mean-moment sandwich. Routing BLP through it yields a plausible, finite, wrong number, and the result is a length-p1 vector where the helper's M_inv is a 1x1. The anchor that proves the wiring is hac_se(HC0) == se bit-identically, elementwise, on a cov_type = "HC0" fit; it is not claimed on cov_type = "nonrobust". BLP and RDD are still NOT sandwich coverage and are not counted in the 16 / 22 above.

    DoubleMLPolicyTree remains deliberately unwired, and v0.97.0 records that as a decision rather than a pending task: its split threshold is CHOSEN FROM THE DATA (policy_tree_build searches features and values for the best split), so the naive per-observation influence function of a leaf mean, (y_i - theta_k) / n_k * 1{i in k}, omits the term contributed by the split selection itself. Correct inference there is the policy-tree / honest-splitting literature, not a derivation available from this codebase, so no influence function was invented for it.

    #The contract

    se() is the reference and is never computed by this file. The moment being inverted is the mean moment f(theta) = E[theta * psi_a + psi_b] from var_est.mbt, so

    sandwich_se(HC0) == se() // to the last ulp
    HC1 / HC0 == sqrt(n / (n - 1)) // to 1e-12
    HC2 == HC1 // leverage h_ii = 1 / n
    HC3 == HC1^2 / HC0 // ditto
    ordering: HC3 > HC1 == HC2 > HC0 // monotonic widening
    cluster(all-singleton) == IID HC0 == se() // pooled clusters differ
    bias_corrected_coef() == coef() // documented no-op

    Exception — DoubleMLDIDCrossSection. It is a projection (argmin_theta) estimator, not a var_est Z-estimator: its fit sets theta_hat = -<psi_a, psi_b> / ||psi_b||^2 and derives its own se, it persists psi_a as the OFFSET and psi_b as the SLOPE (the second inverted-persistence estimator in the package, after DoubleMLLPLR), and its M_inv = [[1 / mean(psi_a)]] is not 1 / (d f / d theta) in any principled sense — the argmin has a vanishing first derivative. The HC ladder and the cluster identities hold; the HC0 == se() identity does not, and since v0.90.0 that is deliberate rather than pending.

    HC2 is equal to HC1, not strictly above it: the moment is single-parameter, so its implicit regression is intercept-only with equal weights, its projection matrix is (1 / n) * J, and every leverage is the constant h_ii = 1 / n_obs. The pre-v0.88 ordering HC1 > HC0 > HC2 > HC3 described a leverage bug (a non-hat-matrix h_ii that came out negative and made HC2 / HC3 shrink), not the model. v0.88.0 fixed it; v0.91.0 fixed the accumulator, which is what buys the HC0 == se() identity above.

    bias_corrected_coef() is a documented no-op returning coef unchanged — all 13 methods (12 landed v0.86.0 - v0.91.0, LPLR's in v0.92.0; v0.91.0 is what turned them into no-ops). coef is the root of the moment, so mean(coef * psi_a + psi_b) == 0 identically: the estimating function is orthogonal by construction, and there is no score-based bias to correct. The v0.79.0 - v0.90.0 form passed the score at -coef rather than at coef and returned coef * (1 - 2 * mean(psi_a)) — exactly 3 * coef on every constant-psi_a estimator.

    DoubleMLLPLR (v0.92.0) is the other estimator whose persisted influence-function components are inverted: it stores psi_a = score offset, psi_b = score derivative, the mirror of the package convention. Its methods therefore pass the two arrays swapped — psi_at(coef, self.psi_b, self.psi_a) and M_inv = [[1 / mean(self.psi_b)]] — which is the same treatment its bootstrap call site has used since v0.90.0. Measured on the v0.90.0 LZZ2020 binary DGP (n = 500): mean(psi_a) =0.01899446402902459 (a cancellation residual) vs the true Jacobian mean(psi_b) = -0.036387245464012986, and sandwich_se(HC0) ==se() == 0.278056227496941 to the last ulp (bit-identical on native / wasm-gc / wasm; the two spellings of the same expression differ by one ulp on js, so the portable contract is the 1e-12 above, not ==).

    #Project layout

    moonbit_doubleML/ <- the library (moon.mod v0.97.0, 165 .mbt files) moonbit_doubleML.mbt <- main re-export file (the import surface) ... <- one file per estimator + DGPs + score / nuisance kernels doc/ <- wasm-gc-targeted numbered tutorials 001_introduction/ ... 006_python_check/ examples/ <- 14 driver binaries (all listed in moon.work) main/ <- 12 estimators, one perfect-DGP run each 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 (`example/consumer_demo`) api_server/ <- HTTP service built on `moonbitlang/async` moon.work <- 16-member workspace aggregator (1 library + doc + 14 examples) AGENTS.md <- this file (per moonbit agent convention) skills/moonbit_doubleML.md <- agent skill: API surface + anti-patterns

    #Dependency rule (per skills/moonbit_doubleML.md)

    • Only official moonbitlang/* packages in the library's source.
    • Non-official packages may only be riantr/* (this repo), plus the single moonbit-community/sqlite3@0.2.3 entry in the moon.mod import block (v0.85.0) — declared, not imported by any .mbt.
    • Pin to the latest published version (e.g. moonbitlang/async@0.20.3).
    • Consequence: examples/api_server/ builds directly on moonbitlang/async's raw Server API. No third-party HTTP framework is allowed.

    #Determinism & validation

    • All randomness flows through chacha8_rng(seed) (seed.mbt). Default seed=3141; same seed ⇒ byte-identical DGP outputs.
    • Python reference scripts validate_*_with_python.py reproduce the upstream doubleml-for-py numbers. CI greps the trailing PASS line from each script.
    • dgp_recovery_test.mbt enforces |coef - theta| < MAX(MODEL_TOL=0.1,2.0 * handrolled_se). The tolerance is contractual.
    • v0.62.0 verified counts: moon test 485 / 485 (native & wasm & js) and 491 / 491 (wasm-gc); python _verify/run_all_validators.py 23 / 23 PASS in ~70 s. moon fmt --check is now clean (was failing on every release since v0.57.0).
    • v0.63.0 verified counts: moon test 491 / 491 (native & wasm & js) and 497 / 497 (wasm-gc); 23 / 23 Python cross-validators PASS in ~90 s. Adds 6 new wbtests (v063_wbtest.mbt) covering APO learner plumbing + APOS bootstrap/confint + BLP plumbing.
    • v0.74.0 verified counts: moon test 554 / 554 (native & wasm & js) and 560 / 560 (wasm-gc); 23 / 23 Python cross-validators PASS. Closes the cluster-aware sensitivity family with sensitivity_analysis_cluster on LPQ / PQ / QTE / APOS / SSM / BLP / CVaR (7 wbtests in v074_wbtest.mbt); 20/22 estimators now expose both IID and cluster-aware sensitivity.
    • v0.77.0 verified counts: moon test 561 / 561 (native & wasm & js) and 567 / 567 (wasm-gc); 23 / 23 Python cross-validators PASS. Adds cross-estimator joint sensitivity (joint_sensitivity in sensitivity.mbt, 3 white-box tests in joint_sensitivity_test.mbt): per-estimator Bonferroni-corrected CIs plus cross-estimator joint CI / RV / RV_q via min(per_estimator_*) collapse (Cinelli & Hazlett 2020 §3.6 family setting).
    • v0.78.0 verified counts: moon test 566 / 566 (native & wasm & js) and 572 / 572 (wasm-gc); 23 / 23 Python cross-validators PASS. Closes the v0.72-v0.74 cluster-aware sensitivity family for the kernel-weighted local-polynomial DoubleMLRDD estimator: extends irm_style_sensitivity_cluster (in sensitivity.mbt) with an optional kernel_weights parameter (default empty = uniform weights, v0.72 behavior); when non-empty, each observation's residual and Riesz row are scaled by the triangular kernel weight w[k] = 1 - |u_k| / h on the bandwidth-restricted sample before the cluster sum. Adds DoubleMLRDD::sensitivity_analysis_cluster(cluster_ids, cf_y?,cf_d?) -> SensitivityResult plus 5 white-box tests in rdd_cluster_test.mbt (smoke + sigma2-differs-from-IID + 3 panic tests); 22 / 22 estimators now expose both IID and cluster-aware sensitivity.
    • v0.83.0 verified counts: moon test 607 / 607 (native & wasm & js) and 613 / 613 (wasm-gc); 23 / 23 Python cross-validators PASS. Closes the v0.80/v0.81/v0.82 memoize + vectorize expand for DoubleMLCVAR (complete v0.82 partial: fix pq_est cache-hit path; cache also stores ipw_vec), DoubleMLSSM (complete v0.82 partial: add memoize_enabled / fit_cache struct fields correctly), DoubleMLBLP (single-pass OLS projection cached byte-for-byte), DoubleMLPLPR (clustered path: cache stores (l_pred, m_pred, g_pred) plus row-to-fold map; cache-hit path re-runs the cluster-robust SE pipeline from cached values), and DoubleMLLPLR (Newton-solved binary-outcome estimator: cache stores (t_pred, m_pred, a_pred, beta_start); cache-hit path re-runs Newton + score + SE from cached values). Per-fold residual loops in each are rewritten in terms of the vectorized.mbt helpers (vector_subtract, vector_scale, vector_divide, vector_multiply, vector_add). 15 / 22 estimators now carry memoize + vectorize.
    • v0.84.0 verified counts: moon test 614 / 614 (native & wasm & js) and 620 / 620 (wasm-gc); 23 / 23 Python cross-validators PASS. Closes the v0.80/v0.81/v0.82/v0.83 memoize + vectorize expand for DoubleMLAPO (clean add: cache stores LAST-rep (g_hat, m_hat, psi_a, psi_b); cache-hit path re-runs var_est from cached values), DoubleMLAPOS (memoize forwarding: parent-level (coefs, ses) cache + .enable_memoize() forwarded to each child DoubleMLAPO), DoubleMLPQ (cache stores (theta, deriv, psi, fold_ids); cache-hit skips the entire solve_pq), DoubleMLQTE (cache stores per-quantile per-treatment (theta1, psi1, deriv1, theta0,psi0, deriv0); cache-hit skips the 2 * n_quantiles solve_pq loop), and DoubleMLRDD (no-fold estimator: cache stores the entire (coef, se, n_local, residuals,psi_a) tuple under a (data, cutoff, bandwidth, fuzzy, cov_type, ml_g) key; cache-hit skips all four rdd_side calls). Per-fold residual loops in each are rewritten in terms of the vectorized.mbt helpers (vector_subtract, vector_scale, vector_divide, vector_multiply, vector_add). 20 / 22 estimators now carry memoize + vectorize.
    • v0.85.0 verified counts: moon test 617 / 617 (native & wasm & js) and 623 / 623 (wasm-gc). Closes the memoize + vectorize expand for DoubleMLPolicyTree (a deterministic policy learner with no n_folds / n_rep / fit_cluster: the cache holds the flat-encoded PolicyTreeNode tree plus the per-leaf leaf_assignment / leaf_signal_mean / leaf_count statistics, keyed on (data_hash, depth, hyperparams_hash); a cache hit skips policy_tree_build and the leaf-walk loop entirely). The per-leaf mean uses vector_divide and sensitivity_analysis uses a single vector_subtract over a gathered per-row leaf mean. 22 / 22 estimators now carry memoize + vectorize. Also adds the moonbit-community/sqlite3@0.2.3 dependency plus the async 0.22.4 header-map type fix in examples/api_server. The three new white-box tests in expand_v085_test.mbt include a ground-truth cross-check of the cache-hit tree against an independent memoize-OFF fit, and a deliberately asymmetric DGP so that a left/right swap in the flat node encoding is detectable (a symmetric interaction DGP yields a mirror-invariant tree and would hide such a bug).
    • v0.86.0 verified counts: moon test 623 / 623 (native & wasm & js) and 629 / 629 (wasm-gc). Adds the shared sandwich_variance(kind, psi_a, psi, m_inv, n_obs, n_params) dispatch in sandwich.mbt and the sandwich_se / cluster_sandwich_se / bias_corrected_coef triple on DoubleMLIIVM / DoubleMLPLIV / DoubleMLDID / DoubleMLCVAR (6 of 22 estimators).
    • v0.87.0 verified counts: moon test 628 / 628 (native & wasm & js) and 634 / 634 (wasm-gc: lib 628 + 6 doc tutorials). Extends the sandwich-variance API to DoubleMLSSM, DoubleMLPLPR, DoubleMLDIDCrossSection, and DoubleMLDIDCSBinary (10 of 22 estimators), all routing through the v0.86.0 shared sandwich_variance(kind, ...) dispatch. DoubleMLLPLR is deliberately skipped: it persists its influence-function components in the inverted (offset, slope) order (psi_a = score - theta_hat * psi_deriv, psi_b =psi_deriv), so mean(psi_a) is a cancellation residual rather than the Jacobian -- feeding it into M_inv = [[1 / mean(psi_a)]] inflates HC0 by ~60x over LPLR's own se(). See expand_v087_test.mbt for the full rationale and the two candidate fixes. The 5 new white-box tests assert the independently recomputed HC0 / HC2 / HC3 variances (not just finiteness), the exact HC1 sqrt(n / (n - 1)) identity, exact singleton-cluster equality with the IID HC0, and the bias-correction identity. (The leverage-signed ordering HC1 > HC0 > HC2 > HC3 they also asserted described the v0.79.0 - v0.87.0 leverage bug and is corrected in v0.88.0 below.)
    • v0.88.0 verified counts: moon test 634 / 634 (native & wasm & js) and 640 / 640 (wasm-gc: lib 634 + 6 doc tutorials). BREAKING NUMERICAL CHANGE, HC2 / HC3 only. Fixes the leverage used by sandwich_variance_hc2 / sandwich_variance_hc3 in sandwich.mbt. v0.79.0 - v0.87.0 used h_ii = psi_a[i] * M_inv[0,0] * psi_a[i], which is not a hat-matrix diagonal; with the package convention M_inv = [[1 / mean(psi_a)]] and the usual mean(psi_a) < 0 it came out negative, so 1 - h_ii > 1 and HC2 / HC3 shrank the variance instead of widening it -- the opposite of MacKinnon (2012) sec 5.4. Worst case (psi_a = -1 constant, i.e. IRM / SSM / CVAR / DID ATT) h_ii = -1 on every row, so HC2 was exactly HC0 / 2 and HC3 exactly HC0 / 4. The moment actually being inverted is the single-parameter mean moment E[psi_a * psi(theta)] = 0, whose implicit regression is an intercept-only, equally weighted mean regression; its projection matrix is (1 / n) * J, so every leverage is the constant h_ii = 1 / n_obs. No estimator in the package persists a per-observation design matrix (only psi_a, psi_b, coef), so 1 / n_obs is used uniformly -- which is also what keeps the fix inside sandwich.mbt with no estimator-file changes. Under that leverage HC2 == HC1 exactly and HC3 == HC1^2 / HC0 exactly, and all three corrections widen (HC3 > HC2 > HC1 == HC2 > HC0). sandwich_se(HC2) / sandwich_se(HC3) therefore increase for all 10 estimators that expose them; HC0 and HC1 are bit-identical to v0.87.0 (regression-pinned in expand_v088_test.mbt, which adds the 6 falsifiable HC2 / HC3 tests: the HC2 == HC1 and HC3 == HC1^2 / HC0 identities, 0 <= h_ii < 1 with h_ii == 1 / n across five psi_a families, the widening ordering, the HC0 / HC1 regression values, and the constant-psi_a = -1 case).
    • v0.89.0 verified counts: moon test 640 / 640 (native & wasm & js) and 646 / 646 (wasm-gc: lib 640 + 6 doc tutorials). Extends the v0.86.0 sandwich API to the APO family and the binary-DID wrapper (coverage 10 -> 12 of 22 estimators):
      • DoubleMLAPO -- clean add. psi_a (structurally the constant -1) and psi_b (the IPW-centred potential-outcome score) are both persisted struct fields, so sandwich_se(kind) / cluster_sandwich_se(cluster_ids) / bias_corrected_coef()
      • DoubleMLDIDBinary -- pure forwarder. The wrapper holds the whole fitted inner DoubleMLDID (inner : DoubleMLDID), which already implements the v0.86.0 API, so the three methods delegate instead of recomputing (the tests assert bit-identical results against self.inner). The inner owns the IF components, so the sandwich sample is the POST-SUBSET wide-format width n_obs_subset() (300 of a 600-row long-format panel in the test DGP), NOT the panel width and NOT the length of the zero-filled psi_a_long().
      • DoubleMLAPOS, DoubleMLDIDCS, DoubleMLDIDMulti deliberately skipped -- see the CHANGELOG entry. APOS persists only (coefs, ses) per level and discards the child APOs' IF components (no own scores, no inner estimator to forward to); DIDCS is multi-cell and stores its per-cell psi_a_matrix on the long panel with out-of-cell rows zero-filled, so the per-cell subset width the HC1 identity needs is not recoverable; DIDMulti is a pure wrapper around DIDCS with no own scores and no scalar coefficient.
      • The 6 new white-box tests in expand_v089_test.mbt assert the v0.88.0 leverage identities on the estimator methods (HC1 == HC0 * sqrt(n / (n - 1)), HC2 == HC1, HC3 == HC1^2 / HC0, i.e. the WIDENING ordering HC1 == HC2 > HC0 and HC3 > HC2 -- the pre-v0.88 ordering HC1 > HC0 > HC2 > HC3 is the bug, not the contract), independently recomputed HC0 / HC2 / HC3 / cluster variances (not just finiteness), exact singleton-cluster equality with the IID HC0 plus a strictly different pooled-cluster value (proving cluster_ids is consumed), the coef + mean(psi_b - coef * psi_a) bias-correction identity (plus APO's closed form 3 * coef, since theta_hat = mean(psi_b) and psi_a = -1) -- that identity is superseded by v0.91.0, which removed the method's score-based correction and made it return coef unchanged, and the post-subset n pin for the DID binary wrapper.
      • Observed n: DoubleMLAPO persists its IF components on the FULL sample domain (psi_a.length() == n_obs(), both the IID and the fit_cluster path), so it has no n hazard; DoubleMLDIDBinary is on the post-subset wide-format panel (300 of 600), like DoubleMLDIDCSBinary (400 of 600) and unlike DoubleMLPLPR (180 of 240).
    • v0.90.0 verified counts: moon test 648 / 648 (native & wasm & js) and 654 / 654 (wasm-gc: lib 648 + 6 doc tutorials). Routes every sandwich and bootstrap call site through a single psi_at(coef, psi_a, psi_b) helper in sandwich.mbt, replacing 13 inline copies of psi_a[i] + coef * psi_b[i] in which the roles of psi_a (the Jacobian / coefficient row) and psi_b (the offset) were swapped — so the sandwich and multiplier-bootstrap families were evaluating g(theta) = E[psi_a + theta * psi_b], a different function whose root is not theta_hat. On a fixed DGP the resulting sandwich_se(HC0) differed from the analytic se() by three orders of magnitude. psi_at makes the order explicit in one place so 13 copies cannot drift again. The score is now also evaluated at the estimate rather than at zero on every path. LPLR's own bootstrap call site is verified bit-identical across v0.89.0 / v0.90.0 (the two errors cancelled there), and its psi is now expressed as the explicit swap (self.psi_b, self.psi_a). DoubleMLLPLR still got no sandwich_se at this point: its HC0 sat at 0.879 * se() because the accumulator defect v0.91.0 fixed was still open.
    • v0.91.0 verified counts: moon test 656 / 656 (native & wasm & js) and 662 / 662 (wasm-gc: lib 656 + 6 doc tutorials). BREAKING NUMERICAL CHANGE, all 12 sandwich estimators. Corrects two independent errors in the sandwich.mbt accumulator, both of which were open items in the v0.90.0 entry:
      • It summed (psi_a[i] * psi[i])^2. The DML moment being inverted is the mean moment E[theta * psi_a + psi_b], whose implicit regressor is the constant 1, so the per-observation quadratic form is psi[i]^2 with no psi_a weight. For constant psi_a the spurious c^2 cancelled against M_inv^2 = 1 / c^2 (a no-op); for non-constant psi_a it re-weighted the meat by a data-dependent factor (0.229 on the PLR DGP).
      • It returned the variance of sqrt(n) * (theta_hat -theta) rather than of (theta_hat - theta): var_est divides by n a second time, and the sandwich did not. This is the sqrt(n) the v0.90.0 release had to accommodate.
      • sandwich_variance_hc0 / _hc1 / _hc2 / _hc3 and cluster_sandwich_variance now accumulate sum_i psi[i]^2 and return M_inv[0,0]^2 * acc / n / n, so se() == sandwich_se(HC0) for every estimator -- including the non-constant-psi_a ones, which no scaling of the old accumulator could produce. Measured on the v0.90.0 DGP (n = 400): IRM 0.21652894217092453 -> 0.010826447108546225 = its se(); PLR 0.19759510529621752 -> 0.020629646119313564 = its se(). Every HC kind moves by the same sqrt(n), and because the HC identities are ratios, HC1 == HC0 *sqrt(n / (n - 1)), HC2 == HC1, HC3 == HC1^2 / HC0 and the ordering HC3 > HC1 == HC2 > HC0 all survive untouched. HC2 == HC1 is now 1e-12 rather than bit-exact, so a test asserting HC2 > HC1 was asserting a falsehood and is now HC2 == HC1. All-singleton clusters still equal IID HC0, and both now equal se().
      • bias_corrected_coef (12 methods) is now a documented no-op returning coef unchanged. Under var_est's convention coef is the root of the moment, so mean(coef * psi_a + psi_b) == 0 identically: the estimating function is orthogonal by construction and there is no score-based bias to correct. The old form passed the score at -coef rather than at coef and returned coef * (1 - 2 * mean(psi_a)), i.e. exactly 3 * coef on every constant-psi_a estimator -- a number that looks like a bias correction and is not one. Removing the methods outright is the obvious follow-up.
      • Not changed: M_inv = [[1 / mean(psi_a)]], the v0.88.0 leverage h_ii = 1 / n_obs, the v0.90.0 psi_at helper, and var_est.mbt (the reference, not the bug). DoubleMLLPLR still gets no sandwich_se in this release -- its accumulator blocker is now resolved (its HC0 equals its se() to the last ulp, was 0.879 * se()), but exposing the accessor is a separate API decision, taken in v0.92.0 below.
    • v0.92.0 verified counts: moon test 664 / 664 (native & wasm & js) and 670 / 670 (wasm-gc: lib 664 + 6 doc tutorials). Adds the sandwich_se / cluster_sandwich_se / bias_corrected_coef triple to DoubleMLLPLR (coverage 12 -> 13 of 22) and backfills the README for v0.87.0 - v0.92.0. se() and the 12 existing sandwich estimators are numerically unchanged; sandwich.mbt and var_est.mbt are untouched.
      • DoubleMLLPLR was skipped in v0.87.0 and again in v0.90.0 for one structural reason: it persists its influence-function components inverted (self.psi_a = the score OFFSET sc.psi - theta_hat * sc.psi_deriv, self.psi_b = the DERIVATIVE sc.psi_deriv), the mirror of the package convention. So both the score and the Jacobian take the arrays swapped -- psi_at(coef, self.psi_b, self.psi_a) and M_inv = [[1 / mean(self.psi_b)]] -- which is exactly the treatment its bootstrap call site has used since v0.90.0, so the two paths cannot drift apart. v0.87.0 fed mean(self.psi_a) (a catastrophic-cancellation residual) into M_inv; on the test DGP that is +0.01899446402902459 where the Jacobian is -0.036387245464012986, i.e. the wrong sign and a 1.9156763469825346x inflation of HC0. (The v0.87.0 report's "~60x" was a different DGP at n = 400 measured through the then-still-broken v0.87.0 accumulator; the two figures are not in conflict.)
      • The payoff invariant now holds for LPLR, to the last ulp: on the v0.90.0 LZZ2020 binary DGP (n = 500, p = 6, n_folds = n_folds_inner = 2, n_rep = 1, seed = 3141) with coef = 0.5220088464187301: mean(psi_a) = 0.01899446402902459 (offset) vs mean(psi_b) = -0.036387245464012986 (derivative); se() == HC0 == 0.278056227496941; HC1 == HC2 ==0.2783347015051384; HC3 == 0.27861345440575247; cluster singleton 0.278056227496941 == se(), pooled (blocks of 4) 0.28937508055158356. The wrong-Jacobian HC0 would have been 0.5326657381470845. On native / wasm-gc / wasm the HC0 == se() equality is bit-exact; on js the two spellings of the same expression (M_inv[0,0]^2 * acc / n / n vs acc / n / (j * j * n)) differ by one ulp, so the portable contract is 1e-12 and the test asserts 1e-14, not ==.
      • bias_corrected_coef is the v0.91.0 documented no-op (returns coef exactly), for the same orthogonality reason as the other 12; LPLR's coef is the root of f(theta) = E[theta * psi_b + psi_a] in its persisted order.
      • 8 white-box tests in expand_v092_test.mbt: lplr_se_equals_sandwich_hc0 (the decisive one, at 1e-14 with a documented js-backend ulp caveat, plus the negative control that the package-order score does not reproduce se()), lplr_hc1_hc0_ratio, lplr_hc2_equals_hc1, lplr_hc3_equals_hc1_squared_over_hc0, lplr_ordering, lplr_singleton_cluster_equals_se, lplr_bias_corrected_coef_is_identity, and lplr_jacobian_is_the_derivative_not_the_offset (the regression pin against the v0.87.0 bug: it recomputes HC0 under both candidate Jacobians and requires the shipped value to match the derivative one).
      • README audit beyond the version / count / ordering updates: the v0.90.0 release entry was missing entirely; the #Quick start block still claimed Total tests: 485 (v0.62.0); #Project layout still said moon.mod v0.80.0 and 148 .mbt files; #Models said 129 files total; moon.work was called a 15-member workspace (it has 16); and the "strict dependency hygiene" / #Dependency rule claims that the library uses only official moonbitlang/* packages had been false since v0.85.0, which added a declared moonbit-community/sqlite3@0.2.3 import. A new #Sandwich variance section now states the HC contract once, in one place, including the DoubleMLDIDCrossSection projection-estimator exception.

    #Attribution

    moonbit_doubleML is a port of the upstream DoubleML/doubleml-for-py package (BSD 3-Clause License). All 19 upstream models are faithfully re-implemented in pure MoonBit with the same score formulae and variance estimators; the 3 MoonBit-only additions (DoubleMLPLPR, DoubleMLLPLR, DoubleMLDIDCSBinary) are extensions beyond the upstream scope.

    #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, with optional JSON in/out for native / wasm-gc / wasm / js backends (Serverless / Wasm / edge deployments).
    • Behaviour-level parity check via the 23 Python reference scripts: within-tolerance equivalence rather than bit-exact re-implementation. This keeps the port resilient to upstream refactors.
    • Strict dependency rule (see above): only moonbitlang/* official packages. Minimal supply-chain surface.

    #Plotting: deliberately not ported

    Upstream doubleml-for-py ships three plotting modules and three plot() entry points — doubleml/utils/_plots.py, doubleml/did/utils/_plot.py, and plot on DoubleMLDIDMulti, DoubleMLDID and DoubleMLPolicyTree (the event-study plot, the aggregated-DID plot, and the policy-tree plot). None of that is ported, and that is a decision rather than an oversight.

    The reason is the dependency rule above. Every one of those entry points reaches matplotlib, and MoonBit's official packages carry no plotting backend; the backends this package does target are wasm / native / js, where a plotting library is either unavailable or a large non-moonbitlang/* dependency. Adding it would trade the property this package is built around — a zero-non-official-dependency supply chain — for three charts.

    If you need them, the estimators already expose what they plot: DoubleMLDIDMulti::aggregate_event / ::aggregate_time / ::aggregate_group return DIDAggregationResult, and DoubleMLPolicyTree exposes leaf_influence, leaf_se and policy_value. Rendering those is a few lines on your side, in whatever tooling you already use.

    The claim is enforced, not just asserted: validate_plotting_scope.py checks that this section exists AND that no plotting entry point has appeared in the package. If plotting is ever added, that validator goes red and this paragraph has to be updated in the same commit — so this sentence cannot quietly become a lie.

    #Used By

    • 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).

    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

    v0.66.0+: Cinelli & Hazlett (2020) omitted-variable bias analysis. Outcome residual is y - g_hat (the APO is conditioned on treated=1); the Riesz-representer variance is mean(psi_a^2) = 1 for the APO score (psi_a = -1 constant). Routes through the shared irm_style_sensitivity helper.

    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::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::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:
    • "nuisance_space": the per-fold ml_m training set is filtered to rows with Y = 0 (the "nuisance space" of the ATE on the treated subsample). The starting beta is computed inside the loop, 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: these two used to be inert. score was validated and stored but never read, so both strings returned the nuisance_space answer bit for bit. If you are upgrading: the nuisance_space numbers move slightly (because ml_m is now fitted on the Y = 0 subsample instead of being aliased to ml_a), and instrument produces a genuinely different estimate for the first time.

    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
    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, 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): cf_y / cf_d are the confounding-strength upper bounds (defaults 0.05) and are passed through to the result for upstream parity.

    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 : PSProcessor
    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::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, 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 is mean(psi_a^2) for the DID ATT score. Routes through the shared irm_style_sensitivity helper.

    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::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 : PSProcessor
    score : String
    in_sample_normalization : Bool
    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):
    • ps_processor field replaces the bare propensity_clip argument. The processor's clipping_threshold is used to bound the propensity scores inside the score denominator; the field-level propensity_clip is retained for backward compat but fit reads the clip threshold from ps_processor.clipping_threshold instead.
    • 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::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, score? : String, in_sample_normalization? : Bool) -> 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 : PSProcessor
    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]]
    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
    } 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::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, in_sample_normalization? : Bool) -> DoubleMLDIDCS

    DoubleMLDIDCS::period_at

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

    Time value at column index t (sorted ascending).

    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::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 : PSProcessor
    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]
    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
    } 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.3) 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::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, score? : String, in_sample_normalization? : Bool) -> 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. Outcome residual is y - g_d0_t0 - (g_d1_t0 - g_d0_t0) * d on the post-subset panel; the Riesz-representer variance is mean(psi_a^2). Routes through the shared irm_style_sensitivity helper.

    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 form (y - g_d0_t0 - (g_d1_t0 - g_d0_t0) * d) and the same psi_a as the IID path; 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 : PSProcessor
    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, 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 test in _verify/test_bootstrap_reference.py).

    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
    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::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, 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

    v0.66.0+: Cinelli & Hazlett (2020) omitted-variable bias analysis. Outcome residual is y - g0_hat - (g1_hat - g0_hat) * d (the doubly-robust outcome regression evaluated at the observed treatment); the Riesz-representer variance is mean(psi_a^2) = 1 for the IRM ATE score (psi_a = -1 constant — the helper short-circuits when nu2 == 1). Routes through the shared irm_style_sensitivity helper (see sensitivity.mbt).

    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::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
    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 outer-OOF predictions (clipped to [1e-8, 1 - 1e-8], then logit); 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). Average across folds for the Newton starting value.
    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_start * a_hat_i (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.

    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.

    DoubleMLLPQ

    pub struct DoubleMLLPQ {
    data : DoubleMLLPQData
    treatment : Double
    quantile : Double
    n_folds : Int
    seed : Int
    propensity_clip : Double
    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 twelve 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) -> 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.

    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.

    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

    The learner_l / learner_m labeled params accept any LearnerDispatch (defaults to the constructor-set values, i.e. a fresh LinearRegression). Per-fit overrides let callers swap in alternative nuisance estimators (ConstantLearner, NoopLearner, ...) without rebuilding the DoubleMLPLR instance.

    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. Outcome residual is y - l_hat; the Riesz-representer variance is mean(psi_a^2) where psi_a = -v^2 for the partialling-out score (v = d - m_hat). Routes through the shared irm_style_sensitivity helper (see sensitivity.mbt).

    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. Same residual formula (y - l_hat) and the same psi_a as the IID path; only the variance / bias computation is cluster-aware (see irm_style_sensitivity_cluster). cluster_ids defaults to DoubleMLData::cluster_vars (the optional 5th constructor arg added in v0.55.0); pass an explicit cluster_ids to override.

    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
    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 thirteen 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

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

    v0.84.0+: turn on memoization. When enabled, the next fit() caches the solve_pq(...) outputs (theta, psi, deriv) 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 outputs. The (coef, se) aggregation from cached values still runs on every fit().

    DoubleMLPQ::fit

    fn DoubleMLPQ::fit(self : DoubleMLPQ, ml_l? : LearnerDispatch, ml_m? : LearnerDispatch) -> DoubleMLPQ

    DoubleMLPQ::has_cache

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

    v0.84.0+: true iff fit_cache holds at least one cached solve_pq(...) result (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.

    DoubleMLPQ::learner_l

    fn DoubleMLPQ::learner_l(self : DoubleMLPQ) -> LearnerDispatch

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

    DoubleMLPQ::learner_m

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

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

    DoubleMLPQ::n_features

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

    Number of features (covariate columns).

    DoubleMLPQ::n_obs

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

    Number of observations.

    DoubleMLPQ::new

    fn DoubleMLPQ::new(data : DoubleMLData, treatment? : Double, quantile? : Double, n_folds? : Int, seed? : Int, propensity_clip? : Double, ml_l? : LearnerDispatch, ml_m? : LearnerDispatch) -> DoubleMLPQ

    DoubleMLPQ::sample_splitting

    fn DoubleMLPQ::sample_splitting(self : DoubleMLPQ) -> 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. folds is what fit cross-fits with; reps is the supplied repetition count, of which fit consumes only the first.

    DoubleMLPQ::sandwich_se

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

    v0.94.0+: heteroskedasticity-consistent (Huber-White) sandwich standard error for the fitted PQ. 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 a hard-coded constant.

    n_obs is self.psi.length(), the full sample: PQ has no transformed or subset domain.

    On a CLUSTERED fit (non-empty data.cluster_vars, DoubleMLPQ::fit_cluster) se() is the unit-level cluster-robust variance, not the IID one, so the sandwich_se(HC0) == se() invariant does not hold there; use cluster_sandwich_se(self.data.cluster_vars), which is the unit-level analogue of this method.

    Preconditions: self.fitted, |psi_a[0]| >= 1e-12.

    DoubleMLPQ::se

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

    DoubleMLPQ::sensitivity_analysis

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

    v0.67.0+: Cinelli & Hazlett (2020) omitted-variable bias analysis for DoubleMLPQ (partial quantile). 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).

    DoubleMLPQ::sensitivity_analysis_cluster

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

    v0.74.0+: cluster-robust analogue of DoubleMLPQ::sensitivity_analysis. Mirrors the LPQ pattern: the centered-IF formulation (sigma2 = Var(y), nu2 = mean(psi^2)) is replicated inside irm_style_sensitivity_cluster by passing residuals = y - mean(y) and psi_a = self.psi. Only the variance / bias computation is cluster-aware.

    cluster_ids defaults to DoubleMLData::cluster_vars (empty array for the non-clustered constructor path, in which case the caller's explicit cluster_ids is required to produce a meaningful cluster-robust estimate).

    DoubleMLPQ::set_sample_splitting

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

    Record a caller-supplied sample splitting and DERIVE the fold count from it. Returns a new DoubleMLPQ; 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 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 is 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.

    PQ has NO n_rep, so the repetition axis has nothing to drive: it is a single-fit estimator with no repetition loop, and fit consumes smpls[0] only. A multi-repetition partition is therefore accepted and validated in full, but repetitions 1.. are not used by fit. sample_splitting reads the repetition count back as supplied, so a caller who passed several can see that the count did not shrink to one. There is no per-quantile reading to confuse this with either: PQ is a single (quantile, treatment) estimator and smpls applies to the one nuisance cross-fit it runs.

    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.

    Cluster data: the supplied folds are ROW-level, and fit_cluster draws its own UNIT-level partition via kfold(n_units, ...) and ignores them. The external splitting applies to the row-level (IID) path only.

    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.

    DoubleMLPQ::tune

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

    v0.108.0+ (NEW): score a grid of nuisance-learner pairs and re-fit DoubleMLPQ with the winner, via the shared tune_score_grid core (fold draw + MSE/RMSE/NegMSE scoring + argmin all live there; this method only adapts the grid shape and calls fit).

    Slots tuned: BOTH ml_l and ml_m, i.e. TuneParam's learner_l / learner_m. PQ's ml_l is the OUTCOME-side learner -- solve_pq calls cross_fit_conditional(ml_l, ...) on the binarized outcome 1{y <= theta} and ml_m is the PROPENSITY learner (fit_propensity(ml_m, ...)), which is the reverse of DoubleMLAPO's pair. So build grid rows with TuneParam::for_outcome, not for_treatment: the fields are named for the partially linear family and do not change meaning with the family (see the slot-semantics table on TuneParam).

    Only ml_l is SCORED (MSE-on-outcome cross-fit, the convention shared by every tune in this package); ml_m rides along as the co-varying slot, exactly as in DoubleMLAPO::tune / DoubleMLPLR::tune.

    Cluster guard: PRESENT, because DoubleMLData has is_cluster_data() and DoubleMLPQ::fit dispatches to fit_cluster. DoubleMLAPO::tune shipped for years without this guard while its siblings had it -- cluster-DML tune folds must be drawn over unique units, not rows, and a row-wise fold schedule on clustered data yields a plausible-looking score for a wrong cross-fit. Do not drop it.

    DoubleMLPanelData

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

    Double / debiased machine learning for the static panel partially linear regression model (upstream: doubleml.plm.DoubleMLPLPR, Clarke & Polselli 2025):

    Y_it = D_it * theta_0 + g_0(X_it) + alpha_i + zeta_it

    where alpha_i is a unit fixed effect. The panel structure is first transformed into a cross-section via one of four static panel approaches, and a standard DML partialling-out / IV-type score is applied to the transformed data:

    • "cre_general": correlated random effects (Mundlak). Augment X with per-unit means of every covariate column. After cross-fitting, adjust the treatment nuisance: m_hat* = m_hat + d_mean - mean_by_id(m_hat) where d_mean is the per-row unit mean of D.
    • "cre_normal": CRE with a normality-style restriction. Same X augmentation, but the treatment regression gets [X, d_mean] as inputs; no post-hoc m_hat adjustment.
    • "fd_exact": exact first differencing. The panel is reindexed to the full id x time grid, y and d are first-differenced within each unit, and covariates become [X_t, X_{t-1}]. Rows missing x_t or x_{t-1} are dropped.
    • "wg_approx": approximate within transformation. within(v) = v - unit_mean(v) + grand_mean(v) for y, d, and every covariate; PLR runs on the within-transformed variables alone.

    All four approaches reuse the shared cross-fit machinery (kfold + cross_fit_predict). Because upstream re-wraps the transformed data as static-panel data with cluster_cols =id_col, estimation always takes the clustered DML path: folds partition whole units, the coefficient is a fold-weighted ratio of cluster score sums (est_coef_cluster), and the SE is unit-level cluster-robust (var_est_cluster), with the closed-form LinearRegression learner.

    DoubleMLPanelData::new

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

    DoubleMLPolicyTree

    pub struct DoubleMLPolicyTree {
    features : Matrix
    orth_signal : Array[Double]
    depth : Int
    root : PolicyTreeNode
    split_feature : Int
    split_value : Double
    left_treatment : Int
    right_treatment : Int
    leaf_assignment : Array[Int]
    leaf_signal_mean : Array[Double]
    leaf_count : Array[Int]
    honest : Bool
    split_seed : Int
    min_leaf_n : Int
    est_indices : Array[Int]
    split_indices : Array[Int]
    leaf_se : Array[Double]
    fitted : Bool
    memoize_enabled : Bool
    fit_cache : FitCache
    } derive(
    Debug
    )

    A compact policy tree. It searches one split per level using weighted variance-reduction gain (Bug #8); the depth parameter controls how many levels of recursion to use (TODO #11c.3: previously the depth field was unused and the fit was always a depth-1 stump).

    DoubleMLPolicyTree::clear_cache

    v0.85.0+: drop any cached policy tree + leaf statistics. Forces the next fit() to recompute from scratch.

    DoubleMLPolicyTree::disable_memoize

    v0.85.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).

    DoubleMLPolicyTree::enable_honesty

    fn DoubleMLPolicyTree::enable_honesty(self : DoubleMLPolicyTree, on : Bool) -> DoubleMLPolicyTree

    v0.98.0+: turn HONESTY on or off. Same immutability contract as enable_memoize(): a new struct is returned, the receiver is untouched, and the config flag can be read with is_honest() BEFORE fit().

    Toggling this on an already-fitted, memoized model keeps the existing fit_cache, but the cache key includes the honesty flag, so the next fit() MISSES and recomputes -- the cache can never hand an adaptive fit's numbers to an honest request, nor the reverse. clear_cache() drops it outright.

    DoubleMLPolicyTree::enable_memoize

    v0.85.0+: turn on memoization for subsequent fit() calls. When enabled, fit() caches the fitted policy tree plus the per-leaf statistics and skips policy_tree_build + the leaf-walk loop on a repeat call whose features, orthogonal signal, and depth are all unchanged. Mirrors the BLP / IRM / PLR / CVAR / SSM plumbing.

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

    DoubleMLPolicyTree::enable_split_seed

    fn DoubleMLPolicyTree::enable_split_seed(self : DoubleMLPolicyTree, seed : Int) -> DoubleMLPolicyTree

    v0.98.0+: re-seed the honesty split. Ignored by the default (non-honest) path, which has no split to seed; folded into the memoize key, so changing it on a memoized model invalidates the cache exactly like toggling honest does.

    DoubleMLPolicyTree::est_indices

    fn DoubleMLPolicyTree::est_indices(self : DoubleMLPolicyTree) -> Array[Int]

    v0.98.0+: the ESTIMATION half -- original row indices of the observations every reported leaf statistic is computed from. Length ceil(n_obs / 2) under honesty. EMPTY when honest = false (there the estimation sample is the whole sample in identity order).

    Under honesty leaf_assignment has THIS length, not n_obs: position j of leaf_assignment describes row est_indices()[j]. leaf_influence returns arrays of the same length, indexed the same way.

    DoubleMLPolicyTree::fit

    DoubleMLPolicyTree::has_cache

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

    v0.85.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 features / orthogonal signal / depth -- check memoize_enabled before assuming a cache hit.

    DoubleMLPolicyTree::is_honest

    fn DoubleMLPolicyTree::is_honest(self : DoubleMLPolicyTree) -> Bool

    v0.98.0+: which regime produced this model's numbers -- true iff the fit split the sample (honesty), false for the v0.97.0 adaptive fit.

    This is the check a caller should make before reading ANY of the uncertainty accessors. leaf_se, policy_value, policy_value_se, leaf_influence and the honest branch of sensitivity_analysis are all defined on the estimation half of an honest fit and refuse to report on an adaptive one; is_honest() lets the caller branch instead of catching an abort. Readable before fit() -- it is a configuration flag, not a fitted quantity.

    DoubleMLPolicyTree::leaf_influence

    fn DoubleMLPolicyTree::leaf_influence(self : DoubleMLPolicyTree, leaf : Int) -> Array[Double]

    v0.98.0+: THE LEAF-MEAN INFLUENCE FUNCTION, ONE LEAF AT A TIME.

    DERIVATION. Leaf k of an honest tree is estimated by the mean of n_k i.i.d. observations of the estimation half. Write its estimating equation as an average over the leaf's own rows:

    f_k(theta) = (1/n_k) * sum_{i in k} (y_i - theta) = (1/n_k) * sum_{i in k} y_i - theta f_k'(theta) = -n_k * (1/n_k) = -1 f_k(theta_hat_k) = 0 at theta_hat_k = mean(y in k)

    For a Z-estimator f(theta) = (1/n) sum_i f_i(theta) the influence function is IF_i = -f_i(theta_hat) / f'(theta_hat). Splitting the estimating function per observation, f_i(theta) = (y_i - theta) / n_k, so f_i'(theta) = -1/n_k and

    IF_k(i) = -[(y_i - theta_hat_k) / n_k] / (-1) = (y_i - theta_hat_k) / n_k

    on the estimation rows of leaf k, and 0 everywhere else. So M_inv = 1 / f_k' = -1 and the per-observation Riesz denominator that irm_style_sensitivity consumes is psi_a[i] = f_i'(theta_hat_k) = -1 / n_k -- see leaf_psi_a.

    TWO CONSISTENCY CHECKS WORTH WRITING DOWN. (i) It sums to zero within the leaf: sum_{i in k} IF_k(i) = (1/n_k) sum_{i in k}(y_i - theta_hat_k) = 0, which is required of any influence function. (ii) Its norm reproduces the leaf SE: sum_{i in k} IF_k(i)^2 = (n_k - 1) s_k^2 / n_k^2, which agrees with leaf_se[k] = s_k / sqrt(n_k) to within the familiar (n_k - 1)/n_k factor -- the two differ because leaf_se uses the n_k - 1 divisor and sqrt(sum IF^2) does not.

    Requires honest = true AND a completed fit(). Length equals est_indices().length(), position j corresponding to original row est_indices()[j] -- NOT to row j. On an adaptive fit the same array is computable but is not a valid influence function (the partition was chosen using these same rows), so this accessor refuses rather than pretending.

    DoubleMLPolicyTree::leaf_psi_a

    fn DoubleMLPolicyTree::leaf_psi_a(self : DoubleMLPolicyTree, leaf : Int) -> Array[Double]

    v0.98.0+: the per-observation Riesz denominator psi_a[i] = -1 / n_k for the rows of leaf leaf in the estimation half and 0.0 elsewhere -- i.e. leaf_influence with its residual divisor pulled out, in exactly the shape sensitivity_analysis feeds to irm_style_sensitivity.

    The default (honest = false) path passes the CONSTANT -1.0 for its own rows instead, and that is what it still passes: sensitivity_analysis's v0.69.0-v0.97.0 numbers are pinned and unchanged. -1 is the per-LEAF derivative f_k' scaled up by n_k; -1/n_k is the per-OBSERVATION derivative f_i', which is the honest one. Both are legitimate inputs to the Cinelli-Hazlett decomposition -- it consumes psi_a only through psi_a^2, so the sign is immaterial and the magnitude sets the variance scale -- but only the honest path's numbers describe an estimator whose partition is independent of the rows it is computed from.

    DoubleMLPolicyTree::leaf_se

    fn DoubleMLPolicyTree::leaf_se(self : DoubleMLPolicyTree) -> Array[Double]

    v0.98.0+: per-leaf standard errors of leaf_signal_mean, measured on the ESTIMATION half, length n_leaves. See policy_tree_honest_leaf_se for the formula and the full derivation.

    WHAT THIS NUMBER IS NOT. It is CONDITIONAL ON THE FITTED STRUCTURE. It is the sampling variance of leaf k's mean given that partition -- it does NOT include the variance from having SEARCHED for that partition. Athey & Imbens (2016) buy nominal coverage for the within-partition effects under honesty; they do not claim the partition itself is exogenous, and neither does this accessor. A leaf mean is a third kind of quantity: it is neither a DML score (so sandwich_variance is wrong) nor a projection of several coefficients (so hac_se is wrong), and it is not routed through either.

    Requires honest = true AND a completed fit(). On an adaptive fit this ABORTS rather than returning the naive same-formula number, because that number is the standard error of an adaptive estimator whose bias does not vanish at a usable rate -- reporting it would be the exact silent failure this release exists to prevent. Use is_honest() to branch.

    DoubleMLPolicyTree::leaf_se_reliable

    fn DoubleMLPolicyTree::leaf_se_reliable(self : DoubleMLPolicyTree) -> Bool

    v0.98.0+: true iff EVERY leaf holds at least min_leaf_n() estimation-half observations, i.e. iff every leaf_se entry is backed by enough degrees of freedom to be worth reading. This is the guard that keeps honesty honest about its own limits.

    WHY THE GUARD EXISTS AT ALL. Cattaneo, Klusowski & Yu, "Accuracy Limits of Causal Trees for Individualized Treatment Effects" (arXiv:2509.11381) prove that CART-type greedy recursive partitioning "selects highly imbalanced splits with nonvanishing probability, producing terminal nodes containing very few observations and leading to large estimation variance", and -- the part that matters here -- that "sample splitting, often called 'honesty', does not remove this limitation". So honesty fixes the BIAS (the partition is no longer chosen by the same rows that fill it) and it does NOT fix the SMALL-LEAF VARIANCE. A leaf holding three estimation observations has a real, computed, and nearly meaningless leaf_se. Reporting it unflagged would be the "silent huge number" failure mode.

    DoubleMLPolicyTree::min_leaf_n

    fn DoubleMLPolicyTree::min_leaf_n(self : DoubleMLPolicyTree) -> Int

    v0.98.0+: the small-leaf guard threshold on ESTIMATION-half leaf counts. Leaves with fewer than this many estimation observations are reported by unreliable_leaves() and excluded from policy_value_se(). Default 5; set via new(min_leaf_n=...). Requires >= 2. Readable before fit().

    DoubleMLPolicyTree::new

    fn DoubleMLPolicyTree::new(features : Matrix, orth_signal : Array[Double], depth? : Int, honest? : Bool, split_seed? : Int, min_leaf_n? : Int) -> DoubleMLPolicyTree

    v0.98.0+: the HONESTY switch, honest, plus its two supporting parameters split_seed and min_leaf_n. All three default to the inert setting, so a v0.97.0 call site sees byte-identical output -- see the honest field docstring on the struct for the definition and the motivation.

    • honest (default false): when true, split the sample and build the tree on one half only. See the struct field.
    • split_seed (default 2024): seeds the kfold(n_obs, 2, split_seed) call that produces the two halves. Ignored when honest = false. Only the FIRST of the two returned folds is used: its train_indices() is the splitting half (floor(n_obs / 2) rows) and its test_indices() is the estimation half (ceil(n_obs / 2) rows).
    • min_leaf_n (default 5): the small-leaf guard threshold on ESTIMATION-half leaf counts. Must be >= 2. See leaf_se for why 5.

    DoubleMLPolicyTree::policy_value

    fn DoubleMLPolicyTree::policy_value(self : DoubleMLPolicyTree) -> Double

    v0.98.0+: THE SCALAR. The policy value of the tree's own decision rule on the estimation half, i.e. the average value the tree assigns to the units it was shown:

    policy_value = sum_k (n_k / n) * theta_k

    over the estimation half, n_k = leaf_count[k], theta_k = leaf_signal_mean[k], n = sum_k n_k.

    THE ESTIMAND, STATED PRECISELY, AND IT IS NOT WHAT YOU MIGHT EXPECT. Because theta_k = (1/n_k) sum_{i in k} y_i, the weights telescope and

    sum_k (n_k / n) * theta_k = (1/n) * sum_k sum_{i in k} y_i = (1/n) * sum_j y_j = mean(y)

    -- the policy value of a leaf-MEAN policy is IDENTICALLY the plain sample mean of orth_signal over the estimation half. That is not a bug in the formula, it is the standard fact that a policy whose action value is the group mean attains the group mean by construction and so has ZERO advantage over treating everyone. All the tree's information is in the per-leaf leaf_signal_mean / leaf_se pairs, NOT in this scalar. The scalar is worth exposing because that identity is the honest headline about what a single-leaf-mean policy tree buys, and because its exact variance is available for free (see policy_value_se).

    This is a VALUE (a mean outcome), not a CATE. Requires honest = true AND a completed fit(). Unguarded: a population-weighted mean is not variance-dominated by one tiny leaf, so no abort is warranted here even when leaf_se_reliable() is false.

    DoubleMLPolicyTree::policy_value_se

    fn DoubleMLPolicyTree::policy_value_se(self : DoubleMLPolicyTree) -> Double

    v0.98.0+: standard error of policy_value(). It is the EXACT standard error of the plain sample mean of orth_signal over the estimation half:

    policy_value_se = sqrt( sum_{j=1..n} (y_j - ybar)^2 / (n * (n - 1)) ) = sd(y) / sqrt(n)

    WHY IT IS NOT sum_k (n_k/n)^2 * se_k^2, WHICH IS THE TEMPTING FORMULA AND IS WRONG. That expression assumes the leaf means are INDEPENDENT. They are not: they are n_k row means of ONE sample, and two disjoint group means from one sample are NEGATIVELY correlated, Cov(theta_k, theta_l) =-s_k^2 s_l^2 / (n (n - 1)) for k != l. Dropping that covariance does not produce a conservative bound, it produces a wrong number in the wrong direction, and it is worst exactly where the tree is most interesting:

    • If all the variation is BETWEEN leaves (s_k^2 = 0 for every leaf -- zero within-leaf noise, genuine heterogeneity), the independence formula returns EXACTLY ZERO. The quantity it describes is a sample mean of genuinely spread-out data, so its true SE is > 0.
    • The two-leaf worst case makes it concrete: two leaves of size n/2 with means ybar +/- d give sum_j (y_j - ybar)^2 = nd^2, hence policy_value_se = |d| / sqrt(n - 1) > 0, while the independence formula still returns 0.

    The exact form needs no cross-leaf covariance, which is why the joint n_leaves x n_leaves covariance matrix -- the honest per-leaf CIs would genuinely want it -- stays out of scope here. FUTURE WORK: expose the full covariance of the leaf means (Cov(theta_k, theta_l) = -s_k^2 s_l^2 / (n (n-1)) off-diagonal, s_k^2 / n_k on it) so per-leaf CIs can be reported honestly at any depth. Building a FOREST of honest trees to recover the precision a single tree loses (Wager & Athey 2018, JASA) is also future work and is deliberately not attempted.

    SAME CAVEAT AS leaf_se(): conditional on the fitted structure, not on the partition having been exogenous.

    Requires honest = true, a completed fit(), AND leaf_se_reliable() == true. The reliability guard is deliberate: a scalar SE that is dominated by a three-observation leaf is a claim about sampling variability that the data cannot support, and aborting (with the standard precondition message) is the explicit failure mode. Check smallest_leaf_count() or unreliable_leaves() first if you want the number anyway.

    DoubleMLPolicyTree::predict

    fn DoubleMLPolicyTree::predict(self : DoubleMLPolicyTree, x : Matrix) -> Array[Int]

    DoubleMLPolicyTree::sensitivity_analysis

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

    v0.69.0+: per-leaf sensitivity analysis for DoubleMLPolicyTree.

    PolicyTree is a deterministic policy learner: each row is predicted with the leaf treatment emitted by policy_tree_predict. The IRM-style per-leaf decomposition treats the leaf mean of orth_signal as the nuisance-persistence anchor (leaf_signal_mean), the per-leaf outcome residual as orth_signal[i] - leaf_signal_mean[leaf(i)], the per-leaf Riesz-representer row as psi_a = -1 (the constant IRM-style treatment-effect IF), and the per-leaf coefficient as leaf_signal_mean[l].

    Returns an Array[SensitivityResult] in the same DFS order as policy_tree_walk_leaves / leaf_signal_mean / leaf_count. Leaves with leaf_count == 0 (impossible in the current build since the build loop only creates leaves containing at least one row) get a zeroed SensitivityResult. cf_y / cf_d default to 0.05 matching the v0.66.0+ sensitivity family.

    v0.98.0+ -- BEHAVIOUR CHANGE UNDER honest = true, AND NOTHING CHANGES WITHOUT IT. This method BECAME HONESTY-AWARE, and the honest numbers DIFFER from the v0.97.0 numbers in two deliberate ways. On the DEFAULT path (honest = false, the v0.97.0 behaviour) the decomposition still runs over all n_obs rows in identity order with psi_a = -1, and every returned number is byte-identical to v0.69.0-v0.97.0; that is pinned in expand_v098_test.mbt. On the HONEST path it instead:

    • runs over the ESTIMATION half only, so n_rows == leaf_assignment.length() == ceil(n_obs / 2) rather than n_obs, with position j describing original row est_indices()[j]; and
    • passes psi_a = -1 / n_l, the true per-observation derivative of the leaf-mean estimating function (derived in full on leaf_influence), rather than the constant -1.

    Both changes are forced by honesty rather than cosmetic: the split half is not in leaf_signal_mean, so including it would contaminate every leaf's residual, and -1 is n_l times the derivative that actually describes an honest leaf mean. Because irm_style_sensitivity consumes psi_a through psi_a^2 only, the sign flip is immaterial but nu2 scales by 1 / n_l^2 and the reported rv / max_bias move accordingly. Callers that want the old numbers must leave honest at its default.

    Calling on an un-fit model aborts via PreconditionError.

    DoubleMLPolicyTree::set_min_leaf_n

    fn DoubleMLPolicyTree::set_min_leaf_n(self : DoubleMLPolicyTree, n : Int) -> DoubleMLPolicyTree

    v0.98.0+: retune the small-leaf guard threshold. Requires >= 2. Raising it makes the guard STRICTER. Purely a reporting knob: it changes no fitted number, which is why it is deliberately NOT part of the memoize key.

    DoubleMLPolicyTree::smallest_leaf_count

    fn DoubleMLPolicyTree::smallest_leaf_count(self : DoubleMLPolicyTree) -> Int

    v0.98.0+: the smallest estimation-half leaf count -- the single number that tells a caller whether this honest fit is in the regime Cattaneo-Klusowski-Yu warn about. Requires honest = true AND a completed fit().

    DoubleMLPolicyTree::split_feature

    fn DoubleMLPolicyTree::split_feature(self : DoubleMLPolicyTree) -> Int

    DoubleMLPolicyTree::split_indices

    fn DoubleMLPolicyTree::split_indices(self : DoubleMLPolicyTree) -> Array[Int]

    v0.98.0+: the SPLITTING half -- original row indices of the observations policy_tree_build was allowed to look at. Length floor(n_obs / 2) under honesty. EMPTY when honest = false. Disjoint from est_indices() and jointly exhaustive of range_indices(n_obs).

    DoubleMLPolicyTree::split_value

    fn DoubleMLPolicyTree::split_value(self : DoubleMLPolicyTree) -> Double

    DoubleMLPolicyTree::unreliable_leaves

    fn DoubleMLPolicyTree::unreliable_leaves(self : DoubleMLPolicyTree) -> Array[Int]

    v0.98.0+: the leaves whose estimation-half count is below min_leaf_n(), in DFS leaf order. Empty iff leaf_se_reliable(). This is the explicit, enumerable failure mode: a caller can see exactly WHICH leaves are untrustworthy rather than inferring it from one enormous leaf_se.

    Leaves with fewer than 2 estimation observations also land here, and additionally carry a NaN in leaf_se() -- their sample variance has zero degrees of freedom and does not exist.