Skip to content

Models

Functions that fit a model and the result classes they return, see Fitting models, Binary and count data, Multilevel and multivariate models and Selection models and location-scale models. metafopy.rma is an alias of metafopy.rma_uni.

Fitting

rma_uni

rma_uni(
    yi: ArrayLike | str | DataFrame | None = None,
    vi: ArrayLike | str | None = None,
    *,
    sei: ArrayLike | str | None = None,
    weights: ArrayLike | str | None = None,
    ai: ArrayLike | str | None = None,
    bi: ArrayLike | str | None = None,
    ci: ArrayLike | str | None = None,
    di: ArrayLike | str | None = None,
    n1i: ArrayLike | str | None = None,
    n2i: ArrayLike | str | None = None,
    x1i: ArrayLike | str | None = None,
    x2i: ArrayLike | str | None = None,
    t1i: ArrayLike | str | None = None,
    t2i: ArrayLike | str | None = None,
    m1i: ArrayLike | str | None = None,
    m2i: ArrayLike | str | None = None,
    sd1i: ArrayLike | str | None = None,
    sd2i: ArrayLike | str | None = None,
    xi: ArrayLike | str | None = None,
    mi: ArrayLike | str | None = None,
    ri: ArrayLike | str | None = None,
    ti: ArrayLike | str | None = None,
    fi: ArrayLike | str | None = None,
    pi: ArrayLike | str | None = None,
    sdi: ArrayLike | str | None = None,
    r2i: ArrayLike | str | None = None,
    mini: ArrayLike | str | None = None,
    maxi: ArrayLike | str | None = None,
    ni: ArrayLike | str | None = None,
    mods: str | ArrayLike | DataFrame | None = None,
    measure: str = 'GEN',
    data: DataFrame | None = None,
    slab: ArrayLike | str | Sequence[str] | None = None,
    subset: ArrayLike | str | None = None,
    add: float | None = None,
    to: Literal['all', 'only0', 'if0all', 'none'] = 'only0',
    drop00: bool = False,
    intercept: bool = True,
    method: str | Sequence[str] = 'REML',
    weighted: bool = True,
    test: str = 'z',
    level: float = 95,
    digits: int | Mapping[str, int] | None = None,
    btt: int | Sequence[int] | str | None = None,
    att: int | Sequence[int] | str | None = None,
    scale: str | ArrayLike | DataFrame | None = None,
    link: Literal['log', 'identity'] = 'log',
    optbeta: bool = False,
    alpha: ArrayLike | None = None,
    beta: ArrayLike | None = None,
    tau2: float | None = None,
    control: Control
    | LSControl
    | Mapping[str, Any]
    | None = None,
    verbose: bool | int = False,
    na_action: Literal['omit', 'fail', 'pass'] = 'omit',
    vtype: str | Sequence[str] = 'LS',
    correct: bool = True,
    cutoff: float | None = None,
    onlyo1: bool = False,
    addyi: bool = True,
    addvi: bool = True,
    knha: bool | None = None,
    dfs: float | Sequence[float] | None = None,
    i2def: Literal['1', '2'] = '1',
    r2def: str = '1',
    skipr2: bool = False,
    abbrev: bool = False,
    skiphes: bool = False,
) -> RMAResult | RMALSResult

Fit an equal-, fixed-, random- or mixed-effects meta-analytic model.

Mirrors metafor's rma.uni() (alias rma). The model is given either as effect sizes with their sampling variances (yi with vi or sei), as a model formula in yi ('yi ~ ablat + year', which then also supplies the moderators), as an escalc data frame, or as raw data (ai, bi, ... with measure), in which case the effect sizes are computed by escalc. Passing scale fits a location-scale model (Viechtbauer & Lopez-Lopez, 2022, doi:10.1002/jrsm.1562).

Parameters:

Name Type Description Default
yi ArrayLike | str | DataFrame | None

Observed effect sizes, as an array or the name of a column of data. May also be a model formula ('yi ~ ablat + year'; needs data; mods is then ignored with a warning and so is intercept, since the formula decides whether there is an intercept), or a data frame (taken as data; its yi and vi columns are used).

None
vi ArrayLike | str | None

Sampling variances, as an array or a column name. A single value is used for every study.

None
sei ArrayLike | str | None

Standard errors, as an array or a column name; their squares are used as vi. Ignored when vi is given.

None
weights ArrayLike | str | None

Optional custom weights for the fit, as an array or a column name; negative weights raise an error. Required for method='GENQ' and 'GENQM'.

None
ai ArrayLike | str | None

2x2 table frequencies (upper left cell). With bi, ci and di and a measure such as 'OR' or 'RR'.

None
bi ArrayLike | str | None

2x2 table frequencies (upper right cell).

None
ci ArrayLike | str | None

2x2 table frequencies (lower left cell).

None
di ArrayLike | str | None

2x2 table frequencies (lower right cell).

None
n1i ArrayLike | str | None

Group sizes or row totals (first group or row).

None
n2i ArrayLike | str | None

Group sizes or row totals (second group or row).

None
x1i ArrayLike | str | None

Number of events (first group).

None
x2i ArrayLike | str | None

Number of events (second group).

None
t1i ArrayLike | str | None

Total person-times (first group).

None
t2i ArrayLike | str | None

Total person-times (second group).

None
m1i ArrayLike | str | None

Means (first group or time point).

None
m2i ArrayLike | str | None

Means (second group or time point).

None
sd1i ArrayLike | str | None

Standard deviations (first group or time point).

None
sd2i ArrayLike | str | None

Standard deviations (second group or time point).

None
xi ArrayLike | str | None

Frequencies of the event of interest.

None
mi ArrayLike | str | None

Frequencies of the complement of the event of interest, or the group means.

None
ri ArrayLike | str | None

Raw correlation coefficients.

None
ti ArrayLike | str | None

Total person-times or t-test statistics.

None
fi ArrayLike | str | None

F-test statistics.

None
pi ArrayLike | str | None

(Signed) p-values.

None
sdi ArrayLike | str | None

Standard deviations.

None
r2i ArrayLike | str | None

R^2 values.

None
mini ArrayLike | str | None

Minimum values.

None
maxi ArrayLike | str | None

Maximum values.

None
ni ArrayLike | str | None

Sample or group sizes, as an array or column name. Passed to escalc for raw data; otherwise stored with the model (as its ni), and taken from an escalc frame when not given.

None
mods str | ArrayLike | DataFrame | None

Moderators, as a one-sided formula string ('~ ablat + year'; needs data), a one-dimensional array (one moderator), a matrix or a data frame, with one row per study. None fits a model with no moderators.

None
measure str

Effect size or outcome measure: 'GEN' (generic, the default, used with yi and vi) or any code of escalc ('SMD', 'OR', 'RR', 'RD', 'ZCOR', ...; with yi and vi it only labels the estimates). 'HR' and 'HD' are also accepted. Must be given when raw data are passed; an escalc frame supplies its own.

'GEN'
data DataFrame | None

Data frame holding the variables named in the other arguments.

None
slab ArrayLike | str | Sequence[str] | None

Study labels, as a sequence or a column name. Defaults to the labels stored by escalc, else 1, 2, ....

None
subset ArrayLike | str | None

Which studies to fit: a boolean array, an array of 0-based indices, or a string expression evaluated on data.

None
add float | None

Constant added to zero cells, counts or frequencies when effect sizes are computed from raw data (default 1/2, but 0 for the measures 'AS', 'PHI', 'ZPHI', 'RTET', 'ZTET', 'IRSD', 'PAS', 'PFT', 'IRS' and 'IRFT'). See escalc.

None
to Literal['all', 'only0', 'if0all', 'none']

Which tables get add: 'only0' (those with a zero cell, the default), 'all', 'if0all' (all, if any table has a zero cell) or 'none'.

'only0'
drop00 bool

Drop studies with no events (or only events) in both groups from the calculations (raw data only).

False
intercept bool

Include an intercept when mods is a vector, matrix or data frame. Ignored when mods (or yi) is a formula. Without moderators an intercept is always included (intercept=False gives a warning).

True
method str | Sequence[str]

Estimator of the amount of heterogeneity tau^2 (case-sensitive): 'EE', 'FE' or 'CE' (equal-, fixed- or common-effects model, tau^2 = 0), 'DL', 'DLIT', 'HE' (also 'CO' and 'VC'), 'HS', 'HSk', 'SJ', 'SJIT', 'ML', 'REML' (the default), 'EB', 'PM' (also 'MP'), 'PMM', 'GENQ' or 'GENQM'. A sequence is tried in order until one succeeds. Location-scale models need 'ML' or 'REML' (the first of a sequence is used).

'REML'
weighted bool

Use inverse-variance weights (True) or ordinary least squares (False).

True
test str

Test for the coefficients (case-insensitive): 'z' (normal, the default), 't' (t distribution with k - p degrees of freedom), 'knha' (Knapp-Hartung adjustment, with t and F distributions; alias 'hksj') or 'adhoc' (Knapp-Hartung, but the adjusted standard errors are never smaller than the unadjusted ones). With one study 'z' is used.

'z'
level float

Confidence interval level in percent (95 is 95%). As in metafor, 0.95 is also read as 95% and 0.05 as an alpha of 0.05.

95
digits int | Mapping[str, int] | None

Number of decimals used when printing, or a mapping with the keys est, se, ... (only est is used, else the first value). Stored in the result; None is 4.

None
btt int | Sequence[int] | str | None

Coefficients to test jointly in the omnibus test, as 0-based indices or a regular expression matched against coefficient names (re.search). Printed output reports them 1-based, as metafor does. Default: all coefficients but the intercept (the intercept itself for a model without moderators).

None
att int | Sequence[int] | str | None

Scale coefficients to test jointly, as btt. Location-scale models only; ignored with a warning otherwise.

None
scale str | ArrayLike | DataFrame | None

Scale moderators of a location-scale model: a one-sided formula ('~ ni100', which includes an intercept unless 0 or -1 is given; needs data), or a matrix or data frame with one row per study, which is used as it is (no intercept column is added). Turns the model into a location-scale model.

None
link Literal['log', 'identity']

Link function of the scale model, 'log' (the default) or 'identity'; anything else raises an error. Location-scale models only.

'log'
optbeta bool

Estimate the location coefficients jointly with the scale coefficients (needs weighted=True). Location-scale models only; ignored with a warning otherwise.

False
alpha ArrayLike | None

Fixed values for the scale coefficients (None or NaN entries are estimated; one number is used for all). Location-scale models only.

None
beta ArrayLike | None

Fixed values for the location coefficients (None or NaN entries are estimated); used only with optbeta=True. Location-scale models only.

None
tau2 float | None

Fixed value of tau^2 instead of estimating it (no effect for method='EE', 'FE' or 'CE'; ignored with a warning for location-scale models).

None
control Control | LSControl | Mapping[str, Any] | None

Settings of the tau^2 estimation (tau2_init, tau2_min, tau2_max, threshold, tol, ll0check, maxiter, stepadj, evtol and REMLf), as a Control or a mapping with the same names as metafor (. becomes _). Names that only other metafor functions read are ignored; any other name raises an error. Location-scale models take an LSControl or a mapping instead.

None
verbose bool | int

Print metafor's iteration log of the tau^2 estimators to stdout; 2 or more also prints progress messages to stderr. Location-scale models print only a blank line and, for 2 or more, the messages about extracting the data.

False
na_action Literal['omit', 'fail', 'pass']

What to do with studies that have missing values (metafor uses the global na.action option instead): 'omit' (the default) leaves them out of the fit and 'fail' raises an error. 'pass' leaves them out of the fit too.

'omit'
vtype str | Sequence[str]

Type of the sampling variance formula used by escalc for raw data, 'LS' by default; may be a sequence with one type per study.

'LS'
correct bool

Bias correction of escalc for the measures that have one (True by default), for raw data only.

True
cutoff float | None

Value above which the absolute value of an estimate computed by escalc is flagged with a warning. The default is 2 for 'SMD' and its variants and no check otherwise; NaN switches the check off.

None
onlyo1 bool

Passed to escalc: add is added to the ai and ci cells of the 2x2 tables only, not to bi and di.

