Skip to content

API Reference

This page documents every public function in catpie. Each entry lists the function's purpose, its arguments (with expected value ranges), its return value and the errors it can raise.

A quick orientation:

For the background and the meaning of the value ranges, see Concepts. For a worked example, see Quickstart.

Item response functions

The building blocks: probability of a correct answer, item information, and the weighted-likelihood helper. See Concepts, sections 3–4.

catpie.irf.pi

pi(th: float, item: Item, D: float = 1.0) -> PiResult

Probability of a correct answer (and its derivatives) for one item.

This is the item response function (IRF): the chance that a person with ability th answers an item correctly, given the item's 4-parameter model. In plain words: the higher the ability relative to the item difficulty, the higher the probability.

Returns the probability P together with its first, second and third derivatives with respect to ability (dP, d2P, d3P) — these are used internally by the information and estimation routines.

Parameters:

Name Type Description Default
th float

Ability level theta. A real number, typically in [-4, 4] (outside that range the probability saturates toward its asymptotes).

required
item Item

Item parameters as a 4-tuple (a, b, c, d):

  • a discrimination, must be > 0 (typically 0.5-2.5)
  • b difficulty (typically in [-3, 3])
  • c guessing / lower asymptote, in [0, 1) (typically 0-0.3)
  • d inattention / upper asymptote, in (0, 1] (typically 0.9-1)
required
D float

Scale constant (catR default 1.0; use 1.702 for the logistic approximation to the normal ogive).

1.0

Returns:

Name Type Description
A PiResult

class:PiResult with fields P, dP, d2P, d3P.

PiResult

P lies between the asymptotes c and d.

Note

P is clamped exactly like catR: P == 0 becomes 1e-10 and P == 1 becomes 1 - 1e-10. When the exponent overflows (extreme ability and/or discrimination), P becomes NaN — the same behaviour as R/catR.

catpie.irf.ii

ii(th: float, item: Item, D: float = 1.0) -> IiResult

Fisher information of one item at ability th (and its derivatives).

Information measures how much a single item can tell you about a person's ability at level th: it is largest where the item discriminates well (around its difficulty) and smallest where the answer is almost certain. High information = a good next question, which is why item selection uses it (see :func:nextItem with criterion="MFI").

Parameters:

Name Type Description Default
th float

Ability level (real number, typically [-4, 4]).

required
item Item

Item parameters (a, b, c, d) — see :func:pi.

required
D float

Scale constant (default 1.0).

1.0

Returns:

Name Type Description
An IiResult

class:IiResult with fields Ii, dIi, d2Ii. Ii is

IiResult

non-negative; it can be NaN on overflow, exactly like catR.

catpie.irf.ji

ji(th: float, item: Item, D: float = 1.0) -> JiResult

Weighted-likelihood quantity of one item (and its derivative).

This helper appears in the maximum-likelihood ("ML") and weighted-likelihood ("WL") ability estimators. You normally do not need to call it directly; it is provided for completeness and for parity with catR.

Parameters:

Name Type Description Default
th float

Ability level (real number).

required
item Item

Item parameters (a, b, c, d) — see :func:pi.

required
D float

Scale constant (default 1.0).

1.0

Returns:

Name Type Description
A JiResult

class:JiResult with fields Ji and dJi.

Ability estimation

Estimate a person's ability (theta) and its standard error from their answers. See Concepts, section 5.

catpie.eap.eapEst

eapEst(
    it: Sequence[Item],
    x: Sequence[int],
    D: float = 1.0,
    priorDist: str = "norm",
    priorPar: Tuple[float, float] = (0, 1),
    lower: float = -4,
    upper: float = 4,
    nqp: int = 33,
) -> float

Ability estimate by Expected A Posteriori (EAP) estimation.

EAP is a Bayesian estimate: it combines what the responses tell us (the likelihood) with a prior belief about the ability distribution. It is the most robust of the implemented estimators and the default choice of this package (and of the EWM experiment).

