Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
f9566d6
feat(gui): add pick patch canvas
holsam Nov 6, 2026
8aff2e3
feat(gui): add box outlines to preview images
holsam Nov 6, 2026
bc19803
feat(review): show 2x2 preview with editable patch
holsam Nov 7, 2026
795fdd1
pr: merge holsam/adjustable-patch to holsam/v0.5.0-release
holsam Nov 7, 2026
7a62349
feat(model): store optional box edge on picks
holsam Nov 7, 2026
ba0ce75
refactor: resolve box edge in one place
holsam Nov 7, 2026
849994f
feat(config): add pick mode & bounds padding
holsam Nov 7, 2026
548e2b9
feat(gui): add two-click bounds picking
holsam Nov 10, 2026
d3cc90f
feat(gui): show per-pick box column in tables
holsam Nov 10, 2026
5aaa2c5
pr: merge holsam/bounds-picking to holsam/v0.5.0-release
holsam Nov 10, 2026
467aed9
refactor(estimate): refactor crop/projection utils
holsam Nov 10, 2026
efbba51
feat(estimate): store direction on fits
holsam Nov 10, 2026
89574bb
feat(config): add filament estimator settings
holsam Nov 10, 2026
9353e02
feat(estimate): add filament estimator
holsam Nov 10, 2026
1af27c5
feat(gui): add filament settings to the settings pane
holsam Nov 10, 2026
01a274d
feat(gui): draw filament axis on canvas and patch
holsam Nov 11, 2026
d2f4eef
feat(average): orient boxes before averaging
holsam Nov 11, 2026
0281e2a
feat(gui): add orientation note in average pane
holsam Nov 11, 2026
1d07dd5
feat(export): write filament psi prior
holsam Nov 11, 2026
6cdb61b
pr: merge holsam/filament-estimator to holsam/v0.5.0-release
holsam Nov 11, 2026
631bd93
refactor(average): share box alignment
holsam Nov 11, 2026
749a878
feat(config): add validation settings
holsam Nov 11, 2026
4c34699
feat(validation): score picks vs kind averages
holsam Nov 11, 2026
96bac27
feat(validation): store scores and flag low scores
holsam Nov 11, 2026
0f13f03
feat(validation): add validation run for kinds
holsam Nov 11, 2026
a51647d
feat(review): add validate button and score column
holsam Nov 11, 2026
49bd4f7
feat(average): montage the lowest scoring picks
holsam Nov 11, 2026
6faab09
feat(gui): show validation section in settings
holsam Nov 11, 2026
db4a1ba
pr: merge holsam/kind-validation to holsam/v0.5.0-release
holsam Nov 11, 2026
9696e60
docs: update readme
holsam Nov 11, 2026
71e8b29
chore: update pickmix version to v0.5.0
holsam Nov 11, 2026
626d15c
feat(ui): show toast on tomogram load failure
holsam Nov 12, 2026
9e11cc2
chore: add light/dark mode icons
holsam Nov 12, 2026
9ccec77
feat(gui): add light/dark mode toggle
holsam Nov 12, 2026
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
14 changes: 14 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ create_new_folder.svg
Source: https://github.com/google/material-design-icons
Modifications: fill colour set to #8a8a8a

dark_mode.svg
Material Symbols "dark_mode" icon
Copyright (c) Google LLC
Licensed under the Apache License, Version 2.0 (see src/pickmix/gui/icons/LICENSE in this directory)
Source: https://github.com/google/material-design-icons
Modifications: fill colour set to #8a8a8a

delete.svg
Material Symbols "delete" icon
Copyright (c) Google LLC
Expand Down Expand Up @@ -98,6 +105,13 @@ left_panel_open.svg
Source: https://github.com/google/material-design-icons
Modifications: fill colour set to #8a8a8a

light_mode.svg
Material Symbols "light_mode" icon
Copyright (c) Google LLC
Licensed under the Apache License, Version 2.0 (see src/pickmix/gui/icons/LICENSE in this directory)
Source: https://github.com/google/material-design-icons
Modifications: fill colour set to #8a8a8a

logout.svg
Material Symbols "logout" icon
Copyright (c) Google LLC
Expand Down
26 changes: 18 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,29 @@ Click `[New project]`, and complete the fields in the dialog. Hover over a field
![Project tab](docs/images/project-tab.png)

#### 2.1 Tomograms
This table lists every tomogram alongside its shape, pixel size and whether a matching denoised volume was identified. Yellow warning indicate usable tomograms with issues to be aware of (e.g. no denoised tomogram found, unusual pixel size), while a red error marks a rejected or unusable tomogram - hover over the error to see the reaon.
This table lists every tomogram alongside its shape, pixel size and whether a matching denoised volume was identified. Yellow warnings indicate usable tomograms with issues to be aware of (e.g. no denoised tomogram found, unusual pixel size), while a red error marks a rejected or unusable tomogram - hover over the error to see the reaon.

