cleverly.survival.ContinuousSurvivalResult#

class cleverly.survival.ContinuousSurvivalResult(estimates: dict[str, ParameterEstimate], record: ContinuousSurvivalRecord, simultaneous: Any, arms: tuple[str, str], causes: tuple[str, ...], horizons: tuple[float, ...], n: int, backend: str | None = None, restricted_horizons: tuple[float, ...] = (), predictable: PredictableCovariance | None = None, estimator: ContinuousSurvivalTMLE | None = None, data: ContinuousSurvivalData | None = None, bootstrap: BootstrapResult | None = None, bootstrap_band: BootstrapBand | None = None, bootstrap_status: Literal['ran', 'bootstrap_unstable'] | None = None, bootstrap_failures: tuple[str, ...] = (), bootstrap_jump_bounded: int = 0)[source]#

The targeted risks of a continuous-time survival fit.

Behaves as a mapping from parameter name to ParameterEstimate. Every method reads targeted estimates, or a smooth function of them: a quantity whose score the fit did not solve, such as a risk between target times or a restricted mean the fit did not target, is refused.

Parameters:
estimatesdict of str to ParameterEstimate

Each arm’s risk (risk_regimen[arm @ t=60], or cif_regimen[arm, cause @ t=60] with competing causes), the risk differences (ate_regimen[...]) and the risk ratios (rr_regimen[...]). A fit with restricted_horizons= adds the restricted mean time lost to each cause (rmtl_regimen[arm, cause @ t=tau]) and the restricted mean survival time (rmst_regimen[arm @ t=tau]) of each arm, and their differences (rmtl_regimen[treated vs reference, cause @ t=tau], rmst_regimen[... vs ...]).

recordContinuousSurvivalRecord

The nuisance selections and the targeting record.

simultaneousSimultaneousBands or None

The sup-t band over every risk and risk difference, when requested.

armstuple of str

(reference, treated).

causestuple of str

The cause labels.

horizonstuple of float

The target times.

nint

The number of units.

backendstr or None

The dataframe library the data arrived in; to_frame() returns a frame of it.

restricted_horizonstuple of float

The restriction times the fit targeted.

predictablePredictableCovariance or None

Under variance="switched", the predictable-variation covariance of every targeted level, with each stored estimate’s gradient over them; contrast() and ratio() read it. None under variance="influence_curve".

estimatorContinuousSurvivalTMLE or None

A copy of the estimator that produced the fit, with its seed resolved and the outer cross-fitting label of each row recorded, so estimator.refit(data, random_state=estimator.random_state) reproduces the fit. None only on a result built by hand, which the refits refuse.

dataContinuousSurvivalData or None

The rows the fit read. None only on a result built by hand.

bootstrapBootstrapResult or None

With n_bootstrap, every replicate’s estimate and standard error of each estimate, and how many refits were requested and failed (n_requested, n_failed); the draws are empty when every refit failed. A replicate’s standard error is its switched-variance standard error with simultaneous=True, whose studentized band reads it, and its influence-curve standard error otherwise. None without a bootstrap. When at most 1% of the refits fail, every bootstrap interval and the band read the refits that fit, with no warning; n_failed and bootstrap_failures say how many did not.

bootstrap_bandBootstrapBand or None

The studentized bootstrap band over every risk and risk difference, with n_bootstrap and simultaneous=True and unless the intervals are withheld. It is the estimate plus or minus the critical value times its standard error on the identity scale, so a small risk’s band can cross 0, and it ignores band_scale.

bootstrap_status{“ran”, “bootstrap_unstable”} or None

"ran" when each estimate carries its bootstrap interval, "bootstrap_unstable" when more than 1% of the refits failed and every bootstrap interval is withheld (the failure rule), and None without a bootstrap.

bootstrap_failurestuple of str

The class and first sentence of each failed refit’s exception, in replicate order.

bootstrap_jump_boundedint

The bootstrap refits that fitted with a nonzero jump_bound_share: the engine scaled some combined hazard jump of one or more below one. A refit warns of nothing; this count, and the reason of every bootstrap interval when it is nonzero, say how often the bound acted.

Notes