The estimate is computed by numerical integration over a grid of ability values (catR's default: 33 points from -4 to 4), so the result is always within [lower, upper].

Parameters:

Name Type Description Default
it Sequence[Item]

The items that were administered, as a list of (a, b, c, d) tuples. Length must equal len(x).

required
x Sequence[int]

The responses, as 0/1 integers (1 = correct) in the same order as it.

required
D float

Scale constant (default 1.0).

1.0
priorDist str

The prior distribution, one of "norm" (normal), "unif" (uniform) or "Jeffreys".

'norm'
priorPar Tuple[float, float]

Prior parameters. For "norm": (mean, sd) — catR default (0, 1) (standard normal). For "unif": (lower, upper) of the uniform interval.

(0, 1)
lower float

Lower bound of the integration grid (default -4).

-4
upper float

Upper bound of the integration grid (default 4).

4
nqp int

Number of quadrature points in the grid (catR default 33).

33

Returns:

Type Description
float

The estimated ability theta (a float, always within

float

[lower, upper]).

catpie.eap.eapSem

eapSem(
    thEst: float,
    it: Sequence[Item],
    x: Sequence[int],
    D: float = 1.0,
    priorDist: str = "norm",
    priorPar: Tuple[float, float] = (0, 1),
    lower: float = -4,
    upper: float = 4,
    nqp: int = 33,
) -> float

Standard error of an EAP ability estimate.

The standard error tells you how confident you can be in the ability estimate :func:eapEst: smaller = more confidence. It is the standard deviation of the posterior distribution, computed by the same numerical integration over the grid.

Parameters:

Name Type Description Default
thEst float

The ability estimate (the output of :func:eapEst).

required
it Sequence[Item]

The administered items, as (a, b, c, d) tuples.

required
x Sequence[int]

The responses (0/1), same order as it.

required
D float

Scale constant (default 1.0).

1.0
priorDist str

Prior distribution, "norm" / "unif" / "Jeffreys".

'norm'
priorPar Tuple[float, float]

Prior parameters (see :func:eapEst).

(0, 1)
lower float

Lower bound of the integration grid (default -4).

-4
upper float

Upper bound of the integration grid (default 4).

4
nqp int

Number of quadrature points (catR default 33).

33

Returns:

Type Description
float

The standard error (a non-negative float; typically a few tenths, and

float

smaller after more informative items are administered).

catpie.estimators.thetaEst

thetaEst(
    it: Sequence[Item],
    x: Sequence[Number],
    method: str = "EAP",
    priorDist: str = "norm",
    priorPar: Tuple[float, float] = (0, 1),
    D: float = 1.0,
    range: Tuple[float, float] = (-4, 4),
    parInt: Tuple[float, float, int] = (-4, 4, 33),
) -> float

Estimate a person's ability (theta) from their responses.

This is the main estimation function. Give it the items that were administered and the person's 0/1 responses, and it returns the best estimate of their ability. The higher the ability, the "better" the person performed.

Four estimation methods are available:

  • "EAP" (default): Bayesian, most robust, uses the prior; the result always lies within the integration grid (default [-4, 4]).
  • "BM": Bayesian modal estimate (posterior maximum), uses the prior.
  • "ML": maximum likelihood; uses only the responses (no prior). Can be extreme (and is unstable on degenerate item banks, exactly like catR).
  • "WL": weighted likelihood; reduces the bias of ML.

Missing responses (NaN/None) and their items are ignored.

Parameters:

Name Type Description Default
it Sequence[Item]

The administered items as (a, b, c, d) tuples (same length as x).

required
x Sequence[Number]

The responses as 0/1 integers (1 = correct); NaN/None entries are dropped together with the corresponding items.

required
method str

One of "EAP" (default), "BM", "ML", "WL".

'EAP'
priorDist str

Prior distribution for EAP/BM: "norm" (default), "unif", "Jeffreys".

'norm'
priorPar Tuple[float, float]

Prior parameters (mean, sd) for "norm" (default (0, 1)) or (lower, upper) for "unif".

(0, 1)
D float

Scale constant (default 1.0).

1.0
range Tuple[float, float]

The search interval (lower, upper) for the BM/ML/WL root finding (default (-4, 4)). Not used by EAP.

(-4, 4)
parInt Tuple[float, float, int]

(lower, upper, npoints) of the integration grid for EAP (default (-4, 4, 33)).

(-4, 4, 33)

Returns:

Type Description
float

The estimated ability as a float (a higher value = higher estimated

float

ability). For EAP it lies within the integration grid; BM/ML/WL may

float

return a range boundary when no interior root exists (like catR).

Raises:

Type Description
ValueError

If method is not one of EAP/BM/ML/WL, or priorDist is not supported.

catpie.estimators.semTheta

semTheta(
    thEst: float,
    it: Sequence[Item],
    x: Sequence[Number],
    method: str = "EAP",
    priorDist: str = "norm",
    priorPar: Tuple[float, float] = (0, 1),
    D: float = 1.0,
    parInt: Tuple[float, float, int] = (-4, 4, 33),
    semType: str = "classic",
    range: Tuple[float, float] = (-4, 4),
) -> float

Standard error (SE) of an ability estimate.

The SE quantifies the uncertainty of an ability estimate :func:thetaEst: small SE = confident estimate, large SE = uncertain. It is used by the stopping rules (e.g. stop once se drops below a threshold) and to build confidence intervals for classification.

The method should match the one used for estimation (method=...).

Parameters:

Name Type Description Default
thEst float

The ability estimate (output of :func:thetaEst).

required
it Sequence[Item]

The administered items as (a, b, c, d) tuples.

required
x Sequence[Number]

The responses (0/1); NaN/None are dropped with their items.

required
method str

Estimation method: "EAP" (default), "BM", "ML", "WL".

'EAP'
priorDist str

Prior distribution for EAP/BM ("norm" default, "unif", "Jeffreys").

'norm'
priorPar Tuple[float, float]

Prior parameters (see :func:thetaEst).

(0, 1)
D float

Scale constant (default 1.0).

1.0
parInt Tuple[float, float, int]

Integration grid (lower, upper, npoints) for EAP (default (-4, 4, 33)).

(-4, 4, 33)
semType str

"classic" (default) or "new" (only implemented for the classic form in this port).

'classic'
range Tuple[float, float]

Accepted for catR signature parity; not used by the implemented methods.

(-4, 4)

Returns:

Type Description
float

The standard error as a non-negative float. As a rough guide, values

float

below ~0.3 are often considered "precise enough" for adaptive testing.

Raises:

Type Description
ValueError

If method is not one of EAP/BM/ML/WL or priorDist is not supported.

catpie.estimateTheta

estimateTheta(
    itemBank: Sequence[Item],
    administered: Sequence[int],
    responses: Sequence[int],
    method: str = "EAP",
    priorDist: str = "norm",
    priorPar: Tuple[float, float] = (0, 1),
    D: float = 1.0,
    range: Tuple[float, float] = (-4, 4),
    parInt: Tuple[float, float, int] = (-4, 4, 33),
    semType: str = "classic",
) -> ThetaResult

Estimate ability and its standard error from the items given so far.

This is the highest-level estimation helper: hand it the whole item bank, the indices of the items already administered, and the person's 0/1 responses, and you get back (theta, se) in one call. It is exactly the helper the EWM experiment's estimate_theta_catr(...) uses.

Parameters:

Name Type Description Default
itemBank Sequence[Item]

The full item bank, as (a, b, c, d) tuples.

required
administered Sequence[int]

0-based indices (into itemBank) of the items administered so far.

required
responses Sequence[int]

0/1 responses in the same order as administered.

required
method str

Estimation method (default "EAP"; also "BM", "ML", "WL").

'EAP'
priorDist str

Prior distribution ("norm" default).

'norm'
priorPar Tuple[float, float]

Prior parameters (default (0, 1)).

(0, 1)
D float

Scale constant (default 1.0).

1.0
range Tuple[float, float]

Search interval for BM/ML/WL (default (-4, 4)).

(-4, 4)
parInt Tuple[float, float, int]

EAP integration grid (default (-4, 4, 33)).

(-4, 4, 33)
semType str

"classic" (default) SE form.

'classic'

Returns:

Name Type Description
A ThetaResult

class:ThetaResult with fields theta and se. If no items

ThetaResult

have been administered yet, returns the prior estimate (0.0, inf).

Item selection

Pick the next, most informative item. See Concepts, section 6.

catpie.selection.nextItem

nextItem(
    itemBank: Sequence[Item],
    theta: float,
    out: Sequence[int] = (),
    criterion: str = "MFI",
    randomesque: int = 1,
    D: float = 1.0,
) -> NextItemResult

Select the next (most informative) item to administer.

This is the heart of adaptive testing: given the current ability estimate theta and the items already used (out), it picks the single item that will tell you the most about the person's true ability. You then administer that item, score the response, re-estimate ability, and repeat.

Two selection criteria are available:

  • "MFI" (default): Maximum Fisher Information — picks the item with the highest information at the current ability estimate (see :func:ii). Usually a "middle-difficulty" item around the current theta.
  • "bOpt": picks the item whose difficulty b is closest to the current ability estimate (simpler, often used early in a test).

When several items tie for the best criterion value, one of them is chosen at random (catR's randomesque = 1 behaviour).

Parameters:

Name Type Description Default
itemBank Sequence[Item]

The full item bank, a list of (a, b, c, d) tuples.

required
theta float

Current ability estimate (a float, typically [-4, 4]).

required
out Sequence[int]

Indices (0-based) of items that have already been administered; they will not be selected again. Default: none.

()
criterion str

"MFI" (default) or "bOpt".

'MFI'
randomesque int

Only the catR default 1 is supported.

1
D float

Scale constant (default 1.0).

1.0

Returns:

Name Type Description
A NextItemResult

class:NextItemResult with fields item (the 0-based index of

NextItemResult

the selected item in the bank), par (its parameters), info

NextItemResult

(the criterion value: information for MFI, |b - theta| for bOpt)

NextItemResult

and criterion.

Raises:

Type Description
ValueError

If criterion is not "MFI"/"bOpt" or randomesque is not 1.

catpie.selectNextItem

selectNextItem(
    itemBank: Sequence[Item],
    theta: float,
    administered: Sequence[int],
    criterion: str = "MFI",
    randomesque: int = 1,
    D: float = 1.0,
) -> NextItemResult

Select the next item to administer (default criterion: MFI).

High-level wrapper around :func:nextItem that makes the most common call shorter. It is exactly the helper the EWM experiment's select_next_item_catr(...) uses.

Parameters:

Name Type Description Default
itemBank Sequence[Item]

The full item bank, as (a, b, c, d) tuples.

required
theta float

Current ability estimate (a float, typically [-4, 4]).

required
administered Sequence[int]

0-based indices of the items already administered (they will not be selected again).

required
criterion str

"MFI" (default) or "bOpt".

'MFI'
randomesque int

Only the catR default 1 is supported.

1
D float

Scale constant (default 1.0).

1.0

Returns:

Name Type Description
A NextItemResult

class:NextItemResult; see :func:nextItem for its fields.

Simulation

Generate fake response patterns, check stopping rules, and run whole adaptive sessions offline. See Concepts, section 7.

catpie.simulation.genPattern

genPattern(
    theta: Union[float, Sequence[float]],
    items: Sequence[Item],
    D: float = 1.0,
    rng: Optional[Rng] = None,
) -> Union[list, list[list]]

Simulate a 0/1 response pattern for one or more abilities.

For each item, the person answers correctly (1) with probability equal to the item response function at the given ability (see :func:pi), and incorrectly (0) otherwise. This is used to generate "fake" participants for simulations and validation.

Parameters:

Name Type Description Default
theta Union[float, Sequence[float]]

The true ability level(s). A single number returns one pattern; a list/tuple of numbers returns one pattern per ability (a list of lists).

required
items Sequence[Item]

The items to respond to, as (a, b, c, d) tuples.

required
D float

Scale constant (default 1.0).

1.0
rng Optional[Rng]

Optional random source — a callable returning a float in [0, 1). Defaults to random.random. Inject a fixed function (e.g. lambda: 0.5) for reproducible tests.

None

Returns:

Type Description
Union[list, list[list]]

A list of 0/1 values (one per item) if theta is a single number,

Union[list, list[list]]

or a list of such lists (one per ability) otherwise.

catpie.simulation.simulateRespondents

simulateRespondents(
    thetas: Sequence[float],
    itemBank: Sequence[Item],
    D: float = 1.0,
    rng: Optional[Rng] = None,
) -> list[list]

Simulate responses for several respondents on a whole item bank.

Convenience wrapper around :func:genPattern: returns one 0/1 pattern per respondent, so you get a matrix of shape (respondents x items). Useful for testing item banks offline before deploying an experiment.

Parameters:

Name Type Description Default
thetas Sequence[float]

True ability of each respondent.

required
itemBank Sequence[Item]

The item bank, as (a, b, c, d) tuples.

required
D float

Scale constant (default 1.0).

1.0
rng Optional[Rng]

Optional random source (see :func:genPattern).

None

Returns:

Type Description
list[list]

A list (one entry per respondent) of 0/1 lists (one entry per item).

catpie.simulation.checkStopRule

checkStopRule(
    th: float,
    se: float,
    n: int,
    rule: Sequence[str] = ("length",),
    thr: Sequence[float] = (20,),
    alpha: float = 0.05,
    items: Optional[Sequence[Item]] = None,
    D: float = 1.0,
) -> StopRuleResult

Decide whether an adaptive test should stop.

After each administered item, call this with the current ability estimate th, its standard error se and the number of items administered n. It returns True (with the rule(s) that triggered) as soon as any of the requested stopping rules is satisfied. Rules are combined with OR.

Available rules (pass a list to rule, thresholds to thr):

  • "length": stop after thr items (e.g. rule=["length"], thr=[20]).
  • "precision": stop when the standard error se drops to thr or below (e.g. thr=[0.3]).
  • "classification": stop when the 95% confidence interval of th lies entirely above or below the threshold thr (e.g. decide whether ability is above 0).
  • "minInfo": stop when the maximum item information in the bank falls to thr or below (i.e. no remaining item can teach much). Requires items.

Parameters:

Name Type Description Default
th float

Current ability estimate.

required
se float

Current standard error (output of :func:semTheta).

required
n int

Number of items administered so far.

required
rule Sequence[str]

List of rule names ("length", "precision", "classification", "minInfo").

('length',)
thr Sequence[float]

List of thresholds, one per rule (same order as rule).

(20,)
alpha float

Significance level for the "classification" rule (default 0.05 -> 95% confidence interval).

0.05
items Optional[Sequence[Item]]

The item bank, required by the "minInfo" rule.

None
D float

Scale constant (default 1.0).

1.0

Returns:

Name Type Description
A StopRuleResult

class:StopRuleResult with fields decision (bool: whether to

StopRuleResult

stop) and rule (list of the rule names that triggered).

Raises:

Type Description
ValueError

If a rule name is unknown, or "minInfo" is used without items.

catpie.simulation.randomCAT

randomCAT(
    trueTheta: float,
    itemBank: Sequence[Item],
    method: str = "BM",
    priorDist: str = "norm",
    priorPar: tuple = (0, 1),
    D: float = 1.0,
    range: tuple = (-4, 4),
    parInt: tuple = (-4, 4, 33),
    itemSelect: str = "MFI",
    startTheta: float = 0.0,
    stop: Optional[dict] = None,
    minItems: int = 0,
    maxSteps: Optional[int] = None,
    responses: Optional[Sequence[int]] = None,
    rng: Optional[Rng] = None,
) -> RandomCatResult

Run a complete (simulated) adaptive test in one call.

This ties everything together: it repeatedly (1) selects the next item, (2) simulates (or replays) the person's response, and (3) re-estimates ability and its standard error, until a stopping rule triggers or the item bank is exhausted. Use it to validate a question bank and stopping rules offline before deploying the real experiment.

Parameters:

Name Type Description Default
trueTheta float

The person's true ability (only used when simulating responses; a number, typically [-4, 4]).

required
itemBank Sequence[Item]

The full item bank, as (a, b, c, d) tuples.

required
method str

Estimation method (default "BM"; "EAP" is the most robust).

'BM'
priorDist str

Prior distribution ("norm" default).

'norm'
priorPar tuple

Prior parameters (default (0, 1)).

(0, 1)
D float

Scale constant (default 1.0).

1.0
range tuple

Search interval for BM/ML/WL estimation (default (-4, 4)).

(-4, 4)
parInt tuple

Integration grid for EAP (default (-4, 4, 33)).

(-4, 4, 33)
itemSelect str

Item selection criterion, "MFI" (default) or "bOpt".

'MFI'
startTheta float

Ability used for the first item selection (default 0).

0.0
stop Optional[dict]

A dict with keys rule (list), thr (list) and alpha passed to :func:checkStopRule. Default: {"rule": ["length"], "thr": [20], "alpha": 0.05}.

None
minItems int

Minimum number of items to administer before stopping is considered (default 0).

0
maxSteps Optional[int]

Hard cap on the number of items (default: the bank size).

None
responses Optional[Sequence[int]]

Optional fixed 0/1 response sequence to replay instead of simulating (handy for testing against catR).

None
rng Optional[Rng]

Optional random source for simulating responses (see :func:genPattern).

None

Returns:

Name Type Description
A RandomCatResult

class:RandomCatResult with the full history: administered

RandomCatResult

(0-based item indices), responses, selected, infoHist,

RandomCatResult

thetaHist, seHist, the triggering stopRule (or None),

RandomCatResult

finalTheta/finalSe, nItems, and the method/itemSelect

RandomCatResult

used.

Result types

The named tuples that catpie returns, with their fields.

catpie.irf.PiResult

Bases: NamedTuple

4PL probability and its first three derivatives (catR Pi()).

Attributes

P instance-attribute

P: float

dP instance-attribute

dP: float

d2P instance-attribute

d2P: float

d3P instance-attribute

d3P: float

catpie.irf.IiResult

Bases: NamedTuple

Fisher information and its first two derivatives (catR Ii()).

Attributes

Ii instance-attribute

Ii: float

dIi instance-attribute

dIi: float

d2Ii instance-attribute

d2Ii: float

catpie.irf.JiResult

Bases: NamedTuple

Weighted-likelihood quantity and its derivative (catR Ji()).

Attributes

Ji instance-attribute

Ji: float

dJi instance-attribute

dJi: float

catpie.selection.NextItemResult

Bases: NamedTuple

Result of an item selection (catR nextItem()).

Attributes

item instance-attribute

item: int

par instance-attribute

par: Item

info instance-attribute

info: float

criterion instance-attribute

criterion: str

catpie.simulation.StopRuleResult

Bases: NamedTuple

Result of a stopping-rule check (catR checkStopRule()).

Attributes

decision instance-attribute

decision: bool

rule instance-attribute

rule: list

catpie.simulation.RandomCatResult

Bases: NamedTuple

Result of a minimal CAT run.

Attributes

administered instance-attribute

administered: list

responses instance-attribute

responses: list

selected instance-attribute

selected: list

infoHist instance-attribute

infoHist: list

thetaHist instance-attribute

thetaHist: list

seHist instance-attribute

seHist: list

stopRule instance-attribute

stopRule: Optional[list]

finalTheta instance-attribute

finalTheta: float

finalSe instance-attribute

finalSe: float

nItems instance-attribute

nItems: int

method instance-attribute

method: str

itemSelect instance-attribute

itemSelect: str

catpie.ThetaResult

Bases: NamedTuple

Ability estimate and its standard error (high-level helper).

Attributes

theta instance-attribute

theta: float

se instance-attribute

se: float

catpie.math.OptimizeResult

Bases: NamedTuple

Result of a scalar optimization, analogous to R's optimize().

Attributes

x instance-attribute

x: float

y instance-attribute

y: float

Numerical helpers

Small functions that mirror R's base functions. You rarely need them directly, but they are part of the public API for completeness and parity with catR.

catpie.math.dnorm

dnorm(x: Number, mean: Number = 0, sd: Number = 1) -> float

Density of the normal distribution, matching R's dnorm.

Gives the height of the normal (bell) curve at point x. Used as the "norm" prior in EAP/BM estimation.

Parameters:

Name Type Description Default
x Number

Point at which to evaluate the density.

required
mean Number

Mean of the normal distribution (default 0).

0
sd Number

Standard deviation, must be > 0 (default 1).

1

Returns:

Type Description
float

The density (a positive float; largest at x == mean).

catpie.math.linspace

linspace(start: Number, stop: Number, n: int) -> list[float]

Return n evenly spaced numbers from start to stop (inclusive).

Matches R's seq(from, to, length.out = n) exactly, including how the step is computed, so results agree with catR to the last bit. Used to build the EAP integration grid (e.g. 33 points from -4 to 4).

Parameters:

Name Type Description Default
start Number

First value.

required
stop Number

Last value.

required
n int

Number of points (>= 2).

required

Returns:

Type Description
list[float]

A list of n floats, start first and stop last.

catpie.math.integrateCatR

integrateCatR(x: Sequence[Number], y: Sequence[Number]) -> float

Integrate y over x using the trapezoid rule.

Approximates the area under the curve by summing trapezoids between consecutive points. Matches catR's integrate.catR exactly. Used to compute the EAP estimate and its standard error over the integration grid.

Parameters:

Name Type Description Default
x Sequence[Number]

The x-coordinates (must be sorted, e.g. from :func:linspace).

required
y Sequence[Number]

The function values at those coordinates (same length as x).

required

Returns:

Type Description
float

The approximate integral (a float).

catpie.math.qnorm

qnorm(p: Number, mean: Number = 0, sd: Number = 1) -> float

Quantile of the normal distribution, matching R's qnorm.

The inverse of the normal cumulative distribution: for a probability p, returns the value z such that P(Z <= z) = p for Z ~ N(mean, sd). Used by the "classification" stopping rule to build confidence intervals (e.g. qnorm(0.975) ~ 1.96 for a 95% interval).

Parameters:

Name Type Description Default
p Number

A probability in (0, 1) (0 -> -inf, 1 -> inf).

required
mean Number

Mean of the normal distribution (default 0).

0
sd Number

Standard deviation, > 0 (default 1).

1

Returns:

Type Description
float

The quantile (a float; qnorm(0.5) == mean).

catpie.math.uniroot

uniroot(
    f: Callable[[float], float],
    lower: float,
    upper: float,
    tol: float = 0.000122,
    maxIter: int = 1000,
) -> float

Find a root of f in [lower, upper] by bisection.

f must change sign over the interval (f(lower) and f(upper) must have opposite signs), which guarantees at least one root. Mirrors R's uniroot semantics and is used internally by the BM/ML/WL ability estimators. You normally do not need to call it directly.

Parameters:

Name Type Description Default
f Callable[[float], float]

A function of one variable returning a number.

required
lower float

Lower bound of the search interval.

required
upper float

Upper bound of the search interval.

required
tol float

Convergence tolerance on the interval width (default matches catR parity: about 1.22e-4).

0.000122
maxIter int

Maximum number of bisection steps (default 1000).

1000

Returns:

Type Description
float

A float x in [lower, upper] with f(x) ~ 0.

Raises:

Type Description
ValueError

If f does not change sign over the interval.

catpie.math.optimizeScalar

optimizeScalar(
    f: Callable[[float], float],
    lower: float,
    upper: float,
    maximize: bool = False,
    tol: float = 1e-12,
    maxIter: int = 200,
) -> OptimizeResult

Find the minimum (or maximum) of f on [lower, upper].

Golden-section search, analogous to R's optimize(). Used internally by the BM/ML/WL ability estimators as a fallback when the score equation has no sign change; you normally do not need to call it directly.

Parameters:

Name Type Description Default
f Callable[[float], float]

A function of one variable returning a number.

required
lower float

Lower bound of the search interval.

required
upper float

Upper bound of the search interval.

required
maximize bool

If True, find the maximum instead of the minimum.

False
tol float

Convergence tolerance on the interval width (default 1e-12).

1e-12
maxIter int

Maximum number of iterations (default 200).

200

Returns:

Name Type Description
An OptimizeResult

class:OptimizeResult with fields x (the location of the

OptimizeResult

optimum) and y (the function value there, i.e. f(x)).