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:
regimensmapping, Regimen, DynamicRegimen, or sequence of regimens

Mapping from label to plan: a sequence of T arms, 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 a DynamicRegimen declared rule_kind="known", as a mapping value or an item of a sequence. A callable written inline in a mapping carries no declaration, and fit() refuses it before any learner. A node that draws its arm from a known policy is a Stochastic node declared density_kind="known", inside a DynamicRegimen or as a mapping value.

referencestr or None

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] and ate_regimen[a vs c] are different parameters. Refused with msm=.

horizonssequence of int or None

Which time points a survival fit reports the cumulative risk at. None reports 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 therefore T(T+1)/2 regressions per regimen rather than T. 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.

msmMSM or None

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_learnerobject or None

Learner specification for the regression at the reported horizon, as for TMLE.

pseudo_learnerobject or None

Learner specification for the intermediate regressions, whose outcome is a [0, 1]-valued prediction rather than the outcome itself. It defaults to outcome_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_learnerobject or None

Learner specification for the treatment mechanism at each node, as for TMLE.

censoring_learnerobject or None

Learner specification for the censoring mechanism at each node, as for TMLE.

competing_learnerobject or None

The learner of each eliminated competing event (eliminate= on the data), fit on the rows that passed censoring at the node. None uses the censoring learner.

n_foldsint

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_foldsint

The inner folds of the default SuperLearner that a learner slot left at None builds.

g_boundsfloat or tuple of float

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), R ltmle’s heuristic convention. It is not an automatic, sample-size-dependent, or follow-up-depth-dependent selection procedure.

q_boundstuple of float or None

The bounds that map a continuous outcome onto the [0, 1] scale of the recursion. None widens the observed range by 10 % on each side. Above one fold, a continuous outcome must declare them, and a binary outcome refuses them.

alphafloat

Predicted probabilities are bounded into [1 - alpha, alpha] before the logit is taken, as for TMLE.

alpha_sigfloat

Significance level for confidence intervals, as for TMLE. The two alphas mean what they mean there and not the other way round: this pair used to be spelled alpha / alpha_shrink here, which made LTMLE(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, and LongitudinalResult.summary() says so.

n_multiplierint, 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_iterint

Maximum targeting iterations per node.

tolfloat

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, tol on the score relative to its largest possible magnitude. "sample_size" stops a node when its score, in the outcome’s units, is at most 1 / n_u, and "scaled_var" when it is at most sd / (sqrt(n_u) * min(log n_u, 10)), as tmle3 does. Here n_u is the number of distinct units, clusters when the data declare id=, among the rows of the panel, and sd is 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 changes converged, n_iter and the warning, and it moves the estimate by the part of the last Newton step it skips. Under survival_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_boundfloat or None

The longest step of one iteration of a node’s targeting, in the units of the fluctuation coefficient. None takes the full Newton step. A positive number takes the tmle3 constrained step: the node’s single coefficient moves by sign(s) times a length in (0, step_bound], where s is the node’s score. A bounded node may stop short of tol, and then it warns and reports converged=False. Under survival_model="hazard" and targeting="iterative" each horizon steps along s / ||s||, with s its score vector. The one-step hazard walk takes its steps in step_size, so a step bound beside it raises MethodConfigurationError.

step_searchbool

With step_bound, True takes the length that minimises the node’s weighted mean quasi-loss over (0, step_bound], and False takes the whole bound. It needs step_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 iterate k >= 1 whose score has the smallest 2-norm, the first of any tie, and judges the node’s converged there. 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_stateint or None

The seed of the outer split. Every learner random_state that is None, including those of a SuperLearner’s candidates, inherits it. None draws a fresh seed for the split.

run_idstr or None

An identifier of your own, recorded on LongitudinalResult.provenance.

n_jobsint

Worker count for the parallel fan-out of the recursion. With n_bootstrap > 0 the replicates run in parallel and each replicate fit runs with one worker, so there is one parallel layer.

n_bootstrapint

Full-refit bootstrap replicates, 0 for 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 from random_state and 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: supported when a registered row lists bootstrap for the fit, and experimental otherwise. A fit that withholds its interval, or that has fewer clusters than the floor, prints bootstrap sd and a percentile range. The registered study measures it with correctly specified cell-mean nuisances on finite binary laws, at n = 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 when id= is declared, and rows otherwise.

repeatsint

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_state as cleverly.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), and LongitudinalResult.repeats holds every draw. Above 1 it needs n_folds of 2 or more and n_bootstrap=0. At 1 the fit is unchanged, and the learners keep random_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 needs n_bootstrap; 199 replicates is the X39 study setting. It carries the label experimental until a registered row lists the bootstrap_bca kind 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 needs targeting="one_step", and pseudo_learner fits 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 requires survival_model="hazard".

step_sizefloat

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_binsint or None

The bin count of a continuous node’s conditional density.

ratio{“density”, “classifier”}

How a continuous node’s policy ratio is estimated.

ratio_trimfloat or None

A quantile in (0, 1) at which every per-node density ratio is trimmed, as lmtp’s .trim does (cleverly.longitudinal.ratio_trim). A fit whose trim moves a ratio reports no interval. None trims nothing. survival_model="hazard" refuses it with CapabilityError, 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). Under survival_model="hazard" it also fits each cause’s hazard once over the eligible rows of every node.

node_boundsmapping or None

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, and None, 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 with ConvergenceWarning, and the node reports failure="bound_excludes_data" and converged=False. A grid time that is not a node, a cause the fit did not declare, lower >= upper and bounds outside the outcome range raise ValueError before any learner. msm= raises CapabilityError. Under survival_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, raises CapabilityError before 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’s variance_source says which variance it reports, and its policy record keeps both. The option needs an in-sample (n_folds=1), unclustered, unweighted and uncensored fit of an end-of-study outcome with simultaneous=False, repeats=1 and no msm=, n_bootstrap or ratio_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 raises CapabilityError before any learner. Its coverage claim needs an exact or known ratio, or, with a learned ratio, a consistent outcome model. The registered study mtp-policy-variance measures it, and an estimate reads supported only 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 needs id=, GLM nuisances (LogisticRegression, LinearRegression, GLM, a Super Learner of those, or a declared mechanism), repeats=1, no bootstrap, the default variance, 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 raises CapabilityError before 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_bytesint or None

The memory budget, in bytes, that two guards read before any learner. The memory guard of LTMLE, SDR and IPSI predicts the peak of the whole call from the units, nodes, regimens, horizons, causes, folds, design columns, density bins, repeats, bootstrap replicates and workers, and raises LongitudinalMemoryError, a MethodConfigurationError, when the prediction exceeds the budget. With None it 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 of docs/technical-reference/longitudinal-tmle.md lists, the prediction is an extrapolation and the refusal says so. Its worker constants assume workers that start cold, so a repeated call with n_jobs > 1 can be over-counted by about n_jobs times 324 MiB. The second guard is the traced-memory limit of a survival_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 raises CapabilityError, and with None keeps 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.

**refusedAny

A point-treatment keyword. Each one raises CapabilityError with the reason that a longitudinal fit does not support it.

Methods#

Attributes#