#### 2.2 Kinds
Each 'kind' is a type of pick and multiple can be added as required. Each kind has a marker size, an extraction box, an estimator (`ring` fits a circle to a pick, `none` passes the click straight through), a colour, an optional parent kind and an extraction pixel size. A kind with a parent takes its membrane-normal orientation from the nearest parent estimate.
Each 'kind' is a type of pick and multiple can be added as required. Each kind has a marker size, an extraction box, an estimator (`ring` fits a circle to a pick, `filament` snaps a pick onto a dark filament, `none` passes the click straight through), a pick mode, a colour, an optional parent kind and an extraction pixel size. A kind with a parent takes its membrane-normal orientation from the nearest parent estimate.

![Kinds dialog](docs/images/kinds-dialog.png)

##### 2.2.1 `filament` estimator
The `filament` estimator finds the nearest dark filament, moves the pick onto its axis, and measures width, in-plane direction and z-extent. The pick's box can be sized one of two ways which is defined by `Box from`, each with different uses:

`Box from` value | Box size derived from | Description
-- | -- | --
`segment` (default) | The length of the filament | The box is large and mostly empty other than a thin filament, but useful for when the full filament is needed for further refinement
`width` | The width of the filament multiplied by a margin | The box is small but a single filament may be split into tiled particles along the axis

##### 2.2.2 `bounds` pick mod
A kind with the `bounds` pick mode is picked using two clicks, one on each side of the particle. The pick centre is then derived from the centre of the line linking the two click points, with box edge derives from this distance plus the kind's configured padding. Extraction and averaging use one box for a kind, therefore leave `Box edge` at 0 to derive this length from the 95th percentile of the picks' boxes.

#### 2.3 Settings
This pane controls general settings for the project, including which volume to use in the picking interface and which hotkeys map to which kinds. Parameters for the `ring` estimator can also be adjusted here as required.
This pane controls general settings for the project, including which volume to use in the picking interface and which hotkeys map to which kinds. Parameters for the `ring` and `filament` estimators, and for kind validation, can also be adjusted here as required.

### 3. Pick

