From 22e861c1f2b99b14ff8718d3f4463bf003bfd090 Mon Sep 17 00:00:00 2001 From: Sam Holland Date: Thu, 12 Nov 2026 11:37:33 +0000 Subject: [PATCH 01/12] fix(gui): fix light/dark theme on linux - Modified __init__.py to check for wayland display environment variable and run via xcb if not found. - Modified gui/style.py to add helpers for applying a theme. - Modified gui/app.py to use theme helpers. - Modified gui/panes/welcome_pane.py to use theme helpers. --- src/pickmix/__init__.py | 4 ++- src/pickmix/gui/app.py | 19 +++++++------ src/pickmix/gui/panes/welcome_pane.py | 6 ++-- src/pickmix/gui/style.py | 41 +++++++++++++++++++++++++++ 4 files changed, 57 insertions(+), 13 deletions(-) diff --git a/src/pickmix/__init__.py b/src/pickmix/__init__.py index cc634dd..1154ac5 100644 --- a/src/pickmix/__init__.py +++ b/src/pickmix/__init__.py @@ -13,6 +13,8 @@ # main: launch the window, opening the config.toml given as the first argument def main() -> None: - import sys + import os, sys + if sys.platform.startswith('linux') and not os.environ.get('WAYLAND_DISPLAY'): + os.environ.setdefault('QT_QPA_PLATFORM', 'xcb') from pickmix.gui.app import run raise SystemExit(run(sys.argv[1:])) diff --git a/src/pickmix/gui/app.py b/src/pickmix/gui/app.py index afadab9..40a6c64 100644 --- a/src/pickmix/gui/app.py +++ b/src/pickmix/gui/app.py @@ -4,29 +4,30 @@ # Import external dependencies from pathlib import Path -from PySide6.QtCore import QSettings, Qt, QTimer +from PySide6.QtCore import QSettings, QTimer from PySide6.QtWidgets import QApplication, QWidget # Import internal pickmix objects from pickmix.gui.main_window import MainWindow -from pickmix.gui.style import retint, standardise +from pickmix.gui.style import apply_theme, is_dark, refresh_palette, retint, standardise # _set_scheme: apply saved colour theme def _set_scheme(app: QApplication) -> None: saved = QSettings('pickmix', 'pickmix').value('theme', '') if saved in ('light', 'dark'): - app.styleHints().setColorScheme(Qt.ColorScheme.Light if saved == 'light' else Qt.ColorScheme.Dark) + apply_theme(app, saved == 'dark') # _toggle_theme: save theme and apply it -def _toggle_theme(app: QApplication) -> None: - dark = app.styleHints().colorScheme() == Qt.ColorScheme.Dark - QSettings('pickmix', 'pickmix').setValue('theme', 'light' if dark else 'dark') - _set_scheme(app) +def _toggle_theme(app: QApplication, window: MainWindow) -> None: + dark = not is_dark() + QSettings('pickmix', 'pickmix').setValue('theme', 'dark' if dark else 'light') + apply_theme(app, dark) + _restyle(app, window) # _restyle: redraw tinted icons in new theme colour def _restyle(app: QApplication, window: MainWindow) -> None: def apply() -> None: - app.setPalette(app.style().standardPalette()) + refresh_palette(app) for top in app.topLevelWidgets(): for widget in (top, *top.findChildren(QWidget)): app.style().unpolish(widget) @@ -42,7 +43,7 @@ def run(args: list[str]) -> int: _set_scheme(app) standardise(app) window = MainWindow() - window.project_tab.welcome.theme_toggled.connect(lambda: _toggle_theme(app)) + window.project_tab.welcome.theme_toggled.connect(lambda: _toggle_theme(app, window)) app.styleHints().colorSchemeChanged.connect(lambda _: _restyle(app, window)) window.show() if args: diff --git a/src/pickmix/gui/panes/welcome_pane.py b/src/pickmix/gui/panes/welcome_pane.py index f031187..28ffc47 100644 --- a/src/pickmix/gui/panes/welcome_pane.py +++ b/src/pickmix/gui/panes/welcome_pane.py @@ -5,12 +5,12 @@ # Import external dependencies from PySide6.QtCore import QSize, Qt, Signal from PySide6.QtGui import QHideEvent, QIcon, QKeySequence, QResizeEvent, QShortcut, QShowEvent -from PySide6.QtWidgets import QApplication, QHBoxLayout, QPushButton, QVBoxLayout, QWidget +from PySide6.QtWidgets import QHBoxLayout, QPushButton, QVBoxLayout, QWidget # Import internal pickmix objects from pickmix import __version__ from pickmix.gui.components.icons import icon -from pickmix.gui.style import big_button, hint, tidy +from pickmix.gui.style import big_button, hint, is_dark, tidy # _CORNER: gap in pixels between the theme button and the window corner _CORNER: int = 10 @@ -55,7 +55,7 @@ def __init__(self) -> None: # update_theme_button: theme button offers the other theme, light_mode while dark and dark_mode while light def update_theme_button(self) -> None: - to_light = QApplication.styleHints().colorScheme() == Qt.ColorScheme.Dark + to_light = is_dark() stem, name = ('light_mode', 'Light mode') if to_light else ('dark_mode', 'Dark mode') found = icon(stem) self.theme_button.setText(name if found is None else '') diff --git a/src/pickmix/gui/style.py b/src/pickmix/gui/style.py index 795fdcb..0d3eea5 100644 --- a/src/pickmix/gui/style.py +++ b/src/pickmix/gui/style.py @@ -3,6 +3,7 @@ ''' # Import external dependencies +import sys from PySide6.QtCore import QSize, Qt from PySide6.QtGui import QColor, QIcon, QPalette from PySide6.QtWidgets import QAbstractButton, QAbstractItemView, QApplication, QHBoxLayout, QLabel, QLayout, QPushButton, QScrollArea, QTableWidget, QToolButton, QVBoxLayout, QWidget @@ -52,6 +53,46 @@ # _SMALL_NATIVE: widget classes whose native font is smaller than a label's _SMALL_NATIVE: tuple[str, ...] = ('QGroupBox', 'QToolButton', 'QHeaderView') +# _EXPLICIT_THEME: Qt does not repaint for setColorScheme on Linux so set palette by hand +_EXPLICIT_THEME: bool = sys.platform.startswith('linux') + +# _DARK: window, base, text and highlight colours of the dark palette +_DARK: dict[QPalette.ColorRole, str] = { + QPalette.ColorRole.Window: '#2b2b2b', QPalette.ColorRole.WindowText: '#e6e6e6', + QPalette.ColorRole.Base: '#1e1e1e', QPalette.ColorRole.AlternateBase: '#262626', + QPalette.ColorRole.Text: '#e6e6e6', QPalette.ColorRole.Button: '#3a3a3a', + QPalette.ColorRole.ButtonText: '#e6e6e6', QPalette.ColorRole.ToolTipBase: '#3a3a3a', + QPalette.ColorRole.ToolTipText: '#e6e6e6', QPalette.ColorRole.PlaceholderText: '#888888', + QPalette.ColorRole.Highlight: '#3d6fa3', QPalette.ColorRole.HighlightedText: '#ffffff', + QPalette.ColorRole.Link: '#5a9bd5', QPalette.ColorRole.BrightText: '#ffffff', + QPalette.ColorRole.Light: '#4a4a4a', QPalette.ColorRole.Midlight: '#424242', + QPalette.ColorRole.Mid: '#303030', QPalette.ColorRole.Dark: '#1a1a1a', QPalette.ColorRole.Shadow: '#000000', +} + +# is_dark: whether application palette is dark +def is_dark() -> bool: + palette = QApplication.palette() + return palette.color(QPalette.ColorRole.Window).lightness() < palette.color(QPalette.ColorRole.WindowText).lightness() + +# apply_theme: switch application to the dark or light theme +def apply_theme(app: QApplication, dark: bool) -> None: + if not _EXPLICIT_THEME: + app.styleHints().setColorScheme(Qt.ColorScheme.Dark if dark else Qt.ColorScheme.Light) + return + app.setStyle('Fusion') + palette = app.style().standardPalette() + if dark: + for role, colour in _DARK.items(): + palette.setColor(role, QColor(colour)) + for role in (QPalette.ColorRole.WindowText, QPalette.ColorRole.Text, QPalette.ColorRole.ButtonText): + palette.setColor(QPalette.ColorGroup.Disabled, role, QColor('#808080')) + app.setPalette(palette) + +# refresh_palette: re-derive palette from the style where Qt owns theme +def refresh_palette(app: QApplication) -> None: + if not _EXPLICIT_THEME: + app.setPalette(app.style().standardPalette()) + # body_pt: point size of an ordinary label, the reference every other widget is matched to def body_pt() -> float: return QLabel().font().pointSizeF() From 67aa4cee1b371fe92c2403a4828b4ab907f43026 Mon Sep 17 00:00:00 2001 From: Sam Holland Date: Thu, 12 Nov 2026 11:59:27 +0000 Subject: [PATCH 02/12] refactor(match): move helper functions - Modified match.py to add helper functions for returning template positions, binned tomograms, and for tomogram scanning. - Modified matcher.py to use shared helper functions. --- src/pickmix/match.py | 43 +++++++++++++++++++++++++++++++++++++-- src/pickmix/matcher.py | 46 +++++++++--------------------------------- 2 files changed, 51 insertions(+), 38 deletions(-) diff --git a/src/pickmix/match.py b/src/pickmix/match.py index b06e4ca..83b3d2f 100644 --- a/src/pickmix/match.py +++ b/src/pickmix/match.py @@ -3,7 +3,7 @@ ''' # Import external dependencies -import math, numpy as np, scipy.fft +import math, numpy as np, os, scipy.fft from collections.abc import Callable, Sequence from dataclasses import dataclass from scipy import ndimage, signal @@ -11,8 +11,10 @@ # Import internal pickmix objects from pickmix.candidates import Hit from pickmix.config import Config, Kind +from pickmix.estimates import EstimateStore from pickmix.extract import crop_box -from pickmix.utils.io import Tomogram, load_volume +from pickmix.model import Pick +from pickmix.utils.io import Tomogram, load_volume, volume_path # _SLAB: planes of a tomogram read and binned at a time _SLAB: int = 32 @@ -156,3 +158,40 @@ def scan( near = separation * template.bin free = [h for h in hits if all((h.x - kx) ** 2 + (h.y - ky) ** 2 + (h.z - kz) ** 2 > near**2 for kx, ky, kz in known)] return free[: params.max_per_tomogram] + +# template_positions: where template is cut for each pick, at its fit when it has a current one +def template_positions(picks: Iterable[Pick], tomos: dict[str, Tomogram], estimates: EstimateStore | None = None) -> list[tuple[str, float, float, float]]: + out = [] + for pick in picks: + if pick.tomogram in tomos: + fit = estimates.get(pick) if estimates else None + out.append((pick.tomogram, *((fit.x, fit.y, fit.z) if fit else (pick.x, pick.y, pick.z)))) + return out + +# binned_volume: tomogram binned by a factor, from out_dir/cache/binned when that is newer than the volume, else made and saved there +def binned_volume(tomo: Tomogram, factor: int, config: Config, stop: Callable[[], bool] = lambda: False) -> np.ndarray: + path = volume_path(tomo, source=config.source) + cached = config.out_dir / 'cache' / 'binned' / f'{path.stem}_x{factor}.npy' + if cached.exists() and cached.stat().st_mtime >= path.stat().st_mtime: + return np.load(cached) + binned = bin_volume(load_volume(tomo, source=config.source), factor, stop=stop) + cached.parent.mkdir(parents=True, exist_ok=True) + partial = cached.with_name(cached.stem + '.partial.npy') + np.save(partial, binned) + os.replace(partial, cached) + return binned + +# scan_tomogram: hits per kind in one tomogram, plus kinds left out because pixel size differs from the template's +def scan_tomogram(tomo: Tomogram, templates: dict[str, Template], config: Config, known: dict[str, list[tuple[float, float, float]]], stop: Callable[[], bool] = lambda: False) -> tuple[dict[str, list[Hit]], list[str]]: + hits: dict[str, list[Hit]] = {} + skipped: list[str] = [] + # one binned volume per binning factor, shared by the kinds that use it + volumes: dict[int, np.ndarray] = {} + for name, template in templates.items(): + if abs(tomo.pixel_size / template.pixel_size - 1) > 0.01: + skipped.append(name) + continue + if template.bin not in volumes: + volumes[template.bin] = binned_volume(tomo, template.bin, config, stop) + hits[name] = scan(volumes[template.bin], template, config.kinds[name], config, known.get(name, [])) + return hits, skipped diff --git a/src/pickmix/matcher.py b/src/pickmix/matcher.py index 47fc785..21d36ef 100644 --- a/src/pickmix/matcher.py +++ b/src/pickmix/matcher.py @@ -3,16 +3,14 @@ ''' # Import external dependencies -import numpy as np, os, threading +import threading from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor # Import internal pickmix objects -from pickmix.config import Config from pickmix.estimates import EstimateStore -from pickmix.match import Cancelled, bin_volume, build_template, scan +from pickmix.match import Cancelled, build_template, scan_tomogram, template_positions from pickmix.model import Session -from pickmix.utils.io import Tomogram, load_volume, volume_path # MatchService: builds a template from picks and scans unvisited tomograms for matches class MatchService: @@ -76,21 +74,13 @@ def _run(self, kind: str, generation: int) -> None: self._active -= 1 self._notify() - # _positions: where the template is cut for each pick of a kind, at the fit when it has a current one - def _positions(self, kind: str) -> list[tuple[str, float, float, float]]: - out = [] - for pick in self.session.store.all(kind): - if pick.tomogram in self.session.project.tomos: - fit = self.estimates.get(pick) if self.estimates else None - out.append((pick.tomogram, *((fit.x, fit.y, fit.z) if fit else (pick.x, pick.y, pick.z)))) - return out - # _scan: build template then scan unvisited tomograms def _scan(self, name: str, stop: Callable[[], bool]) -> None: project = self.session.project config, tomos = project.config, project.tomos kind = config.kinds[name] - template = build_template(name, kind, self._positions(name), tomos, config) + positions = template_positions(self.session.store.all(name), tomos, self.estimates) + template = build_template(name, kind, positions, tomos, config) names = [n for n in self.session.names if n not in self.session.visited] self.total = len(names) self._notify() @@ -98,18 +88,15 @@ def _scan(self, name: str, stop: Callable[[], bool]) -> None: if stop(): raise Cancelled tomo = tomos[tomogram] - if tomogram in self.session.visited: - pass - elif abs(tomo.pixel_size / template.pixel_size - 1) > 0.01: + known = [(p.x, p.y, p.z) for p in self.session.store.picks(tomogram, name)] + hits, skipped = scan_tomogram(tomo, {name: template}, config, {name: known}, stop) + if stop(): + raise Cancelled + if skipped: self.skipped.append(tomogram) else: - binned = _binned(tomo, template.bin, config, stop) - known = [(p.x, p.y, p.z) for p in self.session.store.picks(tomogram, name)] - hits = scan(binned, template, kind, config, known) - if stop(): - raise Cancelled reach = config.match.separation * kind.marker_a / tomo.pixel_size - self.session.candidates.replace(tomogram, name, hits, reach=reach) + self.session.candidates.replace(tomogram, name, hits[name], reach=reach) self.done += 1 self._notify() @@ -117,16 +104,3 @@ def _scan(self, name: str, stop: Callable[[], bool]) -> None: def _notify(self) -> None: for listener in self.listeners: listener() - -# _binned: the tomogram binned by a factor, from out_dir/cache/binned when that is newer than the volume, else made and saved there -def _binned(tomo: Tomogram, factor: int, config: Config, stop: Callable[[], bool]) -> np.ndarray: - path = volume_path(tomo, source=config.source) - cached = config.out_dir / 'cache' / 'binned' / f'{path.stem}_x{factor}.npy' - if cached.exists() and cached.stat().st_mtime >= path.stat().st_mtime: - return np.load(cached) - binned = bin_volume(load_volume(tomo, source=config.source), factor, stop=stop) - cached.parent.mkdir(parents=True, exist_ok=True) - partial = cached.with_name(cached.stem + '.partial.npy') - np.save(partial, binned) - os.replace(partial, cached) - return binned From f27de491ada1559dfafab9261efaf13dbcb9ccf4 Mon Sep 17 00:00:00 2001 From: Sam Holland Date: Thu, 12 Nov 2026 12:05:48 +0000 Subject: [PATCH 03/12] feat(candidates): defer saving on persist - Modified candidates.py to add a persist flag so bulk callers can save once instead of after every tomogram. - Modified tests/test_candidates.py to add test that replace without persist neither saves nor notifies. --- src/pickmix/candidates.py | 5 +++-- tests/test_candidates.py | 10 ++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/pickmix/candidates.py b/src/pickmix/candidates.py index b61be2b..a2b8ae6 100644 --- a/src/pickmix/candidates.py +++ b/src/pickmix/candidates.py @@ -77,7 +77,7 @@ def count(self, kind: str, tomogram: str | None = None, *, min_score: float = 0. return sum(c.status == 'new' and c.kind == kind and (tomogram is None or c.tomogram == tomogram) and c.score >= min_score for c in self._items.values()) # replace: the new candidates of a kind in a tomogram become these hits, except any within reach voxels of a rejected one - def replace(self, tomogram: str, kind: str, hits: Iterable[Hit], *, reach: float) -> None: + def replace(self, tomogram: str, kind: str, hits: Iterable[Hit], *, reach: float, persist: bool = True) -> None: with self._lock: rejected = [c for c in self._items.values() if c.status == 'rejected' and c.tomogram == tomogram and c.kind == kind] for stale in [c.id for c in self._items.values() if c.status == 'new' and c.tomogram == tomogram and c.kind == kind]: @@ -86,7 +86,8 @@ def replace(self, tomogram: str, kind: str, hits: Iterable[Hit], *, reach: float if all((h.x - r.x) ** 2 + (h.y - r.y) ** 2 + (h.z - r.z) ** 2 > reach**2 for r in rejected): candidate = Candidate(next(self._ids), tomogram, kind, h.x, h.y, h.z, h.score) self._items[candidate.id] = candidate - self._changed() + if persist: + self._changed() # reject: mark candidates as not wanted def reject(self, *candidate_ids: int) -> None: diff --git a/tests/test_candidates.py b/tests/test_candidates.py index 36f7d14..df06e77 100644 --- a/tests/test_candidates.py +++ b/tests/test_candidates.py @@ -33,6 +33,16 @@ def test_replace_and_query(self, make_config: Callable[..., Path]) -> None: assert [c.score for c in store.candidates(NAME, min_score=0.5)] == [0.6] assert store.candidates(NAME, 'other') == [] and store.count('cage') == 2 and store.count('cage', NAME, min_score=0.5) == 1 + # test_replace_without_persist: a bulk replace changes nothing on disk until the caller saves + def test_replace_without_persist(self, make_config: Callable[..., Path]) -> None: + store = _store(make_config) + heard: list[int] = [] + store.listeners.append(lambda: heard.append(1)) + store.replace(NAME, 'cage', [Hit(1, 1, 1, 0.3)], reach=2, persist=False) + assert store.count('cage') == 1 and heard == [] and not store.path.exists() + store.save() + assert CandidateStore(store.project).count('cage') == 1 + # test_replace_swaps_old_for_new: a new scan replaces the old candidates of that kind and tomogram only def test_replace_swaps_old_for_new(self, make_config: Callable[..., Path]) -> None: store = _store(make_config) From c9ad4fff998c91293d75ef1e325055570eb325bf Mon Sep 17 00:00:00 2001 From: Sam Holland Date: Thu, 12 Nov 2026 12:16:40 +0000 Subject: [PATCH 04/12] feat(lock): add project lock - Added lock.py to define a lock on a project to refuse concurrent edits. - Added tests/test_lock.py to define tests for refusing a second holder, releasing the lock and opening unprotected without fcntl. --- src/pickmix/lock.py | 66 +++++++++++++++++++++++++++++++++++++++++++++ tests/test_lock.py | 32 ++++++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 src/pickmix/lock.py create mode 100644 tests/test_lock.py diff --git a/src/pickmix/lock.py b/src/pickmix/lock.py new file mode 100644 index 0000000..84fb643 --- /dev/null +++ b/src/pickmix/lock.py @@ -0,0 +1,66 @@ +''' +pickmix: lock so one pickmix process at a time works on a project +''' + +# Import external dependencies +import os, socket, sys, time +from pathlib import Path +from typing import IO, Self + +# fcntl: Unix only so None on Windows +try: + import fcntl +except ImportError: + fcntl = None + +# LOCK_NAME: lockfile in out_dir +LOCK_NAME: str = '.pickmix.lock' + +# ProjectBusy: another pickmix process has project open +class ProjectBusy(Exception): + pass + +# ProjectLock: exclusive advisory lock on project, held until release or process ends, however it ends +class ProjectLock: + # __init__: take lock or raise ProjectBusy naming holder + def __init__(self, out_dir: Path, what: str) -> None: + out_dir.mkdir(parents=True, exist_ok=True) + self.path = out_dir / LOCK_NAME + # False when nothing can be locked, so project is open but unprotected + self.protected = fcntl is not None + self._handle: IO[str] | None = open(self.path, 'a+') + if fcntl is not None: + try: + fcntl.flock(self._handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + self._handle.close() + self._handle = None + raise ProjectBusy(f'{str(out_dir)!r} is in use by {self._holder()}; close it first') from None + except OSError: + self.protected = False + if not self.protected: + print('[pickmix] lock files are not supported on Windows, so do not open the GUI and candidate-search on one project at once', file=sys.stderr) + self._handle.seek(0) + self._handle.truncate() + self._handle.write(f'{what} (pid {os.getpid()} on {socket.gethostname()}, since {time.strftime("%Y-%m-%d %H:%M")})') + self._handle.flush() + + # release: let go of lock + def release(self) -> None: + if self._handle is not None: + self._handle.close() + self._handle = None + + # __enter__, __exit__: hold lock for a with block + def __enter__(self) -> Self: + return self + + def __exit__(self, *_: object) -> None: + self.release() + + # _holder: what wrote lock file + def _holder(self) -> str: + try: + return self.path.read_text().strip() or 'another pickmix process' + except OSError: + return 'another pickmix process' diff --git a/tests/test_lock.py b/tests/test_lock.py new file mode 100644 index 0000000..9e194ce --- /dev/null +++ b/tests/test_lock.py @@ -0,0 +1,32 @@ +''' +pickmix: tests for project lock +''' + +# Import external dependencies +import pytest +from pathlib import Path + +# Import internal pickmix objects +from pickmix.lock import ProjectBusy, ProjectLock + +class TestProjectLock: + # test_second_holder_is_refused: a held lock refuses another and names the holder + def test_second_holder_is_refused(self, tmp_path: Path) -> None: + with ProjectLock(tmp_path / 'out', 'GUI') as first: + assert first.protected + with pytest.raises(ProjectBusy, match=r'GUI \(pid \d+ on '): + ProjectLock(tmp_path / 'out', 'candidate-search') + + # test_release_frees_it: after release, or leaving the with block, the lock can be taken again, and release twice is harmless + def test_release_frees_it(self, tmp_path: Path) -> None: + lock = ProjectLock(tmp_path, 'GUI') + lock.release() + lock.release() + ProjectLock(tmp_path, 'GUI').release() + + # test_no_fcntl_warns_and_opens: without fcntl (Windows) the project opens unprotected, with a warning on stderr + def test_no_fcntl_warns_and_opens(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: + monkeypatch.setattr('pickmix.lock.fcntl', None) + with ProjectLock(tmp_path, 'GUI') as first, ProjectLock(tmp_path, 'candidate-search') as second: + assert not first.protected and not second.protected + assert 'lock files are not supported' in capsys.readouterr().err From 1ec6a0536c2bfacb96ecbc96ae294bd93942221e Mon Sep 17 00:00:00 2001 From: Sam Holland Date: Thu, 12 Nov 2026 12:28:32 +0000 Subject: [PATCH 05/12] feat(search): add parallel candidate search - Added search.py to build a template per kind from picks and scan each unvisited tomogram for all kinds in a worker process, with parent process writing candidates.csv. - Added tests/test_search.py to define tests for scanning tomograms for kind templates. --- src/pickmix/search.py | 112 ++++++++++++++++++++++++++++++++++++++++++ tests/test_search.py | 41 ++++++++++++++++ 2 files changed, 153 insertions(+) create mode 100644 src/pickmix/search.py create mode 100644 tests/test_search.py diff --git a/src/pickmix/search.py b/src/pickmix/search.py new file mode 100644 index 0000000..5dcb4b0 --- /dev/null +++ b/src/pickmix/search.py @@ -0,0 +1,112 @@ +''' +pickmix: candidate search, template matching over unvisited tomograms in worker processes +''' + +# Import external dependencies +from collections.abc import Callable +from concurrent.futures import ProcessPoolExecutor, as_completed +from dataclasses import dataclass, field +from pathlib import Path + +# Import internal pickmix objects +from pickmix.candidates import CandidateStore +from pickmix.estimates import EstimateStore +from pickmix.lock import ProjectLock +from pickmix.match import Template, build_template, scan_tomogram, template_positions +from pickmix.model import PickStore, Progress +from pickmix.project import Project, open_project + +# _SAVE_EVERY: tomograms between saves of candidates.csv, so interrupted searches keeps most of their work +_SAVE_EVERY: int = 25 + +# KindSummary: what a search found for one kind +@dataclass +class KindSummary: + candidates: int = 0 + # tomograms scanned for this kind + tomograms: int = 0 + # tomograms left out because their pixel size differs from the template's + skipped: list[str] = field(default_factory=list) + +# SearchResult: what a search did +@dataclass +class SearchResult: + # a summary for every kind that had a template + kinds: dict[str, KindSummary] + # kinds that could not make a template, with the reason + unusable: dict[str, str] + # tomograms whose scan failed, with the error + failed: dict[str, str] + # tomograms searched + total: int + +# search: build a template per kind from its picks, then scan every unvisited tomogram for all of them, one tomogram per worker process +def search( + config_path: Path, *, kinds: list[str] | None = None, workers: int = 1, threads: int = 1, + progress: Callable[[int, int], None] = lambda done, total: None, + say: Callable[[str], None] = lambda message: None, +) -> SearchResult: + say(f'Reading {str(config_path)!r}') + project = open_project(config_path) + unknown = [k for k in kinds or [] if k not in project.config.kinds] + if unknown: + raise ValueError(f'unknown kinds {unknown!r}, the project has {list(project.config.kinds)!r}') + # raises ProjectBusy when the GUI or another search has the project; the GUI would otherwise overwrite candidates.csv + with ProjectLock(project.config.out_dir, 'candidate-search'): + return _search(project, kinds, workers, threads, progress, say) + +# _search: search tomograms with project lock +def _search( + project: Project, kinds: list[str] | None, workers: int, threads: int, + progress: Callable[[int, int], None], say: Callable[[str], None], +) -> SearchResult: + config = project.config + picks, candidates = PickStore(project), CandidateStore(project) + estimates = EstimateStore(project, picks) + # tomograms opened in the GUI are being picked by hand, so they are left alone + path = config.out_dir / 'progress.json' + visited = set(Progress.model_validate_json(path.read_text()).visited) if path.exists() else set() + names = [n for n in project.tomos if n not in visited] + templates: dict[str, Template] = {} + result = SearchResult({}, {}, {}, len(names)) + for kind in kinds or list(config.kinds): + say(f'Building template for {kind!r}') + try: + templates[kind] = build_template(kind, config.kinds[kind], template_positions(picks.all(kind), project.tomos, estimates), project.tomos, config) + result.kinds[kind] = KindSummary() + except ValueError as e: + result.unusable[kind] = str(e) + if not templates or not names: + return result + # each worker process gets its own correlation thread count + scan_config = config.model_copy(update={'match': config.match.model_copy(update={'workers': threads})}) + say(f'Searching {len(names)} tomograms for {len(templates)} kinds with {min(workers, len(names))} workers') + progress(0, len(names)) + pool = ProcessPoolExecutor(max_workers=min(workers, len(names))) + try: + futures = {pool.submit(scan_tomogram, project.tomos[n], templates, scan_config, {k: [(p.x, p.y, p.z) for p in picks.picks(n, k)] for k in templates}): n for n in names} + for done, future in enumerate(as_completed(futures), start=1): + name = futures[future] + try: + hits, skipped = future.result() + except Exception as e: + result.failed[name] = f'{type(e).__name__}: {e}' + else: + for kind, found in hits.items(): + reach = config.match.separation * config.kinds[kind].marker_a / project.tomos[name].pixel_size + candidates.replace(name, kind, found, reach=reach, persist=False) + result.kinds[kind].tomograms += 1 + result.kinds[kind].candidates += candidates.count(kind, name) + for kind in skipped: + result.kinds[kind].skipped.append(name) + if done % _SAVE_EVERY == 0: + candidates.save() + progress(done, len(names)) + except BaseException: + # interrupt keeps what was found so far + pool.shutdown(wait=False, cancel_futures=True) + raise + finally: + candidates.save() + pool.shutdown() + return result diff --git a/tests/test_search.py b/tests/test_search.py new file mode 100644 index 0000000..6c756a9 --- /dev/null +++ b/tests/test_search.py @@ -0,0 +1,41 @@ +''' +pickmix: tests for candidate search and command line +''' + +# Import external dependencies +import pytest + +# Import internal pickmix objects +from pickmix.candidates import CandidateStore +from pickmix.model import Session +from pickmix.project import open_project +from pickmix.search import search +from test_matcher import blobs # noqa: F401, fixture + +class TestSearch: + # test_finds_blobs_without_touching_progress: picks in A give candidates at planted blobs of B, and search does not mark anything visited + def test_finds_blobs_without_touching_progress(self, blobs: tuple[Session, dict]) -> None: + session, planted = blobs + for x, y, z in planted['A']: + session.store.add('A', 'blob', x, y, z) + config_path = session.project.path + before = session.progress_path.read_text() + result = search(config_path, workers=2) + assert result.failed == {} and result.unusable == {} and result.total == 1 + assert result.kinds['blob'].tomograms == 1 and result.kinds['blob'].candidates >= 2 + assert session.progress_path.read_text() == before + found = CandidateStore(open_project(config_path)).candidates('B', 'blob', min_score=0.3) + assert len(found) == 2 + for x, y, z in planted['B']: + assert any(max(abs(c.x - x), abs(c.y - y), abs(c.z - z)) <= 2 for c in found) + + # test_kind_without_picks_is_unusable: a kind with no picks is reported and nothing is scanned + def test_kind_without_picks_is_unusable(self, blobs: tuple[Session, dict]) -> None: + session, _ = blobs + result = search(session.project.path) + assert 'nothing to build a template from' in result.unusable['blob'] and result.kinds == {} + + # test_unknown_kind: a kind the project lacks is an error + def test_unknown_kind(self, blobs: tuple[Session, dict]) -> None: + with pytest.raises(ValueError, match='unknown kinds'): + search(blobs[0].project.path, kinds=['nope']) From d6ca9d12fba45c8785b06d6d4f6d18661ad1a7ce Mon Sep 17 00:00:00 2001 From: Sam Holland Date: Thu, 12 Nov 2026 12:39:51 +0000 Subject: [PATCH 06/12] feat(cli): add candidate-search command - Added cli.py to define candidate-search command for running template matching via CLI. - Modified __init__.py to run candidate-search before starting the GUI if provided. - Modified tests/test_search.py to add tests for candidate-search summary, a missing config and a project another process has open. --- src/pickmix/__init__.py | 6 ++++- src/pickmix/cli.py | 58 +++++++++++++++++++++++++++++++++++++++++ tests/test_search.py | 27 +++++++++++++++++++ 3 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 src/pickmix/cli.py diff --git a/src/pickmix/__init__.py b/src/pickmix/__init__.py index 1154ac5..30891c9 100644 --- a/src/pickmix/__init__.py +++ b/src/pickmix/__init__.py @@ -11,10 +11,14 @@ except PackageNotFoundError: __version__ = 'unknown' -# main: launch the window, opening the config.toml given as the first argument +# main: launch the window or run candidate-search if asked for, opening the config.toml given as the first argument def main() -> None: import os, sys + if sys.argv[1:2] == ['candidate-search']: + from pickmix.cli import candidate_search + raise SystemExit(candidate_search(sys.argv[2:])) if sys.platform.startswith('linux') and not os.environ.get('WAYLAND_DISPLAY'): os.environ.setdefault('QT_QPA_PLATFORM', 'xcb') from pickmix.gui.app import run raise SystemExit(run(sys.argv[1:])) + diff --git a/src/pickmix/cli.py b/src/pickmix/cli.py new file mode 100644 index 0000000..642bc38 --- /dev/null +++ b/src/pickmix/cli.py @@ -0,0 +1,58 @@ +''' +pickmix: command line entry points +''' + +# Import external dependencies +import argparse, os, sys +from pathlib import Path + +# Import internal pickmix objects +from pickmix.lock import ProjectBusy +from pickmix.search import search + +# _BAR: width of the progress bar in characters +_BAR: int = 30 + +# candidate_search: run template matching search from a terminal or a cluster job and print what it found; returns the exit code +def candidate_search(argv: list[str]) -> int: + parser = argparse.ArgumentParser(prog='pickmix candidate-search', description='Template match every unvisited tomogram of a project for every kind that has picks, saving the candidates for the GUI to show.') + parser.add_argument('config', type=Path, help='the project config.toml') + parser.add_argument('-j', '--workers', type=int, default=os.process_cpu_count() or 1, help='worker processes, one tomogram each (default: the CPUs available)') + parser.add_argument('--threads', type=int, default=1, help='correlation threads inside each worker (default: 1)') + parser.add_argument('-k', '--kind', action='append', dest='kinds', help='only search for this kind; repeat for several (default: all)') + args = parser.parse_args(argv) + if args.workers < 1 or args.threads < 1: + parser.error('--workers and --threads must be at least 1') + try: + result = search(args.config, kinds=args.kinds, workers=args.workers, threads=args.threads, progress=_progress, say=_say) + except ProjectBusy as e: + print(e, file=sys.stderr) + return 1 + except (ValueError, OSError) as e: + print(f'{type(e).__name__}: {e}', file=sys.stderr) + return 1 + except KeyboardInterrupt: + print('\nInterrupted, candidates found so far were saved', file=sys.stderr) + return 130 + print(f'\nSearched {result.total} unvisited tomograms') + for kind, summary in result.kinds.items(): + print(f'{kind}: {summary.candidates} candidates identified across {summary.tomograms} tomograms') + if summary.skipped: + print(f' {len(summary.skipped)} tomograms skipped, pixel size differs from the template') + for kind, reason in result.unusable.items(): + print(f'{kind}: no search, {reason}') + for name, error in result.failed.items(): + print(f'{name}: failed, {error}', file=sys.stderr) + return 1 if result.failed else 0 + +# _say: a stage message on stderr +def _say(message: str) -> None: + print(message, file=sys.stderr, flush=True) + +# _progress: bar redrawn in place on terminal, else one line per tomogram so a cluster log stays readable +def _progress(done: int, total: int) -> None: + if sys.stderr.isatty(): + filled = _BAR * done // total + print(f'\r[{"#" * filled}{"." * (_BAR - filled)}] {done}/{total}', end='', file=sys.stderr, flush=True) + elif done: + print(f'{done}/{total} tomograms', file=sys.stderr, flush=True) diff --git a/tests/test_search.py b/tests/test_search.py index 6c756a9..9f258bf 100644 --- a/tests/test_search.py +++ b/tests/test_search.py @@ -4,9 +4,12 @@ # Import external dependencies import pytest +from pathlib import Path # Import internal pickmix objects +from pickmix.cli import candidate_search from pickmix.candidates import CandidateStore +from pickmix.lock import ProjectBusy, ProjectLock from pickmix.model import Session from pickmix.project import open_project from pickmix.search import search @@ -39,3 +42,27 @@ def test_kind_without_picks_is_unusable(self, blobs: tuple[Session, dict]) -> No def test_unknown_kind(self, blobs: tuple[Session, dict]) -> None: with pytest.raises(ValueError, match='unknown kinds'): search(blobs[0].project.path, kinds=['nope']) + + # test_command_summary: the command prints candidates per kind and exits 0 + def test_command_summary(self, blobs: tuple[Session, dict], capsys: pytest.CaptureFixture[str]) -> None: + session, planted = blobs + session.store.add('A', 'blob', *planted['A'][0]) + assert candidate_search([str(session.project.path), '-j', '1']) == 0 + out = capsys.readouterr().out + assert 'blob: ' in out and 'candidates identified across 1 tomograms' in out + + # test_command_missing_config: a missing config is an error message, not a traceback + def test_command_missing_config(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + assert candidate_search([str(tmp_path / 'none.toml')]) == 1 + assert 'none.toml' in capsys.readouterr().err + + # test_busy_project_is_refused: a project another process has open is not searched, and the command says who has it + def test_busy_project_is_refused(self, blobs: tuple[Session, dict], capsys: pytest.CaptureFixture[str]) -> None: + session, planted = blobs + session.store.add('A', 'blob', *planted['A'][0]) + with ProjectLock(session.project.config.out_dir, 'GUI'): + with pytest.raises(ProjectBusy, match='in use by GUI'): + search(session.project.path) + assert candidate_search([str(session.project.path)]) == 1 + assert 'in use by GUI' in capsys.readouterr().err + assert candidate_search([str(session.project.path), '-j', '1']) == 0 From ebc2120b292d73ed77d8fe3325854161d687643c Mon Sep 17 00:00:00 2001 From: Sam Holland Date: Thu, 12 Nov 2026 12:48:31 +0000 Subject: [PATCH 07/12] feat(gui): lock the project while it is open - Modified gui/tabs/project_tab.py to take project lock before showing a project, keep it over a reload and release it on close. - Modified tests/gui/test_project_tab.py to add tests for a busy project staying closed and for a reload keeping the lock. --- src/pickmix/gui/tabs/project_tab.py | 25 ++++++++++++++++++++++++- tests/gui/test_project_tab.py | 24 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/src/pickmix/gui/tabs/project_tab.py b/src/pickmix/gui/tabs/project_tab.py index 385adfd..51d0f0b 100644 --- a/src/pickmix/gui/tabs/project_tab.py +++ b/src/pickmix/gui/tabs/project_tab.py @@ -15,6 +15,7 @@ from pickmix.gui.panes.welcome_pane import WelcomePane from pickmix.gui.style import hint, icon_button, tidy, title, transparent_scroll from pickmix.gui.workers import run_in_background +from pickmix.lock import ProjectBusy, ProjectLock from pickmix.project import Project, create_project, open_project from pickmix.utils.star import MergeResult @@ -33,6 +34,8 @@ class ProjectTab(QWidget): def __init__(self) -> None: super().__init__() self.project: Project | None = None + # held while project is open + self.lock: ProjectLock | None = None self.welcome = WelcomePane() self.open_button = self.welcome.open_button self.new_button = self.welcome.new_button @@ -88,8 +91,10 @@ def open_config(self, path: Path) -> None: self._busy(f'Scanning tomograms for {str(path)!r}...') run_in_background(lambda: open_project(path), self.set_project, self._failed) - # set_project: show a project and announce it + # set_project: lock then show a project and announce it def set_project(self, project: Project) -> None: + if not self._lock(project): + return self.project = project self.title_label.setText(project.display_name) self.path_label.setText(str(project.path)) @@ -103,10 +108,28 @@ def set_project(self, project: Project) -> None: # close_project: close the open project and go back to the welcome page def close_project(self) -> None: self.project = None + if self.lock is not None: + self.lock.release() + self.lock = None self.stack.setCurrentIndex(0) self.status.setText('') self.project_closed.emit() + # _lock: hold project's lock, keeping one already held when reloading the same project + def _lock(self, project: Project) -> bool: + out_dir = project.config.out_dir + if self.lock is not None and self.lock.path.parent == out_dir: + return True + try: + taken = ProjectLock(out_dir, 'GUI') + except ProjectBusy as e: + self._idle(str(e)) + return False + if self.lock is not None: + self.lock.release() + self.lock = taken + return True + # _kinds_saved: kinds changed, so the hotkey dropdowns list the new ones, then tell the other tabs def _kinds_saved(self) -> None: self.settings_pane.refresh_hotkeys() diff --git a/tests/gui/test_project_tab.py b/tests/gui/test_project_tab.py index c209c26..10da19e 100644 --- a/tests/gui/test_project_tab.py +++ b/tests/gui/test_project_tab.py @@ -11,6 +11,7 @@ from pickmix.config import load_config from pickmix.gui.style import MEDIUM_PAD from pickmix.gui.tabs.project_tab import ProjectTab +from pickmix.lock import ProjectLock from pickmix.project import open_project # TestProjectTab: project tab @@ -104,3 +105,26 @@ def test_start_page_and_close(self, qtbot: QtBot, make_config: Callable[..., Pat with qtbot.waitSignal(tab.project_closed): tab.close_button.click() assert tab.stack.currentIndex() == 0 and tab.project is None + + # test_busy_project_is_not_opened: a project another process has locked stays closed, with the reason shown + def test_busy_project_is_not_opened(self, qtbot: QtBot, make_config: Callable[..., Path]) -> None: + project = open_project(make_config()) + with ProjectLock(project.config.out_dir, 'candidate-search'): + tab = ProjectTab() + qtbot.addWidget(tab) + tab.set_project(project) + assert tab.project is None and tab.stack.currentIndex() == 0 and 'candidate-search' in tab.status.text() + tab.set_project(project) + assert tab.project is project + + # test_reload_keeps_lock: reopening the same project does not lock it out of itself, and closing frees it + def test_reload_keeps_lock(self, qtbot: QtBot, make_config: Callable[..., Path]) -> None: + path = make_config() + tab = ProjectTab() + qtbot.addWidget(tab) + tab.set_project(open_project(path)) + tab.set_project(open_project(path)) + assert tab.project is not None + tab.close_project() + # taking the lock again is the proof it was freed + ProjectLock(open_project(path).config.out_dir, 'again').release() From ce34096b6454391cc3ea193fb1e806a5f363dd07 Mon Sep 17 00:00:00 2001 From: Sam Holland Date: Thu, 12 Nov 2026 12:59:01 +0000 Subject: [PATCH 08/12] fix(gui): update running scan style - Modified gui/panes/match_pane.py to show kind a running scan started with in place of current kind. - Modified tests/gui/test_panes.py to add test for status and button text during a scan. --- src/pickmix/gui/panes/match_pane.py | 3 ++- tests/gui/test_panes.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/pickmix/gui/panes/match_pane.py b/src/pickmix/gui/panes/match_pane.py index 44f17d6..30f7468 100644 --- a/src/pickmix/gui/panes/match_pane.py +++ b/src/pickmix/gui/panes/match_pane.py @@ -83,6 +83,7 @@ def min_score(self) -> float: def refresh(self, *, kind: str | None, picks: int, shown: int, total: int, selected: bool) -> None: busy = self.matcher is not None and self.matcher.busy self.score_label.setText(f'Score at least {self.min_score():.2f}') + self.scan_button.setText(f'Scan {kind}' if kind and not busy else 'Scan') self.scan_button.setEnabled(self.matcher is not None and kind is not None and picks > 0 and not busy) self.stop_button.setEnabled(busy) self.accept_button.setEnabled(selected) @@ -96,7 +97,7 @@ def _status(self, kind: str | None, picks: int, shown: int, total: int, busy: bo if matcher is None or kind is None: return '' if busy: - return f'Scanning {kind}: {matcher.done} of {matcher.total} tomograms' + return f'Scanning {matcher.kind}: {matcher.done} of {matcher.total} tomograms' if matcher.last_error: return f'Scan failed: {matcher.last_error}' if picks == 0: diff --git a/tests/gui/test_panes.py b/tests/gui/test_panes.py index 8b9daca..0205553 100644 --- a/tests/gui/test_panes.py +++ b/tests/gui/test_panes.py @@ -9,6 +9,7 @@ from PySide6.QtGui import QImage, QShortcut from PySide6.QtWidgets import QLabel from pytestqt.qtbot import QtBot +from types import SimpleNamespace # Import internal pickmix objects from pickmix import __version__ @@ -17,6 +18,7 @@ from pickmix.gui.dialogs.kind_dialog import DELETED, KindDialog from pickmix.gui.panes.average_pane import AveragePane from pickmix.gui.panes.kinds_pane import KindsPane +from pickmix.gui.panes.match_pane import MatchPane from pickmix.gui.panes.settings_pane import NO_KIND, SettingsPane from pickmix.gui.panes.tomo_pane import COLOUR_CURRENT, COLOUR_PENDING, COLOUR_VISITED, TomoPane from pickmix.gui.panes.tomograms_pane import TomogramsPane, tomogram_status @@ -350,6 +352,19 @@ def test_add_button_is_on_the_right(self, qtbot: QtBot, make_config: Callable[.. qtbot.waitUntil(lambda: pane.add_button.isVisible()) assert pane.add_button.mapTo(pane, pane.add_button.rect().topRight()).x() > pane.scroll.mapTo(pane, pane.scroll.rect().center()).x() +# TestMatchPane: match pane +class TestMatchPane: + # test_status_names_the_kind_being_scanned: while a scan runs the status and button follow the scan's kind, not the selected one + def test_status_names_the_kind_being_scanned(self, qtbot: QtBot) -> None: + pane = MatchPane() + qtbot.addWidget(pane) + pane.matcher = SimpleNamespace(busy=True, kind='cage', done=1, total=4, last_error='', skipped=[]) # type: ignore[assignment] + pane.refresh(kind='filament', picks=5, shown=0, total=0, selected=False) + assert pane.status.text() == 'Scanning cage: 1 of 4 tomograms' and pane.scan_button.text() == 'Scan' + pane.matcher.busy = False # type: ignore[union-attr] + pane.refresh(kind='filament', picks=5, shown=0, total=0, selected=False) + assert pane.scan_button.text() == 'Scan filament' + # TestSettingsPane: settings pane class TestSettingsPane: # test_shows_project: source and ring values come from the config, and showing them saves nothing From 5cfc4592f5d7c857166f3ab2194ea779a955b307 Mon Sep 17 00:00:00 2001 From: Sam Holland Date: Thu, 12 Nov 2026 13:19:49 +0000 Subject: [PATCH 09/12] feat(project): report each step of project opening - Modified project.py to add a callback to project opening as each step starts. - Modified tests/test_project.py to add test for steps being reported. --- src/pickmix/project.py | 8 ++++++-- tests/test_project.py | 8 +++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/pickmix/project.py b/src/pickmix/project.py index 05f29e7..ea1c8a2 100644 --- a/src/pickmix/project.py +++ b/src/pickmix/project.py @@ -4,7 +4,7 @@ # Import external dependencies from collections import Counter -from collections.abc import Sequence +from collections.abc import Callable, Sequence from dataclasses import dataclass from pathlib import Path @@ -40,8 +40,12 @@ def display_name(self) -> str: return self.config.name or self.path.parent.name # open_project: load a config.toml and discover its tomograms -def open_project(path: Path) -> Project: +def open_project(path: Path, *, say: Callable[[str], None] = lambda message: None) -> Project: + say('Reading config.toml') config = load_config(path) + say(f'Reading {config.tomograms_star.name}') + names = [row['rlnTomoName'] for row in read_star_loop(config.tomograms_star)] + say(f'Checking {len(names)} tomograms in {config.raw_dir}') issues: dict[str, TomogramError] = {} tomos = find_tomograms(config, issues=issues) names = [row['rlnTomoName'] for row in read_star_loop(config.tomograms_star)] diff --git a/tests/test_project.py b/tests/test_project.py index a63a1a0..2f83e96 100644 --- a/tests/test_project.py +++ b/tests/test_project.py @@ -66,4 +66,10 @@ def test_common_pixel_size(self, make_config: Callable[..., Path]) -> None: project = open_project(make_config()) assert project.common_pixel_size == 5.36 project.tomos = {} - assert project.common_pixel_size is None \ No newline at end of file + assert project.common_pixel_size is None + + # test_open_project_reports_steps: say hears each step in order, with the tomogram count + def test_open_project_reports_steps(self, make_config: Callable[..., Path]) -> None: + heard: list[str] = [] + open_project(make_config(), say=heard.append) + assert heard[0] == 'Reading config.toml' and heard[1].startswith('Reading ') and heard[2].startswith('Checking 1 tomograms in ') From a989607ce543b69e9da8635587d8effdbabb48a1 Mon Sep 17 00:00:00 2001 From: Sam Holland Date: Thu, 12 Nov 2026 13:35:16 +0000 Subject: [PATCH 10/12] feat(gui): add loading pane and elided label - Modified gui/components/status.py to let a status badge take an icon size. - Added gui/components/elided_label.py to define a label that cuts middle of text if text is too wide. - Added gui/panes/loading_pane.py to define a pane showing spinner, project path, ticked off steps and an error state. - Modified tests/gui/test_panes.py to add tests for new loading pane. - Modified tests/gui/test_components.py to add test for new elided label. --- src/pickmix/gui/components/elided_label.py | 32 ++++++++ src/pickmix/gui/components/status.py | 13 ++-- src/pickmix/gui/panes/loading_pane.py | 89 ++++++++++++++++++++++ tests/gui/test_components.py | 15 ++++ tests/gui/test_panes.py | 27 +++++++ 5 files changed, 170 insertions(+), 6 deletions(-) create mode 100644 src/pickmix/gui/components/elided_label.py create mode 100644 src/pickmix/gui/panes/loading_pane.py diff --git a/src/pickmix/gui/components/elided_label.py b/src/pickmix/gui/components/elided_label.py new file mode 100644 index 0000000..a4bfea9 --- /dev/null +++ b/src/pickmix/gui/components/elided_label.py @@ -0,0 +1,32 @@ +''' +pickmix: label that shortens long text to fit +''' + +# Import external dependencies +from PySide6.QtCore import Qt +from PySide6.QtGui import QResizeEvent +from PySide6.QtWidgets import QLabel, QSizePolicy + +# ElidedLabel: one line of text with middle cut out as "…" when it's wider than label +class ElidedLabel(QLabel): + # __init__: take width from layout + def __init__(self, text: str = '') -> None: + super().__init__() + self._full = '' + self.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) + self.setText(text) + + # setText: keep full text and show as much of it as fits + def setText(self, text: str) -> None: + self._full = text + self.setToolTip(text) + self._elide() + + # resizeEvent: refit text + def resizeEvent(self, event: QResizeEvent) -> None: + super().resizeEvent(event) + self._elide() + + # _elide: show text cut to width + def _elide(self) -> None: + super().setText(self.fontMetrics().elidedText(self._full, Qt.TextElideMode.ElideMiddle, self.width())) diff --git a/src/pickmix/gui/components/status.py b/src/pickmix/gui/components/status.py index 2bb14cf..9f97880 100644 --- a/src/pickmix/gui/components/status.py +++ b/src/pickmix/gui/components/status.py @@ -31,10 +31,10 @@ _FRAME_MS: int = 80 _FRAME_DEG: int = 30 -# status_icon: the icon of a status, or None without its file -def status_icon(status: Status) -> QIcon | None: +# status_icon: the icon of a status at an edge in pixels, or None without its file +def status_icon(status: Status, size: int = _SIZE) -> QIcon | None: stem, colour, _ = STATUS_STYLE[status] - return tinted(stem, colour, _SIZE) + return tinted(stem, colour, size) # status_item: a centred table cell showing a status, empty for None def status_item(status: Status | None, tip: str = '') -> QTableWidgetItem: @@ -61,9 +61,10 @@ def fit_status(state: str, flag: str) -> Status: # StatusBadge: one status as a label; running turns the icon, so it suits single widgets and short tables class StatusBadge(QLabel): # __init__: start empty - def __init__(self, status: Status | None = None, tip: str = '') -> None: + def __init__(self, status: Status | None = None, tip: str = '', *, size: int = _SIZE) -> None: super().__init__() self.status: Status | None = None + self._size = size self._base: QPixmap | None = None self._angle = 0 self._timer = QTimer(self) @@ -80,11 +81,11 @@ def set_status(self, status: Status | None, tip: str = '') -> None: self.clear() if status is None: return - found = status_icon(status) + found = status_icon(status, self._size) if found is None: self.setText(STATUS_STYLE[status][2]) return - self._base = found.pixmap(_SIZE, _SIZE) + self._base = found.pixmap(self._size, self._size) self.setPixmap(self._base) if status == 'running': self._timer.start() diff --git a/src/pickmix/gui/panes/loading_pane.py b/src/pickmix/gui/panes/loading_pane.py new file mode 100644 index 0000000..3558bba --- /dev/null +++ b/src/pickmix/gui/panes/loading_pane.py @@ -0,0 +1,89 @@ +''' +pickmix: loading pane shown while a project opens or is created +''' + +# Import external dependencies +from typing import Literal +from PySide6.QtCore import Qt, Signal +from PySide6.QtWidgets import QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget + +# Import internal pickmix objects +from pickmix.gui.components.elided_label import ElidedLabel +from pickmix.gui.components.status import StatusBadge +from pickmix.gui.style import MUTED, error_look, tidy, title + +# _ICON: edge in pixels of the spinner +_ICON: int = 48 + +# _WIDTH: widest the column of text grows, pixels +_WIDTH: int = 520 + +# _TITLES: heading while working and heading after a failure, per kind of work +_TITLES: dict[str, tuple[str, str]] = { + 'open': ('Opening project', 'Could not open project'), + 'create': ('Creating project', 'Could not create project'), +} + +# LoadingPane: spinner, what's being opened, and line per step as it happens +class LoadingPane(QWidget): + # dismissed: Back was pressed after a failure + dismissed = Signal() + + # __init__: build the pane + def __init__(self) -> None: + super().__init__() + self._kind: Literal['open', 'create'] = 'open' + self._done: list[str] = [] + self.badge = StatusBadge(size=_ICON) + self.title = title() + self.path = ElidedLabel() + self.path.setStyleSheet(f'color: {MUTED}') + self.detail = QLabel() + self.detail.setWordWrap(True) + self.detail.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + self.back_button = QPushButton('Back') + self.back_button.clicked.connect(self.dismissed) + # one column of text, centred and no wider than _WIDTH + column = QWidget() + column.setMaximumWidth(_WIDTH) + inner = QVBoxLayout(column) + inner.setContentsMargins(0, 0, 0, 0) + inner.addWidget(self.badge, alignment=Qt.AlignmentFlag.AlignHCenter) + for widget in (self.title, self.path, self.detail): + widget.setAlignment(Qt.AlignmentFlag.AlignHCenter) + inner.addWidget(widget) + inner.addWidget(self.back_button, alignment=Qt.AlignmentFlag.AlignHCenter) + row = QHBoxLayout() + row.addStretch(1) + row.addWidget(column, 100) + row.addStretch(1) + layout = QVBoxLayout(self) + tidy(layout) + layout.addStretch() + layout.addLayout(row) + layout.addStretch() + self.back_button.hide() + + # begin: start over for opening or creating the project at this path + def begin(self, kind: Literal['open', 'create'], path: str) -> None: + self._kind, self._done = kind, [] + self.badge.set_status('running') + self.title.setText(_TITLES[kind][0]) + self.path.setText(path) + self.detail.setStyleSheet('') + self.detail.setText('') + self.back_button.hide() + + # step: the next step has started, so the one before is ticked off + def step(self, message: str) -> None: + lines = [f'✓ {line}' for line in self._done] + [f'{message}...'] + self._done.append(message) + self.detail.setText('\n'.join(lines)) + + # fail: stop spinner and show why + def fail(self, message: str) -> None: + self.badge.set_status('error') + self.title.setText(_TITLES[self._kind][1]) + error_look(self.detail) + self.detail.setText(message) + self.back_button.show() diff --git a/tests/gui/test_components.py b/tests/gui/test_components.py index 1e38ccb..678e1fb 100644 --- a/tests/gui/test_components.py +++ b/tests/gui/test_components.py @@ -11,6 +11,7 @@ # Import internal pickmix objects from pickmix.gui.components.canvas import FitView, Marker, SliceCanvas +from pickmix.gui.components.elided_label import ElidedLabel from pickmix.gui.components.icons import ICON_DIR, icon, tinted from pickmix.gui.components.images import FitLabel, draw_box, label_cells, tile_cells, label_image, to_image, to_pixmap from pickmix.gui.components.range_slider import RangeSlider @@ -250,6 +251,20 @@ def test_fill_covers_canvas(self, qtbot: QtBot) -> None: canvas.fill() assert canvas.transform().m11() > fit_scale +# TestElidedLabel: elided label +class TestElidedLabel: + # test_long_text_is_cut_in_the_middle: text wider than the label loses its middle, keeps both ends and the full text in the tooltip + def test_long_text_is_cut_in_the_middle(self, qtbot: QtBot) -> None: + label = ElidedLabel() + qtbot.addWidget(label) + label.show() + label.resize(150, 20) + text = '/dls/ebic/data/staff-scratch/SamH/projects/very/long/path/config.toml' + label.setText(text) + assert '…' in label.text() and label.text().startswith('/dls') and label.text().endswith('config.toml') and label.toolTip() == text + label.resize(2000, 20) + assert label.text() == text + # TestIcons: icon loading and tinting class TestIcons: # test_bundled: every icon the GUI uses ships diff --git a/tests/gui/test_panes.py b/tests/gui/test_panes.py index 0205553..ad8faa9 100644 --- a/tests/gui/test_panes.py +++ b/tests/gui/test_panes.py @@ -18,6 +18,7 @@ from pickmix.gui.dialogs.kind_dialog import DELETED, KindDialog from pickmix.gui.panes.average_pane import AveragePane from pickmix.gui.panes.kinds_pane import KindsPane +from pickmix.gui.panes.loading_pane import LoadingPane from pickmix.gui.panes.match_pane import MatchPane from pickmix.gui.panes.settings_pane import NO_KIND, SettingsPane from pickmix.gui.panes.tomo_pane import COLOUR_CURRENT, COLOUR_PENDING, COLOUR_VISITED, TomoPane @@ -352,6 +353,32 @@ def test_add_button_is_on_the_right(self, qtbot: QtBot, make_config: Callable[.. qtbot.waitUntil(lambda: pane.add_button.isVisible()) assert pane.add_button.mapTo(pane, pane.add_button.rect().topRight()).x() > pane.scroll.mapTo(pane, pane.scroll.rect().center()).x() +# TestLoadingPane: loading pane +class TestLoadingPane: + # test_steps_are_ticked_off: each new step ticks the one before, and the current one ends in dots + def test_steps_are_ticked_off(self, qtbot: QtBot) -> None: + pane = LoadingPane() + qtbot.addWidget(pane) + pane.begin('open', '/p/config.toml') + pane.step('Reading config.toml') + pane.step('Reading tomograms.star') + assert pane.detail.text() == '✓ Reading config.toml\nReading tomograms.star...' and pane.title.text() == 'Opening project' + pane.begin('create', '/p') + assert pane.detail.text() == '' and pane.title.text() == 'Creating project' + + # test_fail_and_back: a failure shows the reason and Back, which announces itself + def test_fail_and_back(self, qtbot: QtBot) -> None: + pane = LoadingPane() + qtbot.addWidget(pane) + pane.show() + pane.begin('open', '/p/config.toml') + pane.fail('FileNotFoundError: nope') + assert pane.title.text() == 'Could not open project' and pane.detail.text() == 'FileNotFoundError: nope' and pane.back_button.isVisible() + with qtbot.waitSignal(pane.dismissed): + pane.back_button.click() + pane.begin('open', '/p/config.toml') + assert not pane.back_button.isVisible() + # TestMatchPane: match pane class TestMatchPane: # test_status_names_the_kind_being_scanned: while a scan runs the status and button follow the scan's kind, not the selected one From f0255268532dc19f5da36137b62d11632938a5be Mon Sep 17 00:00:00 2001 From: Sam Holland Date: Thu, 12 Nov 2026 13:49:08 +0000 Subject: [PATCH 11/12] feat(gui): show loading pane while a project opens - Modified gui/tabs/project_tab.py to show loading pane while a project is opened, created or reloaded, reporting each step, and to show failures on pane until Back is pressed. - Modified tests/gui/test_project_tab.py to add tests for loading page while opening and for a failed open. --- src/pickmix/gui/tabs/project_tab.py | 46 +++++++++++++++++++++-------- tests/gui/test_project_tab.py | 24 ++++++++++++++- 2 files changed, 56 insertions(+), 14 deletions(-) diff --git a/src/pickmix/gui/tabs/project_tab.py b/src/pickmix/gui/tabs/project_tab.py index 51d0f0b..7beffdd 100644 --- a/src/pickmix/gui/tabs/project_tab.py +++ b/src/pickmix/gui/tabs/project_tab.py @@ -3,18 +3,21 @@ ''' # Import external dependencies +from collections.abc import Callable from pathlib import Path +from typing import Literal from PySide6.QtCore import Qt, Signal from PySide6.QtWidgets import QFileDialog, QHBoxLayout, QLabel, QPushButton, QScrollArea, QStackedWidget, QVBoxLayout, QWidget # Import internal pickmix objects from pickmix.gui.dialogs.new_project_dialog import NewProjectDialog from pickmix.gui.panes.kinds_pane import KindsPane +from pickmix.gui.panes.loading_pane import LoadingPane from pickmix.gui.panes.settings_pane import SettingsPane from pickmix.gui.panes.tomograms_pane import TomogramsPane from pickmix.gui.panes.welcome_pane import WelcomePane from pickmix.gui.style import hint, icon_button, tidy, title, transparent_scroll -from pickmix.gui.workers import run_in_background +from pickmix.gui.workers import post, run_in_background from pickmix.lock import ProjectBusy, ProjectLock from pickmix.project import Project, create_project, open_project from pickmix.utils.star import MergeResult @@ -37,6 +40,8 @@ def __init__(self) -> None: # held while project is open self.lock: ProjectLock | None = None self.welcome = WelcomePane() + self.loading = LoadingPane() + self._before = 0 self.open_button = self.welcome.open_button self.new_button = self.welcome.new_button self.reload_button = icon_button('refresh', 'Reload', 'Reload config.toml and rescan the tomograms', size=28) @@ -74,6 +79,7 @@ def __init__(self) -> None: self.stack = QStackedWidget() self.stack.addWidget(self.welcome) self.stack.addWidget(opened) + self.stack.addWidget(self.loading) layout = QVBoxLayout(self) tidy(layout) layout.addWidget(self.stack, 1) @@ -85,11 +91,12 @@ def __init__(self) -> None: self.settings_pane.config_saved.connect(self.config_saved) self.settings_pane.hotkeys_saved.connect(self.kinds_saved) self.kinds_pane.config_saved.connect(self._kinds_saved) + self.loading.dismissed.connect(self._dismissed) # open_config: open a config.toml in the background def open_config(self, path: Path) -> None: - self._busy(f'Scanning tomograms for {str(path)!r}...') - run_in_background(lambda: open_project(path), self.set_project, self._failed) + say = self._busy('open', str(path)) + run_in_background(lambda: open_project(path, say=say), self.set_project, self._failed) # set_project: lock then show a project and announce it def set_project(self, project: Project) -> None: @@ -123,7 +130,9 @@ def _lock(self, project: Project) -> bool: try: taken = ProjectLock(out_dir, 'GUI') except ProjectBusy as e: - self._idle(str(e)) + self._idle('') + self.loading.fail(str(e)) + self.stack.setCurrentWidget(self.loading) return False if self.lock is not None: self.lock.release() @@ -152,8 +161,8 @@ def _new_dialog(self) -> None: if not dialog.exec(): return values = dialog.values() - self._busy('Merging runs and scanning tomograms...') - run_in_background(lambda: _create_and_open(values), self._created, self._failed) + say = self._busy('create', str(values['project_dir'])) + run_in_background(lambda: _create_and_open(values, say), self._created, self._failed) # _created: show the new project and say what the merge did def _created(self, made: tuple[Project, MergeResult]) -> None: @@ -161,11 +170,16 @@ def _created(self, made: tuple[Project, MergeResult]) -> None: self.set_project(project) self.status.setText(f'Created with {result.count} tomograms, {len(result.skipped)} duplicates skipped') - # _busy: block the open, create, reload and close buttons while work runs - def _busy(self, message: str) -> None: + # _busy: show the loading page and block the open, create, reload and close buttons while work runs + def _busy(self, kind: Literal['open', 'create'], path: str) -> Callable[[str], None]: + if self.stack.currentWidget() is not self.loading: + self._before = self.stack.currentIndex() for button in (self.open_button, self.new_button, self.reload_button, self.close_button): button.setEnabled(False) - self.status.setText(message) + self.status.setText('') + self.loading.begin(kind, path) + self.stack.setCurrentWidget(self.loading) + return lambda message: post(lambda: self.loading.step(message)) # _idle: unblock the buttons def _idle(self, message: str) -> None: @@ -173,11 +187,17 @@ def _idle(self, message: str) -> None: button.setEnabled(True) self.status.setText(message) - # _failed: show an error from background work + # _failed: unblock buttons and show an error on the loading page, which stays until Back def _failed(self, message: str) -> None: - self._idle(message) + self._idle('') + self.loading.fail(message) + + # _dismissed: go back to the page that was showing before loading started + def _dismissed(self) -> None: + self.stack.setCurrentIndex(self._before) # _create_and_open: create the project on disk, then open it -def _create_and_open(values: dict[str, object]) -> tuple[Project, MergeResult]: +def _create_and_open(values: dict[str, object], say: Callable[[str], None]) -> tuple[Project, MergeResult]: + say('Merging RELION runs and writing config.toml') path, result = create_project(**values) - return open_project(path), result + return open_project(path, say=say), result diff --git a/tests/gui/test_project_tab.py b/tests/gui/test_project_tab.py index 10da19e..026a052 100644 --- a/tests/gui/test_project_tab.py +++ b/tests/gui/test_project_tab.py @@ -113,7 +113,7 @@ def test_busy_project_is_not_opened(self, qtbot: QtBot, make_config: Callable[.. tab = ProjectTab() qtbot.addWidget(tab) tab.set_project(project) - assert tab.project is None and tab.stack.currentIndex() == 0 and 'candidate-search' in tab.status.text() + assert tab.project is None and tab.stack.currentWidget() is tab.loading and 'candidate-search' in tab.loading.detail.text() tab.set_project(project) assert tab.project is project @@ -128,3 +128,25 @@ def test_reload_keeps_lock(self, qtbot: QtBot, make_config: Callable[..., Path]) tab.close_project() # taking the lock again is the proof it was freed ProjectLock(open_project(path).config.out_dir, 'again').release() + + # test_loading_page_while_opening: opening switches to the loading page, which lists the steps, then the project shows + def test_loading_page_while_opening(self, qtbot: QtBot, make_config: Callable[..., Path]) -> None: + path = make_config() + tab = ProjectTab() + qtbot.addWidget(tab) + tab.open_config(path) + assert tab.stack.currentWidget() is tab.loading and tab.loading.path.toolTip() == str(path) + with qtbot.waitSignal(tab.project_changed): + pass + assert tab.stack.currentIndex() == 1 and 'Reading config.toml' in tab.loading.detail.text() + + # test_failed_open_stays_on_loading_page: a bad config shows why with a Back button, and Back returns to the welcome page + def test_failed_open_stays_on_loading_page(self, qtbot: QtBot, tmp_path: Path) -> None: + tab = ProjectTab() + qtbot.addWidget(tab) + tab.show() + tab.open_config(tmp_path / 'missing.toml') + qtbot.waitUntil(lambda: tab.loading.back_button.isVisible()) + assert tab.stack.currentWidget() is tab.loading and 'missing.toml' in tab.loading.detail.text() and tab.open_button.isEnabled() + tab.loading.back_button.click() + assert tab.stack.currentIndex() == 0 From 1d950ec1a7c0bfb236440d9b999d4e92578682f1 Mon Sep 17 00:00:00 2001 From: Sam Holland Date: Thu, 12 Nov 2026 14:00:46 +0000 Subject: [PATCH 12/12] chore: update pickmix version to v0.6.0 --- pyproject.toml | 2 +- uv.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 4cb72a3..5dd6f9c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "pickmix" -version = "0.5.0" +version = "0.6.0" description = "Multi-kind particle picking GUI for cryo-ET sub-tomogram averaging workflows." readme = "README.md" authors = [ diff --git a/uv.lock b/uv.lock index d2599ef..afe5d8f 100644 --- a/uv.lock +++ b/uv.lock @@ -137,7 +137,7 @@ wheels = [ [[package]] name = "pickmix" -version = "0.5.0" +version = "0.6.0" source = { editable = "." } dependencies = [ { name = "imageio" },