cleverly.longitudinal.StructuralNestedMeanResult#

class cleverly.longitudinal.StructuralNestedMeanResult(estimates: dict[str, ParameterEstimate], kinds: dict[str, str], coefficients: tuple[NDArray[float64], ...], psi_curve: NDArray[float64], data: LongitudinalData, config: StructuralConfig, folds: Folds, provenance: Provenance, structural_diagnostics: StructuralDiagnostics, static_regimens: tuple[_StaticRegimen, ...], estimator: StructuralNestedMean, label: str, simultaneous: SimultaneousBands | None = None, fit_warnings: tuple[FitWarning, ...] = ())[source]#

The fitted blips, the reference mean and the declared regimen values.

Behaves as a mapping from parameter name to ParameterEstimate. The names are blip[<treatment>:<level>:<feature>], ey_reference, ey_regimen[<label>] and ate_regimen[<label> vs <reference>].

Parameters:
estimatesdict of str to ParameterEstimate

The estimates in report order.

kindsdict of str to str

"blip", "reference", "level" or "contrast" for each name.

coefficientstuple of ndarray

The blip coefficients of each node as \(\Psi_t^\top\), shape (p_t, d_t): one row per feature and one column per coding component.

psi_curvendarray

The (n, P) influence curves of the stacked coefficients.

dataLongitudinalData

The prepared data.

configStructuralConfig

The settings of the fit.

foldsFolds

The realized outer folds.

provenanceProvenance

The runtime and data record.

simultaneousSimultaneousBands or None

Joint bands over the regimen parameters, or over the blips with no regimen.

structural_diagnosticsStructuralDiagnostics

The positivity and learner record the fit measured: the smallest standardized eigenvalue of each diagonal Jacobian block, the share of extreme class probabilities, and the learner diagnostics.

static_regimenstuple

The resolved static regimens.

estimatorStructuralNestedMean

The settings the fit ran with, which check_model() reuses.

labelstr

The structural condition under which the intervals are valid.

fit_warningstuple of FitWarning

The package warnings the fit raised, in first-seen order. Set by the fit entry point.

Attributes:
assessment_cacheAssessmentCache

Saved diagnostic and sensitivity outputs. Not a constructor argument, so every constructed result owns its own cache.

See also

StructuralNestedMean

The estimator.

cleverly.longitudinal.LongitudinalResult

The result of the nonparametric estimators.

Methods#

StructuralNestedMeanResult.assess(*, include_refits: bool = False, include_retargets: bool = False, arguments: Mapping[str, Mapping[str, Any]] | None = None, random_state: int | None = None) → Any[source]#

Run the applicable post-fit assessment battery.

refute refits the structural estimator, so it runs only with include_refits=True; every sensitivity row refuses on a structural fit.

Parameters:
include_refitsbool

Run requested operations that refit nuisance models.

include_retargetsbool

Include moderate retargets.

argumentsmapping or None

Per-operation keyword arguments.

random_stateint or None

Common seed for stochastic refit operations.

Returns:
AssessmentReport

Validation, diagnostics, and sensitivity in one report.

StructuralNestedMeanResult.blip(node: int | str) → NDArray[float64][source]#

The blip coefficients of one node, as \(\Psi_t^\top\).

Parameters:
nodeint or str

The node counted from one, or its treatment column.

Returns:
ndarray

The (p_t, d_t) matrix: one row per feature and one column per coding component. It is the transpose of \(\Psi_t\) in the model, which has one row per coding component.

StructuralNestedMeanResult.check_model(*, q_bounds: tuple[float, float] | None = None, rank_floor: float = 1e-06, n_splits: int = 5) → StructuralModelCheck[source]#

Compare the structural contrasts with the nonparametric contrasts.

The check fits LTMLE on the same rows, weights, clusters and folds. Both estimators are asymptotically linear, so the difference of the two contrast vectors is asymptotically normal with the covariance of the difference of the two curves. The mean is zero under the structural model. The joint Wald statistic has one degree of freedom per contrast. A rejection says that the model fails for these contrasts. A non-rejection does not confirm the model.

