Skip to content

Weaving and document checks

weave

Weaving experiment results into literate documents, and checking them.

An {experiment} directive in a literate .qvr.md module names one of the module's experiments. weave_document runs each named experiment (or reads its stored records) and writes the directive's body: the experiment's hash, the content hash of its program, the pinned digests of its data, and the result. check_document checks a literate document the way its build does: every prose reference must name a declaration, every directive must name an experiment of the module, and every woven result must record the experiment's current hash. A result woven before its program, data, or configuration changed records an old hash and is refused as stale, so no number in the document outlives the program that produced it.

ProblemCode

ProblemCode = Literal['prose-reference', 'woven-stale', 'woven-missing', 'woven-experiment']

What a document problem is about.

DocumentProblem didactic-model

DocumentProblem(*, file: str, line: int, column: int, code: ProblemCode, message: str)

Bases: Model

A problem with a literate document's prose or woven results.

PARAMETER DESCRIPTION
file

The document.

TYPE: str

line

The 1-based line.

TYPE: int

column

The 0-based column.

TYPE: int

code

What the problem is about.

TYPE: ProblemCode

message

What is wrong and what to do.

TYPE: str

render

render() -> str

The problem as one diagnostic line.

RETURNS DESCRIPTION
str

file:line:column: error[code]: message.

Source code in src/quivers/literate/weave.py
def render(self) -> str:
    """The problem as one diagnostic line.

    Returns
    -------
    str
        ``file:line:column: error[code]: message``.
    """
    return (
        f"{self.file}:{self.line}:{self.column}: error[{self.code}]: {self.message}"
    )

WeaveResult didactic-model

WeaveResult(*, text: str, woven: tuple[str, ...], computed: int)

Bases: Model

What weaving a document did.

PARAMETER DESCRIPTION
text

The woven document.

TYPE: str

woven

The experiments woven, in document order.

TYPE: tuple[str, ...]

computed

How many runs were computed rather than read from the store.

TYPE: int

render_result

render_result(runs: tuple[PointRun, ...]) -> tuple[str, ...]

The woven lines of an experiment's results.

PARAMETER DESCRIPTION
runs

Its runs.

TYPE: tuple[PointRun, ...]

RETURNS DESCRIPTION
tuple[str, ...]