False
addyi bool

Passed to escalc: True (the default) computes yi from the counts after add and to, False from the unadjusted counts.

True
addvi bool

Passed to escalc: the same for the sampling variances vi.

True
knha bool | None

True is the same as test='knha' and False the same as test='z'.

None
dfs float | Sequence[float] | None

Degrees of freedom of the t and F tests (the first value is used) instead of k - p.

None
i2def Literal['1', '2']

Definition of I^2 and H^2: '1' (the default), or '2' to use the typical sampling variance 1 / mean(1 / vi).

'1'
r2def str

Definition of R^2 of a model with moderators: '1' (the default), '1v', '2', '2v', '3', '3v', '4', '4w', '5', '6', '7' or '8'.

'1'
skipr2 bool

Skip the computation of R^2.

False
abbrev bool

Shorten the names of the coefficients of factor(), poly(), relevel() and I() terms.

False
skiphes bool

Skip the Hessian of location-scale models, so that their standard errors are missing.

False

Returns:

Type Description
RMAResult | RMALSResult

The fitted model, an RMAResult (an RMALSResult when scale is given). Estimates are in beta, se, zval, pval, ci_lb and ci_ub; heterogeneity statistics in tau2, I2, H2, QE and QEp (arrays with one value per study for a location-scale model, except QE and QEp); summary() returns the printout as a string.

Raises:

Type Description
InputError

an argument or the data is invalid.

ArgumentError

control has a name that no function of metafor reads.

NotFoundError

a column name given for an argument is not in data.

EstimationError

every requested tau^2 estimator failed (including 'GENQ' without weights).

NotSupportedError

escalc does not implement the requested combination of measure and inputs.

InternalError

an internal invariant of escalc does not hold.

Examples:

>>> from metafopy import datasets, rma
>>> dat = datasets.load("dat.bcg")
>>> rma(measure="RR", ai="tpos", bi="tneg", ci="cpos", di="cneg", data=dat)
Metafor reference

rma.uni

rma_mh

rma_mh(
    ai: ArrayLike | str | None = None,
    bi: ArrayLike | str | None = None,
    ci: ArrayLike | str | None = None,
    di: ArrayLike | str | None = None,
    n1i: ArrayLike | str | None = None,
    n2i: ArrayLike | str | None = None,
    x1i: ArrayLike | str | None = None,
    x2i: ArrayLike | str | None = None,
    t1i: ArrayLike | str | None = None,
    t2i: ArrayLike | str | None = None,
    measure: str = 'OR',
    data: DataFrame | None = None,
    slab: ArrayLike | str | Sequence[str] | None = None,
    subset: ArrayLike | str | None = None,
    add: float | Sequence[float] = 0.5,
    to: str | Sequence[str] = 'only0',
    drop00: bool | Sequence[bool] = True,
    correct: bool = True,
    level: float = 95,
    verbose: bool | int = False,
    digits: int = 4,
    na_action: Literal['omit', 'fail', 'pass'] = 'omit',
    onlyo1: bool = False,
    addyi: bool = True,
    addvi: bool = True,
) -> MHResult

Fit a Mantel-Haenszel meta-analysis of 2x2 tables (measure 'OR', 'RR', 'RD') or rate data ('IRR', 'IRD').

Mirrors metafor's rma.mh(). The pooled effect is the Mantel-Haenszel estimate (Mantel & Haenszel, 1959; see metafor's help page for the further references). The individual effect sizes and sampling variances are computed as by escalc. For odds ratios the result also holds the Cochran-Mantel-Haenszel test and Tarone's test of heterogeneity, for incidence rate ratios the Mantel-Haenszel test. The first element of add, to and drop00 is used when computing the individual yi/vi values, the second one for the counts entering the Mantel-Haenszel estimator (by default nothing is added to them and no study is dropped there).

Parameters:

Name Type Description Default
ai ArrayLike | str | None

Frequencies of the 2x2 tables, upper left cell (event in group 1), as an array or the name of a column of data.

None
bi ArrayLike | str | None

Frequencies of the 2x2 tables, upper right cell (no event in group 1).

None
ci ArrayLike | str | None

Frequencies of the 2x2 tables, lower left cell (event in group 2).

None
di ArrayLike | str | None

Frequencies of the 2x2 tables, lower right cell (no event in group 2).

None
n1i ArrayLike | str | None

Size of group 1 (row total); can be given instead of bi.

None
n2i ArrayLike | str | None

Size of group 2 (row total); can be given instead of di.

None
x1i ArrayLike | str | None

Number of events in group 1 (rate data, 'IRR' and 'IRD').

None
x2i ArrayLike | str | None

Number of events in group 2 (rate data).

None
t1i ArrayLike | str | None

Total person-time of group 1 (rate data).

None
t2i ArrayLike | str | None

Total person-time of group 2 (rate data).

None
measure str

Effect measure: 'OR' (log odds ratio, the default), 'RR' (log risk ratio), 'RD' (risk difference), 'IRR' (log incidence rate ratio) or 'IRD' (incidence rate difference). Other measures raise an error.

'OR'
data DataFrame | None

Data frame holding the variables named in the other arguments.

None
slab ArrayLike | str | Sequence[str] | None

Study labels, as a sequence or a column name. Defaults to 1, 2, ....

None
subset ArrayLike | str | None

Which studies to use: a boolean array, an array of 0-based indices, or a string expression evaluated on data.

None
add float | Sequence[float]

Constant added to zero cells or counts. A single value, or a pair: the first applies when the yi/vi values of the studies are computed and the second to the counts entering the Mantel-Haenszel estimator. Default 0.5, which with a single value is used for the yi/vi values only (the second is then 0).

0.5
to str | Sequence[str]

Which tables get add: 'all', 'only0' (those with a zero cell, the default), 'if0all' (all, if any table has a zero cell) or 'none'. A single value, or a pair as for add (the second is then 'none').

'only0'
drop00 bool | Sequence[bool]

Drop studies with no events (or only events) in both groups. A single value, or a pair as for add (the second is then False). Default True.

True
correct bool

Use the continuity correction in the Cochran-Mantel-Haenszel test (odds ratios) and in the Mantel-Haenszel test (incidence rate ratios).

True
level float

Confidence interval level in percent (95 is 95%).

95
verbose bool | int

Print metafor's progress messages to stderr (and blank lines to stdout).

False
digits int

Number of decimals used when printing, stored in the result.

4
na_action Literal['omit', 'fail', 'pass']

What to do with studies that have missing values (metafor uses the global na.action option instead): 'omit' (the default) leaves them out with a warning and 'fail' raises an error. 'pass' leaves them out too.

'omit'
onlyo1 bool

Passed to escalc for the yi/vi values: add is added to the ai and ci cells only, not to bi and di.

False
addyi bool

Passed to escalc: True (the default) computes yi from the counts after add and to, False from the unadjusted counts.

True
addvi bool

Passed to escalc: the same for the sampling variances vi.

True

Returns:

Type Description
MHResult

The fitted model. The pooled estimate is in beta with se, zval, pval, ci_lb and ci_ub (on the log scale for

MHResult

'OR', 'RR' and 'IRR'); QE, QEp, I2 and H2 describe the heterogeneity (tau2 is 0); MH/MHp is the

MHResult

Cochran-Mantel-Haenszel test (odds ratios) or the Mantel-Haenszel test (incidence rate ratios), CO/COp the same test with a

MHResult

different variance (odds ratios), and BD/BDp and TA/TAp the Breslow-Day and Tarone tests (odds ratios only); the tests

MHResult

that do not apply are NaN. summary() returns the printout as a string.

Raises:

Type Description
InputError

an argument or the data is invalid, or measure is not one of the supported measures.

Examples:

>>> from metafopy import datasets, rma_mh
>>> dat = datasets.load("dat.bcg")
>>> rma_mh(ai="tpos", bi="tneg", ci="cpos", di="cneg", data=dat)
Metafor reference

rma.mh

rma_peto

rma_peto(
    ai: ArrayLike | str | None = None,
    bi: ArrayLike | str | None = None,
    ci: ArrayLike | str | None = None,
    di: ArrayLike | str | None = None,
    n1i: ArrayLike | str | None = None,
    n2i: ArrayLike | str | None = None,
    data: DataFrame | None = None,
    slab: ArrayLike | str | Sequence[str] | None = None,
    subset: ArrayLike | str | None = None,
    add: float | Sequence[float] = 0.5,
    to: str | Sequence[str] = 'only0',
    drop00: bool | Sequence[bool] = True,
    level: float = 95,
    verbose: bool | int = False,
    digits: int = 4,
    na_action: Literal['omit', 'fail', 'pass'] = 'omit',
) -> PetoResult

Fit Peto's one-step method to a set of 2x2 tables.

Mirrors metafor's rma.peto(). The pooled effect is a log odds ratio (Yusuf et al., 1985). The first element of add, to and drop00 is used for the individual yi/vi values, the second for the counts used in the pooled estimate (by default nothing is added to them).

Parameters:

Name Type Description Default
ai ArrayLike | str | None

Frequencies of the 2x2 tables, upper left cell (event in group 1), as an array or the name of a column of data.

None
bi ArrayLike | str | None

Frequencies of the 2x2 tables, upper right cell (no event in group 1).

None
ci ArrayLike | str | None

Frequencies of the 2x2 tables, lower left cell (event in group 2).

None
di ArrayLike | str | None

Frequencies of the 2x2 tables, lower right cell (no event in group 2).

None
n1i ArrayLike | str | None

Size of group 1 (row total); can be given instead of bi.

None
n2i ArrayLike | str | None

Size of group 2 (row total); can be given instead of di.

None
data DataFrame | None

Data frame holding the variables named in the other arguments.

None
slab ArrayLike | str | Sequence[str] | None

Study labels, as a sequence or a column name. Defaults to 1, 2, ....

None
subset ArrayLike | str | None

Which studies to use: a boolean array, an array of 0-based indices, or a string expression evaluated on data.

None
add float | Sequence[float]

Constant added to zero cells. A single value, or a pair: the first applies when the yi/vi values of the studies are computed and the second to the counts entering the pooled estimate. Default 0.5, which with a single value is used for the yi/vi values only (the second is then 0).

0.5
to str | Sequence[str]

Which tables get add: 'all', 'only0' (those with a zero cell, the default), 'if0all' (all, if any table has a zero cell) or 'none'. A single value, or a pair as for add (the second is then 'none').

'only0'
drop00 bool | Sequence[bool]

Drop studies with no events (or only events) in both groups. A single value, or a pair as for add (the second is then False). Default True.

True
level float

Confidence interval level in percent (95 is 95%).

95
verbose bool | int

Print metafor's progress messages to stderr (and blank lines to stdout).

False
digits int

Number of decimals used when printing, stored in the result.

4
na_action Literal['omit', 'fail', 'pass']

What to do with studies that have missing values (metafor uses the global na.action option instead): 'omit' (the default) leaves them out with a warning and 'fail' raises an error. 'pass' leaves them out too.

'omit'

Returns:

Type Description
PetoResult

The fitted model. The pooled log odds ratio is in beta with se, zval, pval, ci_lb and ci_ub; QE, QEp,

PetoResult