diagnostics, sensitivity, validate() and assess() declare a row for every assessment operation. The support, nuisance, score and influence diagnostics read record and the influence curves, and the E-value reads a risk ratio of the fit. diagnostics.refute() refits estimator on perturbed copies of data (the placebo on a contrast, the random common cause and the subset tests, all descriptive), and diagnostics.truncation_curve() reruns the targeting walk at other floors from refitted initial hazards. sensitivity.simulated_confounding() refits estimator once per cell on event and censoring times redrawn from the replay’s own Cox fits under a simulated common cause, reusing the fit’s fold plan under its own seed (descriptive). Every other sensitivity analysis refuses with its reason and roadmap item.

Methods#

ContinuousSurvivalResult.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.

With include_refits=True the refutation and the truncation curve refit the stored estimator; the simulated common cause and every sensitivity bound refuse on this fit, and the report names each refusal without raising it.

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.

ContinuousSurvivalResult.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]#

A smooth function of reported estimates, with joint delta-method inference.

Each reported estimate solves its score equation, so a smooth function of them solves it to first order: its influence curve is the gradient times the joint curves (cleverly.inference.results.smooth_contrast()). Under variance="switched" the variance is \(h^\top \hat\Sigma_{pv} h\) with \(h\) the function’s gradient over the targeted levels, raised over the influence-curve variance as for a stored estimate, with the switch read on the derived curve. No registered study measures such a function, so the result reads experimental.

Parameters:
functioncallable()

A smooth scalar function of the selected estimates, in the order of names.

namessequence of str

The reported estimates it reads.

namestr or None

The name of the derived estimate. None gives contrast(<names>).

scalestr

The reported scale of the derived estimate. With transform= it must be "level" or "difference".

gradientcallable() or None

The analytic gradient. None uses central differences.

transformTransform or None

The map the interval and the test are computed on, as for cleverly.estimators.TMLEResult.contrast().

Returns:
ParameterEstimate

The derived estimate.

ContinuousSurvivalResult.curve(scale: Literal['risk', 'survival'] = 'risk', *, times: Sequence[float] | None = None) → Any[source]#

The targeted risks and their differences as a curve: one row per arm, cause and time.

Only the target times are reported. A risk between two target times would be a plug-in of the fitted hazards whose score the fit did not solve, so it has no first-order guarantee and is refused. scale="survival" reports \(S(t) = 1 - F(t)\) for a level, mirroring its interval, and the negated difference \(S_a - S_b = -(F_a - F_b)\) for a contrast, with the interval negated and swapped. A fit with several causes refuses it, because event-free survival is one minus the sum of the incidences, not one minus one of them.

Parameters:
scale{“risk”, “survival”}

The view of each row.

timessequence of float or None

The target times to report. None reports every target time.

Returns:
dataframe

One row per arm, cause and time, then one per difference, in the input backend. The columns are estimand (the quantity under the view), parameter (the key of the estimate the row reads), arm, cause (with several causes), time, psi, std_err, ci_lower, ci_upper, band_lower and band_upper (the simultaneous band, when the fit has one), scale ("level" or "difference"), view and support.

Raises:
CapabilityError

When a time is not a target time, or scale="survival" on a fit with several causes.

See also

cleverly.survival.ContinuousSurvivalResult.to_frame

Every estimate, with no time column.

cleverly.survival.ContinuousSurvivalResult.rmst

The area under the survival curve up to a restriction time.

Examples

>>> import numpy as np
>>> import pandas as pd
>>> from cleverly.survival import ContinuousSurvivalTMLE, CoxHazard
>>> rng = np.random.default_rng(0)
>>> x = rng.normal(size=300)
>>> treated = rng.binomial(1, 0.5, size=300)
>>> event_time = rng.exponential(1 / np.exp(-1.0 + 0.5 * x - 0.5 * treated))
>>> dropout = rng.exponential(4.0, size=300)
>>> frame = pd.DataFrame(
...     {
...         "time": np.minimum(event_time, dropout),
...         "event": (event_time <= dropout).astype(int),
...         "treated": treated,
...         "x": x,
...     }
... )
>>> fit = ContinuousSurvivalTMLE(
...     [1.0, 2.0],
...     cross_fit=False,
...     hazard_library=[CoxHazard("main")],
...     censoring_library=[CoxHazard("main")],
...     random_state=0,
... ).fit(frame, time="time", event="event", treatment="treated", baseline=["x"])
>>> curve = fit.curve(scale="survival")
>>> list(curve["estimand"][:2])
['survival_regimen[0 @ t=1]', 'survival_regimen[0 @ t=2]']
>>> bool((curve["psi"][:4] == 1 - fit.curve()["psi"][:4]).all())
True
ContinuousSurvivalResult.plot(**kwargs: Any) → Any[source]#