For a run, its value (and a program's log joint); for a fit, each site's posterior mean and standard deviation, to four significant digits. A point of a sweep is prefixed by its swept values.

Source code in src/quivers/literate/weave.py
def render_result(runs: tuple[PointRun, ...]) -> tuple[str, ...]:
    """The woven lines of an experiment's results.

    Parameters
    ----------
    runs : tuple[PointRun, ...]
        Its runs.

    Returns
    -------
    tuple[str, ...]
        For a run, its value (and a program's log joint); for a fit, each
        site's posterior mean and standard deviation, to four significant
        digits. A point of a sweep is prefixed by its swept values.
    """
    lines: list[str] = []
    for run in runs:
        prefix = f"[{run.point.label}] " if run.point.label else ""
        record = run.record
        outputs = record.get("outputs") if isinstance(record, dict) else None
        if not isinstance(outputs, dict):
            raise ExperimentError("experiment-record", "a record has no outputs")
        if outputs.get("kind") == "fit":
            summary = outputs.get("summary")
            if not isinstance(summary, dict):
                raise ExperimentError(
                    "experiment-record", "a fit record has no summary"
                )
            for site in sorted(summary):
                item = summary[site]
                if not isinstance(item, dict):
                    raise ExperimentError(
                        "experiment-record", "a site summary is malformed"
                    )
                lines.append(
                    f"{prefix}{site}: mean {_format(item.get('mean'))} "
                    f"sd {_format(item.get('sd'))}"
                )
            continue
        result = outputs.get("result")
        if not isinstance(result, dict):
            raise ExperimentError("experiment-record", "a run record has no result")
        line = f"{prefix}value = {_format(result.get('value'))}"
        if "log_joint" in result:
            line += f"  log_joint = {_format(result.get('log_joint'))}"
        lines.append(line)
    return tuple(lines)

weave_document

weave_document(path: str | Path, *, roots: tuple[str | Path, ...] | None = None, store: ArtifactStore | None = None, rerun: bool = False) -> WeaveResult

Weave every {experiment} directive of a literate document.

PARAMETER DESCRIPTION
path

A .qvr.md document.

TYPE: str | Path

roots

The directories module paths are relative to.

TYPE: tuple[str | Path, ...] | None DEFAULT: None

store

Where experiment records are kept; the project's store when None.

TYPE: ArtifactStore | None DEFAULT: None

rerun

Compute every run even when its record is stored.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
WeaveResult

The woven text; the file is not written.

RAISES DESCRIPTION
ExperimentError

If a directive names no experiment of the module, or an experiment cannot be planned or run.

Source code in src/quivers/literate/weave.py
def weave_document(
    path: str | Path,
    *,
    roots: tuple[str | Path, ...] | None = None,
    store: ArtifactStore | None = None,
    rerun: bool = False,
) -> WeaveResult:
    """Weave every ``{experiment}`` directive of a literate document.

    Parameters
    ----------
    path : str | Path
        A ``.qvr.md`` document.
    roots : tuple[str | Path, ...] | None
        The directories module paths are relative to.
    store : ArtifactStore | None
        Where experiment records are kept; the project's store when None.
    rerun : bool
        Compute every run even when its record is stored.

    Returns
    -------
    WeaveResult
        The woven text; the file is not written.

    Raises
    ------
    ExperimentError
        If a directive names no experiment of the module, or an experiment
        cannot be planned or run.
    """
    text = Path(path).read_text(encoding="utf-8")
    bodies: dict[int, str] = {}
    woven: list[str] = []
    computed = 0
    for directive in experiment_directives(text):
        plan = plan_experiment(path, directive.experiment, roots=roots)
        runs = run_experiment(plan, store=store, rerun=rerun)
        computed += sum(1 for run in runs if not run.hit)
        bodies[directive.line] = woven_body(_fields(plan), render_result(runs))
        woven.append(directive.experiment)
    return WeaveResult(
        text=weave_directives(text, bodies), woven=tuple(woven), computed=computed
    )

check_document

check_document(path: str | Path, *, roots: tuple[str | Path, ...] | None = None) -> tuple[DocumentProblem, ...]

Check a literate document's prose references and woven results.

PARAMETER DESCRIPTION
path

A .qvr.md document.

TYPE: str | Path

roots

The directories module paths are relative to.

TYPE: tuple[str | Path, ...] | None DEFAULT: None

RETURNS DESCRIPTION
tuple[DocumentProblem, ...]

Every prose reference that names no declaration, every directive that names no experiment, and every woven result that is missing or stale, in document order; empty when the document checks.

RAISES DESCRIPTION
ValueError

If the document is not a .qvr.md module.

ModuleError

If its module graph does not load or resolve.

CompileError

If its module does not compile.

Source code in src/quivers/literate/weave.py
def check_document(
    path: str | Path, *, roots: tuple[str | Path, ...] | None = None
) -> tuple[DocumentProblem, ...]:
    """Check a literate document's prose references and woven results.

    Parameters
    ----------
    path : str | Path
        A ``.qvr.md`` document.
    roots : tuple[str | Path, ...] | None
        The directories module paths are relative to.

    Returns
    -------
    tuple[DocumentProblem, ...]
        Every prose reference that names no declaration, every directive
        that names no experiment, and every woven result that is missing or
        stale, in document order; empty when the document checks.

    Raises
    ------
    ValueError
        If the document is not a ``.qvr.md`` module.
    ModuleError
        If its module graph does not load or resolve.
    CompileError
        If its module does not compile.
    """
    if not is_literate_path(path):
        raise ValueError(f"{path} is not a literate .qvr.md module")
    file = str(path)
    text = Path(path).read_text(encoding="utf-8")
    graph = load_file_graph(path, roots=roots)
    flat = interpret(graph)
    module = Compiler(
        flat.module, module_name=module_stem(path), file_path=file
    ).qiec_module
    problems = [
        DocumentProblem(
            file=file,
            line=problem.reference.line,
            column=problem.reference.column,
            code="prose-reference",
            message=problem.message,
        )
        for problem in check_references(
            prose_references(text), graph, declared_names(flat, module)
        )
    ]
    for directive in experiment_directives(text):
        try:
            plan = plan_experiment(path, directive.experiment, roots=roots)
        except ExperimentError as error:
            problems.append(
                DocumentProblem(
                    file=file,
                    line=directive.line,
                    column=directive.column,
                    code="woven-experiment",
                    message=error.message,
                )
            )
            continue
        if not directive.recorded_hash:
            problems.append(
                DocumentProblem(
                    file=file,
                    line=directive.line,
                    column=directive.column,
                    code="woven-missing",
                    message=f"the result of experiment {directive.experiment} is "
                    f"not woven; run qvr weave {file}",
                )
            )
        elif directive.recorded_hash != plan.hash:
            problems.append(
                DocumentProblem(
                    file=file,
                    line=directive.line,
                    column=directive.column,
                    code="woven-stale",
                    message=f"the woven result of experiment {directive.experiment} "
                    f"is stale: it was produced by experiment hash "
                    f"{directive.recorded_hash}, and the experiment now hashes "
                    f"{plan.hash}; run qvr weave {file}",
                )
            )
    return tuple(sorted(problems, key=lambda item: (item.line, item.column)))