I2 and H2 describe the heterogeneity (Peto's test; tau2 is 0); summary() returns the printout as a string.

Raises:

Type Description
InputError

an argument or the data is invalid, or one of the two outcomes never occurred in any table.

Examples:

>>> from metafopy import datasets, rma_peto
>>> dat = datasets.load("dat.bcg")
>>> rma_peto(ai="tpos", bi="tneg", ci="cpos", di="cneg", data=dat)
Metafor reference

rma.peto

rma_glmm

rma_glmm(
    *,
    ai: ArrayLike | str | None = None,
    bi: ArrayLike | str | None = None,
    ci: ArrayLike | str | None = None,
    di: ArrayLike | str | None = None,
    n1i: ArrayLike | str | None = None,
    n2i: ArrayLike | str | None = None,
    x1i: ArrayLike | str | None = None,
    x2i: ArrayLike | str | None = None,
    t1i: ArrayLike | str | None = None,
    t2i: ArrayLike | str | None = None,
    xi: ArrayLike | str | None = None,
    mi: ArrayLike | str | None = None,
    ti: ArrayLike | str | None = None,
    ni: ArrayLike | str | None = None,
    mods: str | ArrayLike | DataFrame | None = None,
    measure: str | None = None,
    data: DataFrame | None = None,
    slab: ArrayLike | str | Sequence[str] | None = None,
    subset: ArrayLike | str | None = None,
    add: float | Sequence[float] = 0.5,
    to: str | Sequence[str] = 'only0',
    drop00: bool | Sequence[bool] = True,
    intercept: bool = True,
    model: str | None = None,
    method: str = 'ML',
    coding: float = 0.5,
    cor: bool = False,
    test: str = 'z',
    level: float = 95,
    btt: int | Sequence[int] | str | None = None,
    nAGQ: int = 7,
    verbose: bool | int = False,
    digits: int = 4,
    control: GLMMControl | Mapping[str, Any] | None = None,
    na_action: Literal['omit', 'fail', 'pass'] = 'omit',
    i2def: str = '1',
    onlyo1: bool = False,
    addyi: bool = True,
    addvi: bool = True,
    link: str | None = None,
    family: GLMFamily | str | None = None,
) -> GLMMResult

Fit a generalized linear mixed-effects model to binary or count data.

Mirrors metafor's rma.glmm(). measure is 'OR' (2x2 tables: ai, bi, ci, di or ai, ci, n1i, n2i), 'IRR' (x1i, x2i, t1i, t2i), 'PLO' (xi and mi or ni) or 'IRLN' (xi, ti). model is 'UM.FS' (the default), 'UM.RS', 'CM.AL' or 'CM.EL' and method 'ML' or 'FE' ('EE', 'CE'). Only the first of several add, to and drop00 values is used. All arguments are keyword-only.

The experimental measures 'RR' and 'RD' (arguments as for 'OR', unconditional models only) and 'PR' and 'PLN' (arguments as for 'PLO') are fitted as metafor does and give its warning that their use is experimental; as in metafor, the log and identity links can put fitted probabilities outside (0, 1), in which case fitting fails (EstimationError) or the estimates are unreliable.

link (one of 'logit', 'probit', 'cauchit', 'cloglog', 'log', 'identity', 'sqrt') replaces the link of the model and family ('binomial', 'poisson' or metafopy.core.glm.binomial / metafopy.core.glm.poisson, which carry a link) replaces family and link, like metafor's link and family arguments passed through .... They apply to the unconditional models ('UM.FS', 'UM.RS') and the one-group measures, the models that metafor fits with glm() and glmer(); the conditional models ignore them as in metafor. The family must match the data (binomial for 'OR', 'RR', 'RD', 'PLO', 'PR', 'PLN', Poisson for 'IRR' and 'IRLN').

control={'optimizer': 'clogit'} or 'clogistic' fits the fixed-effects (method='FE') conditional model 'CM.EL' for 'OR' with survival::clogit() or Epi::clogistic() (implemented in metafopy.core.clogit, without building the individual patient data); clogitCtrl and clogisticCtrl entries of control are passed on as in metafor (see metafopy.core.clogit.clogit_settings and metafopy.core.clogit.clogistic_settings). The default 'nlminb' maximises the exact likelihood numerically. The other optimisers of metafor's control$optimizer ('optim' with optmethod, 'Nelder-Mead', 'BFGS', 'CG', 'L-BFGS-B', 'nlm', 'uobyqa', 'newuoa', 'bobyqa', ...) maximise it as metafopy.models.sel_opt minimises: optim with BFGS or Nelder-Mead is R's routine (optCtrl takes maxit, reltol, abstol and ndeps), the others stand in with the closest SciPy method. The Wald test of the saturated model (QE_Wld) of 'CM.EL' can be ill-conditioned; for some data sets it differs between optimisers in R as well. The Hessian of 'CM.EL' is computed as control={'hesspack': ..., 'hessianCtrl': {...}} asks ('numDeriv' with r = 16 unless hessianCtrl gives r, 'pracma' with h, 'calculus' with accuracy and stepsize). Unlike metafor, whose default is the density of BiasedUrn::dFNCHypergeo with precision dnchgprec (1e-10), metafopy uses the untruncated density (dnchgcalc='dnoncenhypergeom') by default; control={'dnchgcalc': 'dFNCHypergeo'} or a dnchgprec entry selects a port of BiasedUrn's algorithm including the truncation of the tails that makes R's finite-difference standard errors noisy.

control={'package': ...} chooses the package that fits the mixed models, as in metafor: 'lme4' (the default), 'GLMMadaptive' (adaptive quadrature with nAGQ points in every dimension, so that 'UM.RS' with method='ML' is not reduced to nAGQ = 1; it fails, like metafor, when a coefficient other than the first exceeds 12 in absolute value, the default max_coef_value of GLMMadaptive 0.9-7) or 'glmmTMB' (Laplace approximation, nAGQ is ignored). They maximise the same likelihood and differ in the integration, in what log-likelihood they report and in the convergence tolerances; see docs/differences.md.

Parameters:

Name Type Description Default
ai ArrayLike | str | None

2x2 table frequencies, upper left cell (event in group 1), as an array or the name of a column of data. Used with measure='OR'.

None
bi ArrayLike | str | None

2x2 table frequencies, upper right cell (no event in group 1).

None
ci ArrayLike | str | None

2x2 table frequencies, lower left cell (event in group 2).

None
di ArrayLike | str | None

2x2 table frequencies, lower right cell (no event in group 2).

None
n1i ArrayLike | str | None

Size of group 1 (row total); an alternative to bi.

None
n2i ArrayLike | str | None

Size of group 2 (row total); an alternative to di.

None
x1i ArrayLike | str | None

Number of events in group 1 (measure='IRR').

None
x2i ArrayLike | str | None

Number of events in group 2 (measure='IRR').

None
t1i ArrayLike | str | None

Total person-time of group 1 (measure='IRR').

None
t2i ArrayLike | str | None

Total person-time of group 2 (measure='IRR').

None
xi ArrayLike | str | None

Number of events (one-group measures 'PLO' and 'IRLN').

None
mi ArrayLike | str | None

Number of non-events ('PLO'); an alternative to ni.

None
ti ArrayLike | str | None

Total person-time ('IRLN').

None
ni ArrayLike | str | None

Sample size ('PLO'); an alternative to mi.

None
mods str | ArrayLike | DataFrame | None

Moderators, as a one-sided formula string ('~ ablat + year'; needs data), a one-dimensional array (one moderator), a matrix or a data frame, with one row per study. None fits a model without moderators.

None
measure str | None

Outcome measure, required: 'OR', 'IRR', 'PLO' or 'IRLN', or the experimental 'RR', 'RD', 'PR' or 'PLN'.

None
data DataFrame | None

Data frame holding the variables named in the other arguments.

None
slab ArrayLike | str | Sequence[str] | None

Study labels, as a sequence or a column name. Defaults to 1, 2, ....

None
subset ArrayLike | str | None

Which studies to use: a boolean array, an array of 0-based indices, or a string expression evaluated on data.

None
add float | Sequence[float]

Constant added to zero cells, counts or frequencies when computing the yi/vi values (only the first value of a sequence is used). Default 0.5.

0.5
to str | Sequence[str]

Which tables get add: 'all', 'only0' (the default), 'if0all' or 'none' (only the first value of a sequence is used).

'only0'
drop00 bool | Sequence[bool]

Drop studies with no events (or only events) in both groups (only the first value of a sequence is used). Default True.

True
intercept bool

Include an intercept when mods is a vector, matrix or data frame. Ignored when mods is a formula. Without moderators an intercept is always included (intercept=False gives a warning).

True
model str | None

Model for 2x2 tables ('OR') and two-group rate data ('IRR'): 'UM.FS' (unconditional, fixed study effects), 'UM.RS' (unconditional, random study effects), 'CM.AL' (conditional, approximate likelihood) or 'CM.EL' (conditional, exact likelihood). Default (None) is 'UM.FS'. For 'IRR' the conditional model is exact already and 'CM.AL' is the same as 'CM.EL'. The one-group measures ignore model (a warning is given when it is passed). 'RR' and 'RD' allow only the unconditional models.

None
method str

'ML' (random or mixed effects, the default), or 'FE' (aliases 'EE', 'CE') for an equal-effects model; the names are case-sensitive.

'ML'
coding float

Coding of the group variable in the random-effects structure of the unconditional models ('UM.FS', 'UM.RS') for 'OR' and 'IRR': 0.5 (the default) codes the first group as +1/2 and the second as -1/2, 1 the first group as 1 and the second as 0, and 0 the first group as 0 and the second as 1. Any other value raises an error.

0.5
cor bool

Allow the random study effects and the random group effects of 'UM.RS' to be correlated (False by default; metafor recommends True for coding 1 or 0).

False
test str

Test for the coefficients: 'z' (the default) or 't' (t and F distributions with k - p degrees of freedom, without the adjustment of the standard errors of test='knha' in rma_uni).

'z'
level float

Confidence interval level in percent (95 is 95%). As in rma_uni, 0.95 is also read as 95%.

95
btt int | Sequence[int] | str | None

Coefficients to test jointly in the omnibus test, as 0-based indices or a regular expression matched against coefficient names. Default: all coefficients but the intercept (the intercept itself for a model without moderators).

None
nAGQ int

Number of quadrature points per dimension of the adaptive Gauss-Hermite approximation of the likelihood of the mixed models (default 7); 1 is the Laplace approximation. With control['package'] 'lme4' (the default) and model='UM.RS', method='ML' a value above 1 is replaced by 1 with a warning, as glmer() does not allow it; 'glmmTMB' ignores it.

7
verbose bool | int

Print metafor's progress messages to stderr (1: the model fits; 2: every stage). The trace output of glm()/glmer() and of the optimisers has no counterpart here.

False
digits int

Number of decimals used when printing, stored in the result.

4
control GLMMControl | Mapping[str, Any] | None

Optimiser and package settings, as a GLMMControl or a mapping with metafor's names (. becomes _).

None
na_action Literal['omit', 'fail', 'pass']

What to do with studies that have missing values, in the table data or the moderators (metafor uses the global na.action option instead): 'omit' (the default) leaves them out with a warning and 'fail' raises an error. 'pass' leaves them out too.

'omit'
i2def str

Definition of I^2 and H^2: '1' (the default) or '2' (the typical sampling variance 1 / mean(1 / vi)); any other value is treated as '1'.

'1'
onlyo1 bool

Passed to escalc for the yi/vi values: add is added to the ai and ci cells only, not to bi and di.

False
addyi bool

Passed to escalc: True (the default) computes yi from the counts after add and to, False from the unadjusted counts.

True
addvi bool

Passed to escalc: the same for the sampling variances vi.

True
link str | None

Link function replacing the one of the model: 'logit', 'probit', 'cauchit', 'cloglog', 'log', 'identity' or 'sqrt'. Default (None) is the link of the measure.

None
family GLMFamily | str | None

Family replacing the family and link of the model: 'binomial', 'poisson' or a metafopy.core.glm family object. Default (None) is the family of the measure.

None

Returns:

Type Description
GLMMResult

The fitted model. Coefficients are in beta with se, zval, pval, ci_lb and ci_ub; tau2 (and sigma2,

GLMMResult

rho for 'UM.RS', else NaN) is the heterogeneity; QE_Wld and QE_LRT test for (residual) heterogeneity and QM is the

GLMMResult

omnibus test; I2 and H2 are computed from the yi/vi values; summary() returns the printout as a string.

Raises:

Type Description
InputError

an argument or the data is invalid.

EstimationError

a model cannot be fitted.

NotSupportedError

the optimiser chosen in control has no counterpart here.

InternalError

a binomial model was built without its group sizes.

Examples:

>>> from metafopy import datasets, rma_glmm
>>> dat = datasets.load("dat.bcg")
>>> rma_glmm(ai="tpos", bi="tneg", ci="cpos", di="cneg", data=dat, measure="OR")
Metafor reference

rma.glmm

rma_mv

rma_mv(
    yi: object,
    V: object,
    *,
    W: object = None,
    mods: object = None,
    data: DataFrame | None = None,
    slab: object = None,
    subset: ArrayLike | str | None = None,
    random: str | Sequence[str] | None = None,
    struct: str | Sequence[str] | None = None,
    intercept: bool = True,
    method: str = 'REML',
    test: str = 'z',
    dfs: str | float | Sequence[float] = 'residual',
    level: float = 95,
    digits: int | Mapping[str, int] | None = None,
    btt: int | Sequence[int] | str | None = None,
    R: Mapping[str, object] | None = None,
    Rscale: str | bool | int = 'cor',
    sigma2: ArrayLike | None = None,
    tau2: ArrayLike | None = None,
    rho: ArrayLike | None = None,
    gamma2: ArrayLike | None = None,
    phi: ArrayLike | None = None,
    sparse: bool = False,
    dist: object = 'euclidean',
    cvvc: bool | str = False,
    optbeta: bool = False,
    beta: ArrayLike | None = None,
    lambda1: float = 0.0,
    lambda2: float = 0.0,
    vccon: Mapping[str, ArrayLike] | None = None,
    restart: RMAMVResult | bool | None = None,
    control: MVControl | Mapping[str, Any] | None = None,
    verbose: bool | int = False,
    na_action: Literal['omit', 'fail', 'pass'] = 'omit',
) -> RMAMVResult

Fit a multivariate/multilevel meta-analytic model.

Mirrors metafor's rma.mv(). yi is a vector, a column of data or a model formula ('yi ~ x1 + x2'); V is a vector of sampling variances, a k x k matrix, a list of block matrices (see bldiag), a column name or 0. random is a formula such as '~ 1 | study', '~ 1 | district/school' or '~ outcome | study' (or a list of them), struct (default 'CS') the variance-covariance structure of the ~ inner | outer terms and R a dict of known correlation matrices (DataFrames with dimension names) keyed by the grouping variable. sigma2, tau2, rho, gamma2 and phi fix the corresponding parameters (nan entries are estimated). dfs is 'residual', 'contain' or numeric. digits (a number of decimals, or a mapping with the keys est, se, ... of which est is used) is stored in the result and used by its printout unless digits is passed to summary() or set with metafopy.setmfopt.

cvvc (False, True, 'varcor', 'varcov' or 'transf') requests the Hessian of the variance components and its inverse (hessian and vvc of the result): variances and correlations for True/'varcor', variances and covariances for 'varcov' (UN and GEN structures only), the transformed parameters for 'transf'. With optbeta=True the coefficients are optimised together with the variance components, and their covariance matrix is taken from the inverse Hessian (lambda1 and lambda2 add a lasso and ridge penalty on the coefficients other than the intercept and imply optbeta=True; see https://github.com/wviechtb/metafor/blob/master/R/rma.mv.r). beta fixes coefficients (nan entries are estimated). vccon is a dict with the keys sigma2, tau2, rho, gamma2 and phi whose entries are group ids: components with the same id are constrained to be equal. restart is a previous fit of the same model whose variance components are the starting values, or True for the last values the optimiser tried in this session, as metafor's restart=TRUE (also after a fit that did not converge). The Hessians are the Richardson extrapolation of numDeriv (hesspack='numDeriv'). verbose prints metafor's table of the variance components and a log line per evaluation of the log-likelihood to stdout (the optimiser differs from metafor's nlminb, so the sequence of evaluations differs too) and, with verbose=2 or more, its progress messages to stderr.

Parameters:

Name Type Description Default
yi object

Observed effect sizes, as a vector, the name of a column of data, or a model formula ('yi ~ x1 + x2', which then also supplies the moderators).

required
V object

Sampling variances or covariances: a vector of variances, a k x k matrix, a list of block matrices (see bldiag), a column name, or 0 for no known sampling variances.

required
W object

Optional weights of the fit, as a vector, a column name or a k x k matrix. Default: weights from the marginal variance-covariance matrix. Cannot be combined with optbeta, lambda1 or lambda2.

None
mods object

Moderators, as a one-sided formula string ('~ ablat + year'), a matrix, or a data frame. None fits a model without moderators.

None
data DataFrame | None

Data frame holding the variables named in the other arguments.

None
slab object

Study labels, as a sequence or a column name. Defaults to 1, 2, ....

None
subset ArrayLike | str | None

Which rows to use: a boolean array, an array of 0-based indices, or a string expression evaluated on data.

None
random str | Sequence[str] | None

Random effects, a formula such as '~ 1 | study', '~ 1 | district/school' or '~ outcome | study', or a sequence of them. Default (None) is a model without random effects.

None
struct str | Sequence[str] | None

Variance-covariance structure of the ~ inner | outer terms: one value (used for both terms) or two (first and second term, matching tau2/rho and gamma2/phi). One of 'CS' (the default), 'HCS', 'UN', 'ID', 'DIAG', 'AR', 'HAR', 'CAR', 'GEN', 'GDIAG' or a spatial structure ('SPEXP', 'SPGAU', 'SPLIN', 'SPRAT', 'SPSPH'); anything else raises InputError. 'GEN' becomes 'GDIAG' when the term is written ~ inner || outer. Case matters. A warning says that struct is disregarded if random has no ~ inner | outer term.

None
intercept bool

Include an intercept in the model with moderators. Ignored (the formula decides) when yi or mods is a formula.

True
method str

'REML' (the default) or 'ML' for random and mixed effects, or 'FE' (aliases 'EE', 'CE') for a fixed-effects model.

'REML'
test str

Test for the coefficients: 'z' (the default), 't', 'knha' (alias 'hksj') or 'adhoc'. Numeric dfs or dfs='contain' turns 'z' into 't'.

'z'
dfs str | float | Sequence[float]

Degrees of freedom of the t tests: 'residual' (the default), 'contain' (the containment method) or numeric.

'residual'
level float

Confidence interval level in percent (95 is 95%).

95
digits int | Mapping[str, int] | None

Number of decimals used when printing, or a mapping with the keys est, se, ... (est is used). Stored in the result.

None
btt int | Sequence[int] | str | None

Coefficients to test jointly in the omnibus test, as 0-based indices or a regular expression matched against coefficient names. Default: all but the intercept.

None
R Mapping[str, object] | None

Known correlation matrices of the random effects, a mapping from the name of the grouping variable to a matrix (a data frame with dimension names).

None
Rscale str | bool | int

How R matrices are rescaled: 'cor' (the default, to a correlation matrix), 'cor0', 'cov0', 'none', a bool (True is 'cor', False is 'none') or an integer 0 to 3 for 'none', 'cor', 'cor0', 'cov0'.

'cor'
sigma2 ArrayLike | None

Fixed values for the variance components of the ~ 1 | factor terms (nan entries are estimated).

None
tau2 ArrayLike | None

Fixed values for the variance components of the inner factor of the first ~ inner | outer term (nan entries are estimated).

None
rho ArrayLike | None

Fixed values for the correlation parameters of the first ~ inner | outer term (nan entries are estimated).

None
gamma2 ArrayLike | None

As tau2 for the second ~ inner | outer term.

None
phi ArrayLike | None

As rho for the second ~ inner | outer term.

None
sparse bool

Use sparse matrices, which can be faster for large models.

False
dist object

Distance measure for the spatial structures (struct 'SPEXP' etc.; otherwise unused): 'euclidean' (the default), 'maximum' or 'manhattan' (names may be abbreviated), a callable that takes the matrix of inner values and returns the square distance matrix, or a square symmetric data frame of distances with unique dimension names. 'gcd' (metafor's great-circle distance) raises NotSupportedError. One value (used for both terms), or a list of two for a list of two ~ inner | outer terms.

'euclidean'
cvvc bool | str

Compute the Hessian of the variance components and its inverse (hessian and vvc of the result): False (the default), True or 'varcor' (variances and correlations), 'varcov' (variances and covariances; for structures other than 'UN' and 'GEN', or with fixed components, a warning is given and 'varcor' is used) or 'transf' (the transformed parameters). Any other string raises InputError. Ignored without random effects or with optbeta=True (where the Hessian includes the coefficients anyway).

False
optbeta bool

Optimise the coefficients together with the variance components; their covariance matrix is then taken from the inverse Hessian.

False
beta ArrayLike | None

Fixed values for the coefficients (nan entries are estimated).

None
lambda1 float

Lasso penalty on the coefficients other than the intercept; a positive value implies optbeta=True.

0.0
lambda2 float

Ridge penalty on the coefficients other than the intercept; a positive value implies optbeta=True.

0.0
vccon Mapping[str, ArrayLike] | None

Constraints on the variance components, a mapping with the keys sigma2, tau2, rho, gamma2 and phi whose entries are group ids; components with the same id are constrained to be equal.

None
restart RMAMVResult | bool | None

Starting values for the variance components: a previous fit of the same model, or True for the last values the optimiser tried in this session (also after a fit that did not converge).

None
control MVControl | Mapping[str, Any] | None

Optimiser settings, as an MVControl or a mapping with metafor's names (. becomes _).

None
verbose bool | int

Print metafor's table of the variance components and a log line per likelihood evaluation to stdout (the optimiser differs from metafor's nlminb, so the sequence of evaluations differs); 2 or more also prints progress messages to stderr.

False
na_action Literal['omit', 'fail', 'pass']

What to do with rows that have missing values (metafor uses the global na.action option instead): 'omit' (the default) drops them with a warning and 'fail' raises an error. 'pass' and 'exclude' drop them too.

'omit'

Returns:

Type Description
RMAMVResult

The fitted model. Coefficients are in beta with se, zval, pval, ci_lb and ci_ub (arrays of length p) and

RMAMVResult

their covariance matrix in vb; the variance components in sigma2, tau2, rho, gamma2 and phi (arrays; [0.]

RMAMVResult

when the model has no such component, see with_s, with_g and with_h); QE (with QEdf and QEp) and QM (with

RMAMVResult

QMdf and QMp) are the tests of residual heterogeneity and of the omnibus hypothesis. There are no I2 or H2 fields as in

RMAMVResult

rma_uni. summary() returns the printout as a string.

Raises:

Type Description
InputError

an argument or the data is invalid (including an unknown method, test, dfs, struct, Rscale or cvvc, W and V of the wrong size, and missing values with na_action='fail').

ArgumentError

control names a setting that does not exist.

NotSupportedError

dist='gcd'.

EstimationError

the model could not be fitted (for example when the marginal variance-covariance matrix is not positive definite at the starting values).

InternalError

a random-effects structure built on an inner factor has none.

NotFoundError

a variable is not found in the data.

Metafor reference

rma.mv

selmodel

selmodel(
    x: RMAResult | SelmodelResult,
    type: str,
    alternative: str = 'greater',
    prec: str | None = None,
    subset: ArrayLike | None = None,
    delta: Any = None,
    steps: Any = None,
    decreasing: bool = False,
    verbose: bool | int = False,
    digits: int | None = None,
    control: Mapping[str, Any] | None = None,
    **kwargs: Any,
) -> SelmodelResult | DataFrame | NDArray[float64]

Fit a selection model to a fitted rma_uni model (metafor's selmodel.rma.uni).

Mirrors metafor's selmodel(). A selection model describes how the probability that an estimate is observed depends on its p-value (and optionally its precision); it is used to assess and adjust for publication bias (Vevea & Hedges, 1995; Citkowicz & Vevea, 2017; Preston, Ashby & Smyth, 2004). Models that were not fitted with ML (or as an equal/fixed-effects model) are refitted with ML first.

Parameters:

Name Type Description Default
x RMAResult | SelmodelResult

A model fitted by rma_uni (not a robust one), or an earlier selection model, whose base model is used. Models with non-positive sampling variances, or unweighted or custom-weighted ones, are refused.

required
type str

Selection function: 'beta', 'halfnorm', 'negexp', 'logistic', 'power', 'negexppow', 'stepfun', 'trunc' or 'truncest'; the variants 'halfnorm1', 'negexp1', 'logistic1', 'power1', 'halfnorm2', 'negexp2', 'logistic2', 'power2' and 'stepcon' exist in metafor's source but not on its help page. As in metafor the string is matched as a regular expression against these names in this order and the first match is used, so 'half' is 'halfnorm' and 'step' is 'stepfun'.

required
alternative str

Direction of the one-sided p-values: 'greater' (the default), 'less' or 'two.sided' (not available for 'trunc' and 'truncest'); may be abbreviated.

'greater'
prec str | None

Measure of precision the selection function may depend on: 'sei', 'vi', 'ninv' or 'sqrtninv' (the last two need the sample sizes stored in x, else InputError). Default (None) is no dependence on precision. It is rescaled by its maximum unless scaleprec=False. It is ignored with a warning for 'beta', 'trunc' and 'truncest'.

None
subset ArrayLike | None

Which studies the selection function applies to (the others are always observed): a boolean or 0-based index vector over the studies of x. Default: all.

None
delta Any

Fixed values of the selection parameters, one per parameter of the chosen type (None or nan elements are estimated); a wrong length or a value outside the parameter space raises InputError.

None
steps Any

Values whose meaning depends on type. 'stepfun' (required): cutpoints of the p-values, sorted and de-duplicated, with 1 appended if missing; the lowest must be above 0. 'beta': the two truncation points (alpha1, alpha2) of the p-values. 'halfnorm', 'negexp', 'logistic', 'power', 'negexppow': a single threshold below which the selection weight is 1 (stored in the result as [threshold, 1]). 'trunc': the single truncation point of the effect sizes (default 0). 'truncest': ignored with a warning. Values must lie in [0, 1] (except for 'trunc'); a wrong number for the type raises InputError.

None
decreasing bool

For type='stepfun' only: constrain the selection weights to be non-increasing over the p-value intervals (the first one is then fixed at 1 and the others are bounded by 1). For any other type it is ignored with a warning.

False
verbose bool | int

Print the progress of the optimiser (to stderr); larger values print more.

False
digits int | None

Number of decimals used when printing, stored in the result. Default (None): the digits of x.

None
control Mapping[str, Any] | None

Optimiser settings as a mapping with metafor's names (delta.init, optimizer, optmethod, intCtrl, ... with . or _) and the optimiser's settings (maxit, reltol, ndeps).

None
**kwargs Any

Further arguments as in metafor: tau2 and beta (fixed values, nan for free), scaleprec, pval, ptable, skiphes, skiphet, skipintcheck, defmap, mapfun, mapinvfun and retopt. Others are disregarded with a warning.

{}

Returns:

Type Description
SelmodelResult | DataFrame | NDArray[float64]

The fitted selection model, a SelmodelResult with the location coefficients in beta, tau2 and the selection

SelmodelResult | DataFrame | NDArray[float64]

parameters in delta (each with standard errors, tests and confidence intervals) and the likelihood ratio tests against the model without

SelmodelResult | DataFrame | NDArray[float64]

selection. With ptable=True and steps given for a type that uses them (not 'trunc' or 'truncest') a data frame with the column

SelmodelResult | DataFrame | NDArray[float64]

k (number of p-values per interval, the intervals as row labels) is returned and no model is fitted; without such steps the model is

SelmodelResult | DataFrame | NDArray[float64]

fitted as usual. With retopt=True a numpy array of the optimiser's solution is returned (the coefficients, for the standardised model

SelmodelResult | DataFrame | NDArray[float64]

matrix if x has moderators, then the log of tau2, then the selection parameters on the optimiser's transformed scale, fixed ones as

SelmodelResult | DataFrame | NDArray[float64]

given); metafor returns the whole optimiser result instead.

Raises:

Type Description
ArgumentError

x is not a model this can be applied to (a robust model, or not from rma_uni).

InputError

an argument or the data is invalid (unknown type, prec or alternative, unsuitable steps or delta, too few studies, no sample sizes for prec='ninv').

EstimationError

the optimiser did not converge or the likelihood could not be integrated.

NotSupportedError

the optimiser chosen in control has no counterpart in metafopy.

Metafor reference

selmodel

Results

RMAResult dataclass

RMAResult(
    beta: FloatArray,
    se: FloatArray,
    zval: FloatArray,
    pval: FloatArray,
    ci_lb: FloatArray,
    ci_ub: FloatArray,
    vb: FloatArray,
    coef_names: tuple[str, ...],
    tau2: float,
    se_tau2: float,
    k: int,
    p: int,
    m: int,
    btt: tuple[int, ...],
    QE: float,
    QEp: float,
    QM: float,
    QMp: float,
    QMdf: tuple[int, float | None],
    I2: float,
    H2: float,
    R2: float | None,
    vt: float,
    fit_stats_ml: FitStats,
    fit_stats_reml: FitStats,
    parms: int,
    method: str,
    test: Test,
    level: float,
    ddf: int | None,
    s2w: float,
    weighted: bool,
    weights: FloatArray | None,
    tau2_fix: bool,
    int_only: bool,
    int_incl: bool,
    allvipos: bool,
    yi: FloatArray,
    vi: FloatArray,
    X: FloatArray,
    slab: tuple[str, ...],
    data: MetaData,
    control: Control,
    iterations: int = 0,
    measure: str = 'GEN',
    robust: RobustInfo | None = None,
    digits: int = 4,
    coef_na: tuple[bool, ...] = (),
    X_f: FloatArray = (lambda: empty((0, 0)))(),
    add: float = 0.5,
    to: str = 'only0',
    drop00: bool = False,
    *,
    call: Call | None = None,
)

Bases: DataFields, RobustFields, FitMethods

A fitted rma.uni model.

Array attributes follow metafor's names with . replaced by _ (ci_lb, se_tau2). btt holds 0-based coefficient indices.

model property

model: str

The kind of model, 'rma.uni' (metafor's model).

tau2_f property

tau2_f: float

The amount of heterogeneity, metafor's tau2.f (the same number as tau2 here).

dfs property

dfs: float | tuple[float, ...] | None

The degrees of freedom of the tests (metafor's dfs): ddf for test='t' or 'knha', those of :func:metafopy.robust for a robust fit.

A model made robust has a single number (the number of clusters minus p) for the default method and one value per coefficient for club_sandwich=True, for which ddf stays None because it holds a single number.

coef

coef(type: str = 'beta') -> Series

Estimated coefficients, indexed by name; type is accepted for metafor's coef(x, type=) and only location-scale fits use it.

vcov

vcov(
    type: Literal[
        'fixed',
        'beta',
        'alpha',
        'delta',
        'obs',
        'marginal',
        'fitted',
        'resid',
    ] = 'fixed',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> DataFrame

Variance-covariance matrix of the coefficients, or with type of the observed effects; see :func:metafopy.vcov.

fitted

fitted(
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> NDArray[float64]

Fitted values X beta.

na_action is 'omit' (the studies used in fitting), 'exclude', 'pass' or 'fail', as in :func:metafopy.residuals.

residuals

residuals(
    type: Literal[
        'response',
        'rstandard',
        'rstudent',
        'pearson',
        'cholesky',
    ] = 'response',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> NDArray[float64]

Residuals; see :func:metafopy.residuals (type is 'response', 'rstandard', 'rstudent', 'pearson' or 'cholesky').

weights_

weights_(
    type: Literal['diagonal', 'matrix'] = 'diagonal',
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> NDArray[float64]

Percentage weights of the estimates in the model fit (type='diagonal') or the weight matrix ('matrix'), metafor's weights().

na_action is 'omit', 'exclude', 'pass' or 'fail' as in :func:metafopy.residuals.

hat_matrix

hat_matrix() -> NDArray[float64]

The full hat matrix X (X'WX)^-1 X'W.

hatvalues

hatvalues(
    type: Literal['diagonal', 'matrix'] = 'diagonal',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> NDArray[float64]

Diagonal of the hat matrix (type='diagonal') or the hat matrix itself ('matrix'), as metafor's hatvalues().

With na_action='exclude' or 'pass' the studies left out because of missing values are NaN rows (and columns); 'fail' stops if any were.

Raises:

Type Description
InputError

type is not 'diagonal' or 'matrix', na_action is unknown, or studies are missing with 'fail'.

plot

plot(*args: Any, **kwargs: Any) -> Any

Draw the forest, funnel, radial and residual plots with :func:metafopy.plot.plot_rma.

summary

summary(
    digits: int | Mapping[str, int] | None = None,
    showfit: bool = True,
    *,
    signif_stars: bool | None = None,
    signif_legend: bool | None = None,
    num: bool = False,
) -> str

The printout with the fit statistics table, as metafor's summary(); str(res) leaves it out like print().

digits defaults to the digits option, else to the digits the model was fitted with. signif_stars (default: the signif_stars option, True) adds the significance stars and signif_legend (default: signif_stars) the legend of the codes. num numbers the rows of the table of coefficients (print(x, num = TRUE) in metafor).

FitStats dataclass

FitStats(
    ll: float,
    dev: float,
    AIC: float,
    BIC: float,
    AICc: float,
)

Log-likelihood, deviance and information criteria (metafor's fit.stats).

RMALSResult dataclass

RMALSResult(
    beta: FloatArray,
    se: FloatArray,
    zval: FloatArray,
    pval: FloatArray,
    ci_lb: FloatArray,
    ci_ub: FloatArray,
    vb: FloatArray,
    coef_names: tuple[str, ...],
    alpha: FloatArray,
    va: FloatArray,
    se_alpha: FloatArray,
    zval_alpha: FloatArray,
    pval_alpha: FloatArray,
    ci_lb_alpha: FloatArray,
    ci_ub_alpha: FloatArray,
    alpha_names: tuple[str, ...],
    alpha_fix: BoolArray,
    tau2: FloatArray,
    k: int,
    p: int,
    q: int,
    m: int,
    m_alpha: int,
    btt: tuple[int, ...],
    att: tuple[int, ...],
    QE: float,
    QEp: float,
    QM: float,
    QMp: float,
    QMdf: tuple[int, float | None],
    QS: float,
    QSp: float,
    QSdf: tuple[int, float | None],
    I2: FloatArray,
    H2: FloatArray,
    vt: float,
    fit_stats_ml: FitStats,
    fit_stats_reml: FitStats,
    parms: int,
    method: str,
    test: Test,
    level: float,
    ddf: int | None,
    ddf_alpha: int | None,
    s2w: float,
    weighted: bool,
    weights: FloatArray | None,
    link: str,
    optbeta: bool,
    beta_fix: BoolArray,
    int_only: bool,
    int_incl: bool,
    Z_int_only: bool,
    Z_int_incl: bool,
    allvipos: bool,
    yi: FloatArray,
    vi: FloatArray,
    X: FloatArray,
    Z: FloatArray,
    slab: tuple[str, ...],
    data: MetaData,
    control: LSControl,
    vcovmat: FloatArray | None = None,
    H: FloatArray | None = None,
    tau2_fix: bool = False,
    measure: str = 'GEN',
    formula_scale: str | None = None,
    Z_f: FloatArray | None = None,
    digits: int = 4,
    coef_na: tuple[bool, ...] = (),
    coef_na_Z: tuple[bool, ...] = (),
    X_f: FloatArray = (lambda: empty((0, 0)))(),
    add: float = 0.5,
    to: str = 'only0',
    drop00: bool = False,
    *,
    call: Call | None = None,
)

Bases: DataFields, FitMethods

A fitted location-scale model.

The location part (beta, se, ..., vb) and the scale part (alpha, se_alpha, ..., va) follow metafor's names with . replaced by _. tau2 holds the fitted heterogeneity of every study used in the fit. btt and att are 0-based coefficient indices.

alphas property

alphas: int

Number of scale coefficients (metafor's alphas).

model property

model: str

The kind of model, 'rma.ls' (metafor's model).

se_tau2 property

se_tau2: float

Not available for location-scale models (NaN, as metafor stores NA).

R2 property

R2: None

Not available for location-scale models (None, as metafor stores NULL).

randhet property

randhet: bool

Whether random heterogeneity is modelled (always False here, metafor's randhet).

Z_intercept property

Z_intercept: bool

Whether the scale model has an intercept, metafor's Z.intercept.

dfs property

dfs: int | None

The degrees of freedom of the tests of the location coefficients (None for the z-test), metafor's dfs.

tau2_f property

tau2_f: FloatArray

The amount of residual heterogeneity of each study after subsetting, NaN for those left out of the fit, metafor's tau2.f.

coef

coef(
    type: Literal['alpha', 'beta'] | None = None,
) -> Series | dict[str, Series]

Location ('beta') and/or scale ('alpha') coefficients, indexed by name.

vcov

vcov(
    type: Literal[
        'fixed',
        'beta',
        'alpha',
        'delta',
        'obs',
        'marginal',
        'fitted',
        'resid',
    ] = 'fixed',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> DataFrame | dict[str, DataFrame]

Variance-covariance matrices; 'fixed' (the default) gives {'beta': ..., 'alpha': ...}, the other types follow :func:metafopy.vcov.

fitted

fitted(
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> dict[str, NDArray[float64]]

Fitted location values X beta and scale values Z alpha (the latter on the link scale); na_action is as for rma_uni fits.

residuals

residuals(
    type: Literal[
        'response',
        'rstandard',
        'rstudent',
        'pearson',
        'cholesky',
    ] = 'response',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> NDArray[float64]

Residuals; see :func:metafopy.residuals (type is 'response', 'rstandard', 'rstudent', 'pearson' or 'cholesky').

weights_

weights_(
    type: Literal['diagonal', 'matrix'] = 'diagonal',
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> NDArray[float64]

Percentage weights of the estimates in the model fit (type='diagonal') or the weight matrix ('matrix'), metafor's weights().

na_action is 'omit', 'exclude', 'pass' or 'fail' as in :func:metafopy.residuals.

hat_matrix

hat_matrix() -> NDArray[float64]

The full hat matrix X (X'WX)^-1 X'W.

hatvalues

hatvalues(
    type: Literal['diagonal', 'matrix'] = 'diagonal',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> NDArray[float64]

Diagonal of the hat matrix (type='diagonal') or the hat matrix itself ('matrix'), as metafor's hatvalues().

With na_action='exclude' or 'pass' the studies left out because of missing values are NaN rows (and columns); 'fail' stops if any were.

Raises:

Type Description
InputError

type is not 'diagonal' or 'matrix', na_action is unknown, or studies are missing with 'fail'.

summary

summary(
    digits: int | Mapping[str, int] | None = None,
    showfit: bool = True,
    *,
    signif_stars: bool | None = None,
    signif_legend: bool | None = None,
    num: bool = False,
) -> str

The printout with the fit statistics table, as metafor's summary(); str(res) leaves it out like print().

digits defaults to the digits option, else to the digits the model was fitted with; signif_stars, signif_legend and num as for :meth:metafopy.models.rma_uni.RMAResult.summary.

MHResult dataclass

MHResult(
    beta: FloatArray,
    se: FloatArray,
    zval: FloatArray,
    pval: FloatArray,
    ci_lb: FloatArray,
    ci_ub: FloatArray,
    vb: FloatArray,
    tau2: float,
    I2: float,
    H2: float,
    QE: float,
    QEp: float,
    k: int,
    k_f: int,
    k_yi: int,
    k_all: int,
    k_pos: int | None,
    p: int,
    parms: int,
    measure: str,
    level: float,
    add: tuple[float, float],
    to: tuple[str, str],
    drop00: tuple[bool, bool],
    fit_stats_ml: FitStats,
    fit_stats_reml: FitStats,
    tables: TableSet,
    data: DataFrame | None = None,
    digits: int = 4,
    coef_names: tuple[str, ...] = ('intrcpt',),
    method: str = 'FE',
    test: str = 'z',
    int_only: bool = True,
    weighted: bool = True,
    CO: float = NAN,
    COp: float = NAN,
    MH: float = NAN,
    MHp: float = NAN,
    BD: float = NAN,
    BDp: float = NAN,
    TA: float = NAN,
    TAp: float = NAN,
    correct: bool = True,
    *,
    call: Call | None = None,
)

Bases: FixedBinaryResult

A fitted rma.mh model; CO/MH are the Cochran and Mantel-Haenszel tests, BD/TA the Breslow-Day and Tarone tests (odds ratios only).

PetoResult dataclass

PetoResult(
    beta: FloatArray,
    se: FloatArray,
    zval: FloatArray,
    pval: FloatArray,
    ci_lb: FloatArray,
    ci_ub: FloatArray,
    vb: FloatArray,
    tau2: float,
    I2: float,
    H2: float,
    QE: float,
    QEp: float,
    k: int,
    k_f: int,
    k_yi: int,
    k_all: int,
    k_pos: int | None,
    p: int,
    parms: int,
    measure: str,
    level: float,
    add: tuple[float, float],
    to: tuple[str, str],
    drop00: tuple[bool, bool],
    fit_stats_ml: FitStats,
    fit_stats_reml: FitStats,
    tables: TableSet,
    data: DataFrame | None = None,
    digits: int = 4,
    coef_names: tuple[str, ...] = ('intrcpt',),
    method: str = 'FE',
    test: str = 'z',
    int_only: bool = True,
    weighted: bool = True,
    *,
    call: Call | None = None,
)

Bases: FixedBinaryResult

A fitted rma.peto model (the pooled effect is a log odds ratio).

GLMMResult dataclass

GLMMResult(
    beta: FloatArray,
    se: FloatArray,
    zval: FloatArray,
    pval: FloatArray,
    ci_lb: FloatArray,
    ci_ub: FloatArray,
    vb: FloatArray,
    tau2: float,
    se_tau2: float,
    sigma2: float,
    rho: float,
    ci_lb_tau2: float,
    ci_ub_tau2: float,
    I2: float,
    H2: float,
    vt: float,
    QE_Wld: float,
    QEp_Wld: float,
    QE_LRT: float,
    QEp_LRT: float,
    QE_df: int | None,
    QM: float,
    QMdf: tuple[int, int | None],
    QMp: float,
    k: int,
    k_f: int,
    k_yi: int,
    k_eff: int,
    k_all: int,
    p: int,
    p_eff: int,
    parms: int,
    int_only: bool,
    int_incl: bool,
    intercept: bool,
    X: FloatArray,
    X_f: FloatArray,
    coef_names: tuple[str, ...],
    tables: TableSet,
    measure: str,
    method: str,
    model: str,
    weighted: bool,
    test: str,
    ddf: int | None,
    btt: tuple[int, ...],
    m: int,
    digits: int,
    level: float,
    add: float,
    to: str,
    drop00: bool,
    fit_stats_ml: FitStats,
    fit_stats_reml: FitStats,
    se_warn: bool,
    data: DataFrame | None = None,
    *,
    call: Call | None = None,
    control: Any = None,
)

Bases: TableFields, FitMethods

A fitted rma.glmm model: a generalized linear mixed-effects model for binary or count data.

beta, se, zval, pval, ci_lb, ci_ub and vb hold one element per coefficient (coef_names). QE_Wld and QE_LRT are the Wald-type and likelihood ratio tests for (residual) heterogeneity, QM the omnibus test of the coefficients btt (0-based). level is the significance level alpha (0.05 for 95% intervals), as in metafor. tables keeps the counts and the yi/vi used for I2/H2.

outdat_f property

outdat_f: dict[str, FloatArray | None]

The counts of the tables after subsetting; ni holds the sample sizes of those tables, as in metafor's outdat.f.

See rma.glmm in https://github.com/wviechtb/metafor/blob/master/R/rma.glmm.r.

dfs property

dfs: int | None

The degrees of freedom of the tests of the coefficients (None for the z-test), metafor's dfs.

ni property

ni: FloatArray

Sample sizes of the tables used in the fit, metafor's ni.

coef

coef(type: str = 'beta') -> Series

Estimated coefficients, indexed by name; type is accepted for metafor's coef(x, type=) and only location-scale fits use it.

vcov

vcov(
    type: Literal[
        'fixed',
        'beta',
        'alpha',
        'delta',
        'obs',
        'marginal',
        'fitted',
        'resid',
    ] = 'fixed',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> DataFrame

Variance-covariance matrix of the coefficients, or with type='fitted' of the fitted values; see :func:metafopy.vcov.

fitted

fitted(
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> NDArray[float64]

Fitted values X beta of the tables used in fitting (metafor's fitted.rma; na_action as for rma_uni fits).

weights_

weights_(
    type: str = 'diagonal', na_action: str = 'omit'
) -> NDArray[float64]

Not available (metafor's weights() stops for this class).

Raises:

Type Description
NotSupportedError

always.

residuals

residuals(
    type: Literal[
        'response',
        'rstandard',
        'rstudent',
        'pearson',
        'cholesky',
    ] = 'response',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> NDArray[float64]

Residuals; see :func:metafopy.residuals (type is 'response', 'rstandard', 'rstudent', 'pearson' or 'cholesky').

summary

summary(
    digits: int | None = None,
    showfit: bool = True,
    *,
    signif_stars: bool | None = None,
    signif_legend: bool | None = None,
    num: bool = False,
) -> str

The printout with the fit statistics table, as metafor's summary(); str(res) leaves it out like print().

signif_stars (default: the signif_stars option, True) adds the significance stars, signif_legend (default: signif_stars) their legend, num numbers the rows of the table of coefficients.

title_lines

title_lines(digits: int, showfit: bool) -> list[str]

Title, model type and optional fit statistics (print.rma.glmm).

RMAMVResult dataclass

RMAMVResult(
    beta: FloatArray,
    se: FloatArray,
    zval: FloatArray,
    pval: FloatArray,
    ci_lb: FloatArray,
    ci_ub: FloatArray,
    vb: FloatArray,
    coef_names: tuple[str, ...],
    sigma2: FloatArray | None,
    tau2: FloatArray | None,
    rho: FloatArray | None,
    gamma2: FloatArray | None,
    phi: FloatArray | None,
    G: FloatArray | None,
    H: FloatArray | None,
    M: Mat,
    V: Mat,
    W: Mat | None,
    X: FloatArray,
    yi: FloatArray,
    vi: FloatArray,
    slab: tuple[str, ...],
    QE: float,
    QEdf: int,
    QEp: float,
    QM: float,
    QMdf: tuple[int, float | None],
    QMp: float,
    k: int,
    k_f: int,
    k_all: int,
    p: int,
    m: int,
    btt: tuple[int, ...],
    parms: int,
    fit_stats_ml: FitStats,
    fit_stats_reml: FitStats,
    method: str,
    test: str,
    dfs: str | float | tuple[float, ...],
    ddf: FloatArray,
    s2w: float,
    level: float,
    int_only: bool,
    int_incl: bool,
    intercept: bool,
    allvipos: bool,
    coef_na: tuple[bool, ...],
    ids: tuple[int, ...],
    not_na: NDArray[bool_],
    struct: tuple[str, str],
    with_s: bool,
    with_g: bool,
    with_h: bool,
    with_r: bool,
    sigma2s: int,
    tau2s: int,
    rhos: int,
    gamma2s: int,
    phis: int,
    vc_fix: dict[str, NDArray[bool_] | None],
    s_names: tuple[str, ...],
    g_names: tuple[str, ...],
    h_names: tuple[str, ...],
    s_nlevels: tuple[int, ...],
    s_levels: tuple[tuple[str, ...], ...],
    Rfix: tuple[bool, ...],
    Rscale: str,
    group_g: Group | None,
    group_h: Group | None,
    s_factors: tuple[Any, ...],
    Z_S: tuple[Mat, ...],
    D_S: tuple[Mat, ...],
    problem: Problem,
    hessian: FloatArray | None,
    vvc: FloatArray | None,
    vc_names: tuple[str, ...],
    spec: dict[str, Any],
    iterations: int = 0,
    measure: str = 'GEN',
    robust: RobustInfo | None = None,
    p_eff: int = 0,
    optbeta: bool = False,
    lambda1: float = 0.0,
    lambda2: float = 0.0,
    beta_est: tuple[bool, ...] = (),
    vccon: dict[str, NDArray[Any]] | None = None,
    cvvc: str | None = None,
    s_levels_f: tuple[tuple[str, ...], ...] = (),
    slab_f: tuple[str, ...] = (),
    X_f: FloatArray | None = None,
    digits: int = 4,
    yi_f: FloatArray = (lambda: empty(0))(),
    vi_f: FloatArray = (lambda: empty(0))(),
    V_f: Mat | None = None,
    W_f: Mat | None = None,
    ni: FloatArray | None = None,
    ni_f: FloatArray | None = None,
    subset: NDArray[bool_] | None = None,
    slab_null: bool = True,
    control: Any = None,
    *,
    call: Call | None = None,
)

Bases: RobustFields, FitMethods

A fitted multivariate/multilevel meta-analytic model (metafor's rma.mv).

Names follow metafor with . replaced by _; btt holds 0-based coefficient indices. spec keeps the arguments of the call, which :func:metafopy.confint and :func:metafopy.profile use to refit the model. hessian and vvc are the Hessian of -ll and its inverse (optbeta=True, where the leading rows are the coefficients, or cvvc), with the row names vc_names; p_eff is the number of estimated (not fixed) coefficients, beta_est flags them, and vccon holds the group ids of constrained variance components. slab_f and s_levels_f are the study labels and the levels of the ~ 1 | id terms before rows with missing values were dropped (metafor's slab and s.levels.f), used to pad results under na_action='exclude'. X_f is the model matrix before rows with missing values were dropped (metafor's X.f; NaN where a moderator value is missing), used by fitted() and predict() under na_action='pass'.

g_nlevels property

g_nlevels: tuple[int, int] | None

Number of levels of the inner and outer factor of the tau2/rho term in the fit (metafor's g.nlevels), None without one.

g_nlevels_f property

g_nlevels_f: tuple[int, int] | None

As :attr:g_nlevels before the rows with missing values were dropped (metafor's g.nlevels.f).

g_levels_f property

g_levels_f: tuple[list[str], list[str]] | None

The levels of the inner and outer factor of the tau2/rho term before the rows with missing values were dropped (g.levels.f).

g_levels_k property

g_levels_k: Series[float] | None

Number of observations at each level of the inner factor of the tau2/rho term, named by the levels (metafor's g.levels.k).

g_levels_comb_k property

g_levels_comb_k: FloatArray | None

Number of observations at each combination of inner levels of the tau2/rho term (metafor's g.levels.comb.k).

h_nlevels property

h_nlevels: tuple[int, int] | None

As :attr:g_nlevels for the gamma2/phi term (metafor's h.nlevels).

h_nlevels_f property

h_nlevels_f: tuple[int, int] | None

As :attr:g_nlevels_f for the gamma2/phi term (metafor's h.nlevels.f).

h_levels_f property

h_levels_f: tuple[list[str], list[str]] | None

As :attr:g_levels_f for the gamma2/phi term (metafor's h.levels.f).

h_levels_k property

h_levels_k: Series[float] | None

As :attr:g_levels_k for the gamma2/phi term (metafor's h.levels.k).

h_levels_comb_k property

h_levels_comb_k: FloatArray | None

As :attr:g_levels_comb_k for the gamma2/phi term (metafor's h.levels.comb.k).

G_dimnames property

G_dimnames: tuple[str, ...]

The row and column names of G (the levels of the inner factor, or the inner variables for GEN/GDIAG), as metafor sets them.

H_dimnames property

H_dimnames: tuple[str, ...]

The row and column names of H, as :attr:G_dimnames.

G_frame property

G_frame: DataFrame | None

G as a data frame with its row and column names, None without a tau2/rho term.

H_frame property

H_frame: DataFrame | None

H as a data frame with its row and column names, None without a gamma2/phi term.

weighted property

weighted: bool

Whether the model is fitted by weighting (always True for rma_mv), metafor's weighted.

data property

data: DataFrame | None

The data frame the model was fitted to (None if the model was fitted to vectors), metafor's data.

sparse property

sparse: bool

Whether sparse matrices were used, metafor's sparse.

dist property

dist: tuple[Any, Any]

The distance measures of the 'SP' structures (the dist argument, two entries), metafor's dist.

random property

random: list[str] | None

The random formulas as given (None without any), metafor's random.

R property

R: Any

The known correlation matrices given as R (None without any), metafor's R: a mapping with an entry for every ~ 1 | factor term, None for the terms without a matrix.

formulas property

formulas: tuple[str | None, str | None]

The two ~ inner | outer formulas of the model (None for a missing one), metafor's formulas.

withS property

withS: bool

Whether the model has ~ 1 | id terms, metafor's withS.

withG property

withG: bool

Whether the model has a first ~ inner | outer term, metafor's withG.

withH property

withH: bool

Whether the model has a second ~ inner | outer term, metafor's withH.

withR property

withR: bool

Whether known correlation matrices were given, metafor's withR.

s_nlevels_f property

s_nlevels_f: tuple[int, ...]

The number of levels of each ~ 1 | id factor before the removal of studies with missing values, metafor's s.nlevels.f.

Z_G1 property

Z_G1: Mat | None

The design matrix of the outer factor of the first ~ inner | outer term, metafor's Z.G1.

Z_G2 property

Z_G2: Mat | None

The design matrix of the inner factor of the first ~ inner | outer term, metafor's Z.G2.

Z_H1 property

Z_H1: Mat | None

The design matrix of the outer factor of the second ~ inner | outer term, metafor's Z.H1.

Z_H2 property

Z_H2: Mat | None

The design matrix of the inner factor of the second ~ inner | outer term, metafor's Z.H2.

k_eff property

k_eff: int

Number of effective observations (the rows used in the fit), metafor's k.eff.

coef

coef(type: str = 'beta') -> Series

Estimated coefficients, indexed by name; type is accepted for metafor's coef(x, type=) and only location-scale fits use it.

named_inner

named_inner(group: Group) -> NDArray[float64] | csc_array

Z1 of a ~ inner | outer term with the column names R gives it: the levels of a factor or the columns of the inner variables.

named_outer

named_outer(group: Group) -> NDArray[float64] | csc_array

Z2 of a ~ inner | outer term with the column names R gives it (mf.g[[nvars]] and the levels).

used_row_names

used_row_names() -> tuple[str, ...]

The row names R gives the matrices of the ~ inner | outer terms: the rows after subset numbered from 1, less those with missing values.

R builds them from a data frame of the subset (.process.G.aftersub) and drops the rows with missing values afterwards, so a subset renumbers the rows and the removal of missing values does not.

vcov

vcov(
    type: Literal[
        'fixed',
        'beta',
        'alpha',
        'delta',
        'obs',
        'marginal',
        'fitted',
        'resid',
    ] = 'fixed',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> DataFrame

Variance-covariance matrix of the coefficients, or with type of the observed effects; see :func:metafopy.vcov.

fitted

fitted(
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> NDArray[float64]

Fitted values X beta.

na_action is 'omit' (the rows used in fitting), 'exclude', 'pass' or 'fail', as in :func:metafopy.residuals.

residuals

residuals(
    type: Literal[
        'response',
        'rstandard',
        'rstudent',
        'pearson',
        'cholesky',
    ] = 'response',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> NDArray[float64]

Residuals; see :func:metafopy.residuals (type is 'response', 'rstandard', 'rstudent', 'pearson' or 'cholesky').

weight_matrix

weight_matrix() -> NDArray[float64]

W: the user-supplied weight matrix or M^-1.

hat_matrix

hat_matrix() -> NDArray[float64]

X (X'WX)^-1 X'W (metafor hatvalues.rma.mv(type="matrix")).

hatvalues

hatvalues(
    type: Literal['diagonal', 'matrix'] = 'diagonal',
    na_action: str = 'omit',
) -> NDArray[float64]

Diagonal of the hat matrix (type='diagonal') or the hat matrix itself ('matrix'), as metafor's hatvalues.rma.mv.

With na_action='exclude' or 'pass' rows (and columns) left out because of missing values are NaN. See https://github.com/wviechtb/metafor/blob/master/R/hatvalues.rma.mv.r.

Raises:

Type Description
InputError

an unknown type or na_action, or missing values with na_action='fail'.

weights_

weights_(
    type: Literal[
        'diagonal', 'matrix', 'rowsum'
    ] = 'diagonal',
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> NDArray[float64]

Percentage weights ('diagonal'), the weight matrix W ('matrix') or the percentage row sums of W ('rowsum', intercept-only).

Raises:

Type Description
InputError

type='rowsum' for a model with moderators, an invalid argument, or na_action='fail' with rows left out.

summary

summary(
    digits: int | Mapping[str, int] | None = None,
    showfit: bool = True,
    *,
    signif_stars: bool | None = None,
    signif_legend: bool | None = None,
    num: bool = False,
) -> str

The printout with the fit statistics table, as metafor's summary(); str(res) leaves it out like print().

digits defaults to the digits option, else to the digits the model was fitted with; signif_stars, signif_legend and num as for :meth:metafopy.models.rma_uni.RMAResult.summary.

SelmodelResult dataclass

SelmodelResult(
    base: RMAResult,
    beta: FloatArray,
    se: FloatArray,
    zval: FloatArray,
    pval: FloatArray,
    ci_lb: FloatArray,
    ci_ub: FloatArray,
    vb: FloatArray,
    betaspec: bool,
    tau2: float,
    se_tau2: float,
    ci_lb_tau2: float,
    ci_ub_tau2: float,
    tau2_fix: bool,
    QM: float,
    QMp: float,
    delta: FloatArray,
    vd: FloatArray,
    se_delta: FloatArray,
    zval_delta: FloatArray,
    pval_delta: FloatArray,
    ci_lb_delta: FloatArray,
    ci_ub_delta: FloatArray,
    deltas: int,
    delta_fix: tuple[bool, ...],
    hessian: FloatArray | None,
    hest: tuple[bool, ...],
    ll: float,
    ll0: float,
    LRT: float,
    LRTdf: int,
    LRTp: float,
    LRT_tau2: float,
    LRTp_tau2: float,
    parms: int,
    fit_stats_ml: FitStats,
    fit_stats_reml: FitStats,
    pvals: FloatArray,
    spec: SelSpec,
    type: str,
    steps: FloatArray,
    decreasing: bool,
    stepsspec: bool,
    pgrp: NDArray[intp] | None,
    ptable: DataFrame | None,
    subset: BoolArray,
    k0: int,
    k1: int,
    alternative: str,
    pval_min: float,
    prec: str | None,
    precspec: bool,
    precis: dict[str, float],
    scaleprec: bool | None,
    delta_lb: FloatArray,
    delta_ub: FloatArray,
    delta_lb_excl: tuple[bool, ...],
    delta_ub_excl: tuple[bool, ...],
    delta_min: FloatArray,
    delta_max: FloatArray,
    tau2_max: float,
    control: dict[str, Any],
    defmap: bool | None,
    mapfun: tuple[str | None, ...] | None,
    mapinvfun: tuple[str | None, ...] | None,
    digits: int = 4,
    *,
    call: Call | None = None,
    trimfill_info: dict[str, Any] = dict(),
)

Bases: FitMethods

A selection model fitted by :func:metafopy.selmodel (metafor's rma.uni.selmodel object).

base is the ML (or equal/fixed-effects) :class:~metafopy.RMAResult the selection model was fitted from; the data (yi, vi, X, ...) come from it. All other names follow metafor with . replaced by _ (se_delta, ci_lb_delta, LRT_tau2). beta, se, vb and tau2 are the estimates under the selection model; delta holds the selection parameters, vd their covariance matrix.

k_all property

k_all: int

Number of studies supplied to the model the fit holds (a model that metafor refits has only the studies used, so this is their number).

k_eff property

k_eff: int

Number of effective observations.

p_eff property

p_eff: int

Number of effective model coefficients.

ni property

ni: FloatArray | None

Sample sizes of the studies used in the fit (None when unknown).

M property

M: FloatArray

The marginal variance-covariance matrix of the observed effects, diag(vi + tau2) with the tau2 of the selection model.

I2 property

I2: float

Not computed for selection models (NaN, as metafor stores NA).

H2 property

H2: float

Not computed for selection models (NaN, as metafor stores NA).

vt property

vt: float

Not computed for selection models (NaN, as metafor stores NA).

QE property

QE: float

Not computed for selection models (NaN, as metafor stores NA).

QEp property

QEp: float

Not computed for selection models (NaN, as metafor stores NA).

model property

model: str

The kind of model, 'rma.uni.selmodel' (metafor's model).

QMdf property

QMdf: tuple[int, None]

Degrees of freedom of the test of the moderators: (m, None), as the test is a chi-square test (metafor's QMdf).

tau2_f property

tau2_f: float

The amount of heterogeneity, metafor's tau2.f (the same number as tau2 here).

data property

data: MetaData

The data of the underlying model (metafor keeps the data frame the model was fitted to).

wi_fun property

wi_fun: Weight | None

The selection function of the model (metafor's wi.fun), vectorised over the studies.

__getattr__

__getattr__(name: str) -> Any

The trim-and-fill details (fill, se_k0, ...) of a trimfill fit the selection model was fitted to, which metafor keeps in the result.

coef

coef(
    type: Literal['beta', 'delta', 'all'] | None = None,
) -> Series | dict[str, Series]

The coefficients and selection parameters as {'beta': ..., 'delta': ...} (as R's coef()), or one of them with type.

type='beta' or 'delta' gives that part as a series and 'all' both concatenated into one series.

vcov

vcov(
    type: Literal[
        'fixed',
        'beta',
        'alpha',
        'delta',
        'obs',
        'marginal',
        'fitted',
        'resid',
    ] = 'fixed',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> DataFrame | dict[str, DataFrame]

Variance-covariance matrices; 'fixed' (the default) gives {'beta': ..., 'delta': ...}, the other types follow :func:metafopy.vcov.

fitted

fitted(
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> NDArray[float64]

Fitted values X beta (na_action is accepted for symmetry: the selection model was fitted to the studies without missing values).

weights_

weights_(
    type: str = 'diagonal', na_action: str = 'omit'
) -> NDArray[float64]

Not available (metafor's weights() stops for this class).

Raises:

Type Description
NotSupportedError

always.

residuals

residuals(
    type: Literal[
        'response',
        'rstandard',
        'rstudent',
        'pearson',
        'cholesky',
    ] = 'response',
    *,
    na_action: Literal[
        'omit', 'exclude', 'pass', 'fail'
    ] = 'omit',
) -> NDArray[float64]

Residuals; see :func:metafopy.residuals (type is 'response', 'rstandard', 'rstudent', 'pearson' or 'cholesky').

plot

plot(*args: Any, **kwargs: Any) -> Any

Draw the selection function with :func:metafopy.plot.plot_selmodel.

summary

summary(
    digits: int | None = None,
    showfit: bool = True,
    *,
    signif_stars: bool | None = None,
    signif_legend: bool | None = None,
    num: bool = False,
) -> str

The printout with the fit statistics table, as metafor's summary(); str(res) leaves it out like print().

signif_stars (default: the signif_stars option, True) adds the significance stars, signif_legend (default: signif_stars) their legend, num numbers the rows of the table of coefficients.

Control settings

Control dataclass

Control(
    tau2_init: float | None = None,
    tau2_min: float = 0.0,
    tau2_max: float = 100.0,
    threshold: float = 1e-05,
    tol: float = eps**0.25,
    ll0check: bool = True,
    maxiter: int = 100,
    stepadj: float = 1.0,
    evtol: float = 1e-07,
    REMLf: bool = True,
    ignored: dict[str, Any] = dict(),
)

Control settings for rma_uni (names follow metafor with . -> _).

ignored class-attribute instance-attribute

ignored: dict[str, Any] = dataclasses.field(
    default_factory=dict, compare=False, repr=False
)

The entries other functions of metafor read (optimizer, vc.min, ...), kept as R keeps them in res$control; read them as attributes.

LSControl dataclass

LSControl(
    alpha_init: ArrayLike | None = None,
    alpha_max: ArrayLike = inf,
    alpha_min: ArrayLike = -inf,
    beta_init: ArrayLike | None = None,
    evtol: float = 1e-07,
    hes_alpha_fix: bool = False,
    hes_beta_fix: bool = False,
    hessian_d: float = 0.1,
    hessian_eps: float = 0.0001,
    hessian_r: int = 4,
    maxiter: int = 5000,
    optimizer: str = 'nlminb',
    optmethod: str = 'BFGS',
    opt_ctrl: Mapping[str, Any] = dict(),
    ncpus: int = 1,
    cl: Any = None,
    parallel: Mapping[str, Any] = dict(),
    polish_converged: bool = True,
    REMLf: bool = True,
    scaleZ: bool = True,
    tau2_max: float = inf,
    tau2_min: float = 0.0,
    ignored: dict[str, Any] = dict(),
)

Control settings for location-scale models (names follow metafor with . -> _).

polish_converged=False skips the Nelder-Mead polish after a converged BFGS run (used by the permutation test). optimizer is 'nlminb' (the default, mapped to SciPy's BFGS or, for the identity link, constrOptim), any other optimiser of metafor's rma.uni ('optim' with optmethod, 'BFGS', 'CG', 'L-BFGS-B', 'Nelder-Mead', 'nlm', 'uobyqa', 'newuoa', 'bobyqa', 'nloptr', 'hjk', 'nmk', 'mads', 'ucminf', 'lbfgsb3c', 'subplex', 'BBoptim', 'optimParallel', 'Rcgmin', 'Rvmmin', and for the identity link 'constrOptim', 'solnp', 'constrOptim.nl'/'alabama' and 'auglag'), mapped as :mod:metafopy.models.sel_opt maps them. opt_ctrl holds the optimiser settings given in control (maxit, reltol, abstol, ndeps, tol). ncpus larger than 1 selects 'optimParallel' as in metafor, but the likelihood is evaluated serially (parallel and cl are accepted and ignored). hessian_d, hessian_eps and hessian_r are the arguments of numDeriv::hessian's Richardson method (metafor sets r = 8, whose eight Richardson steps amplify round-off in the log-likelihood to a relative 1e-4 or more in the standard errors; metafopy defaults to r = 4, which agrees with metafor's values to about 1e-5, see docs/differences.md).

ignored class-attribute instance-attribute

ignored: dict[str, Any] = dataclasses.field(
    default_factory=dict, compare=False, repr=False
)

The entries other functions of metafor read (vc.min, stepadj, ...) and those given under another name (tol is in opt_ctrl), kept as R keeps them in res$control; read them as attributes.

GLMMControl dataclass

GLMMControl(
    package: str = 'lme4',
    scale_x: bool = True,
    evtol: float = 1e-07,
    tau2tol: float = 0.0001,
    int_rel_tol: float = epsilon**0.25,
    int_subdivisions: int = 100,
    hessian_r: int = 16,
    hesspack: str = 'numDeriv',
    hessian_ctrl: Mapping[str, Any] = dict(),
    dnchgcalc: str | None = None,
    dnchgprec: float | None = None,
    gtol: float = 1e-07,
    optimizer: str = 'nlminb',
    optmethod: str = 'BFGS',
    opt_ctrl: Mapping[str, Any] = dict(),
    clogit_ctrl: Mapping[str, Any] = dict(),
    clogistic_ctrl: Mapping[str, Any] = dict(),
    ignored: dict[str, Any] = dict(),
)

Control settings of rma_glmm (names follow metafor's control list with . replaced by _).

int_rel_tol and int_subdivisions are the rel.tol and subdivisions of the intCtrl list used for the integral in the exact conditional model; hessian_r is numDeriv's r. hesspack ('numDeriv', 'pracma' or 'calculus') and hessian_ctrl (metafor's hessianCtrl: d, eps, r, v for numDeriv, h for pracma, accuracy and stepsize for calculus) choose the numerical Hessian of the exact conditional model; dnchgcalc ('dFNCHypergeo' or 'dnoncenhypergeom') and dnchgprec (the precision of BiasedUrn::dFNCHypergeo, 1e-10 in metafor) its density. Without either entry the Hessian uses the untruncated density; with dnchgcalc='dFNCHypergeo' or a dnchgprec it uses :func:metafopy.core.nchg.fisher_log_probability, the port of BiasedUrn's truncating algorithm. package is the package that fits the mixed models: 'lme4', 'GLMMadaptive' or 'glmmTMB'. optimizer is 'nlminb' (the default: a quasi-Newton maximisation of the exact likelihood of model='CM.EL'), 'clogit' or 'clogistic' (survival::clogit() / Epi::clogistic(), only for the fixed-effects methods) or one of the other optimisers of rma.glmm ('optim' with optmethod, 'Nelder-Mead', 'BFGS', 'bobyqa', 'nlm', ...) that :mod:metafopy.models.sel_opt provides: optim with BFGS and Nelder-Mead are ports of R's routines, the others stand in for them with the closest SciPy method. opt_ctrl is metafor's optCtrl list (maxit, reltol, abstol, ndeps); clogit_ctrl and clogistic_ctrl are metafor's clogitCtrl and clogisticCtrl lists (see :func:clogit_settings and :func:clogistic_settings for the entries).

ignored class-attribute instance-attribute

ignored: dict[str, Any] = dataclasses.field(
    default_factory=dict, compare=False, repr=False
)

The entries other functions of metafor read (vc.min, stepadj, ...), kept as R keeps them in res$control; read them as attributes.

MVControl dataclass

MVControl(
    sigma2_init: ArrayLike | None = None,
    tau2_init: ArrayLike | None = None,
    rho_init: ArrayLike | None = None,
    gamma2_init: ArrayLike | None = None,
    phi_init: ArrayLike | None = None,
    REMLf: bool = True,
    evtol: float = 1e-07,
    cholesky: bool | tuple[bool, bool] | None = None,
    check_k_gtr_1: bool = True,
    hesstol: float = sqrt(EPS),
    gtol: float = 1e-07,
    maxiter: int = 5000,
    hessian_d: float = 0.1,
    hessian_eps: float = 0.0001,
    hessian_r: int = 8,
    optimizer: str = 'nlminb',
    optmethod: str = 'BFGS',
    opt_ctrl: Mapping[str, Any] = dict(),
    ncpus: int = 1,
    cl: Any = None,
    parallel: Mapping[str, Any] = dict(),
    nearpd: bool = False,
    hesspack: str = 'numDeriv',
    hessian_ctrl: Mapping[str, Any] = dict(),
    mfmaxit: float = inf,
    ignored: dict[str, Any] = dict(),
)

Control arguments of :func:rma_mv (metafor's control list).

*_init give starting values (on the original scale), cholesky switches the Cholesky parametrisation of the UN and GEN structures on or off per term, gtol and maxiter control the default BFGS optimiser, and hessian_d, hessian_eps and hessian_r are the arguments of numDeriv::hessian's Richardson method (metafor's hessianCtrl with its default hesspack='numDeriv') used for optbeta and cvvc.

optimizer (default 'nlminb', here BFGS with the analytic score) may be any other optimiser of metafor's rma.mv ('optim' with optmethod, 'BFGS', 'Nelder-Mead', 'nlm', 'bobyqa', 'hjk', ...); they are run as :mod:metafopy.models.sel_opt describes (optim with BFGS or Nelder-Mead is R's routine, the others are SciPy stand-ins), on the log-likelihood alone. opt_ctrl holds optimiser settings given in control (maxit, reltol, abstol, ndeps, tol); ncpus above 1 selects 'optimParallel' but the likelihood is evaluated serially (parallel and cl are accepted and ignored). nearpd forces G, H (UN and GEN structures) and M to be positive definite with nearPD (:func:metafopy.core.linalg.near_pd); the score is then taken by finite differences. hesspack ('numDeriv', 'pracma' or 'calculus') and hessian_ctrl (metafor's hessianCtrl: d, eps, r, v and zero.tol of numDeriv, h of pracma, accuracy and stepsize of calculus) choose the Hessian. mfmaxit is the number of likelihood evaluations after which the optimisation stops with an error.

ignored class-attribute instance-attribute

ignored: dict[str, Any] = dataclasses.field(
    default_factory=dict, compare=False, repr=False
)

The entries other functions of metafor read (vc.min, stepadj, ...), kept as R keeps them in res$control; read them as attributes.