Skip to content

pymetrix-labbook

A plugin: a separate package

pymetrix-labbook is a first-party plugin, installed on its own:

python -m pip install --pre pymetrix-labbook

A research lab book for pymetrix: an append-only, hash-chained record of the work, kept in the project and verified by replay.

The names pymetrix_labbook exports (its __all__), with their full documentation. Import them from the plugin: from pymetrix_labbook import .... The plugin's README says more.

Public names

brief

The project brief, notes and objectives: what the work set out to do, written into the lab book before it is done.

The design is pymetrix's docs/design/research-audit.md, layer 2. A brief gives the rest of the lab book its meaning: without a stated scope, an auditor can count what was tried but cannot tell whether it was on topic::

from pymetrix_labbook import brief, note, objective

brief(session, "Fiscal multipliers in Norland", "How large is the government-spending multiplier?",
      objectives={"O1": "Estimate the multiplier over two years"},
      hypotheses={"H1": {"statement": "The multiplier is below one",
                         "supports": "a two-year cumulative multiplier under 1"}},
      primary_outcomes=["two-year cumulative multiplier"], data={"sources": "PSETS: Norland national accounts"})
with objective("O1", "H1"):
    session.run(...)                                     # these steps are linked to O1 and H1
note(session, "Dropped 2020: the survey changed its method", about="O1")
brief(session, ..., reason="Added H2 after the referee's comment")   # an amendment, never an edit
  • A brief writes a brief entry. A later brief is an amendment and needs its reason; the record shows how the project changed, and when. skip_brief records that there is none, and why.
  • A private brief (commit_brief, reveal_brief): only the brief's hash goes into the lab book, to be time-stamped outside pymetrix; the brief itself, kept in a file, is revealed at publication and checked against it.
  • Notes write note entries: the reasoning a paper lab book holds, linked to an objective or a step.
  • Objectives: steps run inside objective(...) are tagged with the objectives and hypotheses they address. verify then reports objectives with no analysis, analyses linked to none (exploratory, which is normal, but labelled), hypotheses added to the brief only after results on them existed, and a brief written after the work began.

briefs

briefs(session_or_chain: Any) -> list[tuple[int, dict[str, Any]]]

Every version of the brief, as (entry, brief): those written openly, at their own entry, and those committed privately and since revealed, at their commitment's entry (when they were written).

current_brief

current_brief(session: Any) -> dict[str, Any] | None

The project's brief as it stands (the latest, amendments included; a committed brief once revealed), or None.

brief

brief(session: Any, title: str, question: str, **fields: Any) -> dict[str, Any]

Record the project brief: its scope and objectives, before the work. Called again, it amends the brief and needs reason; the whole brief is restated, so each brief entry stands on its own.

Keywords: why; objectives: id -> what it aims at ({"O1": "..."}); hypotheses: id -> statement, or {"statement", "supports", "contradicts"}: what would support or contradict it; primary_outcomes and secondary_outcomes; data: the intended sources, vintages, sample period and units; methods: broadly, not exact specifications; limits; team: name -> role; funder; conditions; reason.

To keep the brief private until publication, with its date still provable, use commit_brief.

commit_brief

commit_brief(session: Any, path: str | Path, title: str, question: str, **fields: Any) -> str