The two contrasts nearly cancel, so the difference has a much smaller variance than either estimator. On a cross-fitted fit, the second-order remainder of each estimator depends on the fold split, and the curves do not carry it. It is negligible against either estimator but not against the difference, so at 2 folds a check on one split rejects a correct model too often. The check therefore refits both estimators on n_splits - 1 further splits and tests the mean difference (Chernozhukov et al. 2018, Econometrics Journal 21(1), Section 3.4). Given the data, the splits are independent draws, so the between-split covariance over n_splits is the split part of the variance. The covariance of curves from two different splits estimates the first-order part, free of each curve’s own split noise. An in-sample fit has no split, and its check reads the curves of the fit.

The covariance is itself an estimate. Under weak positivity a few rows carry large inverse weights and most of the variance, so the covariance has few effective degrees of freedom, and a chi-squared reference rejects a correct model too often. The check computes the Welch-Satterthwaite degrees of freedom nu of each diagonal entry and takes the smallest. It reads T (nu - k + 1) / (nu k) against F(k, nu - k + 1), the Hotelling law of a Wald statistic whose covariance has nu degrees of freedom. With nu at most k - 1 it reports no test. For large nu this is the chi-squared law. The correction concerns the reference law only. When the nonparametric estimator under-covers at this sample size, a non-rejection carries less information, and reference_df says how much.

Parameters:
q_boundstuple of float or None, default=None

The known support of a continuous outcome. A cross-fitted fit of a continuous outcome needs it, as LTMLE does.

rank_floorfloat, default=1e-6

The ratio of the smallest eigenvalue of the difference covariance to the largest eigenvalue of the two contrast covariances, below which the check reports no test. A feature map that saturates the contrasts makes the two curves nearly equal.

n_splitsint, default=5

The fold splits of a cross-fitted check, the fit’s own included. It must be at least 2, because one split cannot estimate the between-split covariance. Each further split refits both estimators. An in-sample fit ignores it.

Returns:
StructuralModelCheck

The contrasts, their difference, the covariance and the statistic.

Raises:
CapabilityError

For a continuous node (INVALID_DECLARATION), a blip feature that reads a time-varying covariate (IMPLEMENTATION_GAP), a status that supplies no inference (INFERENCE_GAP), fewer than two regimens, or a cross-fitted continuous outcome with no q_bounds.

ValueError

For n_splits below 2.

StructuralNestedMeanResult.contrast(function: Callable[[NDArray[float64]], float], names: Sequence[str], *, name: str | None = None, scale: Literal['level', 'difference', 'ratio', 'fraction'] = 'difference', gradient: Callable[[NDArray[float64]], NDArray[float64]] | None = None, transform: Transform | None = None) → ParameterEstimate[source]#

Return a smooth function of estimates with joint delta-method inference.

Parameters:
functioncallable()

A smooth scalar function of the selected estimates.

namessequence of str

The names passed to function in order.

namestr or None

The name of the derived estimate.

scalestr

The reported scale.

gradientcallable() or None

The analytic gradient. None uses central differences.

transformTransform or None

The map the interval is computed on.

Returns:
ParameterEstimate

The derived estimate, with the inference status of the selected estimates.

StructuralNestedMeanResult.covariance(names: Sequence[str] | None = None) → NDArray[float64][source]#

Return the joint covariance of selected estimates.

Parameters:
namessequence of str or None

Names in output order. None selects all estimates.

Returns:
ndarray

The covariance of the estimators, at the cluster level on a clustered fit.

StructuralNestedMeanResult.items() → Any[source]#

The (name, estimate) pairs in report order.

Returns:
ItemsView of (str, ParameterEstimate)

The items of estimates.

StructuralNestedMeanResult.keys() → Any[source]#

The parameter names in report order.

Returns:
KeysView of str

The keys of estimates.

StructuralNestedMeanResult.psi(name: str | None = None) → float[source]#

Return a point estimate by parameter name.

Parameters:
namestr or None

The parameter name. None is allowed when the fit reported one.