Plot each arm’s risk and their difference at the target times.

Each estimate is drawn at its target time with its interval and, when the fit holds one, its simultaneous band: the multiplier band, or with band="bootstrap" the studentized bootstrap band of a fit with n_bootstrap= and simultaneous=True. Nothing is drawn between target times, where the fit estimates no risk.

Parameters:
**kwargs

Passed to cleverly.plotting.curve() (scale=, measure=, band=, cause=, regimens=, labels=, units=, time_label=, truth= and title=).

Returns:
Figure

The levels above and their difference below, one column per cause.

Raises:
CapabilityError

When the fit refuses the requested view, with the fit’s own reason.

ValueError

When band=, measure=, scale= or cause= do not fit together or the fit, such as band="bootstrap" on a fit with no bootstrap band or cause= with measure="rmst".

DataError

When cause= or regimens= names a cause or arm the fit does not hold.

ContinuousSurvivalResult.ratio(numerator: str, denominator: str, *, kind: Literal['rr', 'or'] = 'rr', view: Literal['risk', 'survival'] = 'risk', name: str | None = None) → ParameterEstimate[source]#

The risk ratio or odds ratio of the two arms’ risks at one cause and time.

The interval is formed on the log scale and exponentiated, with curve \(IC_1/\psi_1 - IC_0/\psi_0\) for a risk ratio and \(IC_1/\{\psi_1(1-\psi_1)\} - IC_0/\{\psi_0(1-\psi_0)\}\) for an odds ratio (cleverly.inference.results.ratio_contrast()). view="survival" takes the ratio of \(1 - F\) instead, which is event-free survival on a fit with one event type only. Under variance="switched" the log-scale variance is \(h^\top \hat\Sigma_{pv} h\) with \(h\) the gradient of the log ratio over the targeted levels, raised over the influence-curve variance as for a stored estimate, with the switch read on the ratio’s own curve. No registered study measures a continuous-time ratio, so it reads experimental.

Parameters:
numeratorstr

The name of one arm’s risk.

denominatorstr

The name of the other arm’s risk at the same cause and time.

kind{“rr”, “or”}

A ratio of the risks, or a ratio of their odds.

view{“risk”, “survival”}

Whether to take the ratio of the risks or of their complements.

namestr or None

The name of the derived estimate. None gives rr_regimen[a vs b @ t=...], with the cause on a fit with several causes; or_regimen for an odds ratio, and a survival_ prefix for the survival view. The risk ratio of the treated arm over the reference arm is the reported rr_regimen estimate.

Returns:
ParameterEstimate

The ratio, on the "ratio" scale with log_psi set.

Raises:
CapabilityError

When the two names are not the two arms’ risks at one cause and one time, when a name is a risk at a time the fit did not target, or when view="survival" is asked of a fit with several causes.

See also

cleverly.sensitivity.evalue

The E-value of this ratio.

cleverly.survival.ContinuousSurvivalResult.contrast

Any other smooth function of reported estimates.

Examples

