Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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 = [
Expand Down
10 changes: 8 additions & 2 deletions src/pickmix/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +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 sys
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:]))

5 changes: 3 additions & 2 deletions src/pickmix/candidates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand All @@ -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:
Expand Down
58 changes: 58 additions & 0 deletions src/pickmix/cli.py
Original file line number Diff line number Diff line change
@@ -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)
19 changes: 10 additions & 9 deletions src/pickmix/gui/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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:
Expand Down
32 changes: 32 additions & 0 deletions src/pickmix/gui/components/elided_label.py
Original file line number Diff line number Diff line change
@@ -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()))
13 changes: 7 additions & 6 deletions src/pickmix/gui/components/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
Expand All @@ -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()
Expand Down
89 changes: 89 additions & 0 deletions src/pickmix/gui/panes/loading_pane.py
Original file line number Diff line number Diff line change
@@ -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()
3 changes: 2 additions & 1 deletion src/pickmix/gui/panes/match_pane.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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:
Expand Down
6 changes: 3 additions & 3 deletions src/pickmix/gui/panes/welcome_pane.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 '')
Expand Down
Loading
Loading