Returns:
float

The point estimate.

StructuralNestedMeanResult.save(path: Any) → Any[source]#

Persist the fitted result to a trusted joblib artifact.

The artifact records cleverly.__version__. A load by a different version warns with VersionMismatchWarning.

Parameters:
pathpath-like

Destination file.

Returns:
Path

The destination path.

StructuralNestedMeanResult.summary(*, detail: Literal['short', 'full'] = 'short') → Summary[source]#

The estimates, what each row means, the blip features and the model condition.

Parameters:
detail{“short”, “full”}, default=”short”

"full" adds the assumptions, the settings and diagnostics in words, the method and the study description.

Returns:
Summary

The summary. It prints as text and renders as HTML in a notebook.

StructuralNestedMeanResult.to_frame() → Any[source]#

One row per reported parameter, in the backend the data came from.

Returns:
dataframe

The columns of a point-treatment report, plus kind (blip, reference, level or contrast) and model, the structural condition under which the interval is valid.

StructuralNestedMeanResult.validate() → Any[source]#

Run the inexpensive default battery without refitting.

Returns:
ValidationReport

One item per validated check; on a structural fit each states its refusal or redirect.

StructuralNestedMeanResult.values() → Any[source]#

The estimates in report order.

Returns:
ValuesView of ParameterEstimate

The values of estimates.

Attributes#

StructuralNestedMeanResult.assessment_family: ClassVar[str] = 'structural'#

The assessment family: one declaration per assessment operation in cleverly.assessment.ASSESSMENT_CAPABILITIES. A structural fit is not a LongitudinalResult: it holds one split, no regimen plans and no targeting state, so the longitudinal declarations do not describe it.

StructuralNestedMeanResult.diagnostics#

The diagnostics facade: refute runs, and every other row refuses or redirects.

The positivity and learner record the fit measured is structural_diagnostics, to which the support and nuisance_models rows redirect.

StructuralNestedMeanResult.estimate#

The sole estimate, refusing ambiguity on a multi-parameter result.

StructuralNestedMeanResult.fit_warnings: tuple[FitWarning, ...] = ()#

The warnings the fit raised (cleverly._warnings), so a summary printed later still names them.

StructuralNestedMeanResult.fitted_method: ClassVar[str] = 'snmm'#

The method identity of the result.

StructuralNestedMeanResult.inference_status#

The inference status of the fit.

"influence_curve" is the interval status. The structural condition label states what the interval is valid for.

StructuralNestedMeanResult.influence_curves#

The influence curves by parameter name.

StructuralNestedMeanResult.n#

The number of rows.

StructuralNestedMeanResult.replayability#

Which assessment operations survive from the stored structural artifacts.

StructuralNestedMeanResult.sensitivity#

The sensitivity-analysis facade.

Every row refuses on a structural fit, with its reason code and the roadmap item that tracks the derivation.

StructuralNestedMeanResult.simultaneous: SimultaneousBands | None = None#
StructuralNestedMeanResult.estimates: dict[str, ParameterEstimate]#
StructuralNestedMeanResult.kinds: dict[str, str]#
StructuralNestedMeanResult.coefficients: tuple[NDArray[float64], ...]#
StructuralNestedMeanResult.psi_curve: NDArray[float64]#
StructuralNestedMeanResult.data: LongitudinalData#
StructuralNestedMeanResult.config: StructuralConfig#
StructuralNestedMeanResult.folds: Folds#
StructuralNestedMeanResult.provenance: Provenance#
StructuralNestedMeanResult.structural_diagnostics: StructuralDiagnostics#
StructuralNestedMeanResult.static_regimens: tuple[_StaticRegimen, ...]#
StructuralNestedMeanResult.estimator: StructuralNestedMean#
StructuralNestedMeanResult.label: str#
StructuralNestedMeanResult.assessment_cache: AssessmentCache#

Assessment results keyed by operation and normalized arguments. init=False, as on LongitudinalResult, so a mapping handed to the constructor by dataclasses.replace cannot answer for another fit.