Commit to a brief without disclosing it: the brief, with a random salt, is written to path (keep it private, and unchanged), and the lab book records only its hash. Register that hash with a time-stamping service (OSF, an RFC 3161 authority, a journal's registered-report system) to prove when it was written; reveal_brief discloses it later. Returns the hash. Keywords as brief's; a later commitment amends and needs reason.

reveal_brief

reveal_brief(session: Any, path: str | Path) -> dict[str, Any]

Disclose a committed brief: the file commit_brief wrote is checked against the commitment and the brief enters the lab book, counted as written when it was committed.

skip_brief

skip_brief(session: Any, reason: str) -> dict[str, Any]

Record that the project has no brief, and why (exploratory work, a teaching exercise...).

note

note(session: Any, text: str, about: str = '', step: int | None = None) -> dict[str, Any]

Record a note: the reasoning behind a choice. about: the objective or hypothesis it concerns; step: the lab-book entry (its number) it concerns, such as the step it explains.

objective

objective(*ids: str) -> Iterator[None]

Link the steps run inside the block to these objectives or hypotheses (nested blocks add to the outer ones).

set_active_objectives

set_active_objectives(session: Any, ids: Sequence[str]) -> None

Link every step run in session from now on to these objectives, until changed (the app's Lab book panel: its ticks). An empty list ends it.

active_objectives

active_objectives(session: Any) -> tuple[str, ...]

The objectives ticked for session (set_active_objectives).

current_objectives

current_objectives(session: Any = None) -> tuple[str, ...]

The objectives and hypotheses the steps now being run are linked to: those of any objective(...) block and those ticked for the session (the recorder reads this).

Chain dataclass

Chain(entries: list[dict[str, Any]] = list())

The entries of a lab book, appended in order.

head property

head: str

The hash of the last entry (GENESIS when empty): what a time-stamp would anchor.

append

append(event: str, data: dict[str, Any], during: str = 'work', time: datetime | None = None, by: dict[str, str] | None = None) -> dict[str, Any]

Add an entry after the last one, chained to it, and return it. by: who acted (see the module docstring).

from_bytes classmethod

from_bytes(blob: bytes) -> Chain

Read a lab book; lines that are not JSON objects are kept as problems for check to report.

check

check() -> list[ChainProblem]

Every break in the chain: unreadable lines, numbering, links and hashes. Empty when intact.

ChainProblem dataclass

ChainProblem(seq: int | None, message: str)

Where a lab book's chain is broken.

commit_brief

commit_brief(session: Any, path: str | Path, title: str, question: str, **fields: Any) -> str

Commit to a brief without disclosing it: the brief, with a random salt, is written to path (keep it private, and unchanged), and the lab book records only its hash. Register that hash with a time-stamping service (OSF, an RFC 3161 authority, a journal's registered-report system) to prove when it was written; reveal_brief discloses it later. Returns the hash. Keywords as brief's; a later commitment amends and needs reason.

current_brief

current_brief(session: Any) -> dict[str, Any] | None

The project's brief as it stands (the latest, amendments included; a committed brief once revealed), or None.

current_plan

current_plan(session_or_chain: Any) -> dict[str, Any] | None

The plan in force (the latest plan entry's data), or None if none was locked.

fingerprint

fingerprint(obj: Any) -> str | None

A short fingerprint of a dataset's values or a result's estimates, for checking a replay; None for objects it cannot fingerprint. Estimates are rounded to 10 significant digits, so a replay on another machine matches.

lab_book

lab_book(session: Any, new: tuple[Any, ...] = ()) -> Chain

The lab book of a session: read from its project, or started now (a start entry). new: the records of the event that starts it, which are not work done before it.

lock_plan

lock_plan(session: Any, specifications: Sequence[Any], *, data: Sequence[str] = (), sample: str = '', exclusions: str = '', hypotheses: Sequence[str] = (), primary_outcomes: Sequence[str] = (), data_request: str = '', reason: str = '') -> dict[str, Any]

Lock the analysis plan: the model specifications (steps' code, or pymetrix commands), the datasets they use (data, by name), the sample and exclusion rules, the hypotheses tested and the primary outcomes. Locking again changes the plan and needs reason.

note

note(session: Any, text: str, about: str = '', step: int | None = None) -> dict[str, Any]

Record a note: the reasoning behind a choice. about: the objective or hypothesis it concerns; step: the lab-book entry (its number) it concerns, such as the step it explains.

objective

objective(*ids: str) -> Iterator[None]

Link the steps run inside the block to these objectives or hypotheses (nested blocks add to the outer ones).

observe

observe(event: Any) -> None

The SessionObserver's handler: one entry for each event (none for steps replayed while opening).

reveal_brief

reveal_brief(session: Any, path: str | Path) -> dict[str, Any]

Disclose a committed brief: the file commit_brief wrote is checked against the commitment and the brief enters the lab book, counted as written when it was committed.

skip_brief

skip_brief(session: Any, reason: str) -> dict[str, Any]

Record that the project has no brief, and why (exploratory work, a teaching exercise...).

specification_curve

specification_curve(session_or_chain: Any, outcome: str, term: str, highlight: str | None = None) -> Any

A matplotlib figure: the estimate of term in each specification fitted for outcome (its latest fit), sorted, with 95% intervals; highlight (a result's name) marks the one reported.

tried

Counting what was tried: how many specifications of each outcome were fitted, and their specification curve.

The design is pymetrix's docs/design/research-audit.md, layer 3. Forking paths are disclosed from the lab book, not from the researcher's memory::

from pymetrix_labbook import specification_curve, tried

tried(session, "fit")          # 'fit is 1 of 23 specifications fitted for c (31 fits, lab book entries 2-58)'
specification_curve(session, "c", "y", highlight="fit").savefig("curve.png")

Every fit counts: kept, undone, removed or failed, since the point is what was tried, not what was kept. Two fits are the same specification when their code is the same apart from the result's name, and their sample is the same.

fits

fits(session_or_chain: Any, outcome: str | None = None) -> list[dict[str, Any]]

Every fit the lab book recorded (of outcome, if given): its entry, name, outcome, sample, estimates, the specification it belongs to (spec, the code without the result's name, and the sample) and whether it failed.

outcome_counts

outcome_counts(session_or_chain: Any) -> dict[str, tuple[int, int]]

Outcome -> (distinct specifications, fits).

tried

tried(session: Any, name: str) -> str

One line for a report: where the result name stands among the specifications fitted for its outcome.

specification_curve

specification_curve(session_or_chain: Any, outcome: str, term: str, highlight: str | None = None) -> Any

A matplotlib figure: the estimate of term in each specification fitted for outcome (its latest fit), sorted, with 95% intervals; highlight (a result's name) marks the one reported.

report_note

report_note(session: Any, name: str) -> str | None

The line an exported report carries for the result name (pymetrix's ReportNote, extension API 1.6): tried's, or None for a result the lab book has no fit of.

Verification dataclass

Verification(path: str, entries: int = 0, head: str = '', errors: list[str] = list(), warnings: list[str] = list(), notes: list[str] = list(), checked: list[str] = list(), actors: dict[str, int] = dict())

What verify found: errors (the lab book or the project is not what it should be), warnings (gaps the lab book cannot account for) and notes (what could not be checked, and why).

ok property

ok: bool

No errors (warnings and notes may remain).

verify

Checking a project's lab book: deterministic checks, with no AI involved.

verify(path) reads the project file and checks, in order:

  1. The chain: every entry's hash, its number and its link to the entry before (Chain.check).
  2. Coverage: the project's save log against the lab book. A save made without the lab book active, or more saves than the lab book recorded, means work the lab book did not see.
  3. The steps: the project's steps, as saved, are those the lab book recorded at its last save.
  4. The replay (replay=True): the project is opened, which runs its steps again, and each current result's fingerprint is compared with the one the lab book recorded when it was made.
  5. The brief (brief_report): whether one was written before the work, objectives with no analysis, analyses linked to no objective, and hypotheses added only after results on them existed.
  6. The plan (plan.plan_report): planned data read before the plan was locked, planned specifications not run, exploratory steps since, and changes to the plan.
  7. What was tried (tried.outcome_counts): how many specifications of each outcome were fitted.

What the replay cannot check is listed rather than passed over: typed code not run because it is not trusted, steps whose plugin is missing, results not computed yet, and objects without a fingerprint.

Verification dataclass

Verification(path: str, entries: int = 0, head: str = '', errors: list[str] = list(), warnings: list[str] = list(), notes: list[str] = list(), checked: list[str] = list(), actors: dict[str, int] = dict())

What verify found: errors (the lab book or the project is not what it should be), warnings (gaps the lab book cannot account for) and notes (what could not be checked, and why).

ok property
ok: bool

No errors (warnings and notes may remain).

describe_actor

describe_actor(by: dict[str, Any] | None) -> str

One actor as a line reads it: "person geoff (app)", "agent claude-ai 0.1.0 (mcp)"; "not recorded" for entries written before the lab book recorded who acted.

actors

actors(chain: Chain) -> dict[str, int]

How many steps (run or failed) each actor took, in the order they first acted.

brief_report

brief_report(chain: Chain) -> tuple[list[str], list[str], list[str]]

What the lab book shows about the project brief: (warnings, notes, checked).

verify

verify(path: str | Path, replay: bool = True, trust: bool | None = None) -> Verification

Check a project's lab book (see the module docstring). trust is passed to load_project for the replay: None runs typed code only if it is trusted.

Plugin plumbing

What pymetrix's plugin loader reads (PLUGIN, register) and the plugin's version.

PLUGIN module-attribute

PLUGIN = PluginInfo(name='pymetrix-labbook', version=__version__, api='1.13', license='BSD-3-Clause', maintainer='Geoffrey Heenan', description='A research lab book: an append-only, hash-chained record of every step, kept in the project and verified by replay')

register

register() -> None

The entry point: register the observer that writes the lab book (once).