cleverly.sensitivity.BalanceOverTime#

class cleverly.sensitivity.BalanceOverTime(rows: tuple[TimeBalanceRow, ...], treatments: tuple[str, ...], diagnostics: tuple[str, ...], omitted: tuple[tuple[str, str], ...], dropped: tuple[DroppedStrata, ...], threshold: float, n: int, n_repeats: int, cross_fitted: bool, limits: tuple[float, float] | None, bounded_share: float, weighted_data: bool, family: str, notes: tuple[str, ...] = ())[source]#

Covariate balance over time of a fit with weights that vary over time.

"confounding" rows compare the covariates measured at or before a treatment decision across that decision, within the units that share the earlier treatments (Jackson 2016, Table 1, Diagnostic 1 before weighting and Diagnostic 3 after). "feedback" rows compare a covariate measured after an earlier decision across that decision (Diagnostic 2a). "censoring" rows compare the covariates across leaving the study at a time point and staying, within the units that share the treatments so far. A continuous-time survival fit has "confounding" rows at its baseline treatment, "joint" rows that compare the arms among the units whose status at a target time is known, weighted by treatment and censoring, and "censoring" rows that compare those units with their whole arm, weighted by censoring alone.

Parameters:
rowstuple of TimeBalanceRow

One row per diagnostic, exposure, stratum, comparison and covariate.

treatmentstuple of str

The treatment decisions compared, in time order.

diagnosticstuple of str

The diagnostics with rows.

omittedtuple of tuple of str

(diagnostic, reason) for each diagnostic the fit cannot report.

droppedtuple of DroppedStrata

The strata with no comparison, per diagnostic and exposure.

thresholdfloat

The size an absolute standardized difference is held against.

nint

The units.

n_repeatsint

The cross-fitting repeats the fit holds; the first one’s probabilities are used.

cross_fittedbool

Whether the probabilities are out-of-fold predictions; in-sample otherwise.

limitstuple of float or None

The limits put on each cumulative probability before it is inverted.

bounded_sharefloat

The share of weighted rows whose cumulative probability those limits moved.

weighted_databool

Whether the data carried observation weights, which every column uses.

family{“longitudinal”, “continuous_survival”}

The kind of fit.

notestuple of str

Further readings of this fit’s report, such as the reading of a collaborative fit.

Examples

>>> from sklearn.linear_model import LinearRegression, LogisticRegression
>>> from cleverly import CausalStudy, LongitudinalTreatment, RegimeMean
>>> from cleverly.datasets import make_longitudinal
>>> from cleverly.sensitivity import covariate_balance
>>> frame, _ = make_longitudinal(n=600, seed=0)
>>> study = CausalStudy(
...     frame,
...     design=LongitudinalTreatment(
...         outcome="Y",
...         treatment=["A1", "A2"],
...         baseline=["W1", "W2"],
...         time_varying=[[], ["L2"]],
...         censoring=["C1", "C2"],
...     ),
... )
>>> result = study.identify(RegimeMean({"always": 1, "never": 0})).estimate(
...     outcome_learner=LinearRegression(),
...     treatment_learner=LogisticRegression(max_iter=1000),
...     censoring_learner=LogisticRegression(max_iter=1000),
...     cross_fit=False,
...     random_state=0,
... )
>>> balance = covariate_balance(result)
>>> balance.treatments
('A1', 'A2')
>>> frame = balance.average(over="history", diagnostic="confounding")
>>> frame[["exposure", "covariate"]].values.tolist()
[['A1', 'W1'], ['A1', 'W2'], ['A2', 'W1'], ['A2', 'W2'], ['A2', 'L2']]

Methods#

BalanceOverTime.average(over: Literal['history', 'time', 'all'] = 'history', *, diagnostic: str | None = None, distances: Sequence[tuple[int, int]] | None = None, backend: str | None = None) → Any[source]#

Average the differences over strata, weighting each by its size.

Jackson (2016, Table 2) averages a diagnostic over the earlier treatments, then over time, then over the distance between the covariate and the exposure, each stratum counting by its size: the data’s weights for the unweighted column and the stabilized weights for the weighted one. The averages are of the signed differences, so strata that differ in opposite directions offset each other; smd_min and smd_max give the range of the strata’s weighted standardized differences.

Covariates are matched over time by name. A long panel’s column "L@2" matches as "L"; on a wide frame each column is its own covariate, so over="time" and over="all" pool a covariate only with itself.

Parameters:
over{“history”, “time”, “all”}, default=”history”

"history": one row per exposure, comparison and covariate, averaged over the earlier treatments. "time": one row per distance and covariate, also averaged over the time points. "all": one row per covariate, also averaged over the distances.

diagnosticstr or None, default=None

One diagnostic; every diagnostic with rows when omitted.

distancessequence of tuple of int or None, default=None

With over="all", ranges (low, high) of distance, both ends included, to average within instead of over every distance; one row per range and covariate.

backend{“pandas”, “polars”, “pyarrow”} or None, default=None

Dataframe backend to return.

Returns:
dataframe

The grouping columns, then n_strata, difference_unweighted, difference_weighted, smd_unweighted, smd_weighted, smd_min, smd_max, person_time_unweighted and person_time_weighted.

Raises:
CapabilityError

When diagnostic is one the fit cannot report.

ValueError

When over or diagnostic is not one of the accepted values, or distances is passed without over="all".

BalanceOverTime.plot(**kwargs: Any) → Any[source]#

Plot the balance over time.

Parameters:
**kwargs

Passed to cleverly.plotting.balance(): diagnostic=, view=, nodes=, max_covariates=, labels= and the label options.

Returns:
Figure

The figure.

BalanceOverTime.rows_of(diagnostic: str) → tuple[TimeBalanceRow, ...][source]#

The rows of one diagnostic.

Parameters:
diagnostic{“confounding”, “feedback”, “censoring”, “joint”}

The diagnostic.

Returns:
tuple of TimeBalanceRow

Its rows, in report order.

Raises:
CapabilityError

When the fit cannot report that diagnostic.

ValueError

When diagnostic is not one of the four.

BalanceOverTime.summary(detail: Detail = 'short') → Summary[source]#

Return the printed summary of the balance over time.

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

"short" prints, per diagnostic and exposure, each covariate’s difference before and after weighting, averaged over the earlier treatments. "full" adds the strata with no comparison.

Returns:
Summary

A str whose value is the printed text. Its facts, tables, notes and reading hold the parts as data.

BalanceOverTime.to_frame(backend: str | None = None) → Any[source]#

Return one row per diagnostic, exposure, stratum, comparison and covariate.

Parameters:
backend{“pandas”, “polars”, “pyarrow”} or None, default=None

Dataframe backend to return. None uses pandas when installed, then the first available backend.

Returns:
dataframe

The fields of TimeBalanceRow, one column each.

Attributes#

BalanceOverTime.notes: tuple[str, ...] = ()#
BalanceOverTime.rows: tuple[TimeBalanceRow, ...]#
BalanceOverTime.treatments: tuple[str, ...]#
BalanceOverTime.diagnostics: tuple[str, ...]#
BalanceOverTime.omitted: tuple[tuple[str, str], ...]#
BalanceOverTime.dropped: tuple[DroppedStrata, ...]#
BalanceOverTime.threshold: float#
BalanceOverTime.n: int#
BalanceOverTime.n_repeats: int#
BalanceOverTime.cross_fitted: bool#
BalanceOverTime.limits: tuple[float, float] | None#
BalanceOverTime.bounded_share: float#
BalanceOverTime.weighted_data: bool#
BalanceOverTime.family: str#