Data, prediction and results
Input preparation, effect contrasts, summaries, bounds and plots.
quantize(exposures, *, q=4, breaks=None)
Convert exposure measurements to ordered category scores.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Notes
Follows R qgcomp 2.19.6: calculate type-7 quantiles, remove duplicates from the full sequence and replace its outer endpoints by +/-1e64. A value on an interior boundary belongs to the lower category. Ties can leave one category, which cannot then be used as an identifiable regression column. The 100,000-group limit bounds memory allocation in this implementation; it is not a restriction of the statistical method.
Examples:
>>> quantize([0, 1, 2, 3], q=2).scores.ravel().tolist()
[0.0, 0.0, 1.0, 1.0]
qgcomp(formula, data, exposures, *, family='gaussian', rr=True, q=4, breaks=None, alpha=0.05, weights=None, missing='raise', B=None, seed=None, exposure_time=None, cluster_ids=None, offset=None)
Choose a supported additive quantile g-computation fit by family.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Notes
The supported routes follow selected behavior of R qgcomp 2.19.6. In
particular, binomial rr=True with four quantiles uses a degree-one
log-binomial marginal structural model, not the two-level risk ratio.
Marginal survival bootstrap, nonlinear, zero-inflated and other routes
need separate methods.
se_comb(exposure_names, covariance, *, names, grad=None)
Standard error of a named linear combination of coefficients.
names gives covariance row and column order. By default each selected
exposure receives coefficient one; grad may be a scalar for all
selected exposures or a full vector in names order.
vc_comb(exposure_names, covariance, *, names, aname='(Intercept)', grad=None)
Covariance of a named coefficient and an exposure contrast.
The off-diagonal uses the supplied gradient. R qgcomp 2.19.6 does not
apply grad to that entry; the default unweighted behavior agrees.
split_data(data, *, cluster=None, prop_train=0.4, seed=None)
Randomly partition rows, with optional whole-cluster assignment.
The training fraction is rounded to the nearest integer. A seed makes the
Python split reproducible; it does not reproduce R's random-number stream.
With cluster, each distinct cluster is assigned wholly to one side.
This corrects an R 2.19.6 implementation difference: its cluster helper
samples rows inside each cluster despite its group-preserving description.
Missing cluster IDs and a split with an empty side are rejected.
qgcomp_partials(train_y, train_exposures, validation_y, validation_exposures, *, train_covariates=None, validation_covariates=None, q=4, fixed_breaks=True, alpha=0.05, family='gaussian')
Select coefficient signs in training rows and estimate in held-out rows.
This interface needs an independently chosen train/validation split.
family is "gaussian", "binomial" or "poisson". For each
nonempty sign group, its held-out fit treats the other
exposures as adjustment variables. With raw exposures, only the selected
group is quantized in held-out fits, matching R's expnms convention.
The default reuses training cutpoints. fixed_breaks=False computes new
held-out cutpoints. The binary result is a conditional log odds ratio;
the count result is a conditional log mean ratio for equal observation
periods. Cross-fitting, bootstrap, case weights, Poisson time offsets,
other families and inference for a data-dependent split are outside this
interface. Keeping clusters on one side with split_data does not make
these model-based intervals cluster-robust.
pointwisebound_noboot(result, *, pointwiseref=1, alpha=0.05)
Compare each joint exposure score with a selected score level.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
pointwisebound_boot(result, *, pointwiseref=1, alpha=0.05)
Compare marginal fitted means at each score against one reference score.
pointwiseref is one-based, matching R. In R qgcomp 2.19.6, the
Poisson bootstrap covariance is calculated from marginal-model predictions
on the log scale. The displayed fitted means are calculated on the response
scale, then logged for the linear-predictor column.
modelbound_boot(result, *, alpha=0.05, pwonly=False)
Bound a fitted additive marginal curve at every joint score.
Pointwise limits use the bootstrap standard deviation at each score. Simultaneous limits follow R qgcomp 2.19.6: retain resampled marginal coefficient vectors inside a chi-square ellipsoid around the original coefficients, then take the minimum and maximum fitted curve among those retained vectors at each score. These are reference-method bounds, not a guaranteed finite-sample or causal coverage statement.
modelbound_ee(result, *, alpha=0.05, pwonly=False, seed=None)
Return pointwise and R-method simultaneous bounds for Gaussian EE.
Like R qgcomp 2.19.6, this samples 5,000 marginal coefficient vectors
from the fitted normal approximation. seed makes Python's draws
reproducible; the same integer does not give the same draws in R.
These bounds are sampling-based and do not establish repeated-data coverage.
msm_predict(result, newdata=None)
Predict from a fitted bootstrap marginal structural model.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Notes
This matches the selected additive behavior of R qgcomp 2.19.6
msm.predict. It predicts from the marginal model, not the conditional
outcome model. It returns no confidence or individual prediction interval.
tidy(result, *, conf_level=None, exponentiate=False, quick=False)
Report the fitted intercept and joint effect in a small named table.
Only additive non-bootstrap Gaussian, binomial, Poisson and conditional
Cox fits are supported. Cox has no intercept row. By default the
confidence level is the fit's 1-alpha. quick=True returns only
term names and estimates. Exponentiation is available for log or logit
links; standard errors and test statistics remain on the link scale.
Unlike R qgcomp 2.19.6's tidy method, the upper exponentiated limit
uses the upper limit, and an intercept has its own p-value instead of a
recycled joint-effect p-value. These are explicit correctness repairs.
The Gaussian joint p-value retains R qgcomp's reference degrees of
freedom; its intercept uses the fitted model's residual degrees of
freedom. Normal confidence limits are used for both.
glance(result)
Give one row of likelihood and fit measures for a conditional model.
Supports additive Gaussian, Bernoulli-logit and Poisson-log fits. nobs
counts rows, df_model counts slope coefficients, and df_residual
is the number of rows minus all fitted coefficients. deviance and
null_deviance are weighted when case weights were used; Gaussian
null deviance is the weighted total sum of squares. The null
Poisson model retains each row's observation time. AIC and BIC use the
maximized full likelihood for Gaussian and the model likelihood for the
two generalized linear models. Gaussian AIC/BIC count the error variance
as one additional parameter; BIC uses the number of rows.
Zero residual sum of squares makes a Gaussian maximum-likelihood variance
degenerate. In that case likelihood-based measures are None instead
of infinite. An undefined R-squared or F test is also None.
Bootstrap, estimating-equation, Cox and other result classes are not yet
supported; they must not inherit likelihood claims from a different fit.
plot_weights(result, *, ax=None)
Draw descriptive positive and negative exposure weights.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Notes
The positive and negative groups are normalized separately. Bar lengths must not be compared as shares of one common total. The family changes the coefficient scale, not this within-sign definition.
plot_response(result, *, ax=None)
Draw saved standardized responses at joint exposure scores.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Notes
The line connects fitted points for display. It is not an uncertainty band or a new model fit. Each score sets every exposure to that category while retaining the fitted method's adjustment distribution.
impute_leftcenslognorm(y, ry, x=None, wy=None, *, lod=None, seed=None)
Draw positive values below a limit of detection (LOD).
y is one measured variable. ry marks observed values; selected
left-censored rows have ry=False and are marked by wy (by default,
all unobserved rows). Observed values must be finite and positive. x
contains complete numeric predictors without an intercept; an intercept
is added. lod is a positive scalar or one positive value per row. If
omitted, the smallest observed value is used for every censored row.
A lognormal regression uses both observed densities and censored lower- tail probabilities. One parameter vector is drawn from the fitted normal approximation, then each selected value is sampled from its lognormal distribution truncated above at its LOD. The return contains imputed values in selected-row order, as in R's MICE helper. Assign them to those rows in an external imputation workflow; this package does not silently pool multiply imputed analyses.
This is a Python interface to the R qgcomp 2.19.6 left-censored lognormal
method, not an R MICE callback. Its random stream and optimizer differ
from R's survreg implementation. The normal parameter draw is an
asymptotic approximation and can be unreliable in small or weakly
identified samples. impute_tobit is an alias for this same algorithm.
impute_tobit = impute_leftcenslognorm
module-attribute
simdata_quantized(outcometype='continuous', *, n=100, corr=None, b0=0.0, coef=(1.0, 0.0, 0.0, 0.0), q=4, yscale=1.0, shape0=3.0, scale0=5.0, censtime=4.0, ncheck=True, seed=None)
Generate balanced quantized exposures and one synthetic outcome.
outcometype is "continuous", "logistic", "survival" or
"multinomial". Each exposure column has scores from zero through
q-1. corr gives signed template-copy probabilities for exposures
after the first, not exact target Pearson correlations. A positive value
copies the first exposure's shuffled score template; a negative value
copies its reverse. Other rows are shuffled within that exposure.
coef is a vector with one coefficient per exposure, except for
multinomial outcomes, where it is a matrix of shape
(exposures, nonreference_categories). The multinomial outcome y
uses one-based category labels. Survival returns time and d;
d=1 means the event preceded administrative censoring at censtime.
The returned mapping includes x1, x2, ... and outcome columns;
the known coefficients are separate attributes, not data columns.
NumPy's local random generator makes Python runs repeat for the same seed.
Its draws are not bitwise equal to R's random stream. Two R 2.19.6 source
errors are corrected deliberately: when ncheck is true, n is
increased to the next multiple of q (R adds the remainder), and
survival baseline times use scale0 (R passes shape0 as scale).
This helper generates synthetic examples; it does not validate a method.