Skip to content

Reference checks

check

Checking an experiment's results against stored reference results.

An experiment may name a reference file (reference "PATH" @blake3:...) and pin the tolerances of the comparison (tolerance mean = 0.05, sd = 0.1), as posteriordb stores reference posteriors to test inference against. check_experiment compares every point's run with the reference's point of the same swept values:

  • for a fit, every site's posterior mean and standard deviation, elementwise: the fitted mean must lie within mean reference standard deviations of the reference mean, and the fitted standard deviation within sd times the reference standard deviation of it;
  • for a run, the value, elementwise, within the absolute tolerance value; a value that is not a number must be equal.

Every statistic compared needs a pinned tolerance, so a comparison never falls back to a default. write_reference stores the current results as a reference file and returns the pin to write.

REFERENCE_FORMAT module-attribute

REFERENCE_FORMAT = 'qvr-experiment-reference/v1'

The format of a reference file.

Statistic

Statistic = Literal['mean', 'sd', 'value']

A compared statistic.

Comparison didactic-model

Comparison(*, site: str, statistic: Statistic, position: tuple[int, ...], fitted: float | str, reference: float | str, bound: float, passed: bool)

Bases: Model

One compared number.

PARAMETER DESCRIPTION
site

The site compared, or empty for a run's value.

TYPE: str

statistic

What is compared.

TYPE: Statistic

position

The element's position in the statistic's tensor.

TYPE: tuple[int, ...]

fitted

The experiment's number (or a non-numeric value, as JSON).

TYPE: float | str

reference

The reference's.

TYPE: float | str

bound

The largest difference accepted.

TYPE: float

passed

Whether the difference is within the bound.

TYPE: bool

PointCheck didactic-model

PointCheck(*, label: str, comparisons: tuple[Comparison, ...])

Bases: Model

The comparison of one point with the reference.

PARAMETER DESCRIPTION
label

The point's swept values.

TYPE: str

comparisons

Every compared number.

TYPE: tuple[Comparison, ...]

passed property

passed: bool

Whether every comparison passed.

RETURNS DESCRIPTION
bool

True when none failed.

CheckReport didactic-model

CheckReport(*, experiment: str, reference: str, points: tuple[PointCheck, ...])

Bases: Model

The comparison of an experiment with its reference.

PARAMETER DESCRIPTION
experiment

The experiment.

TYPE: str

reference

The reference file.

TYPE: str

points

One check per point.

TYPE: tuple[PointCheck, ...]

passed property

passed: bool

Whether every point passed.

RETURNS DESCRIPTION
bool

True when every comparison of every point passed.

reference_data

reference_data(plan: ExperimentPlan, runs: Sequence[PointRun]) -> JsonValue

The reference file content of an experiment's current results.

PARAMETER DESCRIPTION
plan

The experiment.

TYPE: ExperimentPlan

runs

Its runs.

TYPE: Sequence[PointRun]

RETURNS DESCRIPTION
JsonValue

The reference: one entry per point with its swept values and its posterior means and standard deviations (a fit) or value (a run).

Source code in src/quivers/experiments/check.py
def reference_data(plan: ExperimentPlan, runs: Sequence[PointRun]) -> JsonValue:
    """The reference file content of an experiment's current results.

    Parameters
    ----------
    plan : ExperimentPlan
        The experiment.
    runs : Sequence[PointRun]
        Its runs.

    Returns
    -------
    JsonValue
        The reference: one entry per point with its swept values and its
        posterior means and standard deviations (a fit) or value (a run).
    """
    return {
        "format": REFERENCE_FORMAT,
        "experiment": plan.name,
        "kind": plan.kind,
        "points": [
            {"values": _point_values(run.record), **_results(run.record)}
            for run in runs
        ],
    }

write_reference

write_reference(plan: ExperimentPlan, runs: Sequence[PointRun], path: str | Path) -> str

Store an experiment's current results as its reference file.

PARAMETER DESCRIPTION
plan

The experiment.

TYPE: ExperimentPlan

runs

Its runs.

TYPE: Sequence[PointRun]

path

The reference file to write.

TYPE: str | Path

RETURNS DESCRIPTION
str

The pin to write after the reference's path, @blake3:<digest>.

Source code in src/quivers/experiments/check.py
def write_reference(
    plan: ExperimentPlan, runs: Sequence[PointRun], path: str | Path
) -> str:
    """Store an experiment's current results as its reference file.

    Parameters
    ----------
    plan : ExperimentPlan
        The experiment.
    runs : Sequence[PointRun]
        Its runs.
    path : str | Path
        The reference file to write.

    Returns
    -------
    str
        The pin to write after the reference's path, ``@blake3:<digest>``.
    """
    data = (
        json.dumps(
            reference_data(plan, runs), indent=2, sort_keys=True, allow_nan=False
        )
        + "\n"
    ).encode("utf-8")
    Path(path).write_bytes(data)
    return render_pin(file_digest(data))