Open the Pick tab. To the left is a a list of tomograms in the project, clicking a tomogram will jump there as will typing either its name or number into the search bar (the search bar automatically moves to the first match). If needed, the tomogram list can be hidden using the button next to the tomogram title. Select a kind using a hotkey or from the Kinds group, and left-click to add or select a pick. Picks can be moved by selecting & dragging, or deleted using the delete button (or `Delete` key). Right-click to pan across the current slice, and Ctrl/Cmd+Scroll to adjust zoom. Scrolling updates the current Z slice, and `Enter`/`Shift+Enter` steps forward/backward between tomograms. The settings pane has brightness/contrast controls, including `Auto` (the tomogram's own limits) and `Invert`, as well as auto-zoom functions `Fit` and `Fill`. The views group shows/hides fitted rings, boxes and normals. The pick table beneath shows each pick's estimate status: a green tick, a yellow warning (when flagged), a red error (when error occured during estimation), or a blue spinner (during processing).
Open the Pick tab. To the left is a a list of tomograms in the project, clicking a tomogram will jump there as will typing either its name or number into the search bar (the search bar automatically moves to the first match). If needed, the tomogram list can be hidden using the button next to the tomogram title. Select a kind using a hotkey or from the Kinds group, and left-click to add or select a pick. Picks can be moved by selecting & dragging, or deleted using the delete button (or `Delete` key). Right-click to pan across the current slice, and Ctrl/Cmd+Scroll to adjust zoom. Scrolling updates the current Z slice, as do the `Up`/`Down` arrow keys (`Shift` for ten slices at a time), and `Enter`/`Shift+Enter` steps forward/backward between tomograms. For a two-click kind, click one side of the structure then the other (`Esc` cancels). The settings pane has brightness/contrast controls, including `Auto` (the tomogram's own limits) and `Invert`, as well as auto-zoom functions `Fit` and `Fill`. The views group shows/hides fitted rings and filament axes, boxes and normals. The pick table beneath shows each pick's estimate status: a green tick, a yellow warning (when flagged), a red error (when error occured during estimation), or a blue spinner (during processing).

![Pick tab](docs/images/pick-tab.png)

Expand All @@ -62,13 +72,13 @@ Once several picks exist for a kind, the Match group within the settings pane ca

### 4. Review

Open the Review tab. Picks can be filtered by kind, tomogram, minimum SNR and whether they were flagged, with options to delete the selected pick or all currently shown. All picks can be queued for re-estimation here if required as well. Single-click a pick to view XY/XZ/YZ previews, or double-click to open that pick in the Pick tab.
Open the Review tab. Picks can be filtered by kind, tomogram, minimum SNR and whether they were flagged, with options to delete the selected pick or all currently shown. All picks can be queued for re-estimation here if required as well. Single-click a pick to view XY/XZ/YZ previews as well as a close-up patch. The pick's box is outlined in every panel, with the z range of its fit dotted in XZ and YZ, and a filament's axis is drawn in the patch. Drag the dot or the box in the patch to nudge the pick position and trigger re-estimation. Double-click a pick to open it in the Pick tab. `Validate` scores each pick of the chosen kind (all if none is chosen) against the average of its kind, taken over small shifts and without the lowest scoring picks, and flags picks scoring far below the rest as `lowcc`. Clean kinds won't be flagged, and the cut-off can be adjusted in Settings as required. The scores show in a `Score` column and `Worst first` orders by them.

![Review tab](docs/images/review-tab.png)

### 5. Average and export

Open the Export tab. At the top, the averaging pane allows selection of a kind to build a mean projection and montage of the picks for that kind (optionally filterable by tomogram). The mean and montage images can be saved to `out/` from here, as well as per-tomogram extracted picks if desired. Below, a table summarises the collected data for all kinds and allow specification of a minimum SNR and whether to include flagged picks in exports. Click the checkboxes for the desired output filetype(s) and click `Export` to save. `Extract` alternatively generates a subvolume from each pick and saves as MRC files under `out/particles/<kind>`.
Open the Export tab. At the top, the averaging pane allows selection of a kind to build a mean projection and montage of the picks for that kind (optionally filterable by tomogram). Filaments are turned along x before they are averaged, with their two ends not told apart. `Montage lowest scoring first` fills the montage with the lowest validation scores. The mean and montage images can be saved to `out/` from here, as well as per-tomogram extracted picks if desired. Below, a table summarises the collected data for all kinds and allow specification of a minimum SNR and whether to include flagged picks in exports. Click the checkboxes for the desired output filetype(s) and click `Export` to save. `Extract` alternatively generates a subvolume from each pick and saves as MRC files under `out/particles/<kind>`.

![Export tab](docs/images/export-tab.png)

Expand All @@ -79,5 +89,5 @@ project/
config.toml settings and kinds
tomograms.star merged RELION tomogram table
tilt_series/ one star file per tomogram
out/ picks, candidates, estimates, averages, RELION & .csv exports
out/ picks, candidates, estimates, validation scores, averages, RELION & .csv exports
```
Binary file modified docs/images/export-tab.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/kinds-dialog.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/pick-tab.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/project-tab.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/review-tab.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/welcome-page.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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.4.1"
version = "0.5.0"
description = "Multi-kind particle picking GUI for cryo-ET sub-tomogram averaging workflows."
readme = "README.md"
authors = [
Expand Down
75 changes: 60 additions & 15 deletions src/pickmix/average.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,15 @@
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from scipy import ndimage
from skimage.transform import resize
from skimage.util import montage

# Import internal pickmix objects
from pickmix.config import Config, Kind
from pickmix.estimate.registry import Fit
from pickmix.export import Item
from pickmix.model import Pick
from pickmix.extract import box_pixels, crop_box, pixel_size_of
from pickmix.utils.io import Tomogram, load_volume

Expand All @@ -37,34 +41,50 @@ class AverageResult:
labels: list[str]
# boxes averaged per tomogram
counts: dict[str, int]
# whether any box was turned so its filament axis lies along x
aligned: bool = False


# average_kind: cut a box at every item, project the central slab of each along z, normalise it, and average per tomogram and overall; nothing is written until save_average
def average_kind(
# box_images: the normalised projection of every item's box, tomogram by tomogram in order of first appearance, and the box edge in pixels. Each is the central slab of a box cut at the fit (the planes of the fit, turned so the axis lies along x, for a filament). A pick with a box of its own is cut at that size and resampled to the kind's box, so picks of different sizes can be compared
def box_images(
name: str, kind: Kind, items: list[Item], tomos: dict[str, Tomogram], config: Config,
*, log: Callable[[str], None] = lambda _: None,
) -> AverageResult:
) -> tuple[list[tuple[Pick, np.ndarray]], int]:
if not items:
raise ValueError(f'kind {name!r}: nothing to average')
px = pixel_size_of(name, items, tomos)
box = box_pixels(kind, items, px)
# slab as thick as the particle, so the projection is not washed out by empty box
half = min(max(round(kind.marker_a / 2 / px), 1), box // 2)
centre = box // 2
images: dict[str, list[np.ndarray]] = {}
origins: list[str] = []
out: list[tuple[Pick, np.ndarray]] = []
for tomogram in dict.fromkeys(p.tomogram for p, _ in items):
vol = load_volume(tomos[tomogram], source=config.source)
count = 0
for p, f in items:
if p.tomogram != tomogram:
continue
cube = crop_box(vol, (round(f.z), round(f.y), round(f.x)), box)
img = cube[centre - half : centre + half + 1].mean(axis=0)
images.setdefault(tomogram, []).append((img - img.mean()) / (img.std() or 1.0))
origins.append(f'{len(images[tomogram])} ({tomogram})')
log(f'{name} {tomogram}: {len(images[tomogram])} boxes')
img = _sized_image(vol, p, f, box, kind, px)
out.append((p, (img - img.mean()) / (img.std() or 1.0)))
count += 1
log(f'{name} {tomogram}: {count} boxes')
return out, box

# average_kind: cut a box at every item, project the central slab of each along z (the slab of the fit for a filament, turned so its axis lies along x), normalise it, and average per tomogram and overall; nothing is written until save_average
def average_kind(
name: str, kind: Kind, items: list[Item], tomos: dict[str, Tomogram], config: Config,
*, log: Callable[[str], None] = lambda _: None, scores: dict[int, float] | None = None,
) -> AverageResult:
pairs, box = box_images(name, kind, items, tomos, config, log=log)
images: dict[str, list[np.ndarray]] = {}
origins: list[str] = []
for pick, img in pairs:
images.setdefault(pick.tomogram, []).append(img)
origins.append(f'{len(images[pick.tomogram])} ({pick.tomogram})')
everything = [img for imgs in images.values() for img in imgs]
chosen = np.linspace(0, len(everything) - 1, min(len(everything), _MONTAGE_MAX)).astype(int)
if scores:
# unscored picks go last
ranked = sorted(range(len(pairs)), key=lambda i: scores.get(pairs[i][0].id, math.inf))
chosen = np.array(ranked[:_MONTAGE_MAX])
origins = [o if pairs[i][0].id not in scores else f'{o} {scores[pairs[i][0].id]:.2f}' for i, o in enumerate(origins)]
else:
chosen = np.linspace(0, len(everything) - 1, min(len(everything), _MONTAGE_MAX)).astype(int)
grid = math.ceil(math.sqrt(len(chosen)))
result = AverageResult(
name,
Expand All @@ -78,9 +98,18 @@ def average_kind(
MONTAGE_PAD,
[origins[i] for i in chosen],
{t: len(imgs) for t, imgs in images.items()},
any(f.psi_deg is not None for _, f in items),
)
return result

# _sized_image: the projection of one item's box at the kind's box edge. A pick with a box of its own is cut at that size, with the slab scaled to match, and resampled to the kind's box
def _sized_image(vol: np.ndarray, pick: Pick, fit: Fit, box: int, kind: Kind, px: float) -> np.ndarray:
own = box if pick.box_a is None else max(int(round(pick.box_a / px / 2)) * 2, 2)
# slab as thick as the particle, so the projection is not washed out by empty box
half = min(max(round(kind.marker_a / 2 / px * own / box), 1), own // 2)
img = _box_image(vol, fit, own, half)
return img if own == box else resize(img, (box, box), order=1, anti_aliasing=own > box, preserve_range=True).astype(np.float32)

# save_average: clear the kind's old PNGs and write the overall mean and montage, and each tomogram's mean when asked; returns the paths written
def save_average(result: AverageResult, *, per_tomogram: bool = False) -> list[Path]:
result.folder.mkdir(parents=True, exist_ok=True)
Expand All @@ -95,6 +124,22 @@ def save_average(result: AverageResult, *, per_tomogram: bool = False) -> list[P
_save(written[-1], img)
return written

# _box_image: projection of an item's box (fits without direction use central slab with half voxels either side, filament takes the planes z_lo to z_hi of fit from a box 1.5 times as wide, oriented so axis is along x)
def _box_image(vol: np.ndarray, fit: Fit, box: int, half: int) -> np.ndarray:
centre = (round(fit.z), round(fit.y), round(fit.x))
if fit.psi_deg is None:
cube = crop_box(vol, centre, box)
return cube[box // 2 - half : box // 2 + half + 1].mean(axis=0)
# even, so the centre voxel sits at big // 2 as in crop_box
big = 2 * math.ceil(box * 1.5 / 2)
cube = crop_box(vol, centre, big)
lo, hi = (min(max(z - centre[0] + big // 2, 0), big - 1) for z in (fit.z_lo, fit.z_hi))
img = cube[lo : hi + 1].mean(axis=0)
# a positive turn lays an axis at psi, measured from x towards y, along x
turned = ndimage.rotate(img, fit.psi_deg, reshape=False, order=1, mode='constant', cval=float(img.mean()))
start = (big - box) // 2
return turned[start : start + box, start : start + box]

# _save: write an image stretched between its 1st and 99th percentiles as an 8-bit PNG
def _save(path: Path, arr: np.ndarray) -> None:
lo, hi = np.percentile(arr, (1, 99))
Expand Down
Loading
Loading