"""The files of a response matrix, of ability estimates and of a calibration (ADR-0018).
The response matrix and the ability estimates go to CSV files in the item bank's conventions
(:py:meth:`ItemBank.to_csv <irtlib.ItemBank.to_csv>`), gzip-compressed when the path ends in ``.gz``; a missing
response is written ``NA``, and a number that is not finite ``Inf``, ``-Inf`` or ``NaN``, as R writes them. A
calibration goes to a NumPy ``.npz`` file, read without unpickling. The names of a file's items and examinees are
returned beside what is read, and given to the function that writes.
"""
import builtins
import math
import os
import re
import zipfile
from dataclasses import fields
from importlib.metadata import version
from pathlib import Path
from types import NoneType
from typing import Any, get_args
import numpy
import numpy.typing as npt
from numpy.lib.npyio import NpzFile
from scipy.integrate import IntegrationWarning
from . import _csv
from ._responses import response_matrix
from .ability import AbilityEstimates
from .bank import ItemBank, _generated_names, _index_names
from .calibration import Calibration, ConvergenceWarning
from .mcmc import MCMCCalibration
from .quadrature import QuadratureGrid
from .typing import FloatArray
_FORMAT = 1
"""The format number of a calibration file, which goes up with every change that an earlier reader cannot read."""
_CALIBRATIONS = {kind.__name__: kind for kind in (Calibration, MCMCCalibration)}
"""The classes a calibration file holds, by name."""
_ABILITY_COLUMNS = ("theta", "standard_errors", "evaluations", "from_fallback", "warnings")
"""The columns of an abilities file besides its name column, named as the attributes of the estimates."""
_TRUE, _FALSE = ("True", "TRUE", "true"), ("False", "FALSE", "false")
"""The Booleans of a CSV file, as Python and R write them."""
_CONTINUED = " "
"""The indent of a line of a warning's message after its first, in an abilities file."""
_WARNING_LINE = re.compile(r"([A-Za-z_]\w*): (.*)", flags=re.DOTALL)
"""A line of an abilities file's warnings that starts a warning: its category, a colon, and its message."""
_CATEGORIES: dict[str, type[Warning]] = {
**{name: kind for name, kind in vars(builtins).items() if isinstance(kind, type) and issubclass(kind, Warning)},
"ConvergenceWarning": ConvergenceWarning,
"IntegrationWarning": IntegrationWarning,
}
"""The categories of warning a file restores by name: Python's own, and those irtlib issues."""
[docs]
def read_responses(path: str | os.PathLike[str]) -> tuple[FloatArray, tuple[str, ...], tuple[str, ...] | None]:
"""Read a response matrix, with its items' and examinees' names, from a CSV file.
The header names the items, one column each. A first column headed ``name`` or left empty, as R's ``write.csv``
heads row names, holds the examinees' names, so the first item cannot be named ``name``. Each following row is one
examinee, whose responses are ``0``, ``1``, or, for a missing one, an empty field, ``NA`` or ``NaN``. Only blank
lines at the end of the file are skipped, and a path ending in ``.gz`` is read as a gzip-compressed file.
Parameters
----------
path : str or os.PathLike
The file to read.
Returns
-------
tuple[numpy.ndarray, tuple of str, tuple of str or None]
The response matrix, one row per examinee and NaN for a missing response; the items' names; and the
examinees' names, None without a name column.
Raises
------
ValueError
If the file is empty; its item names are not unique and non-empty; a row does not hold one value per column; or
a response is not one of the values above.
"""
path = Path(path)
header, rows = _csv.read(path, "a response file")
named = bool(header) and header[0] in _csv.NAME_HEADERS
names = header[1:] if named else header
try:
_index_names(names, len(names))
except ValueError as error:
msg = f"{path}: {error}"
raise ValueError(msg) from error
matrix = numpy.empty((len(rows), len(names)), dtype=float)
for examinee, (line, row) in enumerate(rows):
_csv.check_length(path, line, row, header)
for item, text in enumerate(row[1:] if named else row):
value = _csv.parse(text)
if value is None or not (math.isnan(value) or value in {0.0, 1.0}):
msg = (
f"{path}, line {line}, column {names[item]!r}: {text!r} is not 0, 1, or empty or NA for a missing response"
)
raise ValueError(msg)
matrix[examinee, item] = value
return matrix, tuple(names), tuple(row[0] for _, row in rows) if named else None
[docs]
def write_responses(
path: str | os.PathLike[str],
responses: npt.ArrayLike,
item_names: tuple[str, ...] | list[str] | None = None,
examinee_names: tuple[str, ...] | list[str] | None = None,
) -> None:
"""Write a response matrix to a CSV file that :py:func:`read_responses` reads back.
The header names the items, after a ``name`` column when the examinees have names. A response is written as ``0``
or ``1``, and a missing one as ``NA``. A path ending in ``.gz`` is written gzip-compressed, and an existing file is
overwritten.
Parameters
----------
path : str or os.PathLike
The file to write.
responses : array_like
The response matrix: one row per examinee, one column per item, holding 1, 0 or NaN.
item_names : sequence of str, optional
One name per item, unique and non-empty, the first not ``name`` when the examinees have no names. Default is
None, which names each item ``item_`` followed by its index, as :py:class:`irtlib.ItemBank` does.
examinee_names : sequence of str, optional
One name per examinee. Default is None, which writes no name column.
Raises
------
TypeError
If the responses are neither Booleans, integers nor floats, or an item name is not a string.
ValueError
If the responses are not a matrix of 1, 0 and NaN; the item names are not one unique, non-empty name per item,
or the first is ``name`` without examinee names; or the examinee names are not one per examinee.
"""
matrix = response_matrix(responses)
n_examinees, n_items = matrix.shape
names = _generated_names(n_items) if item_names is None else list(item_names)
_index_names(names, n_items)
examinees = _row_names(examinee_names, n_examinees, "examinee")
if not examinees and names[:1] == ["name"]:
msg = (
"the first item is named 'name', which heads the examinees' names in a response file; "
"rename it, or give examinee names"
)
raise ValueError(msg)
rows = (
[*examinees[row : row + 1], *("NA" if math.isnan(value) else str(int(value)) for value in values)]
for row, values in enumerate(matrix.tolist())
)
_csv.write(Path(path), [*(["name"] if examinees else []), *names], rows)
[docs]
def read_abilities(path: str | os.PathLike[str]) -> tuple[AbilityEstimates, tuple[str, ...] | None]:
"""Read ability estimates, with their examinees' names, from a CSV file that :py:func:`write_abilities` writes.
The header names the columns, in any order: ``theta``, ``standard_errors``, ``evaluations``, ``from_fallback`` and
``warnings``, and an optional name column headed ``name`` or left empty. Each following row is one examinee. A
number may be ``Inf``, ``-Inf``, ``NaN`` or ``NA``; ``from_fallback`` is ``True`` or ``False``, in any of R's and
Python's spellings; ``warnings`` holds one warning per line, its category, a colon and its message, a line of the
message after its first indented by two spaces. A warning of a category irtlib cannot name is read as a
:py:class:`Warning`. A path ending in ``.gz`` is read as a
gzip-compressed file.
Parameters
----------
path : str or os.PathLike
The file to read.
Returns
-------
tuple[irtlib.ability.AbilityEstimates, tuple of str or None]
The estimates, and the examinees' names, None without a name column.
Raises
------
ValueError
If the file is empty; its header lacks a column, names one twice or names an unknown one; or a row does not
hold one value per column, or holds a value of the wrong kind.
"""
path = Path(path)
header, rows = _csv.read(path, "an abilities file")
name_position, positions = _ability_header(header, path)
thetas: list[float] = []
errors: list[float] = []
evaluations: list[int] = []
fallbacks: list[bool] = []
found: list[tuple[Warning, ...]] = []
for line, row in rows:
_csv.check_length(path, line, row, header)
where = f"{path}, line {line}, column"
thetas.append(_number(row[positions["theta"]], f"{where} 'theta'"))
errors.append(_number(row[positions["standard_errors"]], f"{where} 'standard_errors'"))
evaluations.append(_count(row[positions["evaluations"]], f"{where} 'evaluations'"))
fallbacks.append(_boolean(row[positions["from_fallback"]], f"{where} 'from_fallback'"))
found.append(_read_warnings(row[positions["warnings"]]))
abilities = AbilityEstimates(
theta=numpy.array(thetas, dtype=float),
standard_errors=numpy.array(errors, dtype=float),
evaluations=numpy.array(evaluations, dtype=int),
from_fallback=numpy.array(fallbacks, dtype=bool),
warnings=tuple(found),
)
return abilities, None if name_position is None else tuple(row[name_position] for _, row in rows)
[docs]
def write_abilities(
path: str | os.PathLike[str], abilities: AbilityEstimates, names: tuple[str, ...] | list[str] | None = None
) -> None:
"""Write ability estimates to a CSV file that :py:func:`read_abilities` reads back.
The header is ``theta,standard_errors,evaluations,from_fallback,warnings``, after a ``name`` column when the
examinees have names. Each number is written with the fewest digits that read back as the same float, and as
``Inf``, ``-Inf`` or ``NaN`` when it is not finite. Each warning is written on its own line of the ``warnings``
field, as its category, a colon and its message, a line of the message after its first indented by two spaces. A
path ending in ``.gz`` is written gzip-compressed, and an existing file is overwritten.
Parameters
----------
path : str or os.PathLike
The file to write.
abilities : irtlib.ability.AbilityEstimates
The estimates.
names : sequence of str, optional
One name per examinee. Default is None, which writes no name column.
Raises
------
ValueError
If ``names`` does not hold one name per examinee.
"""
examinees = _row_names(names, abilities.theta.size, "examinee")
rows = (
[
*examinees[row : row + 1],
_csv.number(theta),
_csv.number(error),
str(int(evaluations)),
str(bool(fallback)),
_warnings_text(found),
]
for row, (theta, error, evaluations, fallback, found) in enumerate(
zip(
abilities.theta.tolist(),
abilities.standard_errors.tolist(),
abilities.evaluations.tolist(),
abilities.from_fallback.tolist(),
abilities.warnings,
strict=True,
)
)
)
_csv.write(Path(path), [*(["name"] if examinees else []), *_ABILITY_COLUMNS], rows)
[docs]
def write_calibration(path: str | os.PathLike[str], calibration: Calibration) -> None:
"""Write a calibration, every attribute of it, to a NumPy ``.npz`` file that :py:func:`read_calibration` reads.
Each array is stored under its attribute's name. The bank is stored as its item matrix and names, the grid as its
nodes and weights, and a joint calibration's abilities as their arrays, with each examinee's warnings as text. The
file also records the calibration's class, irtlib's version and the file's format number. The file is written at
``path`` as given, without a suffix added, and an existing file is overwritten.
Parameters
----------
path : str or os.PathLike
The file to write.
calibration : irtlib.calibration.Calibration
The calibration, by any method; a Markov chain Monte Carlo calibration keeps its draws.
Raises
------
TypeError
If ``calibration`` is neither a :py:class:`~irtlib.calibration.Calibration` nor a
:py:class:`~irtlib.mcmc.MCMCCalibration`.
"""
kind = type(calibration).__name__
if _CALIBRATIONS.get(kind) is not type(calibration):
msg = f"write_calibration writes a Calibration or an MCMCCalibration, got {kind}"
raise TypeError(msg)
arrays = {
"format": numpy.array(_FORMAT),
"class": numpy.array(kind),
"irtlib_version": numpy.array(version("irtlib")),
}
for field in fields(calibration):
arrays |= _arrays(field.name, getattr(calibration, field.name))
with Path(path).open("wb") as file:
numpy.savez_compressed(file, allow_pickle=False, **arrays)
[docs]
def read_calibration(path: str | os.PathLike[str]) -> Calibration:
"""Read a calibration from a file that :py:func:`write_calibration` writes, as the class that wrote it.
The file is read without unpickling, so it cannot run code. Every object is built again through its constructor,
which checks it as it does any other.
Parameters
----------
path : str or os.PathLike
The file to read.
Returns
-------
irtlib.calibration.Calibration
The calibration, an :py:class:`~irtlib.mcmc.MCMCCalibration` when one was written.
Raises
------
ValueError
If the file is not a calibration file, truncated ones included, holds an object array, is of a format number
this version of irtlib does not read, or lacks an attribute of its class.
"""
# opened here, so that it closes when NumPy cannot read it
with Path(path).open("rb") as file:
try:
loaded = numpy.load(file, allow_pickle=False)
except zipfile.BadZipFile as error:
msg = f"{path} is not a calibration file: {error}"
raise ValueError(msg) from error
if not isinstance(loaded, NpzFile):
msg = f"{path} is not a calibration file: it holds a single array, not the arrays of an .npz file"
raise ValueError(msg) # noqa: TRY004 - the file's content is wrong, not the argument's type
with loaded:
stored = {key: loaded[key] for key in loaded.files}
if "format" not in stored or "class" not in stored:
msg = f"{path} is not a calibration file: it records no format number or class"
raise ValueError(msg)
number = int(stored["format"])
if number != _FORMAT:
msg = f"{path} is a calibration file of format {number}; this version of irtlib reads format {_FORMAT}"
raise ValueError(msg)
kind = _CALIBRATIONS.get(str(stored["class"]))
if kind is None:
msg = f"{path} holds a {stored['class']}, which is not a calibration irtlib reads"
raise ValueError(msg)
# Any: the values come from a file, and the constructor checks them
try:
values: dict[str, Any] = {field.name: _value(field.name, stored) for field in fields(kind)}
except KeyError as error:
msg = f"{path} lacks the array {error} of its {kind.__name__}"
raise ValueError(msg) from error
missing = [
field.name for field in fields(kind) if values[field.name] is None and NoneType not in get_args(field.type)
]
if missing:
msg = f"{path} lacks the {', '.join(missing)} of its {kind.__name__}"
raise ValueError(msg)
return kind(**values)
def _row_names(names: tuple[str, ...] | list[str] | None, n_rows: int, noun: str) -> list[str]:
"""Return the names of a file's rows, an empty list for none, after checking that there is one per row."""
if names is None:
return []
given = list(names)
if len(given) != n_rows:
msg = f"{len(given)} {noun} names for {n_rows} {noun}s; give one name per {noun}"
raise ValueError(msg)
return given
def _ability_header(header: list[str], path: Path) -> tuple[int | None, dict[str, int]]:
"""Return the position of an abilities file's name column, or None, and each other column's position."""
name_position: int | None = None
positions: dict[str, int] = {}
for position, column in enumerate(header):
if column in _csv.NAME_HEADERS and name_position is None:
name_position = position
elif column in _ABILITY_COLUMNS and column not in positions:
positions[column] = position
else:
msg = (
f"{path} has an unknown or repeated column {column!r}; its header names the columns "
f"{', '.join(_ABILITY_COLUMNS)} once each, and an optional name column headed 'name' or ''"
)
raise ValueError(msg)
missing = [column for column in _ABILITY_COLUMNS if column not in positions]
if missing:
msg = f"{path} has no {', '.join(repr(column) for column in missing)} column"
raise ValueError(msg)
return name_position, positions
def _number(text: str, where: str) -> float:
"""Return the number a field holds, after checking that it holds one."""
value = _csv.parse(text)
if value is None:
msg = f"{where}: {text!r} is not a number"
raise ValueError(msg)
return value
def _count(text: str, where: str) -> int:
"""Return the count a field holds, after checking that it holds digits alone."""
if not text.isascii() or not text.isdigit():
msg = f"{where}: {text!r} is not a count"
raise ValueError(msg)
return int(text)
def _boolean(text: str, where: str) -> bool:
"""Return the Boolean a field holds, after checking that it holds one."""
if text in _TRUE:
return True
if text in _FALSE:
return False
msg = f"{where}: {text!r} is not True or False"
raise ValueError(msg)
def _warnings_text(found: tuple[Warning, ...]) -> str:
"""Return an examinee's warnings as text, one per line: its category, a colon, and its message, indented after."""
return "\n".join(f"{type(warning).__name__}: " + str(warning).replace("\n", f"\n{_CONTINUED}") for warning in found)
def _read_warnings(text: str) -> tuple[Warning, ...]:
"""Return the warnings of the text :py:func:`_warnings_text` writes, an indented line continuing the last."""
found: list[tuple[type[Warning], str]] = []
for line in text.split("\n") if text else []:
if line.startswith(_CONTINUED) and found:
found[-1] = (found[-1][0], f"{found[-1][1]}\n{line.removeprefix(_CONTINUED)}")
continue
start = _WARNING_LINE.fullmatch(line)
category, message = (start.group(1), start.group(2)) if start is not None else ("Warning", line)
found.append((_CATEGORIES.get(category, Warning), message))
return tuple(category(message) for category, message in found)
def _arrays(name: str, value: object) -> dict[str, numpy.ndarray]:
"""Return the arrays that store an attribute of a calibration in its file, none when it is None."""
match value:
case None:
return {}
case ItemBank():
return {f"{name}.items": value.items, f"{name}.names": numpy.array(value.names)}
case QuadratureGrid():
return {f"{name}.nodes": value.nodes, f"{name}.weights": value.weights}
case AbilityEstimates():
arrays = {
f"{name}.{field.name}": getattr(value, field.name) for field in fields(value) if field.name != "warnings"
}
return arrays | {f"{name}.warnings": numpy.array([_warnings_text(found) for found in value.warnings], dtype=str)}
case _:
return {name: numpy.asarray(value)}
def _value(name: str, stored: dict[str, numpy.ndarray]) -> object:
"""Return a calibration's attribute from the arrays of its file, None when they hold none."""
if name in stored:
array = stored[name]
return array.item() if array.ndim == 0 else array
if f"{name}.items" in stored:
return ItemBank(stored[f"{name}.items"], names=stored[f"{name}.names"].tolist())
if f"{name}.nodes" in stored:
return QuadratureGrid(nodes=stored[f"{name}.nodes"], weights=stored[f"{name}.weights"])
if f"{name}.theta" in stored:
return AbilityEstimates(
theta=stored[f"{name}.theta"],
standard_errors=stored[f"{name}.standard_errors"],
evaluations=stored[f"{name}.evaluations"],
from_fallback=stored[f"{name}.from_fallback"],
warnings=tuple(_read_warnings(text) for text in stored[f"{name}.warnings"].tolist()),
)
return None