cleverly.longitudinal.LTMLE#
- class cleverly.longitudinal.LTMLE(regimens: Any, *, reference: str | None = None, horizons: Sequence[int] | None = None, msm: MSM | None = None, outcome_learner: Any | None = None, pseudo_learner: Any | None = None, treatment_learner: Any | None = None, censoring_learner: Any | None = None, competing_learner: Any | None = None, n_folds: int = 10, learner_folds: int = 5, g_bounds: float | tuple[float, float] = (0.01, 1.0), q_bounds: tuple[float, float] | None = None, alpha: float = 0.9995, alpha_sig: float = 0.05, simultaneous: bool = True, n_multiplier: int = 10000, multiplier_kind: str = 'mammen', band_scale: str = 'logit', band_reference: str = 'normal', max_iter: int = 20, tol: float = 1e-10, random_state: int | None = None, run_id: str | None = None, n_jobs: int = 1, n_bootstrap: int = 0, bootstrap_resampling: Literal['auto', 'iid', 'cluster'] = 'auto', bootstrap_interval: Literal['percentile', 'bca'] = 'percentile', density_bins: int | None = None, ratio: str = 'density', repeats: int = 1, stopping: Literal['relative', 'scaled_var', 'sample_size'] = 'relative', step_bound: float | None = None, step_search: bool = True, iterate: Literal['last', 'best'] = 'last', survival_model: str = 'iterated_mean', targeting: str = 'iterative', step_size: float = 0.001, isotonic: bool = False, ratio_trim: float | None = None, hazard_pooling: str = 'node', node_bounds: Mapping[Any, Any] | None = None, variance: str = 'influence_curve', cluster_variance: str = 'influence_curve', max_memory_bytes: int | None = None, **refused: Any)[source]#
Sequential-regression TMLE for a treatment regimen over time.
- Parameters:
- regimens
mapping,Regimen,DynamicRegimen,orsequenceofregimens Mapping from label to plan: a sequence of
Tarms, or a single arm meaning that arm at every node.{"always": 1, "never": 0}is the usual pair. A plan with a rule node is aDynamicRegimendeclaredrule_kind="known", as a mapping value or an item of a sequence. A callable written inline in a mapping carries no declaration, andfit()refuses it before any learner. A node that draws its arm from a known policy is aStochasticnode declareddensity_kind="known", inside aDynamicRegimenor as a mapping value.- reference
strorNone Which regimen contrasts are taken against; the first declared by default. Part of the estimand rather than a display setting –
ate_regimen[a vs b]andate_regimen[a vs c]are different parameters. Refused withmsm=.- horizonssequence
ofintorNone Which time points a survival fit reports the cumulative risk at.
Nonereports all of them, which is the curve. Each horizon is its own backward pass – the pseudo-outcome carried back differs at every node, so nothing is shared between them but the mechanism – and the cost is thereforeT(T+1)/2regressions per regimen rather thanT. At two or three nodes that is not worth a keyword; over a monthly panel it is the difference between a fit and an afternoon, so name the horizons you will report. Refused on a fit with one end-of-study outcome, where the only horizon is the end of the study.- msm
MSMorNone A working model over the regimen and horizon cells, which reports coefficients and no contrasts. Above one fold, each fold runs the untargeted recursion of every cell, and one stacked fluctuation per node pools the update over every follower of every cell.
- outcome_learner
objectorNone Learner specification for the regression at the reported horizon, as for
TMLE.- pseudo_learner
objectorNone Learner specification for the intermediate regressions, whose outcome is a
[0, 1]-valued prediction rather than the outcome itself. It defaults tooutcome_learner’s library read as a regression. A hazard fit uses it only on a design with covariates measured after baseline, and refuses it otherwise.- treatment_learner
objectorNone Learner specification for the treatment mechanism at each node, as for
TMLE.- censoring_learner
objectorNone Learner specification for the censoring mechanism at each node, as for
TMLE.- competing_learner
objectorNone The learner of each eliminated competing event (
eliminate=on the data), fit on the rows that passed censoring at the node.Noneuses the censoring learner.- n_folds
int Outer cross-fitting folds; one split serves every node and every regimen, so a unit is out of fold in all of them at once. Above one fold the fit follows the cross-fitted construction of Díaz, Williams, Hoffman and Schenck (2023, JASA 118(542), Section 5.2, Steps 1-4). Each fold fits the mechanism and runs an untargeted backward regression sequence on its training rows, and the held-out predictions are stitched into one out-of-fold initial estimate per node. One pooled fluctuation per node then targets those predictions over every follower, with the out-of-fold mechanism in its loss weight, so every node’s score equation is solved as on a single-fold fit. The fit divides by the out-of-fold mechanism alone. With
msm=, the fold recursions run for every regimen and horizon cell, and the pooled fluctuation at each node is one stacked solve over every live cell.- learner_folds
int The inner folds of the default
SuperLearnerthat a learner slot left atNonebuilds.- g_bounds
floatortupleoffloat Fixed truncation applied to each cumulative treatment-and-censoring probability, after multiplying the raw node factors. The default is the explicit pair
(0.01, 1.0), Rltmle’s heuristic convention. It is not an automatic, sample-size-dependent, or follow-up-depth-dependent selection procedure.- q_bounds
tupleoffloatorNone The bounds that map a continuous outcome onto the
[0, 1]scale of the recursion.Nonewidens the observed range by 10 % on each side. Above one fold, a continuous outcome must declare them, and a binary outcome refuses them.- alpha
float Predicted probabilities are bounded into
[1 - alpha, alpha]before the logit is taken, as forTMLE.- alpha_sig
float Significance level for confidence intervals, as for
TMLE. The twoalphas mean what they mean there and not the other way round: this pair used to be spelledalpha/alpha_shrinkhere, which madeLTMLE(alpha=0.9995)a silent 0.05 %-level interval.- simultaneousbool
Whether to report simultaneous confidence bands across the reported parameters, via the multiplier bootstrap. A fit with several regimens reports several correlated parameters, which is what the bands are for; see
cleverly.inference.multiplier. A fit whose inference status supplies no inference builds no band, andLongitudinalResult.summary()says so.- n_multiplier
int, default=10_000 The number of multiplier draws behind each band.
- multiplier_kind{“rademacher”, “mammen”, “normal”}, default=”mammen”
The distribution of the multiplier draws.
- band_scale{“logit”, “identity”}, default=”logit”
The scale of the band of a probability or a difference of two probabilities:
"logit"builds it on the logit of the estimate’s position in its range (simultaneous_bands()).- band_reference{“normal”, “t”}, default=”normal”
"t"bands each estimate at the critical value’s tail on its own Student t reference, with degrees of freedom from its influence curve (simultaneous_bands()).- max_iter
int Maximum targeting iterations per node.
- tol
float Targeting tolerance per node. It is the bar of
stopping="relative".- stopping{“relative”, “scaled_var”, “sample_size”}
The rule that decides each node’s score equation is solved.
"relative"is the shipped test,tolon the score relative to its largest possible magnitude."sample_size"stops a node when its score, in the outcome’s units, is at most1 / n_u, and"scaled_var"when it is at mostsd / (sqrt(n_u) * min(log n_u, 10)), astmle3does. Heren_uis the number of distinct units, clusters when the data declareid=, among the rows of the panel, andsdis the sample standard deviation of the node’s per-unit score contribution. A node stops at the first Newton iterate that meets the rule, so a declared rule changesconverged,n_iterand the warning, and it moves the estimate by the part of the last Newton step it skips. Undersurvival_model="hazard"the rule judges the score vector of each horizon (targeting="iterative") or of every target ("one_step"), with each target’s influence curve as its contribution.- step_bound
floatorNone The longest step of one iteration of a node’s targeting, in the units of the fluctuation coefficient.
Nonetakes the full Newton step. A positive number takes thetmle3constrained step: the node’s single coefficient moves bysign(s)times a length in(0, step_bound], wheresis the node’s score. A bounded node may stop short oftol, and then it warns and reportsconverged=False. Undersurvival_model="hazard"andtargeting="iterative"each horizon steps alongs / ||s||, withsits score vector. The one-step hazard walk takes its steps instep_size, so a step bound beside it raisesMethodConfigurationError.- step_searchbool
With
step_bound,Truetakes the length that minimises the node’s weighted mean quasi-loss over(0, step_bound], andFalsetakes the whole bound. It needsstep_bound.- iterate{“last”, “best”}
Which iterate of a node’s targeting walk is reported.
"last"reports the iterate at which the walk stopped."best"reports the iteratek >= 1whose score has the smallest 2-norm, the first of any tie, and judges the node’sconvergedthere. A bounded step without a search can oscillate around the root, which is where the two differ. The one-step hazard walk ranks its steps by the norm it walks on and takes the last of any tie, so"best"there reports the last accepted step.- random_state
intorNone The seed of the outer split. Every learner
random_statethat isNone, including those of aSuperLearner’s candidates, inherits it.Nonedraws a fresh seed for the split.- run_id
strorNone An identifier of your own, recorded on
LongitudinalResult.provenance.- n_jobs
int Worker count for the parallel fan-out of the recursion. With
n_bootstrap > 0the replicates run in parallel and each replicate fit runs with one worker, so there is one parallel layer.- n_bootstrap
int Full-refit bootstrap replicates,
0for none. Otherwise at least 2. Each replicate resamples whole rows of the wide table, or whole clusters, and refits everything: the outer split, the treatment and censoring mechanisms, every backward regression and fluctuation, and the working-model projection. A failed replicate is dropped and counted, never redrawn. The bootstrap stream is spawned fromrandom_stateand draws nothing the fit itself uses, so the fit’s own numbers do not move. A truncation-curve replay does not rerun it. The percentile interval is published as inference with the support label of the fit:supportedwhen a registered row listsbootstrapfor the fit, andexperimentalotherwise. A fit that withholds its interval, or that has fewer clusters than the floor, printsbootstrap sdand a percentile range. The registered study measures it with correctly specified cell-mean nuisances on finite binary laws, atn = 1000. Each replicate also records its own influence-curve standard error, which the studentized sup-t band (LongitudinalResult.bootstrap_band) divides by. An in-sample fit with declared mechanisms and frequency-exact learners computes each replicate as a frequency-weighted fit on the distinct rows (FrequencyReplicate), which equals the materialized refit to rounding.- bootstrap_resampling{“auto”, “iid”, “cluster”}
"auto"resamples clusters whenid=is declared, and rows otherwise.- repeats
int How many independent draws of the outer split the fit combines, at least 1. Each draw is a complete fit at its own fold assignment and seed, spawned from
random_stateascleverly.learners.CrossFitPlan.seeds()spawns them, and every learner of that draw takes that seed. The report is the median of the draws on each estimate’s inference scale, with the split-adjusted variance of Chernozhukov et al. (2018, Definition 3.3 and equation 3.14), andLongitudinalResult.repeatsholds every draw. Above 1 it needsn_foldsof 2 or more andn_bootstrap=0. At 1 the fit is unchanged, and the learners keeprandom_state.- bootstrap_interval{“percentile”, “bca”}, default=”percentile”
The pointwise bootstrap interval.
"bca"is the bias-corrected and accelerated interval, with the acceleration from each estimate’s own influence curve (summed within clusters when clusters are resampled). It needsn_bootstrap; 199 replicates is the X39 study setting. It carries the labelexperimentaluntil a registered row lists thebootstrap_bcakind for the fit.- survival_model{“iterated_mean”, “hazard”}
How a survival curve is modelled.
"iterated_mean"runs one backward recursion per horizon, and its curve can decrease."hazard"fits the cause-specific hazard at every node and targets it (Moore and van der Laan 2009; Cai and van der Laan 2020). It needs one baseline treatment held over every node; other designs are refused before any learner. The outcome learner is then the hazard learner. With covariates measured after baseline it needstargeting="one_step", andpseudo_learnerfits each node’s regression of the future (Rytgaard, Gerds and van der Laan 2022).- targeting{“iterative”, “one_step”}
The hazard targeting algorithm.
"iterative"targets each horizon on its own, restarting from the initial hazards."one_step"walks one set of hazards until every horizon’s score is solved, so every curve is non-decreasing. It requiressurvival_model="hazard".- step_size
float The first step of the one-step walk, halved after any step that raises the score norm. Accepted and unused under
targeting="iterative".- isotonicbool
Whether to project each regimen’s and cause’s reported levels, and the limits of its simultaneous band, onto a non-decreasing curve over the reported horizons by unit-weight isotonic regression (Westling, van der Laan and Carone 2020). Every influence curve, standard error and critical value is unchanged. A curve with no violation is returned bit for bit.
- density_bins
intorNone The bin count of a continuous node’s conditional density.
- ratio{“density”, “classifier”}
How a continuous node’s policy ratio is estimated.
- ratio_trim
floatorNone A quantile in
(0, 1)at which every per-node density ratio is trimmed, aslmtp’s.trimdoes (cleverly.longitudinal.ratio_trim). A fit whose trim moves a ratio reports no interval.Nonetrims nothing.survival_model="hazard"refuses it withCapabilityError, because the hazard targeting has no density-ratio matrix to trim.- hazard_pooling{“node”, “pooled”}
"pooled"fits one censoring model over every node’s at-risk rows, with the node time as a column (cleverly.longitudinal.pooled_hazards). Undersurvival_model="hazard"it also fits each cause’s hazard once over the eligible rows of every node.- node_bounds
mappingorNone A declared outcome range for chosen nodes of an iterated-mean fit. The keys are grid times, the values are
(lower, upper)pairs on the reported outcome scale, and a competing-risk fit takes one such mapping for each cause name. A named node regresses(Y - lower) / (upper - lower)with the pseudo-outcome learner, clips the prediction to[0, 1]and maps it back into the bounds. It fluctuates along the logit of the rescaled prediction (Gruber and van der Laan 2010), so its targeted prediction stays inside the bounds. A node with no entry, andNone, give the shipped fit bit for bit, and so does a node whose bounds equal the outcome range. The score equation of a bounded node has a root only when the weighted mean outcome of the node’s followers lies strictly inside the bounds. Otherwise the node runs no Newton step, the fit warns withConvergenceWarning, and the node reportsfailure="bound_excludes_data"andconverged=False. A grid time that is not a node, a cause the fit did not declare,lower >= upperand bounds outside the outcome range raiseValueErrorbefore any learner.msm=raisesCapabilityError. Undersurvival_model="hazard"the bounds are on the cause-specific hazard, inside[0, 1], and a named node bounds every cause. Cause \(j\) there fluctuates along \(\operatorname{logit}((\lambda_j - l_j) / (u_j - l_j))\), the initial hazards are clipped into the bounds, and the record holds the clipped share. A node that bounds some causes and not others, or whose upper bounds sum to more than one, raisesCapabilityErrorbefore any learner.- variance{“influence_curve”, “policy_weighted”}
The variance of every reported interval.
"influence_curve"reads it from the influence curve of the fitted rows."policy_weighted"also computes the change-of-measure sequential plug-in of that variance, which reads every node’s residual through the ratio at each row’s policy dose (cleverly.longitudinal.policy_variance), and reports the larger of the two for every level and contrast. The estimate does not change, and the interval contains the default one in every sample. Each estimate’svariance_sourcesays which variance it reports, and itspolicyrecord keeps both. The option needs an in-sample (n_folds=1), unclustered, unweighted and uncensored fit of an end-of-study outcome withsimultaneous=False,repeats=1and nomsm=,n_bootstraporratio_trim, with no node that holds a vector of treatments, no treatment held from baseline, no data-tuned policy cap and no learned or separable-effects regimen. Any other setting or design raisesCapabilityErrorbefore any learner. Its coverage claim needs an exact or known ratio, or, with a learned ratio, a consistent outcome model. The registered studymtp-policy-variancemeasures it, and an estimate readssupportedonly where a support row licenses the option.- cluster_variance{“influence_curve”, “jackknife”}
The variance of a clustered fit’s estimates.
"influence_curve"(default) is the cluster-robust variance of the influence curve."jackknife"refits the whole estimator once per cluster with that cluster’s rows removed, every node’s nuisances refitted and the targeting redone, on the drawn split less those rows, and reports the delete-one-cluster jackknife variance with the same Student t reference (cleverly.inference.cluster_jackknife). A boundary-node supplement is added to it. It needsid=, GLM nuisances (LogisticRegression,LinearRegression,GLM, a Super Learner of those, or a declared mechanism),repeats=1, no bootstrap, the defaultvariance, no learned regimen and no continuous node, and, when cross-fitted, a split whose every fold holds two clusters after the fold count is reduced to the cluster count. Anything else raisesCapabilityErrorbefore any learner. The fit costs one refit per cluster and builds no simultaneous band. The option is experimental until its validation study is registered.- max_memory_bytes
intorNone The memory budget, in bytes, that two guards read before any learner. The memory guard of
LTMLE,SDRandIPSIpredicts the peak of the whole call from the units, nodes, regimens, horizons, causes, folds, design columns, density bins, repeats, bootstrap replicates and workers, and raisesLongitudinalMemoryError, aMethodConfigurationError, when the prediction exceeds the budget. WithNoneit reads the memory available when the fit starts (available_memory()), and checks nothing where the platform does not report it, as on macOS. The prediction counts the arrays the estimator holds, calibrated with GLM, logistic and linear learners, and other learners’ own memory is not counted, so a fit with heavier learners can pass the check and still run out of memory. Outside the calibrated ranges, which the “Memory” section ofdocs/technical-reference/longitudinal-tmle.mdlists, the prediction is an extrapolation and the refusal says so. Its worker constants assume workers that start cold, so a repeated call withn_jobs > 1can be over-counted by aboutn_jobstimes 324 MiB. The second guard is the traced-memory limit of asurvival_model="hazard"fit with a treatment decision at several nodes, no covariate after baseline and a regimen that draws from a known policy, which holds the hazards of every treatment path for every unit (path_peak()); it raisesCapabilityError, and withNonekeeps its fixed limit of 2 GiB (PATH_PEAK_LIMIT). A positive integer replaces both, higher or lower. The binned density’s own refusal during the fit reads the available memory only, and this setting does not override it.- **refused
Any A point-treatment keyword. Each one raises
CapabilityErrorwith the reason that a longitudinal fit does not support it.
- regimens