Source code for irtlib.plot._screening

"""Plots that screen a response matrix: its numbers correct, its items' rest score curves and classical statistics."""

import numpy
import numpy.typing as npt
from matplotlib.axes import Axes

from .._responses import response_matrix
from ..ability import NumberCorrectEstimates
from ..bank import _generated_names
from ..classical import _rest_scores, item_rest_correlation, proportion_correct
from ..typing import FloatArray, IntArray
from ._common import integer_ticks, item_position, number_correct_axis, prepare_axes, reference_style

_BAR_WIDTH = 0.8
"""The width of a bar at each number correct, which leaves a gap between neighbouring numbers."""
_SMOOTH_POINTS = 201
"""The rest scores a kernel smooth is evaluated at, evenly spaced from the lowest to the highest."""
_BANDWIDTH_FACTOR = 1.06
"""The factor of the rule-of-thumb bandwidth, 1.06 s n^(-1/5), of Mazza, Punzo and McGuire (2014, p. 6, Equation 5)."""
_MIN_SMOOTH_SCORES = 2
"""The fewest distinct rest scores a kernel smooth needs: with one, their standard deviation and bandwidth are 0."""


[docs] def number_correct_histogram( responses: npt.ArrayLike, *, expected: NumberCorrectEstimates | None = None, ax: Axes | None = None, title: str | None = None, label: str | None = None, ) -> Axes: """Plot how many examinees got each number correct, from 0 to the number of items, and how many a model expects. An examinee's number correct counts the items answered correctly, and every number from 0 to the number of items has a bar, empty or not. With ``expected``, dots joined by a line mark the number of examinees the model expects at each number correct, its probability times the number of examinees, both labelled for a legend; the :doc:`/methods/ability/number-correct-eap` page gives the probabilities. .. plot:: :filename-prefix: number_correct_histogram :caption: 1,000 examinees on a 20-item test, against the counts a 2PL calibration of their responses expects. import matplotlib.pyplot as plt import numpy from irtlib import ItemBank from irtlib.ability import number_correct_eap from irtlib.drawing import draw_responses from irtlib.mml import MMLCalibrator from irtlib.plot import number_correct_histogram items = ItemBank.generate(20, "2PL", rng=0) theta = numpy.random.default_rng(1).normal(0, 1, 1000) responses = draw_responses(theta, items.items, rng=2) calibration = MMLCalibrator("2PL").calibrate(responses) expected = number_correct_eap(calibration.estimates, grid=calibration.grid) number_correct_histogram(responses, expected=expected) plt.show() Parameters ---------- responses : array_like The response matrix, one row per examinee and one column per item: 1 or True for a correct response, 0 or False for an incorrect one, and NaN for a missing one, which ``expected`` does not allow. expected : irtlib.ability.NumberCorrectEstimates or None, optional The model's estimates by number correct on the same items, such as ``number_correct_eap(calibration.estimates, grid=calibration.grid)``, whose probabilities give the counts the model expects. Default is None, which draws the observed counts alone. ax : matplotlib.axes.Axes or None, optional The axes to draw on. Default is None, which draws on the axes of a new figure. title : str or None, optional The plot title. Default is None, which sets none. label : str or None, optional The bars' label, for a legend. Default is None, which sets none, or "Observed" with ``expected``. Returns ------- matplotlib.axes.Axes The axes the bars are on. Raises ------ TypeError If the responses are neither Booleans, integers nor floats, before any figure is created. ValueError If ``responses`` is not a matrix with at least one row and one column, or a response is not 0, 1 or NaN; or, with ``expected``, a response is missing or ``expected`` is not of the same number of items, before any figure is created. """ matrix = response_matrix(responses) if matrix.shape[0] == 0: msg = "responses has no rows; pass the responses of at least one examinee" raise ValueError(msg) n_items = matrix.shape[1] if n_items == 0: msg = "responses has no columns; pass the responses to at least one item" raise ValueError(msg) if expected is not None: _check_expected(matrix, expected) counts = numpy.bincount(numpy.nansum(matrix, axis=1).astype(int), minlength=n_items + 1) scores = numpy.arange(n_items + 1) if label is None and expected is not None: label = "Observed" ax = prepare_axes(ax, title) ax.bar(scores, counts, _BAR_WIDTH, label=label) if expected is not None: # The bars and a line take the first colour of their cycles alike, so the line takes the axes' edge colour. expected_counts = matrix.shape[0] * expected.probability ax.plot(scores, expected_counts, "o-", color=reference_style(ax)[0], label="Expected") ax.legend() number_correct_axis(ax, n_items) ax.set_ylabel("Examinees") return ax
[docs] def item_statistics( responses: npt.ArrayLike, *, ax: Axes | None = None, title: str | None = None, label: str | None = None ) -> Axes: """Plot each item's item-rest correlation against its proportion correct, one dot per item. An item whose proportion correct or item-rest correlation is undefined, NaN, is left out. The :doc:`/methods/classical` page gives both statistics. .. plot:: :filename-prefix: item_statistics :caption: The 20 items of a test taken by 1,000 examinees, item 3 miskeyed. import matplotlib.pyplot as plt import numpy from irtlib import ItemBank from irtlib.drawing import draw_responses from irtlib.plot import item_statistics items = ItemBank.generate(20, "3PL", rng=0) theta = numpy.random.default_rng(1).normal(0, 1, 1000) responses = draw_responses(theta, items.items, rng=2) responses[:, 3] = 1 - responses[:, 3] item_statistics(responses) plt.show() Parameters ---------- responses : array_like The response matrix, one row per examinee and one column per item: 1 or True for a correct response, 0 or False for an incorrect one, and NaN for a missing one. ax : matplotlib.axes.Axes or None, optional The axes to draw on. Default is None, which draws on the axes of a new figure. title : str or None, optional The plot title. Default is None, which sets none. label : str or None, optional The dots' label, for a legend. Default is None, which sets none. Returns ------- matplotlib.axes.Axes The axes the dots are on. Raises ------ TypeError If the responses are neither Booleans, integers nor floats, before any figure is created. ValueError If ``responses`` is not a matrix, a response is not 0, 1 or NaN, or no item has both statistics, before any figure is created. """ proportions, correlations = proportion_correct(responses), item_rest_correlation(responses) defined = numpy.isfinite(proportions) & numpy.isfinite(correlations) if not defined.any(): msg = "no item has both a proportion correct and an item-rest correlation; there is no dot to draw" raise ValueError(msg) ax = prepare_axes(ax, title) ax.plot(proportions[defined], correlations[defined], "o", label=label) ax.set_xlabel("Proportion correct") ax.set_ylabel("Item-rest correlation") return ax
[docs] def rest_score_curve( responses: npt.ArrayLike, item: int, *, smooth: bool = False, ax: Axes | None = None, title: str | None = None, label: str | None = None, ) -> Axes: """Plot an item's proportion correct at each rest score, the number correct on the other items. Only examinees who answered the item count; a missing response elsewhere adds nothing to a rest score (:doc:`/methods/classical`). Each rest score some examinee has is a dot, joined in order. With ``smooth``, the dots stand alone and a line in their colour is the kernel smooth of :cite:t:`Mazza2014` (pp. 3-6), over rest scores rather than ability estimates, with their sample standard deviation in the bandwidth. .. plot:: :filename-prefix: rest_score_curve :caption: An item with a guessing parameter of 0.25, on a 15-item test taken by 3,000 examinees. import matplotlib.pyplot as plt import numpy from irtlib import ItemBank from irtlib.drawing import draw_responses from irtlib.plot import rest_score_curve items = ItemBank.generate(15, "2PL", rng=0).items.copy() items[0, 2] = 0.25 theta = numpy.random.default_rng(1).normal(0, 1, 3000) rest_score_curve(draw_responses(theta, items, rng=2), 0, smooth=True) plt.show() Parameters ---------- responses : array_like The response matrix, one row per examinee and one column per item: 1 or True for a correct response, 0 or False for an incorrect one, and NaN for a missing one. item : int The item's position, its column in ``responses``. smooth : bool, optional Whether to draw the kernel smooth, in place of the lines that join the dots. Default is False. ax : matplotlib.axes.Axes or None, optional The axes to draw on. Default is None, which draws on the axes of a new figure. title : str or None, optional The plot title. Default is None, which sets none. label : str or None, optional The curve's label, for a legend, on the smooth when there is one. Default is None, which names the item by its position, as a bank built from the item matrix does. Returns ------- matplotlib.axes.Axes The axes the curve is on. Raises ------ TypeError If the responses are neither Booleans, integers nor floats, or ``item`` is not an integer, before any figure is created. ValueError If ``responses`` is not a matrix, a response is not 0, 1 or NaN, ``item`` is not a column of it, no examinee answered the item, or, with ``smooth``, the rest scores take a single value, before any figure is created. """ matrix = response_matrix(responses) n_items = matrix.shape[1] item = item_position("item", item, n_items) answered = ~numpy.isnan(matrix[:, item]) if not answered.any(): msg = f"no examinee answered item {item}; its proportion correct is undefined at every rest score" raise ValueError(msg) rest = _rest_scores(matrix)[answered, item].astype(int) examinees = numpy.bincount(rest, minlength=n_items) right = numpy.bincount(rest, weights=matrix[answered, item], minlength=n_items) scores = numpy.flatnonzero(examinees) if smooth and scores.size < _MIN_SMOOTH_SCORES: msg = f"the rest scores of item {item} take the single value {scores[0]}; there is nothing to smooth" raise ValueError(msg) label = _generated_names(n_items)[item] if label is None else label ax = prepare_axes(ax, title) (dots,) = ax.plot(scores, right[scores] / examinees[scores], "o" if smooth else "o-", label=None if smooth else label) if smooth: span = numpy.linspace(scores[0], scores[-1], _SMOOTH_POINTS) ax.plot(span, _kernel_smooth(scores, examinees[scores], right[scores], span), color=dots.get_color(), label=label) integer_ticks(ax.xaxis) ax.set_xlabel("Rest score") ax.set_ylabel("Proportion correct") return ax
def _check_expected(matrix: FloatArray, expected: NumberCorrectEstimates) -> None: """Check that a model's estimates by number correct fit a complete response matrix, raising ValueError if not.""" if numpy.isnan(matrix).any(): row, column = (int(index) for index in numpy.argwhere(numpy.isnan(matrix))[0]) msg = f"responses[{row}, {column}] is missing; the counts a model expects are of examinees who answered every item" raise ValueError(msg) if expected.probability.shape != (matrix.shape[1] + 1,): msg = ( f"expected has the probabilities of {expected.probability.size} numbers correct, and responses has " f"{matrix.shape[1]} items; it needs one for each number from 0 to {matrix.shape[1]}" ) raise ValueError(msg) def _kernel_smooth(scores: IntArray, examinees: IntArray, right: FloatArray, span: FloatArray) -> FloatArray: """Return the Nadaraya-Watson regression of the responses on the rest scores at each point of ``span``. It is Ramsay's (1991) estimator as Mazza et al. (2014, pp. 3-4, Equations 1-3) describe it, with a Gaussian kernel (p. 4) and the bandwidth 1.06 s n^(-1/5) (p. 6, Equation 5). ``examinees`` and ``right`` count, at each rest score of ``scores``, the examinees and the correct responses, so each of Equation 3's sums over the examinees is a sum over the rest scores. It departs from them twice. The regression runs on the rest scores, where theirs runs on ordinal ability estimates, normal quantiles of the ranks of the total score (pp. 4-5). And s is the rest scores' sample standard deviation, with divisor n - 1, irtlib's choice where Equation 5 takes the ability's standard deviation and names no divisor (p. 6). Returns ------- numpy.ndarray The smooth's proportion correct at each point of ``span``. """ n = examinees.sum() mean = (scores * examinees).sum() / n spread = numpy.sqrt((examinees * (scores - mean) ** 2).sum() / (n - 1)) bandwidth = _BANDWIDTH_FACTOR * spread * n ** (-1 / 5) log_kernel = -0.5 * ((span[:, numpy.newaxis] - scores[numpy.newaxis, :]) / bandwidth) ** 2 # Each point's largest kernel weight is set to 1 before the sums, so that no point's weights all underflow to 0. weights = numpy.exp(log_kernel - log_kernel.max(axis=1, keepdims=True)) return (weights @ right) / (weights @ examinees)