cleverly.msm.MSM#
- class cleverly.msm.MSM(design: Callable[[Any, Any], Any], terms: tuple[str, ...], weights: Callable[[Any, Any], Any] | None = None, link: Literal['identity', 'log', 'logit'] = 'identity', from_linear: bool = False, doses: tuple[float, ...] = (), weights_kind: Literal['known', 'estimated'] | None = None, design_kind: Literal['known', 'estimated'] | None = None)[source]#
A working model, declared as a design function and the names of its terms.
designis handed one treatment level – the user’s own label, not an internal code – and a dataframe of the covariates in the backend the data arrived in, and returns the(n, p)design \(\varphi(a, V)\) for that arm. It is called once per arm. A written design declares that it is a fixed function withdesign_kind="known".MSM( design=lambda a, w: np.column_stack([np.ones(len(w)), np.full(len(w), a)]), terms=("(intercept)", "a"), design_kind="known", )
Reading the covariate frame rather than the whole dataset is the same restriction
cleverly.interventions.Ruleworks under and for the same reason: a working model whose design readYwould not be a model for a counterfactual mean, and one that read the observedAwould be summarising the arms nobody was assigned to differently from the ones they were. The columns are the encoded covariates, so a categorical column appears as the indicators the data layer expanded it into;data.covariate_namesis the list to write a design against.- Parameters:
- design
callable() (arm_label, covariate_frame) -> (n, p)for a point treatment, and(regimen_label, horizon, baseline_frame) -> (n, p)for a longitudinal regimen MSM. It must be a known function, anddesign_kinddeclares that it is.- terms
tupleofstr One name per design column, used verbatim in the reported parameter names:
msm[a:W1].- weights
callable()orNone h(a, V), as(arm_label, covariate_frame) -> (n,).Nonemeans uniform, which weights every arm and every unit equally. It must be a known function, andweights_kinddeclares that it is.- link{“identity”, “log”, “logit”}
"identity","log"or"logit". The link also chooses the projection’s loss: least squares for the identity, the quasi-Poisson loss for the log and the quasi-binomial loss for the logit, each convex in \(\beta\) (Link). Every link’s fit is a single fluctuation. What the coefficients mean changes with it – under"log"a coefficient is a log risk ratio and under"logit"a log odds ratio, which is whatcoefficients()exponentiates.- from_linearbool
Set by
linear()and by nothing else. That shorthand reads the label it is handed as a dose, which a treatment arm can be and a regimen cannot, so a working model over regimens refuses it (cleverly.longitudinal.msm)._numeric_levelalready refuses a string label, but a regimen legitimately called"0"would be read as a dose of zero and reported without complaint – a flag on the declaration is what makes that structural rather than lucky. It declares nothing about the design: the design declaration isdesign_kind.- doses
tupleoffloat Increasing dose grid used to integrate a continuous-treatment projection. Empty on the ordinary finite-arm path. The grid is part of the estimand, not a random Monte Carlo tuning parameter.
- weights_kind{“known”, “estimated”}
orNone The declaration that
weightsis a known function. A callableweightsneeds"known": a fixed function of the arm and the covariates, chosen without reading the data.Nonewith a callable, and"estimated", are refused byrefuse_msm_functions(), because a weight computed from the sample makesha functional of \(P\) and the reported influence curve omits its pathwise derivative. It is unrelated tocleverly.data.weighting.WeightKind, which describes observation weights. It followsdoses, solinkstays the fourth positional argument.- design_kind{“known”, “estimated”}
orNone The declaration that
designis a known function: a fixed function of the arm (or the regimen and horizon) and the covariates, chosen without reading the data.Noneand"estimated"are refused byrefuse_msm_functions(). A population-law target using a sample-computed design, such as a covariate centred at its sample mean, can need a pathwise derivative through that statistic, which the reported curve lacks.Nonereads as"known"only when the design has the exact type thatlinear()builds. That design is known by construction, solinear()leaves this fieldNone, and a design swapped into its model withdataclasses.replace()needs its own declaration.
- design
Methods#
- classmethod MSM.linear(*, modifiers: Sequence[str] = (), interaction: bool = True, weights: Callable[[Any, Any], Any] | None = None, weights_kind: Literal['known', 'estimated'] | None = None, link: Literal['identity', 'log', 'logit'] = 'identity', doses: Sequence[float] = ()) MSM[source]#
The usual dose-response model, without writing the design out by hand.
MSM.linear(modifiers=("W1",))is \(m(a, V) = \beta_0 + \beta_1 a + \beta_2 W_1 + \beta_3 a W_1\), andinteraction=Falsedrops the last term. With no modifiers it is a plain dose-response line, whose slope is the average change in counterfactual mean per unit of treatment under the \(h\)-weighted projection.link=puts that linear predictor inside a link, solink="log"makes \(\beta_1\) a log risk ratio per unit of treatment rather than a risk difference.The arm enters as a number, so this requires numeric treatment levels: it reads the arms as a dose to be extrapolated between. A string-labelled treatment is refused rather than coded silently, because
{"low", "medium", "high"}sorts alphabetically and the resulting slope would be per-step in an order nobody chose. Passdesign=withdesign_kind='known'and code the arms yourself where that is what you want.The design this builds is a fixed function of the arm and the named covariates, so it needs no declaration, and the model leaves
design_kindNone.refuse_msm_functions()reads the exact type of this design as known. A design swapped in withdataclasses.replace()has another type, so it needsdesign_kind="known"of its own.weights=andweights_kind=are forwarded unchanged, so a callable weight needsweights_kind="known"here as it does onMSM.- Parameters:
- modifierssequence
ofstr The encoded covariates that enter the model as main effects.
- interactionbool
Whether each modifier also enters as a product with the dose, named
a:<modifier>.- weights
callable()orNone The projection weight
h(a, V), forwarded toMSM.Nonemeans uniform.- weights_kind{“known”, “estimated”}
orNone The declaration of
weights, forwarded toMSM.- link{“identity”, “log”, “logit”}
The link, forwarded to
MSM.- dosessequence
offloat The increasing dose grid of a continuous-treatment projection. Empty on the finite-arm path.
- modifierssequence
- Returns:
MSMA working model whose design is linear in the dose and the modifiers, with
from_linear=Trueanddesign_kind=None.