pymetrix-labbook 0.1.0a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pymetrix_labbook/__init__.py +58 -0
- pymetrix_labbook/_version.py +1 -0
- pymetrix_labbook/app.py +553 -0
- pymetrix_labbook/audit.py +216 -0
- pymetrix_labbook/brief.py +228 -0
- pymetrix_labbook/chain.py +107 -0
- pymetrix_labbook/cli.py +61 -0
- pymetrix_labbook/plan.py +125 -0
- pymetrix_labbook/recorder.py +191 -0
- pymetrix_labbook/tried.py +107 -0
- pymetrix_labbook/verify.py +286 -0
- pymetrix_labbook-0.1.0a1.dist-info/METADATA +159 -0
- pymetrix_labbook-0.1.0a1.dist-info/RECORD +16 -0
- pymetrix_labbook-0.1.0a1.dist-info/WHEEL +4 -0
- pymetrix_labbook-0.1.0a1.dist-info/entry_points.txt +8 -0
- pymetrix_labbook-0.1.0a1.dist-info/licenses/LICENSE +28 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""A research lab book for pymetrix (``pymetrix-labbook``): an append-only, hash-chained record of the work, kept in
|
|
2
|
+
the project and checked by ``verify``. See pymetrix's docs/design/research-audit.md.
|
|
3
|
+
|
|
4
|
+
Installed, it records every session (scripts, notebooks, the app, the MCP server) with no further set-up: each step
|
|
5
|
+
run, failed, cancelled, undone or removed, and each project opened or saved. ``verify(path)``, or
|
|
6
|
+
``pymetrix-labbook verify project.pymx`` at a command line, checks the chain, the save log, the steps and a replay.
|
|
7
|
+
``brief``, ``note`` and ``objective`` record the project's scope and objectives before the work, the reasoning behind
|
|
8
|
+
choices, and what each step addresses.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from ._version import __version__
|
|
14
|
+
from pymetrix.extension import PluginInfo, SessionObserver
|
|
15
|
+
|
|
16
|
+
PLUGIN = PluginInfo(
|
|
17
|
+
name="pymetrix-labbook",
|
|
18
|
+
version=__version__,
|
|
19
|
+
license="BSD-3-Clause",
|
|
20
|
+
maintainer="Geoffrey Heenan",
|
|
21
|
+
description="A research lab book: an append-only, hash-chained record of every step, kept in the project and "
|
|
22
|
+
"verified by replay",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
from .brief import brief, commit_brief, current_brief, note, objective, reveal_brief, skip_brief # noqa: E402
|
|
26
|
+
from .chain import Chain, ChainProblem # noqa: E402
|
|
27
|
+
from .plan import current_plan, lock_plan # noqa: E402
|
|
28
|
+
from .tried import specification_curve, tried # noqa: E402
|
|
29
|
+
from .recorder import fingerprint, lab_book, observe # noqa: E402
|
|
30
|
+
from .verify import Verification, verify # noqa: E402
|
|
31
|
+
|
|
32
|
+
_registered = False
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def register() -> None:
|
|
36
|
+
"""The entry point: register the observer that writes the lab book (once)."""
|
|
37
|
+
global _registered
|
|
38
|
+
if _registered:
|
|
39
|
+
return
|
|
40
|
+
from pymetrix.extension import plugin_context, register as add
|
|
41
|
+
|
|
42
|
+
import pymetrix.extension as extension
|
|
43
|
+
from pymetrix.extension import AppPanel
|
|
44
|
+
|
|
45
|
+
from .app import create_panel
|
|
46
|
+
from .tried import report_note
|
|
47
|
+
|
|
48
|
+
with plugin_context(PLUGIN):
|
|
49
|
+
add("observers", SessionObserver("labbook", observe), name="labbook")
|
|
50
|
+
add("panels", AppPanel("Lab book", create_panel, area="right"), name="labbook_panel") # View → Lab book
|
|
51
|
+
if hasattr(extension, "ReportNote"): # extension API 1.6: reports carry "1 of 23 fitted"
|
|
52
|
+
add("report_notes", extension.ReportNote("tried", "What was tried", report_note), name="tried")
|
|
53
|
+
_registered = True
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
__all__ = ["PLUGIN", "Chain", "ChainProblem", "Verification", "brief", "commit_brief", "current_brief", "current_plan",
|
|
57
|
+
"fingerprint", "lab_book", "lock_plan", "note", "objective", "observe", "register", "reveal_brief", "skip_brief",
|
|
58
|
+
"specification_curve", "tried", "verify"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0a1"
|
pymetrix_labbook/app.py
ADDED
|
@@ -0,0 +1,553 @@
|
|
|
1
|
+
"""The Lab book panel in the desktop app: the project brief, notes, the objectives steps are linked to, and what
|
|
2
|
+
``verify`` would say about them, as the work goes on.
|
|
3
|
+
|
|
4
|
+
The panel docks on the right (View → Lab book). It shows:
|
|
5
|
+
|
|
6
|
+
- the brief, or a prompt to write one before the work (or to say why there is none);
|
|
7
|
+
- **Brief…**, **Skip…** and **Note…**, which write ``brief``, ``brief_skipped`` and ``note`` entries;
|
|
8
|
+
- the brief's objectives and hypotheses, with ticks: steps run while one is ticked are linked to it;
|
|
9
|
+
- the brief's checks (``verify.brief_report``) and the latest entries.
|
|
10
|
+
|
|
11
|
+
Qt is imported only when the panel is built, so the lab book works without the app. The forms' text is parsed by
|
|
12
|
+
plain functions (``parse_pairs``, ``parse_lines``), tested without a window.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from .brief import (
|
|
20
|
+
_has_brief,
|
|
21
|
+
active_objectives,
|
|
22
|
+
brief,
|
|
23
|
+
commit_brief,
|
|
24
|
+
current_brief,
|
|
25
|
+
note,
|
|
26
|
+
reveal_brief,
|
|
27
|
+
set_active_objectives,
|
|
28
|
+
skip_brief,
|
|
29
|
+
)
|
|
30
|
+
from .plan import current_plan, lock_plan, plan_report
|
|
31
|
+
from .recorder import lab_book
|
|
32
|
+
from .tried import fits, outcome_counts, specification_curve, tried
|
|
33
|
+
from .verify import brief_report, describe_actor
|
|
34
|
+
|
|
35
|
+
__all__ = ["BRIEF_FIELDS", "create_panel", "curve_dialog", "format_pairs", "parse_lines", "parse_pairs", "plan_dialog"]
|
|
36
|
+
|
|
37
|
+
# the brief dialog's fields: (keyword, label, kind) with kind "line", "text", "pairs" (id: text a line) or "lines"
|
|
38
|
+
BRIEF_FIELDS = (
|
|
39
|
+
("title", "Title", "line"),
|
|
40
|
+
("question", "Research question", "text"),
|
|
41
|
+
("why", "Why it matters", "text"),
|
|
42
|
+
("objectives", "Objectives (one a line, id: text)", "pairs"),
|
|
43
|
+
("hypotheses", "Hypotheses (one a line, id: statement)", "pairs"),
|
|
44
|
+
("primary_outcomes", "Primary outcomes (one a line)", "lines"),
|
|
45
|
+
("secondary_outcomes", "Secondary outcomes (one a line)", "lines"),
|
|
46
|
+
("data", "Intended data (one a line, e.g. sources: ..., sample: ...)", "pairs"),
|
|
47
|
+
("methods", "Intended methods, broadly", "text"),
|
|
48
|
+
("limits", "What the project leaves out", "text"),
|
|
49
|
+
("team", "Team (one a line, name: role)", "pairs"),
|
|
50
|
+
("funder", "Funder", "line"),
|
|
51
|
+
("conditions", "Ethics or data-access conditions", "text"),
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def parse_pairs(text: str) -> dict[str, str]:
|
|
56
|
+
"""``"O1: estimate it\\nO2: test it"`` -> {"O1": "estimate it", "O2": "test it"}; a line without a colon is an
|
|
57
|
+
error, so a typo is not silently dropped."""
|
|
58
|
+
out: dict[str, str] = {}
|
|
59
|
+
for line in text.splitlines():
|
|
60
|
+
if not line.strip():
|
|
61
|
+
continue
|
|
62
|
+
key, sep, value = line.partition(":")
|
|
63
|
+
if not sep or not key.strip() or not value.strip():
|
|
64
|
+
raise ValueError(f"write this line as 'id: text': {line.strip()!r}")
|
|
65
|
+
out[key.strip()] = value.strip()
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def parse_lines(text: str) -> list[str]:
|
|
70
|
+
"""One item a line, blank lines left out."""
|
|
71
|
+
return [line.strip() for line in text.splitlines() if line.strip()]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def format_pairs(pairs: dict[str, Any]) -> str:
|
|
75
|
+
"""The inverse of ``parse_pairs``, for filling in the form from the brief as it stands (a hypothesis's
|
|
76
|
+
statement)."""
|
|
77
|
+
return "\n".join(f"{k}: {v['statement'] if isinstance(v, dict) else v}" for k, v in pairs.items())
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _summary(entry: dict[str, Any]) -> str:
|
|
81
|
+
data = entry.get("data", {})
|
|
82
|
+
what = (data.get("code") or ", ".join(data.get("codes", [])) or data.get("title") or data.get("text")
|
|
83
|
+
or data.get("reason") or data.get("path") or "")
|
|
84
|
+
first = str(what).strip().splitlines()[0] if str(what).strip() else ""
|
|
85
|
+
linked = data.get("objectives") if entry.get("event") in ("step", "failed") else None # a brief's are its own
|
|
86
|
+
tags = f" [{', '.join(linked)}]" if linked else ""
|
|
87
|
+
if entry.get("event") in ("step", "failed") and data.get("plan"):
|
|
88
|
+
tags += f" ({data['plan']})"
|
|
89
|
+
if entry.get("event") == "brief_commitment":
|
|
90
|
+
first = f"private brief, hash {data.get('hash', '')[:16]}…"
|
|
91
|
+
if entry.get("event") == "brief_revealed":
|
|
92
|
+
first = f"revealed: {data.get('brief', {}).get('title', '')}"
|
|
93
|
+
if entry.get("event") == "plan":
|
|
94
|
+
first = f"{len(data.get('specifications', []))} specification(s), locked"
|
|
95
|
+
event = {"start": "lab book started", "brief_skipped": "no brief", "brief_commitment": "brief committed",
|
|
96
|
+
"brief_revealed": "brief revealed"}.get(entry.get("event", "?"), entry.get("event", "?"))
|
|
97
|
+
by = f" · {describe_actor(entry['by'])}" if entry.get("by") else "" # not "· not recorded" on the first entry
|
|
98
|
+
return f"{entry.get('seq', '?')} {event} {first}{tags}{by}".rstrip()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def create_panel(app: Any) -> Any:
|
|
102
|
+
"""The panel's widget (``AppPanel.create``): ``app`` is pymetrix's ``AppInterface``."""
|
|
103
|
+
from PySide6 import QtCore, QtWidgets
|
|
104
|
+
|
|
105
|
+
panel = QtWidgets.QWidget()
|
|
106
|
+
panel.setObjectName("labbook-panel")
|
|
107
|
+
layout = QtWidgets.QVBoxLayout(panel)
|
|
108
|
+
status = QtWidgets.QLabel()
|
|
109
|
+
status.setWordWrap(True)
|
|
110
|
+
layout.addWidget(status)
|
|
111
|
+
buttons = QtWidgets.QHBoxLayout()
|
|
112
|
+
brief_button = QtWidgets.QPushButton("Brief…")
|
|
113
|
+
skip_button = QtWidgets.QPushButton("Skip…")
|
|
114
|
+
note_button = QtWidgets.QPushButton("Note…")
|
|
115
|
+
plan_button = QtWidgets.QPushButton("Plan…")
|
|
116
|
+
reveal_button = QtWidgets.QPushButton("Reveal…")
|
|
117
|
+
for b, tip in ((brief_button, "Write the project brief before the work, or amend it (with a reason)"),
|
|
118
|
+
(skip_button, "Record that this project has no brief, and why"),
|
|
119
|
+
(note_button, "Record the reasoning behind a choice"),
|
|
120
|
+
(plan_button, "Lock the analysis plan (exact specifications) before reading the data"),
|
|
121
|
+
(reveal_button, "Disclose a private brief from its file, checked against its commitment")):
|
|
122
|
+
b.setToolTip(tip)
|
|
123
|
+
buttons.addWidget(b)
|
|
124
|
+
layout.addLayout(buttons)
|
|
125
|
+
more = QtWidgets.QHBoxLayout()
|
|
126
|
+
curve_button = QtWidgets.QPushButton("Specification curve…")
|
|
127
|
+
curve_button.setToolTip("Every specification fitted for an outcome, with the selected result highlighted")
|
|
128
|
+
more.addWidget(curve_button)
|
|
129
|
+
more.addStretch(1)
|
|
130
|
+
layout.addLayout(more)
|
|
131
|
+
ticks_label = QtWidgets.QLabel("Objectives the next steps address (tick them):")
|
|
132
|
+
ticks_label.setWordWrap(True)
|
|
133
|
+
layout.addWidget(ticks_label)
|
|
134
|
+
ticks = QtWidgets.QListWidget()
|
|
135
|
+
ticks.setObjectName("labbook-objectives")
|
|
136
|
+
layout.addWidget(ticks)
|
|
137
|
+
no_ticks = QtWidgets.QLabel("No objectives yet: a brief's objectives and hypotheses are listed here, to tick the ones "
|
|
138
|
+
"the next steps address.")
|
|
139
|
+
no_ticks.setWordWrap(True)
|
|
140
|
+
no_ticks.setObjectName("labbook-objectives-empty")
|
|
141
|
+
no_ticks.setStyleSheet("color: palette(placeholder-text);")
|
|
142
|
+
layout.addWidget(no_ticks)
|
|
143
|
+
layout.addWidget(QtWidgets.QLabel("Checks:"))
|
|
144
|
+
checks = QtWidgets.QListWidget()
|
|
145
|
+
checks.setObjectName("labbook-checks")
|
|
146
|
+
layout.addWidget(checks)
|
|
147
|
+
layout.addWidget(QtWidgets.QLabel("Latest lab-book entries:"))
|
|
148
|
+
entries = QtWidgets.QListWidget()
|
|
149
|
+
entries.setObjectName("labbook-entries")
|
|
150
|
+
layout.addWidget(entries)
|
|
151
|
+
for listing in (checks, entries): # long lines wrap, in full in their tooltips, with no sideways scroll bar
|
|
152
|
+
listing.setWordWrap(True)
|
|
153
|
+
listing.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
|
154
|
+
listing.setResizeMode(QtWidgets.QListView.ResizeMode.Adjust)
|
|
155
|
+
|
|
156
|
+
state = {"filling": False}
|
|
157
|
+
|
|
158
|
+
def refresh() -> None:
|
|
159
|
+
import shiboken6
|
|
160
|
+
|
|
161
|
+
if not (shiboken6.isValid(panel) and shiboken6.isValid(status)):
|
|
162
|
+
return # the panel, or its window, is gone (an app may still call it): nothing to show
|
|
163
|
+
session = app.session
|
|
164
|
+
book = lab_book(session)
|
|
165
|
+
current = current_brief(session)
|
|
166
|
+
skipped = any(e.get("event") == "brief_skipped" for e in book.entries)
|
|
167
|
+
amendments = sum(1 for e in book.entries if e.get("event") == "brief") - 1
|
|
168
|
+
plan = current_plan(book)
|
|
169
|
+
locked = f"<br>Plan locked: {len(plan['specifications'])} specification(s)" if plan else ""
|
|
170
|
+
if current:
|
|
171
|
+
status.setText(f"<b>{current['title']}</b>" + (f" (amended {amendments}×)" if amendments > 0 else "") + locked)
|
|
172
|
+
elif any(e.get("event") == "brief_commitment" for e in book.entries):
|
|
173
|
+
status.setText("<b>Private brief committed</b>: only its hash is in the lab book (Reveal… at publication)."
|
|
174
|
+
+ locked)
|
|
175
|
+
elif skipped:
|
|
176
|
+
status.setText("No brief: skipped (see Checks)." + locked)
|
|
177
|
+
else:
|
|
178
|
+
status.setText("<b>No brief yet.</b> Write one before the work (Brief…), or say why there is none (Skip…)."
|
|
179
|
+
+ locked)
|
|
180
|
+
state["filling"] = True
|
|
181
|
+
ticks.clear()
|
|
182
|
+
ticked = set(active_objectives(session))
|
|
183
|
+
for key, value in {**(current or {}).get("objectives", {}), **(current or {}).get("hypotheses", {})}.items():
|
|
184
|
+
text = value["statement"] if isinstance(value, dict) else value
|
|
185
|
+
item = QtWidgets.QListWidgetItem(f"{key}: {text}")
|
|
186
|
+
item.setData(QtCore.Qt.ItemDataRole.UserRole, key)
|
|
187
|
+
item.setFlags(item.flags() | QtCore.Qt.ItemFlag.ItemIsUserCheckable)
|
|
188
|
+
item.setCheckState(QtCore.Qt.CheckState.Checked if key in ticked else QtCore.Qt.CheckState.Unchecked)
|
|
189
|
+
ticks.addItem(item)
|
|
190
|
+
state["filling"] = False
|
|
191
|
+
ticks.setVisible(bool(ticks.count()))
|
|
192
|
+
no_ticks.setVisible(not ticks.count())
|
|
193
|
+
warnings, notes, checked = brief_report(book)
|
|
194
|
+
plan_warnings, plan_notes, plan_checked = plan_report(book)
|
|
195
|
+
warnings, notes, checked = warnings + plan_warnings, notes + plan_notes, checked + plan_checked
|
|
196
|
+
notes = notes + [f"{o}: {k} specification(s) fitted ({n} fit(s))" for o, (k, n) in sorted(outcome_counts(book).items())]
|
|
197
|
+
selected = app.selected()
|
|
198
|
+
if selected:
|
|
199
|
+
try:
|
|
200
|
+
notes.append(tried(app.session, selected))
|
|
201
|
+
except ValueError:
|
|
202
|
+
pass
|
|
203
|
+
checks.clear()
|
|
204
|
+
for prefix, items in (("⚠ ", warnings), ("· ", notes), ("✓ ", checked)):
|
|
205
|
+
for text in items:
|
|
206
|
+
checks.addItem(prefix + text)
|
|
207
|
+
checks.item(checks.count() - 1).setToolTip(text)
|
|
208
|
+
if not checks.count():
|
|
209
|
+
checks.addItem("No checks yet: they appear once there is a brief, a plan or a fitted step.")
|
|
210
|
+
entries.clear()
|
|
211
|
+
for entry in book.entries[-12:]:
|
|
212
|
+
entries.addItem(_summary(entry))
|
|
213
|
+
entries.item(entries.count() - 1).setToolTip(_summary(entry))
|
|
214
|
+
entries.item(entries.count() - 1).setData(QtCore.Qt.ItemDataRole.UserRole, entry.get("seq"))
|
|
215
|
+
entries.scrollToBottom()
|
|
216
|
+
|
|
217
|
+
def ticked_changed(_item: Any) -> None:
|
|
218
|
+
if state["filling"]:
|
|
219
|
+
return
|
|
220
|
+
ids = [ticks.item(i).data(QtCore.Qt.ItemDataRole.UserRole) for i in range(ticks.count())
|
|
221
|
+
if ticks.item(i).checkState() == QtCore.Qt.CheckState.Checked]
|
|
222
|
+
set_active_objectives(app.session, ids)
|
|
223
|
+
app.status(f"Steps now address {', '.join(ids)}" if ids else "Steps now address no objective")
|
|
224
|
+
|
|
225
|
+
def write_brief() -> None:
|
|
226
|
+
dialog = brief_dialog(panel, current_brief(app.session), _has_brief(app.session))
|
|
227
|
+
while dialog.exec():
|
|
228
|
+
try:
|
|
229
|
+
if dialog.private.isChecked():
|
|
230
|
+
path, _ = QtWidgets.QFileDialog.getSaveFileName(panel, "Keep the private brief in", "brief.json",
|
|
231
|
+
"JSON (*.json)")
|
|
232
|
+
if not path:
|
|
233
|
+
continue
|
|
234
|
+
digest = commit_brief(app.session, path, **dialog.values())
|
|
235
|
+
QtWidgets.QApplication.clipboard().setText(digest)
|
|
236
|
+
QtWidgets.QMessageBox.information(
|
|
237
|
+
panel, "Private brief", f"The brief is in {path}: keep it private and unchanged.\n\nIts hash, "
|
|
238
|
+
f"now on the clipboard, is in the lab book:\n{digest}\n\nRegister the hash with a time-stamping "
|
|
239
|
+
"service (OSF, an RFC 3161 authority) to prove when it was written. Reveal… discloses it later.")
|
|
240
|
+
break
|
|
241
|
+
brief(app.session, **dialog.values())
|
|
242
|
+
except (ValueError, OSError) as exc:
|
|
243
|
+
QtWidgets.QMessageBox.warning(panel, "Project brief", str(exc))
|
|
244
|
+
continue
|
|
245
|
+
app.status("Brief recorded in the lab book")
|
|
246
|
+
break
|
|
247
|
+
refresh()
|
|
248
|
+
|
|
249
|
+
def skip() -> None:
|
|
250
|
+
reason, ok = QtWidgets.QInputDialog.getText(panel, "No project brief", "Why is there no brief?")
|
|
251
|
+
if ok and reason.strip():
|
|
252
|
+
skip_brief(app.session, reason.strip())
|
|
253
|
+
refresh()
|
|
254
|
+
|
|
255
|
+
def entry_menu(item: Any) -> Any:
|
|
256
|
+
"""The right-click menu on a lab-book entry: a note about it (linked to its number), or the entry copied, as
|
|
257
|
+
shown or as its full record (JSON)."""
|
|
258
|
+
import json
|
|
259
|
+
|
|
260
|
+
menu = QtWidgets.QMenu(panel)
|
|
261
|
+
seq = item.data(QtCore.Qt.ItemDataRole.UserRole) if item is not None else None
|
|
262
|
+
if seq is None:
|
|
263
|
+
return menu
|
|
264
|
+
record = next((e for e in lab_book(app.session).entries if e.get("seq") == seq), None)
|
|
265
|
+
|
|
266
|
+
def note_on() -> None:
|
|
267
|
+
current = current_brief(app.session) or {}
|
|
268
|
+
dialog = note_dialog(panel, [*current.get("objectives", {}), *current.get("hypotheses", {})])
|
|
269
|
+
dialog.setWindowTitle(f"Note on lab-book entry {seq}")
|
|
270
|
+
if dialog.exec():
|
|
271
|
+
text, about = dialog.values()
|
|
272
|
+
if text:
|
|
273
|
+
note(app.session, text, about=about, step=seq)
|
|
274
|
+
refresh()
|
|
275
|
+
|
|
276
|
+
clip = QtWidgets.QApplication.clipboard()
|
|
277
|
+
menu.addAction(f"Add a note on entry {seq}…", note_on)
|
|
278
|
+
menu.addAction("Copy the entry", lambda: clip.setText(item.text()))
|
|
279
|
+
menu.addAction("Copy its full record (JSON)",
|
|
280
|
+
lambda: clip.setText(json.dumps(record, ensure_ascii=False, indent=1, default=str))).setEnabled(record is not None)
|
|
281
|
+
return menu
|
|
282
|
+
|
|
283
|
+
entries.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
|
|
284
|
+
entries.customContextMenuRequested.connect(
|
|
285
|
+
lambda pos: entry_menu(entries.itemAt(pos)).popup(entries.viewport().mapToGlobal(pos)) if entries.itemAt(pos) else None)
|
|
286
|
+
checks.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
|
|
287
|
+
|
|
288
|
+
def check_menu(pos: Any) -> None:
|
|
289
|
+
item = checks.itemAt(pos)
|
|
290
|
+
if item is not None:
|
|
291
|
+
menu = QtWidgets.QMenu(panel)
|
|
292
|
+
menu.addAction("Copy the check", lambda: QtWidgets.QApplication.clipboard().setText(item.toolTip() or item.text()))
|
|
293
|
+
menu.popup(checks.viewport().mapToGlobal(pos))
|
|
294
|
+
|
|
295
|
+
checks.customContextMenuRequested.connect(check_menu)
|
|
296
|
+
panel.entry_menu = entry_menu
|
|
297
|
+
|
|
298
|
+
def add_note() -> None:
|
|
299
|
+
current = current_brief(app.session) or {}
|
|
300
|
+
dialog = note_dialog(panel, [*current.get("objectives", {}), *current.get("hypotheses", {})])
|
|
301
|
+
if dialog.exec():
|
|
302
|
+
text, about = dialog.values()
|
|
303
|
+
if text:
|
|
304
|
+
note(app.session, text, about=about)
|
|
305
|
+
refresh()
|
|
306
|
+
|
|
307
|
+
def write_plan() -> None:
|
|
308
|
+
session = app.session
|
|
309
|
+
dialog = plan_dialog(panel, current_plan(session), [r.code for r in session.history])
|
|
310
|
+
while dialog.exec():
|
|
311
|
+
try:
|
|
312
|
+
lock_plan(session, **dialog.values())
|
|
313
|
+
except ValueError as exc:
|
|
314
|
+
QtWidgets.QMessageBox.warning(panel, "Analysis plan", str(exc))
|
|
315
|
+
continue
|
|
316
|
+
app.status("Plan locked in the lab book: later steps are labelled planned or exploratory")
|
|
317
|
+
break
|
|
318
|
+
refresh()
|
|
319
|
+
|
|
320
|
+
def reveal() -> None:
|
|
321
|
+
path, _ = QtWidgets.QFileDialog.getOpenFileName(panel, "The private brief's file", "", "JSON (*.json)")
|
|
322
|
+
if not path:
|
|
323
|
+
return
|
|
324
|
+
try:
|
|
325
|
+
reveal_brief(app.session, path)
|
|
326
|
+
except (ValueError, OSError) as exc:
|
|
327
|
+
QtWidgets.QMessageBox.warning(panel, "Reveal the brief", str(exc))
|
|
328
|
+
return
|
|
329
|
+
app.status("Brief revealed: it matches its commitment")
|
|
330
|
+
refresh()
|
|
331
|
+
|
|
332
|
+
brief_button.clicked.connect(write_brief)
|
|
333
|
+
reveal_button.clicked.connect(reveal)
|
|
334
|
+
|
|
335
|
+
def curve() -> None:
|
|
336
|
+
session = app.session
|
|
337
|
+
counts = outcome_counts(session)
|
|
338
|
+
if not counts:
|
|
339
|
+
QtWidgets.QMessageBox.information(panel, "Specification curve", "No fitted model with an outcome yet.")
|
|
340
|
+
return
|
|
341
|
+
dialog = curve_dialog(panel, session, sorted(counts), app.selected())
|
|
342
|
+
dialog.exec()
|
|
343
|
+
|
|
344
|
+
curve_button.clicked.connect(curve)
|
|
345
|
+
plan_button.clicked.connect(write_plan)
|
|
346
|
+
skip_button.clicked.connect(skip)
|
|
347
|
+
note_button.clicked.connect(add_note)
|
|
348
|
+
ticks.itemChanged.connect(ticked_changed)
|
|
349
|
+
app.on_history_changed(refresh)
|
|
350
|
+
panel.refresh = refresh # for tests and the app
|
|
351
|
+
refresh()
|
|
352
|
+
return panel
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def brief_dialog(parent: Any, current: dict[str, Any] | None, amending: bool | None = None) -> Any:
|
|
356
|
+
"""The project brief form, filled in from the brief as it stands; an amendment also asks for its reason.
|
|
357
|
+
``dialog.values()`` gives ``brief``'s keywords."""
|
|
358
|
+
from PySide6 import QtWidgets
|
|
359
|
+
|
|
360
|
+
dialog = QtWidgets.QDialog(parent)
|
|
361
|
+
amending = bool(current) if amending is None else amending # a private brief not yet revealed is amended too
|
|
362
|
+
dialog.setWindowTitle("Amend the project brief" if amending else "Project brief")
|
|
363
|
+
form = QtWidgets.QFormLayout(dialog)
|
|
364
|
+
widgets: dict[str, Any] = {}
|
|
365
|
+
for key, label, kind in BRIEF_FIELDS:
|
|
366
|
+
value = (current or {}).get(key)
|
|
367
|
+
if kind == "line":
|
|
368
|
+
widget = QtWidgets.QLineEdit(value or "")
|
|
369
|
+
else:
|
|
370
|
+
widget = QtWidgets.QPlainTextEdit()
|
|
371
|
+
widget.setFixedHeight(56)
|
|
372
|
+
if kind == "pairs":
|
|
373
|
+
widget.setPlainText(format_pairs(value or {}))
|
|
374
|
+
elif kind == "lines":
|
|
375
|
+
widget.setPlainText("\n".join(value or []))
|
|
376
|
+
else:
|
|
377
|
+
widget.setPlainText(value or "")
|
|
378
|
+
widget.setObjectName(f"brief-{key}")
|
|
379
|
+
widgets[key] = (widget, kind)
|
|
380
|
+
form.addRow(label, widget)
|
|
381
|
+
private = QtWidgets.QCheckBox("Keep it private until publication: the lab book records only its hash")
|
|
382
|
+
private.setObjectName("brief-private")
|
|
383
|
+
form.addRow("", private)
|
|
384
|
+
if amending:
|
|
385
|
+
reason = QtWidgets.QLineEdit()
|
|
386
|
+
reason.setObjectName("brief-reason")
|
|
387
|
+
reason.setPlaceholderText("why the brief changes (kept in the lab book)")
|
|
388
|
+
widgets["reason"] = (reason, "line")
|
|
389
|
+
form.addRow("Reason for the amendment", reason)
|
|
390
|
+
box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.StandardButton.Ok | QtWidgets.QDialogButtonBox.StandardButton.Cancel)
|
|
391
|
+
box.accepted.connect(dialog.accept)
|
|
392
|
+
box.rejected.connect(dialog.reject)
|
|
393
|
+
form.addRow(box)
|
|
394
|
+
hypotheses = (current or {}).get("hypotheses", {})
|
|
395
|
+
|
|
396
|
+
def values() -> dict[str, Any]:
|
|
397
|
+
out: dict[str, Any] = {}
|
|
398
|
+
for key, (widget, kind) in widgets.items():
|
|
399
|
+
text = widget.text() if kind == "line" else widget.toPlainText()
|
|
400
|
+
if kind == "pairs":
|
|
401
|
+
out[key] = parse_pairs(text)
|
|
402
|
+
elif kind == "lines":
|
|
403
|
+
out[key] = parse_lines(text)
|
|
404
|
+
else:
|
|
405
|
+
out[key] = text.strip()
|
|
406
|
+
# keep what the form does not show (a hypothesis's supports and contradicts) for unchanged statements
|
|
407
|
+
out["hypotheses"] = {k: ({**hypotheses[k], "statement": v} if k in hypotheses else v)
|
|
408
|
+
for k, v in out["hypotheses"].items()}
|
|
409
|
+
return out
|
|
410
|
+
|
|
411
|
+
dialog.widgets = widgets
|
|
412
|
+
dialog.values = values
|
|
413
|
+
dialog.private = private
|
|
414
|
+
return dialog
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def note_dialog(parent: Any, ids: list[str]) -> Any:
|
|
418
|
+
"""A note's text and what it concerns. ``dialog.values()`` gives (text, about)."""
|
|
419
|
+
from PySide6 import QtWidgets
|
|
420
|
+
|
|
421
|
+
dialog = QtWidgets.QDialog(parent)
|
|
422
|
+
dialog.setWindowTitle("Note in the lab book")
|
|
423
|
+
form = QtWidgets.QFormLayout(dialog)
|
|
424
|
+
text = QtWidgets.QPlainTextEdit()
|
|
425
|
+
text.setObjectName("note-text")
|
|
426
|
+
about = QtWidgets.QComboBox()
|
|
427
|
+
about.setObjectName("note-about")
|
|
428
|
+
about.addItems(["(none)", *ids])
|
|
429
|
+
form.addRow("Note", text)
|
|
430
|
+
form.addRow("About", about)
|
|
431
|
+
box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.StandardButton.Ok | QtWidgets.QDialogButtonBox.StandardButton.Cancel)
|
|
432
|
+
box.accepted.connect(dialog.accept)
|
|
433
|
+
box.rejected.connect(dialog.reject)
|
|
434
|
+
form.addRow(box)
|
|
435
|
+
dialog.values = lambda: (text.toPlainText().strip(), "" if about.currentIndex() == 0 else about.currentText())
|
|
436
|
+
return dialog
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def plan_dialog(parent: Any, current: dict[str, Any] | None, history: list[str]) -> Any:
|
|
440
|
+
"""The analysis-plan form: the specifications (a step's code a line; the session's steps are offered to copy
|
|
441
|
+
from), the datasets, the sample and exclusion rules, the hypotheses and the primary outcomes. Changing a locked
|
|
442
|
+
plan also asks for the reason. ``dialog.values()`` gives ``lock_plan``'s keywords."""
|
|
443
|
+
from PySide6 import QtWidgets
|
|
444
|
+
|
|
445
|
+
current = current or {}
|
|
446
|
+
dialog = QtWidgets.QDialog(parent)
|
|
447
|
+
dialog.setWindowTitle("Change the analysis plan" if current else "Lock the analysis plan")
|
|
448
|
+
form = QtWidgets.QFormLayout(dialog)
|
|
449
|
+
specs = QtWidgets.QPlainTextEdit("\n".join(current.get("specifications", [])))
|
|
450
|
+
specs.setObjectName("plan-specifications")
|
|
451
|
+
specs.setPlaceholderText("fit = Equation('c ~ y').fit(data, method=OLS())")
|
|
452
|
+
form.addRow("Specifications (a step's code a line)", specs)
|
|
453
|
+
if history:
|
|
454
|
+
steps = QtWidgets.QComboBox()
|
|
455
|
+
steps.setObjectName("plan-history")
|
|
456
|
+
steps.addItems(["Add a step from the history…", *history])
|
|
457
|
+
|
|
458
|
+
def add(index: int) -> None:
|
|
459
|
+
if index > 0:
|
|
460
|
+
specs.appendPlainText(history[index - 1])
|
|
461
|
+
steps.setCurrentIndex(0)
|
|
462
|
+
|
|
463
|
+
steps.currentIndexChanged.connect(add)
|
|
464
|
+
form.addRow("", steps)
|
|
465
|
+
fields: dict[str, Any] = {}
|
|
466
|
+
for key, label, value in (("data", "Datasets it uses (by name, comma-separated)", ", ".join(current.get("data", []))),
|
|
467
|
+
("sample", "Sample", current.get("sample", "")),
|
|
468
|
+
("exclusions", "Exclusion rules", current.get("exclusions", "")),
|
|
469
|
+
("hypotheses", "Hypotheses tested (ids, comma-separated)", ", ".join(current.get("hypotheses", []))),
|
|
470
|
+
("primary_outcomes", "Primary outcomes (comma-separated)",
|
|
471
|
+
", ".join(current.get("primary_outcomes", []))),
|
|
472
|
+
("data_request", "Data request", current.get("data_request", ""))):
|
|
473
|
+
widget = QtWidgets.QLineEdit(value)
|
|
474
|
+
widget.setObjectName(f"plan-{key}")
|
|
475
|
+
fields[key] = widget
|
|
476
|
+
form.addRow(label, widget)
|
|
477
|
+
if current:
|
|
478
|
+
reason = QtWidgets.QLineEdit()
|
|
479
|
+
reason.setObjectName("plan-reason")
|
|
480
|
+
reason.setPlaceholderText("why the plan changes (kept in the lab book, with the work done before it)")
|
|
481
|
+
fields["reason"] = reason
|
|
482
|
+
form.addRow("Reason for the change", reason)
|
|
483
|
+
box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.StandardButton.Ok | QtWidgets.QDialogButtonBox.StandardButton.Cancel)
|
|
484
|
+
box.accepted.connect(dialog.accept)
|
|
485
|
+
box.rejected.connect(dialog.reject)
|
|
486
|
+
form.addRow(box)
|
|
487
|
+
|
|
488
|
+
def values() -> dict[str, Any]:
|
|
489
|
+
def items(text: str) -> list[str]:
|
|
490
|
+
return [t.strip() for t in text.split(",") if t.strip()]
|
|
491
|
+
|
|
492
|
+
out: dict[str, Any] = {"specifications": parse_lines(specs.toPlainText())}
|
|
493
|
+
for key, widget in fields.items():
|
|
494
|
+
out[key] = items(widget.text()) if key in ("data", "hypotheses", "primary_outcomes") else widget.text().strip()
|
|
495
|
+
return out
|
|
496
|
+
|
|
497
|
+
dialog.specs, dialog.fields, dialog.values = specs, fields, values
|
|
498
|
+
return dialog
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def curve_dialog(parent: Any, session: Any, outcomes: list[str], selected: str | None) -> Any:
|
|
502
|
+
"""The specification curve, in a window: choose the outcome and the coefficient; the result selected in the app
|
|
503
|
+
(``selected``) is highlighted. ``dialog.draw()`` redraws; ``dialog.figure`` is the current figure."""
|
|
504
|
+
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg
|
|
505
|
+
from PySide6 import QtWidgets
|
|
506
|
+
|
|
507
|
+
dialog = QtWidgets.QDialog(parent)
|
|
508
|
+
dialog.setWindowTitle("Specification curve")
|
|
509
|
+
layout = QtWidgets.QVBoxLayout(dialog)
|
|
510
|
+
row = QtWidgets.QHBoxLayout()
|
|
511
|
+
outcome = QtWidgets.QComboBox()
|
|
512
|
+
outcome.setObjectName("curve-outcome")
|
|
513
|
+
outcome.addItems(outcomes)
|
|
514
|
+
term = QtWidgets.QComboBox()
|
|
515
|
+
term.setObjectName("curve-term")
|
|
516
|
+
row.addWidget(QtWidgets.QLabel("Outcome"))
|
|
517
|
+
row.addWidget(outcome)
|
|
518
|
+
row.addWidget(QtWidgets.QLabel("Coefficient"))
|
|
519
|
+
row.addWidget(term)
|
|
520
|
+
layout.addLayout(row)
|
|
521
|
+
holder = QtWidgets.QVBoxLayout()
|
|
522
|
+
layout.addLayout(holder)
|
|
523
|
+
mine = [f for f in fits(session) if f["name"] == selected]
|
|
524
|
+
if mine and mine[-1]["outcome"] in outcomes:
|
|
525
|
+
outcome.setCurrentText(mine[-1]["outcome"])
|
|
526
|
+
|
|
527
|
+
def terms() -> None:
|
|
528
|
+
names = list(dict.fromkeys(t for f in fits(session, outcome.currentText()) for t in f["estimates"]))
|
|
529
|
+
term.blockSignals(True)
|
|
530
|
+
term.clear()
|
|
531
|
+
term.addItems(names)
|
|
532
|
+
slopes = [t for t in names if t not in ("const", "Intercept")]
|
|
533
|
+
if slopes:
|
|
534
|
+
term.setCurrentText(slopes[0])
|
|
535
|
+
term.blockSignals(False)
|
|
536
|
+
draw()
|
|
537
|
+
|
|
538
|
+
def draw() -> None:
|
|
539
|
+
while holder.count():
|
|
540
|
+
old = holder.takeAt(0).widget()
|
|
541
|
+
if old is not None:
|
|
542
|
+
old.deleteLater()
|
|
543
|
+
if not term.currentText():
|
|
544
|
+
return
|
|
545
|
+
dialog.figure = specification_curve(session, outcome.currentText(), term.currentText(), highlight=selected)
|
|
546
|
+
holder.addWidget(FigureCanvasQTAgg(dialog.figure))
|
|
547
|
+
|
|
548
|
+
outcome.currentIndexChanged.connect(lambda _i: terms())
|
|
549
|
+
term.currentIndexChanged.connect(lambda _i: draw())
|
|
550
|
+
dialog.figure = None
|
|
551
|
+
dialog.draw = draw
|
|
552
|
+
terms()
|
|
553
|
+
return dialog
|