>>> import numpy as np
>>> import pandas as pd
>>> from cleverly.survival import ContinuousSurvivalTMLE, CoxHazard
>>> rng = np.random.default_rng(0)
>>> x = rng.normal(size=300)
>>> treated = rng.binomial(1, 0.5, size=300)
>>> event_time = rng.exponential(1 / np.exp(-1.0 + 0.5 * x - 0.5 * treated))
>>> dropout = rng.exponential(4.0, size=300)
>>> frame = pd.DataFrame(
...     {
...         "time": np.minimum(event_time, dropout),
...         "event": (event_time <= dropout).astype(int),
...         "treated": treated,
...         "x": x,
...     }
... )
>>> fit = ContinuousSurvivalTMLE(
...     [1.0, 2.0],
...     cross_fit=False,
...     hazard_library=[CoxHazard("main")],
...     censoring_library=[CoxHazard("main")],
...     random_state=0,
... ).fit(frame, time="time", event="event", treatment="treated", baseline=["x"])
>>> rr = fit.ratio("risk_regimen[1 @ t=2]", "risk_regimen[0 @ t=2]")
>>> rr.name, rr.scale
('rr_regimen[1 vs 0 @ t=2]', 'ratio')
>>> bool(np.isclose(rr.psi, fit["rr_regimen[1 vs 0 @ t=2]"].psi))
True
ContinuousSurvivalResult.rmst(arm: str, tau: float, *, versus: str | None = None) → ParameterEstimate[source]#

The restricted mean survival time up to \(\tau\).

\(\mathrm{RMST}_a(\tau) = E \min(T^a, \tau) = \tau - \sum_j \mathrm{RMTL}_{a,j}(\tau)\), with the curve \(-\sum_j\) of theirs, so its score is solved by linearity. The fit targets it only when \(\tau\) is in restricted_horizons=.

Parameters:
armstr

The arm label.

taufloat

The restriction time, one of the fit’s restricted_horizons.

versusstr or None

The other arm. The result is then the difference arm minus versus.

Returns:
ParameterEstimate

A "level" estimate, or a "difference" estimate with versus=.

Raises:
CapabilityError

When tau is not one of the fit’s restricted_horizons.

ValueError

When an arm is unknown.

See also

cleverly.survival.ContinuousSurvivalResult.rmtl

The restricted mean time lost to one cause.

cleverly.survival.ContinuousSurvivalResult.curve

The targeted risks the restricted mean summarizes.

Examples

>>> import numpy as np
>>> import pandas as pd
>>> from cleverly.survival import ContinuousSurvivalTMLE, CoxHazard
>>> rng = np.random.default_rng(0)
>>> x = rng.normal(size=300)
>>> treated = rng.binomial(1, 0.5, size=300)
>>> event_time = rng.exponential(1 / np.exp(-1.0 + 0.5 * x - 0.5 * treated))
>>> dropout = rng.exponential(4.0, size=300)
>>> frame = pd.DataFrame(
...     {
...         "time": np.minimum(event_time, dropout),
...         "event": (event_time <= dropout).astype(int),
...         "treated": treated,
...         "x": x,
...     }
... )
>>> fit = ContinuousSurvivalTMLE(
...     [1.0, 2.0],
...     restricted_horizons=(2.0,),
...     cross_fit=False,
...     hazard_library=[CoxHazard("main")],
...     censoring_library=[CoxHazard("main")],
...     random_state=0,
... ).fit(frame, time="time", event="event", treatment="treated", baseline=["x"])
>>> gain = fit.rmst("1", 2.0, versus="0")
>>> gain.name, gain.scale
('rmst_regimen[1 vs 0 @ t=2]', 'difference')
>>> lost = fit.rmtl("1", 2.0)
>>> round(fit.rmst("1", 2.0).psi + lost.psi, 12)
2.0
ContinuousSurvivalResult.rmtl(arm: str, tau: float, cause: str | None = None, *, versus: str | None = None) → ParameterEstimate[source]#

The restricted mean time lost to one cause up to \(\tau\).

\[\mathrm{RMTL}_{a,j}(\tau) = E \int_0^\tau F_j(u \mid a, L)\, du = \sum_{u_m \le \tau} \hat F_j(u_m) \{\min(u_{m+1}, \tau) - u_m\},\]

exactly for the fitted step function on the grid of observed times, with the curve \(\sum_m \{\min(u_{m+1}, \tau) - u_m\} D_{a,j,u_m}\). The fit targets it only when \(\tau\) is in restricted_horizons=: the walk solves the scores of the risks at the target times alone, so the integral of the targeted curve between them has no solved score, and that request is refused.

Parameters:
armstr

The arm label.

taufloat

