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:
- estimates
dictofstrtoParameterEstimate Each arm’s risk (
risk_regimen[arm @ t=60], orcif_regimen[arm, cause @ t=60]with competing causes), the risk differences (ate_regimen[...]) and the risk ratios (rr_regimen[...]). A fit withrestricted_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 ...]).- record
ContinuousSurvivalRecord The nuisance selections and the targeting record.
- simultaneous
SimultaneousBandsorNone The sup-t band over every risk and risk difference, when requested.
- arms
tupleofstr (reference, treated).- causes
tupleofstr The cause labels.
- horizons
tupleoffloat The target times.
- n
int The number of units.
- backend
strorNone The dataframe library the data arrived in;
to_frame()returns a frame of it.- restricted_horizons
tupleoffloat The restriction times the fit targeted.
- predictable
PredictableCovarianceorNone Under
variance="switched", the predictable-variation covariance of every targeted level, with each stored estimate’s gradient over them;contrast()andratio()read it.Noneundervariance="influence_curve".- estimator
ContinuousSurvivalTMLEorNone 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.Noneonly on a result built by hand, which the refits refuse.- data
ContinuousSurvivalDataorNone The rows the fit read.
Noneonly on a result built by hand.- bootstrap
BootstrapResultorNone 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 withsimultaneous=True, whose studentized band reads it, and its influence-curve standard error otherwise.Nonewithout 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_failedandbootstrap_failuressay how many did not.- bootstrap_band
BootstrapBandorNone The studentized bootstrap band over every risk and risk difference, with
n_bootstrapandsimultaneous=Trueand 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 ignoresband_scale.- bootstrap_status{“ran”, “bootstrap_unstable”}
orNone "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), andNonewithout a bootstrap.- bootstrap_failures
tupleofstr The class and first sentence of each failed refit’s exception, in replicate order.
- bootstrap_jump_bounded
int 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.
- estimates
Notes
diagnostics,sensitivity,validate()andassess()declare a row for every assessment operation. The support, nuisance, score and influence diagnostics readrecordand the influence curves, and the E-value reads a risk ratio of the fit.diagnostics.refute()refitsestimatoron perturbed copies ofdata(the placebo on a contrast, the random common cause and the subset tests, all descriptive), anddiagnostics.truncation_curve()reruns the targeting walk at other floors from refitted initial hazards.sensitivity.simulated_confounding()refitsestimatoronce 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=Truethe 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:
- Returns:
AssessmentReportValidation, 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()). Undervariance="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 readsexperimental.- Parameters:
- function
callable() A smooth scalar function of the selected estimates, in the order of
names.- namessequence
ofstr The reported estimates it reads.
- name
strorNone The name of the derived estimate.
Nonegivescontrast(<names>).- scale
str The reported scale of the derived estimate. With
transform=it must be"level"or"difference".- gradient
callable()orNone The analytic gradient.
Noneuses central differences.- transform
TransformorNone The map the interval and the test are computed on, as for
cleverly.estimators.TMLEResult.contrast().
- function
- Returns:
ParameterEstimateThe 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:
- Returns:
dataframeOne 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_lowerandband_upper(the simultaneous band, when the fit has one),scale("level"or"difference"),viewandsupport.
- Raises:
CapabilityErrorWhen a time is not a target time, or
scale="survival"on a fit with several causes.
See also
cleverly.survival.ContinuousSurvivalResult.to_frameEvery estimate, with no time column.
cleverly.survival.ContinuousSurvivalResult.rmstThe 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 withn_bootstrap=andsimultaneous=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=andtitle=).
- Returns:
FigureThe levels above and their difference below, one column per cause.
- Raises:
CapabilityErrorWhen the fit refuses the requested view, with the fit’s own reason.
ValueErrorWhen
band=,measure=,scale=orcause=do not fit together or the fit, such asband="bootstrap"on a fit with no bootstrap band orcause=withmeasure="rmst".DataErrorWhen
cause=orregimens=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. Undervariance="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 readsexperimental.- Parameters:
- numerator
str The name of one arm’s risk.
- denominator
str 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.
- name
strorNone The name of the derived estimate.
Nonegivesrr_regimen[a vs b @ t=...], with the cause on a fit with several causes;or_regimenfor an odds ratio, and asurvival_prefix for the survival view. The risk ratio of the treated arm over the reference arm is the reportedrr_regimenestimate.
- numerator
- Returns:
ParameterEstimateThe ratio, on the
"ratio"scale withlog_psiset.
- Raises:
CapabilityErrorWhen 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.evalueThe E-value of this ratio.
cleverly.survival.ContinuousSurvivalResult.contrastAny 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:
- Returns:
ParameterEstimateA
"level"estimate, or a"difference"estimate withversus=.
- Raises:
CapabilityErrorWhen
tauis not one of the fit’srestricted_horizons.ValueErrorWhen an arm is unknown.
See also
cleverly.survival.ContinuousSurvivalResult.rmtlThe restricted mean time lost to one cause.
cleverly.survival.ContinuousSurvivalResult.curveThe 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:
- Returns:
ParameterEstimateA
"level"estimate, or a"difference"estimate withversus=.
- Raises:
CapabilityErrorWhen
tauis not one of the fit’srestricted_horizons.ValueErrorWhen an arm or the cause is unknown, or the cause is missing on a fit with several causes.
See also
cleverly.survival.ContinuousSurvivalResult.rmstThe 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:
PathThe 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:
SummaryThe report.
- ContinuousSurvivalResult.to_dict() dict[str, Any][source]#
A JSON-ready record of the fit.
- Returns:
dictofstrtoAnyestimates, each estimate’sto_dict()by name;record, the selected models and how the walk ended; andsettings, the arms, causes, target times, restriction times, units, significance level and variance; andpredictable_covariance, the targets and matrix of the predictable-variation covariance undervariance="switched", elseNone; andbootstrap, withn_bootstrap, the status, the replicates requested and failed, each failure’s reason and the studentized band, elseNone(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, readsNone, so the mapping passesjson.dumps(..., allow_nan=False).
Attributes#
- ContinuousSurvivalResult.assessment_family: ClassVar[str] = 'continuous_survival'#
The assessment family: one declaration per assessment operation in
cleverly.assessment.ASSESSMENT_CAPABILITIES.
- ContinuousSurvivalResult.bootstrap: BootstrapResult | None = None#
- ContinuousSurvivalResult.diagnostics#
The support, score, nuisance and influence diagnostics of the fit.
- ContinuousSurvivalResult.estimator: ContinuousSurvivalTMLE | None = None#
- 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,
1for a full-sample fit.
- ContinuousSurvivalResult.replayability#
Which assessment operations survive from the stored fit.
- 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.assessment_cache: AssessmentCache#
Assessment results keyed by operation and normalized arguments.
init=False, so a mapping handed to the constructor bydataclasses.replacecannot answer for another fit.