check_experiment

check_experiment(plan: ExperimentPlan, runs: Sequence[PointRun]) -> CheckReport

Compare an experiment's runs with its pinned reference.

PARAMETER DESCRIPTION
plan

The experiment.

TYPE: ExperimentPlan

runs

Its runs, one per point.

TYPE: Sequence[PointRun]

RETURNS DESCRIPTION
CheckReport

Every comparison, with whether it passed.

RAISES DESCRIPTION
ExperimentError

With code experiment-reference if the experiment names no reference, the reference is unpinned or its pin does not match, it is not a reference of this experiment's kind, it lacks a point, or a compared statistic has no pinned tolerance.

Source code in src/quivers/experiments/check.py
def check_experiment(plan: ExperimentPlan, runs: Sequence[PointRun]) -> CheckReport:
    """Compare an experiment's runs with its pinned reference.

    Parameters
    ----------
    plan : ExperimentPlan
        The experiment.
    runs : Sequence[PointRun]
        Its runs, one per point.

    Returns
    -------
    CheckReport
        Every comparison, with whether it passed.

    Raises
    ------
    ExperimentError
        With code ``experiment-reference`` if the experiment names no
        reference, the reference is unpinned or its pin does not match, it
        is not a reference of this experiment's kind, it lacks a point, or
        a compared statistic has no pinned tolerance.
    """
    experiment = next(
        item for item in declared_experiments(plan.file) if item.name == plan.name
    )
    if experiment.reference is None:
        raise ExperimentError(
            "experiment-reference",
            f"experiment {plan.name} names no reference; add a "
            '`reference "PATH" @blake3:...` clause',
            file=plan.file,
            line=experiment.line,
            column=experiment.col,
        )
    clause = experiment.reference
    path = (Path(plan.file).resolve().parent / clause.path).resolve()
    try:
        data = path.read_bytes()
    except OSError as error:
        raise ExperimentError(
            "experiment-reference",
            f"cannot read reference {clause.path}: {error.strerror or error}",
            file=plan.file,
            line=clause.line,
            column=clause.col,
        ) from error
    check_pin(
        path,
        clause.pin,
        file_digest(data),
        origin=plan.file,
        line=clause.line,
        column=clause.col,
    )
    tolerances = _tolerances(experiment, plan.kind, plan.file)
    reference = _object(cast(JsonValue, json.loads(data)), "the reference")
    if (
        reference.get("format") != REFERENCE_FORMAT
        or reference.get("kind") != plan.kind
    ):
        raise ExperimentError(
            "experiment-reference",
            f"{clause.path} is not a {plan.kind} reference ({REFERENCE_FORMAT})",
            file=plan.file,
            line=clause.line,
            column=clause.col,
        )
    stored = reference.get("points")
    if not isinstance(stored, list):
        raise ExperimentError("experiment-reference", f"{clause.path} has no points")
    checks: list[PointCheck] = []
    for run in runs:
        values = _point_values(run.record)
        match = next(
            (
                _object(item, "a reference point")
                for item in stored
                if _object(item, "a reference point").get("values") == values
            ),
            None,
        )
        if match is None:
            raise ExperimentError(
                "experiment-reference",
                f"{clause.path} has no point {run.point.label or '(the only point)'}",
                file=plan.file,
                line=clause.line,
                column=clause.col,
            )
        ours = _results(run.record)
        comparisons: list[Comparison] = []
        if plan.kind == "fit":
            fitted = _object(ours["summary"], "a fit's summary")
            expected = _object(match.get("summary"), "a reference summary")
            for site in sorted(expected):
                if site not in fitted:
                    raise ExperimentError(
                        "experiment-reference",
                        f"the reference has site {site!r} and the fit does not",
                    )
                mine = _object(fitted[site], "a site summary")
                theirs = _object(expected[site], "a reference site summary")
                comparisons.extend(
                    _compare_values(
                        site,
                        "mean",
                        mine["mean"],
                        theirs["mean"],
                        theirs["sd"],
                        tolerances["mean"],
                    )
                )
                comparisons.extend(
                    _compare_values(
                        site,
                        "sd",
                        mine["sd"],
                        theirs["sd"],
                        theirs["sd"],
                        tolerances["sd"],
                    )
                )
        else:
            comparisons.extend(
                _compare_values(
                    "",
                    "value",
                    ours["value"],
                    match.get("value"),
                    1.0,
                    tolerances["value"],
                )
            )
        checks.append(PointCheck(label=run.point.label, comparisons=tuple(comparisons)))
    return CheckReport(
        experiment=plan.name, reference=clause.path, points=tuple(checks)
    )