The restriction time, one of the fit’s restricted_horizons.

causestr or None

The cause. Required on a fit with several causes.

versusstr or None

The other arm. The result is then the difference arm minus versus.

Returns:
ParameterEstimate

A "level" estimate, or a "difference" estimate with versus=.

Raises:
CapabilityError

When tau is not one of the fit’s restricted_horizons.

ValueError

When an arm or the cause is unknown, or the cause is missing on a fit with several causes.

See also

cleverly.survival.ContinuousSurvivalResult.rmst

The restricted mean survival time, tau minus the sum over causes.

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

Write this result to a trusted joblib artifact; see cleverly.load().

Parameters:
pathpath-like

Destination file.

Returns:
Path

The destination path, as given.

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

A printable report of the fit.

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

"full" adds the assumptions and how the update ended.

Returns:
Summary

The report.

ContinuousSurvivalResult.to_dict() → dict[str, Any][source]#

A JSON-ready record of the fit.

Returns:
dict of str to Any

estimates, each estimate’s to_dict() by name; record, the selected models and how the walk ended; and settings, the arms, causes, target times, restriction times, units, significance level and variance; and predictable_covariance, the targets and matrix of the predictable-variation covariance under variance="switched", else None; and bootstrap, with n_bootstrap, the status, the replicates requested and failed, each failure’s reason and the studentized band, else None (each estimate’s own mapping carries its bootstrap interval). A value that is not a finite number, such as the p-value of a range-logit estimate, reads None, so the mapping passes json.dumps(..., allow_nan=False).

ContinuousSurvivalResult.to_frame() → Any[source]#

One row per parameter, in the backend the data arrived in.

Returns:
dataframe

The estimates with their standard errors and intervals.

ContinuousSurvivalResult.validate() → Any[source]#

Run the inexpensive default battery without refitting.

Returns:
ValidationReport

The score-equation, support and nuisance-model checks, read off the record.

Attributes#

ContinuousSurvivalResult.assessment_family: ClassVar[str] = 'continuous_survival'#

The assessment family: one declaration per assessment operation in cleverly.assessment.ASSESSMENT_CAPABILITIES.

ContinuousSurvivalResult.backend: str | None = None#
ContinuousSurvivalResult.bootstrap: BootstrapResult | None = None#
ContinuousSurvivalResult.bootstrap_band: BootstrapBand | None = None#
ContinuousSurvivalResult.bootstrap_failures: tuple[str, ...] = ()#
ContinuousSurvivalResult.bootstrap_jump_bounded: int = 0#
ContinuousSurvivalResult.bootstrap_status: Literal['ran', 'bootstrap_unstable'] | None = None#
ContinuousSurvivalResult.data: ContinuousSurvivalData | None = None#
ContinuousSurvivalResult.diagnostics#

The support, score, nuisance and influence diagnostics of the fit.

ContinuousSurvivalResult.estimator: ContinuousSurvivalTMLE | None = None#
ContinuousSurvivalResult.fitted_method: ClassVar[str] = 'tmle'#

The method identity of the result.

ContinuousSurvivalResult.initial_estimates#

Every risk and risk difference at the initial hazard fits, before any step.

ContinuousSurvivalResult.n_folds#

The number of cross-fitting folds, 1 for a full-sample fit.

ContinuousSurvivalResult.predictable: PredictableCovariance | None = None#
ContinuousSurvivalResult.replayability#

Which assessment operations survive from the stored fit.

ContinuousSurvivalResult.restricted_horizons: tuple[float, ...] = ()#
ContinuousSurvivalResult.sensitivity#

The sensitivity-analysis facade, whose every row refuses on this fit.

ContinuousSurvivalResult.estimates: dict[str, ParameterEstimate]#
ContinuousSurvivalResult.record: ContinuousSurvivalRecord#
ContinuousSurvivalResult.simultaneous: Any#
ContinuousSurvivalResult.arms: tuple[str, str]#
ContinuousSurvivalResult.causes: tuple[str, ...]#
ContinuousSurvivalResult.horizons: tuple[float, ...]#
ContinuousSurvivalResult.n: int#
ContinuousSurvivalResult.assessment_cache: AssessmentCache#

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