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:
  • exposures ((array - like, shape(n, d) or (n,))) –

    Measurements for n observations and d exposures. A vector represents one exposure. Values must be real, finite and complete. Named columns are retained and must have unique names.

  • q (int or None, default: 4 ) –

    Requested number of quantile groups, from 2 to 100,000. Ties can reduce the actual number. Booleans are not accepted. With q=None and no breaks, inputs must already be nonnegative integer scores smaller than 2**53; arbitrary raw measurements are not accepted.

  • breaks (array-like or sequence of array-like, default: None ) –

    Category boundaries, including both outer endpoints, for each exposure. Supply one vector for a single exposure or one vector per exposure for multiple columns. Each vector must be finite and strictly increasing. Supplied breaks take priority over q.

Returns:
  • QuantizationResult –

    Read-only scores, saved boundaries, category counts and diagnostics. Its transform method applies the saved boundaries to new data.

Raises:
  • ValueError –

    If inputs or boundaries are invalid, values fall outside supplied boundaries, an exposure is constant in automatic mode, or automatic input magnitudes are at least 1e64.

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:
  • formula (str) –

    A simple additive formula, named columns, and the exposure names. C(name) may encode a categorical adjustment variable. Write an observation-time offset as exposure_time="column" instead of an R-style offset(log(column)) formula term.

  • data (str) –

    A simple additive formula, named columns, and the exposure names. C(name) may encode a categorical adjustment variable. Write an observation-time offset as exposure_time="column" instead of an R-style offset(log(column)) formula term.

  • exposures (str) –

    A simple additive formula, named columns, and the exposure names. C(name) may encode a categorical adjustment variable. Write an observation-time offset as exposure_time="column" instead of an R-style offset(log(column)) formula term.

  • family (str, default: 'gaussian' ) –

    "gaussian" for a continuous outcome, "binomial" for a zero-one outcome, "poisson" for nonnegative integer counts, or "cox" for a conditional right-censored survival fit.

  • rr (bool, default: True ) –

    For binomial outcomes, True (R's default) selects a marginal bootstrap risk ratio per one joint-score increase. False selects a conditional odds ratio. R ignores rr for Gaussian and Poisson outcomes, and so does this dispatcher.

  • q (int | None, default: 4 ) –

    Exposure categories or saved boundaries and interval error level, passed to the selected fitter.

  • breaks (int | None, default: 4 ) –

    Exposure categories or saved boundaries and interval error level, passed to the selected fitter.

  • alpha (int | None, default: 4 ) –

    Exposure categories or saved boundaries and interval error level, passed to the selected fitter.

  • weights (Any, default: None ) –

    Positive case weights and explicit "raise" or "drop" missing row handling for conditional fits. The binary risk-ratio branch does not yet support weights or missing-row removal.

  • missing (Any, default: None ) –

    Positive case weights and explicit "raise" or "drop" missing row handling for conditional fits. The binary risk-ratio branch does not yet support weights or missing-row removal.

  • B (int | None, default: None ) –

    Row-bootstrap count and local random seed, accepted only for the binary risk-ratio branch. Its default count is 200.

  • seed (int | None, default: None ) –

    Row-bootstrap count and local random seed, accepted only for the binary risk-ratio branch. Its default count is 200.

  • exposure_time (str | None, default: None ) –

    Name of a positive observation-time column for Poisson conditional fitting. This corresponds to an R offset(log(time)) term; R's additive dispatcher sends that term to its non-bootstrap fit.

  • cluster_ids (Any, default: None ) –

    Optional row-aligned cluster IDs and known log-hazard offsets for the conditional Cox route only.

  • offset (Any, default: None ) –

    Optional row-aligned cluster IDs and known log-hazard offsets for the conditional Cox route only.

Returns:
Raises:
  • ValueError –

    If the family, formula, options or selected route are unsupported.

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:
  • result (QGCompResult | BinomialResult | PoissonResult) –

    An additive Gaussian, binomial-logit or Poisson-log fit made with a non-null quantile count. Poisson fits with observation-time offsets are excluded because this conditional reference profile omits time.

  • pointwiseref (int, default: 1 ) –

    One-based reference level from 1 to result.q. For example, 1 compares every score with joint score zero.

  • alpha (float, default: 0.05 ) –

    Tail area of each normal confidence interval, strictly between zero and one.

Returns:
  • PointwiseBoundResult –

    Read-only columns named as in R qgcomp 2.19.6. linpred is on the model link scale. Gaussian mean.diff is a conditional mean difference. Binary or is a conditional odds ratio; Poisson rr is a conditional mean ratio for equal observation periods. The standard error is on the link scale. These are not marginal contrasts or uncertainty intervals for individual predictions.

Raises:
  • TypeError –

    If the fit type is outside the supported non-bootstrap families.

  • ValueError –

    If quantile levels, reference level, alpha or computed values are invalid, or if a Poisson time offset is present.

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:
  • result (GaussianBootstrapResult | PoissonBootstrapResult) –

    An additive Gaussian or Poisson row-bootstrap fit. Conditional fits and other bootstrap families are outside this interface.

  • newdata (Any, default: None ) –

    Optional mapping or data frame with a one-dimensional psi column of joint exposure scores. A one-dimensional numeric array of scores is also accepted. Scores may lie outside the fitted levels; these predictions extrapolate the fitted linear response on its link scale. With None, return one prediction for every original row at every fitted intervention level, in consecutive level blocks as in R.

Returns:
  • ndarray –

    Read-only one-dimensional predictions on the outcome scale. Gaussian values are marginal expected outcomes; Poisson values are marginal expected counts over the observation times in the fitted data.

Raises:
  • TypeError –

    If result is not a supported bootstrap fit.

  • ValueError –

    If the new score column is missing, empty, nonnumeric, nonfinite or not one-dimensional, or predictions exceed the finite numeric range.

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:
  • result ((QGCompResult, BinomialResult or PoissonResult)) –

    A conditional additive fit. Weights within each sign group sum to one when that group has a nonzero coefficient. A zero coefficient is omitted. Weights describe fitted coefficients; they are not causal importance, selection probabilities, or uncertainty measures.

  • ax (Matplotlib Axes, default: None ) –

    Axes to draw on. If absent, create one with optional Matplotlib.

Returns:
  • Matplotlib Axes –

    Horizontal bars on the supplied or newly created Axes.

Raises:
  • TypeError –

    If the result is outside the three supported additive families.

  • ImportError –

    If new Axes are requested and Matplotlib is not installed.

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:
  • result ((GaussianBootstrapResult, PoissonBootstrapResult)) –

    BinomialRiskRatioResult or BinomialOddsRatioResult A supported marginal fit with saved intervention levels and standardized responses. Binary points are risks; Poisson points are expected counts, including any saved observation-time offset.

  • ax (Matplotlib Axes, default: None ) –

    Axes to draw on. If absent, create one with optional Matplotlib.

Returns:
  • Matplotlib Axes –

    A line through the saved response points.

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.