diff --git a/NOTICE b/NOTICE index 984a462..d3db53a 100644 --- a/NOTICE +++ b/NOTICE @@ -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 @@ -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 diff --git a/README.md b/README.md index be1c97e..0d66c67 100644 --- a/README.md +++ b/README.md @@ -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) @@ -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/`. +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/`. ![Export tab](docs/images/export-tab.png) @@ -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 ``` diff --git a/docs/images/export-tab.png b/docs/images/export-tab.png index 5af1f9d..9692e01 100644 Binary files a/docs/images/export-tab.png and b/docs/images/export-tab.png differ diff --git a/docs/images/kinds-dialog.png b/docs/images/kinds-dialog.png index 9e2a41c..170775b 100644 Binary files a/docs/images/kinds-dialog.png and b/docs/images/kinds-dialog.png differ diff --git a/docs/images/pick-tab.png b/docs/images/pick-tab.png index 8b6286b..5798c1a 100644 Binary files a/docs/images/pick-tab.png and b/docs/images/pick-tab.png differ diff --git a/docs/images/project-tab.png b/docs/images/project-tab.png index 503a1dd..3d407bd 100644 Binary files a/docs/images/project-tab.png and b/docs/images/project-tab.png differ diff --git a/docs/images/review-tab.png b/docs/images/review-tab.png index ed7b493..e89890f 100644 Binary files a/docs/images/review-tab.png and b/docs/images/review-tab.png differ diff --git a/docs/images/welcome-page.png b/docs/images/welcome-page.png index 1f18f4b..50252e5 100644 Binary files a/docs/images/welcome-page.png and b/docs/images/welcome-page.png differ diff --git a/pyproject.toml b/pyproject.toml index ffda14d..4cb72a3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 = [ diff --git a/src/pickmix/average.py b/src/pickmix/average.py index 1ed6991..f98eed0 100644 --- a/src/pickmix/average.py +++ b/src/pickmix/average.py @@ -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 @@ -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, @@ -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) @@ -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)) diff --git a/src/pickmix/config.py b/src/pickmix/config.py index 89cde38..58d30ba 100644 --- a/src/pickmix/config.py +++ b/src/pickmix/config.py @@ -29,6 +29,10 @@ class Kind(BaseModel): tilt_prior_deg: float | None = Field(default=None, title='Tilt prior (°)', description='Written as rlnAngleTiltPrior when set, and left out otherwise.') # pixel size of the RELION extraction in Angstrom per pixel extract_angpix: float = Field(default=10.68, gt=0, title='Extract pixel size (Å/px)', description='Pixel size of the RELION extraction in Å per pixel.') + # how many clicks to create pick: one click, or two clicks on opposite sides of the structure + pick_mode: Literal['point', 'bounds'] = Field(default='point', title='Pick mode', description="'point': one click places the pick. 'bounds': click one side of the structure then the other; the pick goes midway between them and its box edge is the distance between the clicks plus padding. Extraction uses one box for the kind, taken from the picks' boxes when Box edge is 0.") + # fraction added to distance between two clicks of bounds pick + bounds_padding: float = Field(default=0.2, ge=0, title='Bounds padding (fraction)', description='Added to the distance between the two clicks of a bounds pick, as a fraction of it: 0.2 makes the box edge 20 per cent longer than the distance.') # RingParams: settings of the ring estimator, all lengths in Angstrom; title and description feed the settings form class RingParams(BaseModel): @@ -51,6 +55,46 @@ class RingParams(BaseModel): # box edge as a multiple of the ring diameter when the kind takes its box from the estimator box_margin: float = Field(default=1.25, title='Box margin (× diameter)', description='Box edge as a multiple of the ring diameter, for kinds that take their box from the estimator.') +# FilamentParams: settings of the filament estimator, all lengths in Angstrom; title and description feed the settings form +class FilamentParams(BaseModel): + # filament width as full width at half maximum, swept on a geometric ladder + width_range_a: tuple[float, float] = Field(default=(60.0, 300.0), title='Width range (Å)', description='Narrowest and widest filament width (full width at half maximum) looked for.') + width_steps: int = Field(default=5, ge=1, title='Width steps', description='How many widths are tried across the range.') + # how far from the pick the axis may be, and the longest stretch used to find direction and length + search_range_a: float = Field(default=300.0, gt=0, title='Search range (Å)', description='How far the filament axis may be from the pick in xy.') + max_length_a: float = Field(default=2000.0, gt=0, title='Max length (Å)', description='Longest stretch of filament used to find its direction and length.') + # z slab about the pick for the first look, and how far the z extent is searched + slab_half_a: float = Field(default=200.0, gt=0, title='First slab half-thickness (Å)', description='Half-thickness of the slab about the pick used to find the filament axis.') + z_max_half_a: float = Field(default=600.0, gt=0, title='Max z half-extent (Å)', description='The z extent of the filament is looked for this far above and below the pick.') + z_fraction: float = Field(default=0.5, gt=0, lt=1, title='Z extent threshold', description='A plane counts as filament while its contrast stays above this fraction of the best plane.') + # preparation of each projection + smooth_sigma_a: float = Field(default=8.0, gt=0, title='Smoothing σ (Å)', description='Light Gaussian smoothing of each projection.') + highpass_sigma_a: float = Field(default=600.0, gt=0, title='High-pass σ (Å)', description='Gaussian width removed from each projection to flatten the background.') + # share of the strongest ridge response kept when tracing the filament + ridge_fraction: float = Field(default=0.4, gt=0, lt=1, title='Ridge threshold', description='Pixels with at least this fraction of the strongest ridge response are traced as filament.') + # box + box_margin: float = Field(default=1.25, gt=0, title='Box margin (× width)', description='Box edge as a multiple of the filament width, for kinds that take their box from the estimator.') + min_box_a: float = Field(default=100.0, gt=0, title='Smallest box (Å)', description='The estimated box is never smaller than this.') + box_from: Literal['width', 'segment'] = Field(default='segment', title='Box from', description="'segment' sizes the box to the measured length of filament (up to Max length), so it holds the whole stretch, but it is large, varies with the length, and is mostly empty for a thin filament. 'width' sizes the box to the filament width times the margin, which is small and the same everywhere and suits tiling particles along the axis, but a long filament runs out of the box.") + # flags + weak_snr: float = Field(default=3.0, ge=0, title='Weak below SNR', description="Fits with an SNR below this are flagged 'weak'.") + min_elongation: float = Field(default=2.0, ge=1, title='Short below elongation', description="Traced stretches whose length is less than this many times their width are flagged 'short', as they are probably a spot and not a filament.") + +# ValidationParams: settings of kind validation, which scores each pick against the average of its kind; title and description feed the settings form +class ValidationParams(BaseModel): + # fewest picks a kind can be validated with + min_picks: int = Field(default=10, ge=3, title='Fewest picks', description='Only validate kinds with at least this many picks.') + # share of the lowest scoring picks left out of the average the scores are taken against + trim_fraction: float = Field(default=0.2, ge=0, lt=0.5, title='Trimmed share', description='Share of the lowest scoring picks left out of the average the scores are measured against, so bad picks do not bias average towards themselves.') + # how far a box may be shifted to find its best match, as a multiple of the box edge + shift_fraction: float = Field(default=0.125, ge=0, le=0.5, title='Search shift (× box)', description='How far a box may be shifted to find its best match with the average, as a multiple of the box edge.') + # a pick is flagged when its score sits this many robust standard deviations below the kind's median + flag_deviations: float = Field(default=6.0, gt=0, title='Flag deviations', description="A pick is flagged 'lowcc' when its score is this many robust standard deviations (from the median absolute deviation) below the median score of its kind.") + # smallest spread the kind's scores are taken to have, so a very uniform kind does not flag trivial differences + mad_floor: float = Field(default=0.02, gt=0, title='Smallest spread', description='Scores within a kind are expected to be at least this, so uniform kinds aren\'t flagged for minute differences.') + # absolute floor, 0 for none + min_score: float = Field(default=0.0, ge=0, lt=1, title='Lowest score', description="Picks scoring below this are also flagged 'lowcc'. 0 disables this flag.") + # MatchParams: settings of the template matching scan; title and description feed the settings form class MatchParams(BaseModel): # template is binned until its edge is about this many pixels, which sets the speed of the scan @@ -88,6 +132,8 @@ class Config(BaseModel): # most memory the slice cache may hold; scrolling is smooth where a whole tomogram fits cache_mb: int = Field(default=2048, ge=64, title='Slice cache (MB)', description='Most memory the viewer may use to keep slices of tomograms ready for scrolling.') ring: RingParams = Field(default_factory=RingParams) + filament: FilamentParams = Field(default_factory=FilamentParams) + validation: ValidationParams = Field(default_factory=ValidationParams) match: MatchParams = Field(default_factory=MatchParams) kinds: dict[str, Kind] = Field(default_factory=_default_kinds) # kind chosen by each of the keys 1 to 9, '' for an unused key @@ -129,11 +175,12 @@ def _fill_hotkeys(self) -> 'Config': self.hotkeys = [*keys, *[''] * (HOTKEYS - len(keys))] return self - # _relations: parents must exist and form no cycle, and a passthrough kind needs a box + # _relations: parents must exist and form no cycle, and a passthrough kind needs a box unless picks have own @model_validator(mode='after') def _relations(self) -> 'Config': for name, kind in self.kinds.items(): - if kind.estimator == 'none' and kind.box_a == 0: + # bounds kinds takes box from clicks + if kind.estimator == 'none' and kind.box_a == 0 and kind.pick_mode == 'point': raise ValueError(f'kind {name!r}: estimator "none" needs box_a above 0') seen, parent = {name}, kind.parent while parent is not None: diff --git a/src/pickmix/estimate/common.py b/src/pickmix/estimate/common.py new file mode 100644 index 0000000..4c5a78f --- /dev/null +++ b/src/pickmix/estimate/common.py @@ -0,0 +1,23 @@ +''' +pickmix: helpers shared by the estimators that fit a z slab projection +''' + +# Import external dependencies +import numpy as np +from scipy import ndimage + +# prepare: a projection smoothed by smooth_sigma_a and flattened by subtracting a copy smoothed by highpass_sigma_a, both in Angstrom +def prepare(slab: np.ndarray, smooth_sigma_a: float, highpass_sigma_a: float, px: float) -> np.ndarray: + smoothed = ndimage.gaussian_filter(slab, smooth_sigma_a / px) + return smoothed - ndimage.gaussian_filter(smoothed, highpass_sigma_a / px) + +# crop: sub-volume (z range clipped) round (y, x) with edge padding, the xy mask of real voxels, and the first z index +def crop(vol: np.ndarray, z0: int, z1: int, y: int, x: int, half: int) -> tuple[np.ndarray, np.ndarray, int]: + z0, z1 = max(z0, 0), min(z1, vol.shape[0] - 1) + ys = slice(max(y - half, 0), min(y + half + 1, vol.shape[1])) + xs = slice(max(x - half, 0), min(x + half + 1, vol.shape[2])) + block = np.asarray(vol[z0 : z1 + 1, ys, xs], dtype=np.float32) + pad_y = (ys.start - (y - half), (y + half + 1) - ys.stop) + pad_x = (xs.start - (x - half), (x + half + 1) - xs.stop) + valid = np.pad(np.ones(block.shape[1:], dtype=bool), (pad_y, pad_x)) + return np.pad(block, ((0, 0), pad_y, pad_x), mode='edge'), valid, z0 diff --git a/src/pickmix/estimate/filament.py b/src/pickmix/estimate/filament.py new file mode 100644 index 0000000..85ba8c1 --- /dev/null +++ b/src/pickmix/estimate/filament.py @@ -0,0 +1,224 @@ +''' +pickmix: filament estimator, snaps a pick onto the axis of a dark filament and measures its direction, width, length and z extent +''' + +# Import external dependencies +import math, numpy as np +from dataclasses import dataclass +from scipy import ndimage +from skimage.feature import hessian_matrix, hessian_matrix_eigvals + +# Import internal pickmix objects +from pickmix.config import Config, FilamentParams, Kind +from pickmix.estimate.common import prepare +from pickmix.estimate.registry import Fit, register + +# _FWHM_PER_SIGMA: full width at half maximum of a gaussian dip per unit of the Hessian scale that responds most strongly to it +_FWHM_PER_SIGMA: float = 1.665 + +# Trace: the stretch of ridge joined to the seed, in crop coordinates (y, x), with the axis as a unit vector (ux, uy) and the stretch's ends as distances along it from the seed +@dataclass(frozen=True) +class Trace: + y: float + x: float + ux: float + uy: float + s_lo: float + s_hi: float + + # length_px: how far the stretch reaches along the axis, in pixels + @property + def length_px(self) -> float: + return self.s_hi - self.s_lo + 1.0 + +# filament: snap to the axis of the filament nearest the pick, find how far it reaches in z, then measure it on the slab of those planes +@register('filament') +def filament(vol: np.ndarray, xyz: tuple[float, float, float], kind: Kind, pixel_size_a: float, config: Config) -> Fit: + params, px = config.filament, pixel_size_a + x0, y0, z0 = (round(v) for v in xyz) + z0 = min(max(z0, 0), vol.shape[0] - 1) + widths = _widths(params, px) + half = math.ceil((params.search_range_a + params.max_length_a / 2) / px) + math.ceil(params.width_range_a[1] / px) + # first look: a slab about the pick, to find the axis + k = round(params.slab_half_a / px) + img, valid = _projection(vol, max(z0 - k, 0), min(z0 + k, vol.shape[0] - 1), y0, x0, half, params, px) + ridge, scale = _ridge(img, valid, widths) + seed = _seed(ridge, (half, half), params.search_range_a / px) + trace = _trace(ridge, valid, seed, params, px) + # z extent from the contrast of the filament plane by plane + z_lo, z_hi, flags = _z_extent(vol, (x0, y0, z0), half, trace, float(widths[scale[seed]]), params, px) + # second look: the slab of those planes, which has far less noise + img, valid = _projection(vol, z_lo, z_hi, y0, x0, half, params, px) + ridge, scale = _ridge(img, valid, widths) + seed = _seed(ridge, (trace.y, trace.x), 2 * float(widths[scale[seed]])) + trace = _trace(ridge, valid, seed, params, px) + width_px = _width(img, trace, float(widths[scale[seed]])) + (cy, cx), snr = _centre(img, trace, width_px) + ends = [(cx + s * trace.ux, cy + s * trace.uy) for s in (trace.s_lo, trace.s_hi)] + # the segment's middle, or the filament point nearest the pick, which keeps particles where they were picked along the axis + along = (trace.s_lo + trace.s_hi) / 2 if params.box_from == 'segment' else (half - cx) * trace.ux + (half - cy) * trace.uy + fx, fy = cx + along * trace.ux, cy + along * trace.uy + width_a, length_a = width_px * px, trace.length_px * px + # crop coordinates map back by (value - half) + ex, ey = x0 + (fx - half), y0 + (fy - half) + if any(not (1 <= x0 + (x - half) <= vol.shape[2] - 2 and 1 <= y0 + (y - half) <= vol.shape[1] - 2) for x, y in ends): + flags.append('edge') + if snr < params.weak_snr: + flags.append('weak') + if length_a < params.min_elongation * width_a: + flags.append('short') + if math.hypot(fx - half, fy - half) > 0.75 * params.search_range_a / px: + flags.append('moved') + box_a = max(width_a * params.box_margin, params.min_box_a) + if params.box_from == 'segment': + box_a = max(box_a, min(length_a, params.max_length_a)) + return Fit( + x=ex, y=ey, z=(z_lo + z_hi) / 2, radius_a=width_a / 2, box_a=kind.box_a if kind.box_a > 0 else box_a, + snr=snr, z_lo=z_lo, z_hi=z_hi, flag=','.join(flags), psi_deg=round(math.degrees(math.atan2(trace.uy, trace.ux)), 6) % 180.0, + ) + +# _widths: the filament widths tried, in pixels, on a geometric ladder across the range +def _widths(params: FilamentParams, px: float) -> np.ndarray: + lo, hi = params.width_range_a + return np.geomspace(lo, hi, params.width_steps) / px + +# _window: a (2 half + 1) square of a plane centred on voxel (y, x), edge padded where it leaves the plane, with a mask of the pixels that are real +def _window(plane: np.ndarray, y: int, x: int, half: int) -> tuple[np.ndarray, np.ndarray]: + ys = slice(max(y - half, 0), min(y + half + 1, plane.shape[0])) + xs = slice(max(x - half, 0), min(x + half + 1, plane.shape[1])) + block = np.asarray(plane[ys, xs], dtype=np.float32) + pad = ((ys.start - (y - half), (y + half + 1) - ys.stop), (xs.start - (x - half), (x + half + 1) - xs.stop)) + return np.pad(block, pad, mode='edge'), np.pad(np.ones(block.shape, dtype=bool), pad) + +# _projection: mean of planes z_lo to z_hi (inclusive) in a window round (y, x), prepared, with the mask of real pixels +def _projection(vol: np.ndarray, z_lo: int, z_hi: int, y: int, x: int, half: int, params: FilamentParams, px: float) -> tuple[np.ndarray, np.ndarray]: + ys = slice(max(y - half, 0), min(y + half + 1, vol.shape[1])) + xs = slice(max(x - half, 0), min(x + half + 1, vol.shape[2])) + mean = np.asarray(vol[z_lo : z_hi + 1, ys, xs]).mean(axis=0, dtype=np.float32) + padded = np.zeros((vol.shape[1], vol.shape[2]), dtype=np.float32) + padded[ys, xs] = mean + window, valid = _window(padded, y, x, half) + return prepare(window, params.smooth_sigma_a, params.highpass_sigma_a, px), valid + +# _ridge: strongest dark-ridge response over the widths at every pixel, and the index of the width that gave it; blobs, which curve both ways, score nothing +def _ridge(img: np.ndarray, valid: np.ndarray, widths: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + best = np.zeros(img.shape, dtype=np.float32) + which = np.zeros(img.shape, dtype=np.intp) + for i, w in enumerate(widths): + sigma = w / _FWHM_PER_SIGMA + l1, l2 = hessian_matrix_eigvals(hessian_matrix(img, sigma=sigma, order='rc', use_gaussian_derivatives=True)) + response = (sigma**2 * np.maximum(l1 - np.abs(l2), 0)).astype(np.float32) + better = response > best + best[better], which[better] = response[better], i + best[~valid] = 0 + return best, which + +# _seed: the ridge pixel (y, x) with the best response within reach of a centre, nearer ones favoured +def _seed(ridge: np.ndarray, centre: tuple[float, float], reach_px: float) -> tuple[int, int]: + yy, xx = np.indices(ridge.shape) + d = np.hypot(yy - centre[0], xx - centre[1]) + score = np.where(d <= reach_px, ridge * np.exp(-0.5 * (d / max(reach_px, 1.0)) ** 2), -1.0) + y, x = np.unravel_index(np.argmax(score), ridge.shape) + return int(y), int(x) + +# _trace: the stretch of strong ridge joined to the seed within max_length of it, with its axis and its extent along the axis from the seed +def _trace(ridge: np.ndarray, valid: np.ndarray, seed: tuple[int, int], params: FilamentParams, px: float) -> Trace: + yy, xx = np.indices(ridge.shape) + reach = params.max_length_a / 2 / px + mask = (ridge >= params.ridge_fraction * ridge[seed]) & valid & (np.hypot(yy - seed[0], xx - seed[1]) <= reach) + # close one pixel gaps so noise does not cut a filament in two, and keep the seed itself + closed = ndimage.binary_closing(mask, structure=np.ones((3, 3), dtype=bool)) + closed[seed] = True + labels, _ = ndimage.label(closed, structure=np.ones((3, 3), dtype=bool)) + ys, xs = np.nonzero((labels == labels[seed]) & mask) + if len(ys) < 3: + return Trace(float(seed[0]), float(seed[1]), 1.0, 0.0, 0.0, 0.0) + cy, cx = ys.mean(), xs.mean() + _, vectors = np.linalg.eigh(np.cov(np.vstack([xs - cx, ys - cy]))) + ux, uy = (float(v) for v in vectors[:, -1]) + s = (xs - seed[1]) * ux + (ys - seed[0]) * uy + return Trace(float(seed[0]), float(seed[1]), ux, uy, float(s.min()), float(s.max())) + +# _strip: a plane sampled on a grid along an axis (columns, s) and across it (rows, t), both in pixels from a point (y, x) +def _strip(plane: np.ndarray, point: tuple[float, float], u: tuple[float, float], s: np.ndarray, t: np.ndarray) -> np.ndarray: + ss, tt = np.meshgrid(s, t) + ys = point[0] + ss * u[1] + tt * u[0] + xs = point[1] + ss * u[0] - tt * u[1] + return ndimage.map_coordinates(plane, [ys, xs], order=1, mode='nearest') + +# _contrast: how much darker the core of a strip is than its flanks, and the pixel noise of the flanks; t is the row coordinate +def _contrast(strip: np.ndarray, t: np.ndarray, width_px: float) -> tuple[float, float]: + core = np.abs(t) <= 0.25 * width_px + flank = (np.abs(t) >= width_px) & (np.abs(t) <= 2 * width_px) + return float(strip[flank].mean() - strip[core].mean()), float(strip[flank].std()) + 1e-6 + +# _z_extent: planes z_lo to z_hi, inclusive, over which the filament stays at least z_fraction as dark as at its darkest plane near the pick; flags say when the search or the volume ended it +def _z_extent( + vol: np.ndarray, pick: tuple[int, int, int], half: int, trace: Trace, width_px: float, params: FilamentParams, px: float, +) -> tuple[int, int, list[str]]: + x0, y0, z0 = pick + reach = max(abs(trace.s_lo), abs(trace.s_hi), 2 * width_px) + s = np.arange(-reach, reach + 1.0) + t = np.arange(-math.ceil(2.5 * width_px), math.ceil(2.5 * width_px) + 1.0) + first, last = max(z0 - round(params.z_max_half_a / px), 0), min(z0 + round(params.z_max_half_a / px), vol.shape[0] - 1) + contrast = np.array([ + _contrast(_strip(_window(vol[z], y0, x0, half)[0], (trace.y, trace.x), (trace.ux, trace.uy), s, t), t, width_px)[0] + for z in range(first, last + 1) + ]) + smooth = ndimage.gaussian_filter1d(contrast, max(params.smooth_sigma_a / px, 1.0)) + # the darkest plane within the first slab, so a second filament far above or below is not taken for this one + k = round(params.slab_half_a / px) + near = np.arange(max(z0 - k, first), min(z0 + k, last) + 1) - first + peak = int(near[np.argmax(smooth[near])]) + if smooth[peak] <= 0: + return z0, z0, [] + keep = smooth >= params.z_fraction * smooth[peak] + lo = hi = peak + while lo > 0 and keep[lo - 1]: + lo -= 1 + while hi < len(keep) - 1 and keep[hi + 1]: + hi += 1 + flags = [] + if (lo == 0 and first > 0) or (hi == len(keep) - 1 and last < vol.shape[0] - 1): + flags.append('zmax') + if (lo == 0 and first == 0) or (hi == len(keep) - 1 and last == vol.shape[0] - 1): + flags.append('zedge') + return first + lo, first + hi, flags + +# _width: full width at half depth of the dark profile across the traced stretch, interpolated; the ridge scale's width when the profile gives none +def _width(img: np.ndarray, trace: Trace, fallback_px: float) -> float: + s = np.arange(trace.s_lo, trace.s_hi + 1.0) + t = np.arange(-math.ceil(3 * fallback_px), math.ceil(3 * fallback_px) + 1.0) + profile = _strip(img, (trace.y, trace.x), (trace.ux, trace.uy), s, t).mean(axis=1) + edge = max(len(t) // 6, 1) + baseline = float(np.concatenate([profile[:edge], profile[-edge:]]).mean()) + low = int(np.argmin(profile)) + depth = baseline - float(profile[low]) + if depth <= 0: + return fallback_px + level = baseline - depth / 2 + left = next((i for i in range(low, 0, -1) if profile[i - 1] >= level), None) + right = next((i for i in range(low, len(profile) - 1) if profile[i + 1] >= level), None) + if left is None or right is None: + return fallback_px + # the crossing lies between the pixel below the level and the one above it + a = left - (level - profile[left]) / (profile[left - 1] - profile[left]) + b = right + (level - profile[right]) / (profile[right + 1] - profile[right]) + return max(float(b - a), 1.0) + +# _centre: the point (y, x) of the seed's position along the axis moved across to the middle of the filament, and the SNR of the stretch +def _centre(img: np.ndarray, trace: Trace, width_px: float) -> tuple[tuple[float, float], float]: + s = np.arange(trace.s_lo, trace.s_hi + 1.0) + t = np.arange(-math.ceil(3 * width_px), math.ceil(3 * width_px) + 1.0) + strip = _strip(img, (trace.y, trace.x), (trace.ux, trace.uy), s, t) + profile = strip.mean(axis=1) + # middle across the filament from the profile minimum, refined by a parabola through it + i = int(np.argmin(profile)) + offset = float(t[i]) + if 0 < i < len(t) - 1: + curve = profile[i - 1] - 2 * profile[i] + profile[i + 1] + if curve > 0: + offset += 0.5 * float(profile[i - 1] - profile[i + 1]) / float(curve) + diff, noise = _contrast(strip, t, width_px) + # across is the axis turned a quarter, so a step of offset moves x by -uy and y by ux + return (trace.y + offset * trace.ux, trace.x - offset * trace.uy), diff / noise diff --git a/src/pickmix/estimate/registry.py b/src/pickmix/estimate/registry.py index 2df6db1..a8f5840 100644 --- a/src/pickmix/estimate/registry.py +++ b/src/pickmix/estimate/registry.py @@ -23,6 +23,8 @@ class Fit(BaseModel): z_hi: int # comma-separated warnings, empty when fine flag: str = '' + # in-plane direction of the structure in degrees from the voxel x axis towards y, in [0, 180); None for structures with no direction + psi_deg: float | None = None # Estimator: volume (z, y, x), pick (x, y, z) in voxels, kind, pixel size in Angstrom, config type Estimator = Callable[[np.ndarray, tuple[float, float, float], Kind, float, Config], Fit] @@ -39,4 +41,4 @@ def add(fn: Estimator) -> Estimator: return add # imported last so the module can use the names above -from pickmix.estimate import none as _none, ring as _ring # noqa: E402,F401 +from pickmix.estimate import filament as _filament, none as _none, ring as _ring # noqa: E402,F401 diff --git a/src/pickmix/estimate/ring.py b/src/pickmix/estimate/ring.py index 9766144..c946681 100644 --- a/src/pickmix/estimate/ring.py +++ b/src/pickmix/estimate/ring.py @@ -5,11 +5,11 @@ # Import external dependencies import numpy as np from dataclasses import dataclass -from scipy import ndimage from skimage.feature import match_template # Import internal pickmix objects from pickmix.config import Config, Kind, RingParams +from pickmix.estimate.common import crop, prepare from pickmix.estimate.registry import Fit, register # Step: ring fit for one slab half-thickness k; y, x are crop coordinates, radius_px in voxels @@ -29,7 +29,7 @@ def ring(vol: np.ndarray, xyz: tuple[float, float, float], kind: Kind, pixel_siz half = int(np.ceil((params.bg_range[1] * params.radius_range_a[1] + params.locate_range_a) / px)) kmax = round(params.walk_max_half_a / px) shift = round(params.z_shift_a / px) - sub, valid, zlo = _crop(vol, z0 - kmax - shift, z0 + kmax + shift, y0, x0, half) + sub, valid, zlo = crop(vol, z0 - kmax - shift, z0 + kmax + shift, y0, x0, half) zc = z0 - zlo best = _walk_z(sub, valid, zc, params, px) dz, snr = _scan_z(sub, valid, zc, best, shift, params, px) @@ -96,7 +96,7 @@ def _walk_z(sub: np.ndarray, valid: np.ndarray, zc: int, params: RingParams, px: for zi in (lo, hi): if 0 <= zi < sub.shape[0]: slab = np.minimum(slab, sub[zi]) - img = _prepare(slab, params, px) + img = prepare(slab, params.smooth_sigma_a, params.highpass_sigma_a, px) y, x, r = _locate(img, centre, sweep, sigma, params, px) r = _radial_radius(img, valid, (y, x), r, params, px) step = Step(k, y, x, r, ring_snr(img, valid, (y, x), r, params, px)) @@ -116,11 +116,6 @@ def _distance(shape: tuple[int, ...], centre: tuple[float, float]) -> np.ndarray yy, xx = np.indices(shape) return np.hypot(yy - centre[0], xx - centre[1]) -# _prepare: smoothed, background-flattened minimum projection -def _prepare(slab: np.ndarray, params: RingParams, px: float) -> np.ndarray: - smoothed = ndimage.gaussian_filter(slab, params.smooth_sigma_a / px) - return smoothed - ndimage.gaussian_filter(smoothed, params.highpass_sigma_a / px) - # _locate: (y, x, radius_px) maximising ring NCC within locate_range of the previous centre def _locate(img: np.ndarray, centre: tuple[float, float], radii: np.ndarray, sigma: float, params: RingParams, px: float) -> tuple[float, float, float]: ncc, radius = ring_ncc(img, radii, sigma) @@ -141,19 +136,8 @@ def _scan_z(sub: np.ndarray, valid: np.ndarray, zc: int, best: Step, shift: int, scan = (0, best.snr) for dz in range(-shift, shift + 1): lo, hi = max(zc + dz - best.k, 0), min(zc + dz + best.k, sub.shape[0] - 1) - img = _prepare(sub[lo : hi + 1].min(axis=0), params, px) + img = prepare(sub[lo : hi + 1].min(axis=0), params.smooth_sigma_a, params.highpass_sigma_a, px) snr = ring_snr(img, valid, (best.y, best.x), best.radius_px, params, px) if snr > scan[1]: scan = (dz, snr) return scan - -# _crop: sub-volume (z range clipped) round (y, x) with edge padding, the xy mask of real voxels, and the first z index -def _crop(vol: np.ndarray, z0: int, z1: int, y: int, x: int, half: int) -> tuple[np.ndarray, np.ndarray, int]: - z0, z1 = max(z0, 0), min(z1, vol.shape[0] - 1) - ys = slice(max(y - half, 0), min(y + half + 1, vol.shape[1])) - xs = slice(max(x - half, 0), min(x + half + 1, vol.shape[2])) - block = np.asarray(vol[z0 : z1 + 1, ys, xs], dtype=np.float32) - pad_y = (ys.start - (y - half), (y + half + 1) - ys.stop) - pad_x = (xs.start - (x - half), (x + half + 1) - xs.stop) - valid = np.pad(np.ones(block.shape[1:], dtype=bool), (pad_y, pad_x)) - return np.pad(block, ((0, 0), pad_y, pad_x), mode='edge'), valid, z0 diff --git a/src/pickmix/estimates.py b/src/pickmix/estimates.py index aca14f6..99d2017 100644 --- a/src/pickmix/estimates.py +++ b/src/pickmix/estimates.py @@ -6,13 +6,27 @@ import csv, hashlib, json, os, threading from collections.abc import Callable from concurrent.futures import CancelledError, Future, ThreadPoolExecutor +from pydantic import field_validator from typing import Literal # Import internal pickmix objects +from pickmix.config import Kind from pickmix.estimate.registry import ESTIMATORS, Fit from pickmix.loader import Loader from pickmix.model import Pick, PickStore, Session from pickmix.project import Project +from pickmix.validation import ValidationStore + +# _PICKING: kind settings about how a pick is made, which do not change how it is estimated +_PICKING: set[str] = {'pick_mode', 'bounds_padding'} + +# effective_box_a: the box edge in Angstrom for a pick: its own if it has one, else the fit's, else the kind's, else the marker's +def effective_box_a(pick: Pick, kind: Kind, fit: Fit | None) -> float: + if pick.box_a is not None: + return pick.box_a + if fit is not None and fit.box_a > 0: + return fit.box_a + return kind.box_a if kind.box_a > 0 else kind.marker_a # _Row: one estimates.csv row, the fit plus the pick it was computed for and a digest of the settings used class _Row(Fit): @@ -23,6 +37,12 @@ class _Row(Fit): pick_z: float digest: str + # _blank: an empty csv cell is no direction + @field_validator('psi_deg', mode='before') + @classmethod + def _blank(cls, value: object) -> object: + return None if value == '' else value + # _Key: tomogram, kind and rounded coordinates of a pick; picks have no stable id across sessions type _Key = tuple[str, str, float, float, float] @@ -50,7 +70,10 @@ def digest(self, kind: str) -> str | None: self._digests = (config, {}) cache = self._digests[1] if kind not in cache and kind in config.kinds: - blob = json.dumps({'kind': config.kinds[kind].model_dump(), 'ring': config.ring.model_dump(), 'source': config.source}, sort_keys=True) + parts = {'kind': config.kinds[kind].model_dump(exclude=_PICKING), 'ring': config.ring.model_dump(), 'source': config.source} + if config.kinds[kind].estimator == 'filament': + parts['filament'] = config.filament.model_dump() + blob = json.dumps(parts, sort_keys=True) cache[kind] = hashlib.sha1(blob.encode()).hexdigest()[:12] return cache.get(kind) @@ -61,9 +84,10 @@ def state(self, pick: Pick) -> Literal['ok', 'stale', 'missing']: return 'missing' return 'ok' if row.digest == self.digest(pick.kind) else 'stale' - # get: the fit for a pick if it is current + # get: the fit for a pick if it is current, with pick's own box edge in place of estimator's when it has one def get(self, pick: Pick) -> Fit | None: - return self._rows.get(_key(pick.tomogram, pick.kind, pick.x, pick.y, pick.z)) if self.state(pick) == 'ok' else None + fit = self._rows.get(_key(pick.tomogram, pick.kind, pick.x, pick.y, pick.z)) if self.state(pick) == 'ok' else None + return fit if fit is None or pick.box_a is None else fit.model_copy(update={'box_a': pick.box_a}) # put: store a fit for the pick as it was when asked, save, and tell listeners def put(self, pick: Pick, fit: Fit, digest: str) -> None: @@ -97,6 +121,7 @@ class EstimateService: def __init__(self, session: Session, loader: Loader) -> None: self.session, self.loader = session, loader self.store = EstimateStore(session.project, session.store) + self.validation = ValidationStore(session.project, session.store, self.store.digest) self.last_error = '' self._pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix='pickmix-estimate') self._lock = threading.Lock() diff --git a/src/pickmix/export.py b/src/pickmix/export.py index 327959e..8525147 100644 --- a/src/pickmix/export.py +++ b/src/pickmix/export.py @@ -71,6 +71,8 @@ def export_kind( columns += ['rlnTomoSubtomogramRot', 'rlnTomoSubtomogramTilt', 'rlnTomoSubtomogramPsi', 'rlnAngleRot', 'rlnAngleTilt', 'rlnAnglePsi'] if kind.tilt_prior_deg is not None: columns.append('rlnAngleTiltPrior') + if kind.estimator == 'filament': + columns.append('rlnAnglePsiPrior') rows = [] for p, f in kept: row = [p.tomogram, *(f'{v:.2f}' for v in to_centred_angstrom((f.x, f.y, f.z), tomos[p.tomogram])), f'{f.snr:.3f}'] @@ -80,6 +82,8 @@ def export_kind( row += [f'{g.rot:.4f}', f'{g.tilt:.4f}', f'{g.psi:.4f}', '0.0000', '0.0000', '0.0000'] if kind.tilt_prior_deg is not None: row.append(f'{kind.tilt_prior_deg:.4f}') + if kind.estimator == 'filament': + row.append(f'{f.psi_deg or 0.0:.4f}') rows.append(row) folder = out_dir / 'relion' / name for stale in folder.glob('*.star'): diff --git a/src/pickmix/gui/app.py b/src/pickmix/gui/app.py index b1614fb..afadab9 100644 --- a/src/pickmix/gui/app.py +++ b/src/pickmix/gui/app.py @@ -4,17 +4,46 @@ # Import external dependencies from pathlib import Path -from PySide6.QtWidgets import QApplication +from PySide6.QtCore import QSettings, Qt, QTimer +from PySide6.QtWidgets import QApplication, QWidget # Import internal pickmix objects from pickmix.gui.main_window import MainWindow -from pickmix.gui.style import standardise +from pickmix.gui.style import 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) + +# _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) + +# _restyle: redraw tinted icons in new theme colour +def _restyle(app: QApplication, window: MainWindow) -> None: + def apply() -> None: + app.setPalette(app.style().standardPalette()) + for top in app.topLevelWidgets(): + for widget in (top, *top.findChildren(QWidget)): + app.style().unpolish(widget) + app.style().polish(widget) + widget.update() + retint(top) + window.project_tab.welcome.update_theme_button() + QTimer.singleShot(1, apply) # run: show the main window, opening the config.toml in args if one is given, and return the exit code def run(args: list[str]) -> int: app = QApplication.instance() or QApplication(['pickmix']) + _set_scheme(app) standardise(app) window = MainWindow() + window.project_tab.welcome.theme_toggled.connect(lambda: _toggle_theme(app)) + app.styleHints().colorSchemeChanged.connect(lambda _: _restyle(app, window)) window.show() if args: window.open_config(Path(args[0])) diff --git a/src/pickmix/gui/components/assets/dark_mode.svg b/src/pickmix/gui/components/assets/dark_mode.svg new file mode 100644 index 0000000..d64f188 --- /dev/null +++ b/src/pickmix/gui/components/assets/dark_mode.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/pickmix/gui/components/assets/light_mode.svg b/src/pickmix/gui/components/assets/light_mode.svg new file mode 100644 index 0000000..29fed0a --- /dev/null +++ b/src/pickmix/gui/components/assets/light_mode.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/pickmix/gui/components/canvas.py b/src/pickmix/gui/components/canvas.py index 56cc458..85c0a89 100644 --- a/src/pickmix/gui/components/canvas.py +++ b/src/pickmix/gui/components/canvas.py @@ -6,7 +6,7 @@ import math, numpy as np from dataclasses import dataclass from PySide6.QtCore import QPointF, Qt, Signal -from PySide6.QtGui import QColor, QImage, QMouseEvent, QPainter, QPen, QPixmap, QWheelEvent +from PySide6.QtGui import QColor, QImage, QKeyEvent, QMouseEvent, QPainter, QPen, QPixmap, QWheelEvent from PySide6.QtWidgets import QGraphicsEllipseItem, QGraphicsLineItem, QGraphicsRectItem, QGraphicsScene, QGraphicsView # Import internal pickmix objects @@ -21,7 +21,7 @@ # _DRAG_PX: screen distance before a press on a marker becomes a drag _DRAG_PX: float = 3.0 -# FitView: a fit as the canvas draws it; centre in voxels, ring and box sizes in pixels, slab as inclusive slices +# FitView: a fit as the canvas draws it; centre in voxels, ring and box sizes in pixels, slab as inclusive slices, direction of filament in degrees (from x to y) @dataclass(frozen=True) class FitView: cx: float @@ -31,6 +31,7 @@ class FitView: box_px: float | None z_lo: int z_hi: int + psi_deg: float | None = None # Marker: a pick as the canvas draws it; x, y in voxels, z the slice it was picked on @dataclass(frozen=True) @@ -55,6 +56,8 @@ class SliceCanvas(QGraphicsView): add_requested = Signal(float, float) # move_requested: marker dragged and released, pick id and new voxel x, y move_requested = Signal(int, float, float) + # bounds_requested: two clicks made in bounds mode, as voxel x1, y1, x2, y2 + bounds_requested = Signal(float, float, float, float) # marker_clicked: marker pressed and released without moving marker_clicked = Signal(int) # z_scrolled: wheel steps, positive is up @@ -74,6 +77,7 @@ def __init__(self) -> None: self._items: dict[int, QGraphicsEllipseItem] = {} self._extras: dict[int, tuple[QGraphicsEllipseItem | None, QGraphicsRectItem | None]] = {} self._arrows: dict[int, QGraphicsLineItem] = {} + self._axes: dict[int, QGraphicsLineItem] = {} self._rings = True self._boxes = True self._normals = True @@ -82,10 +86,17 @@ def __init__(self) -> None: self._drag_moved = False self._pan: QPointF | None = None self._wheel = 0 + # bounds mode: whether a click starts or finishes a pair, the padding the box gets, its colour, and the first click and what is drawn for it + self._bounds = False + self._padding = 0.0 + self._bounds_colour = 'yellow' + self._first: QPointF | None = None + self._rubber: tuple[QGraphicsLineItem, QGraphicsRectItem] | None = None self.setTransformationAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse) self.setRenderHint(QPainter.RenderHint.Antialiasing) self.setBackgroundBrush(QColor(WELL_BG)) self.setFocusPolicy(Qt.FocusPolicy.ClickFocus) + self.viewport().setMouseTracking(True) # has_image: whether a slice is showing @property @@ -114,6 +125,34 @@ def normal_visible(self, marker_id: int) -> bool: arrow = self._arrows.get(marker_id) return arrow is not None and arrow.isVisible() + # bounds_pending: whether a first click of a bounds pair has been made + @property + def bounds_pending(self) -> bool: + return self._first is not None + + # set_bounds_mode: on, a click on empty image starts a bounds pair and the next one finishes it, with the box padded by this fraction and previewed in this colour; off, a click places a pick. Changing the mode drops a pair under way + def set_bounds_mode(self, on: bool, padding: float = 0.0, colour: str = 'yellow') -> None: + self.cancel_bounds() + self._bounds, self._padding, self._bounds_colour = on, padding, colour + + # cancel_bounds: forget a first click + def cancel_bounds(self) -> None: + self._first = None + if self._rubber is not None: + for item in self._rubber: + self._scene.removeItem(item) + self._rubber = None + + # axis_visible: whether a marker's filament axis is showing on this slice + def axis_visible(self, marker_id: int) -> bool: + axis = self._axes.get(marker_id) + return axis is not None and axis.isVisible() + + # axis_angle: the direction in degrees of a marker's filament axis as drawn, from the x axis towards y, None if it has none + def axis_angle(self, marker_id: int) -> float | None: + axis = self._axes.get(marker_id) + return None if axis is None else math.degrees(math.atan2(axis.line().dy(), axis.line().dx())) % 180.0 + # set_overlay: show or hide the fit rings, boxes and normals def set_overlay(self, *, rings: bool, boxes: bool, normals: bool = True) -> None: self._rings, self._boxes, self._normals = rings, boxes, normals @@ -146,10 +185,13 @@ def set_markers(self, markers: list[Marker]) -> None: for item in extra: if item is not None: self._scene.removeItem(item) + for axis in self._axes.values(): + self._scene.removeItem(axis) self._markers = {m.id: m for m in markers} self._items = {} self._extras = {} self._arrows = {} + self._axes = {} for m in markers: ring = QGraphicsEllipseItem(-m.radius_px, -m.radius_px, 2 * m.radius_px, 2 * m.radius_px) ring.setPos(m.x + 0.5, m.y + 0.5) @@ -168,6 +210,8 @@ def set_markers(self, markers: list[Marker]) -> None: self._items[m.id] = ring if m.fit is not None: self._extras[m.id] = self._add_fit(m, m.fit) + if m.fit.psi_deg is not None and m.fit.box_px: + self._axes[m.id] = self._add_axis(m, m.fit) if self.selected_id not in self._markers: self.selected_id = None self._restyle() @@ -179,6 +223,7 @@ def select(self, marker_id: int | None) -> None: # clear: remove the slice and every marker, for a tomogram change def clear(self) -> None: + self.cancel_bounds() self._slice = None self._pixmap.setPixmap(QPixmap()) self.set_markers([]) @@ -203,7 +248,15 @@ def mousePressEvent(self, event: QMouseEvent) -> None: self.select(hit) self._drag, self._drag_moved = (hit, pos), False elif self._slice is not None and self._inside(pos): - self.add_requested.emit(pos.x() - 0.5, pos.y() - 0.5) + if not self._bounds: + self.add_requested.emit(pos.x() - 0.5, pos.y() - 0.5) + elif self._first is None: + self._first = pos + self._start_rubber(pos) + else: + first = self._first + self.cancel_bounds() + self.bounds_requested.emit(first.x() - 0.5, first.y() - 0.5, pos.x() - 0.5, pos.y() - 0.5) else: super().mousePressEvent(event) @@ -226,8 +279,17 @@ def mouseMoveEvent(self, event: QMouseEvent) -> None: m = self._markers[pick_id] self._items[pick_id].setPos(m.x + 0.5 + delta.x(), m.y + 0.5 + delta.y()) else: + if self._first is not None: + self._update_rubber(self.mapToScene(event.position().toPoint())) super().mouseMoveEvent(event) + # keyPressEvent: Escape drops a bounds pair under way + def keyPressEvent(self, event: QKeyEvent) -> None: + if event.key() == Qt.Key.Key_Escape and self._first is not None: + self.cancel_bounds() + else: + super().keyPressEvent(event) + # mouseReleaseEvent: finish a pan, or finish a marker press as a click or a move def mouseReleaseEvent(self, event: QMouseEvent) -> None: if event.button() == Qt.MouseButton.RightButton and self._pan is not None: @@ -287,6 +349,10 @@ def _restyle(self) -> None: item.setPen(pen) for arrow in self._arrows.values(): arrow.setVisible(self._normals) + for marker_id, axis in self._axes.items(): + fit = self._markers[marker_id].fit + assert fit is not None + axis.setVisible(self._rings and fit.z_lo <= self._z <= fit.z_hi) for marker_id, (ring, box) in self._extras.items(): fit = self._markers[marker_id].fit assert fit is not None @@ -313,6 +379,18 @@ def _add_fit(self, m: Marker, fit: FitView) -> tuple[QGraphicsEllipseItem | None self._scene.addItem(box) return ring, box + # _add_axis: solid line through the fit centre along a filament, as long as the box is wide + def _add_axis(self, m: Marker, fit: FitView) -> QGraphicsLineItem: + assert fit.psi_deg is not None and fit.box_px is not None + reach = fit.box_px / 2 + dx, dy = math.cos(math.radians(fit.psi_deg)) * reach, math.sin(math.radians(fit.psi_deg)) * reach + axis = QGraphicsLineItem(-dx, -dy, dx, dy) + axis.setPen(self._fit_pen(m.colour, Qt.PenStyle.SolidLine, 2)) + axis.setPos(fit.cx + 0.5, fit.cy + 0.5) + axis.setZValue(1) + self._scene.addItem(axis) + return axis + # _fit_pen: cosmetic pen for fit outlines and arrows def _fit_pen(self, colour: str, style: Qt.PenStyle, width: int = 1) -> QPen: pen = QPen(QColor(colour)) @@ -321,6 +399,26 @@ def _fit_pen(self, colour: str, style: Qt.PenStyle, width: int = 1) -> QPen: pen.setStyle(style) return pen + # _start_rubber: the line and box that follow the pointer after a first click + def _start_rubber(self, pos: QPointF) -> None: + line = QGraphicsLineItem(pos.x(), pos.y(), pos.x(), pos.y()) + line.setPen(self._fit_pen(self._bounds_colour, Qt.PenStyle.SolidLine, 2)) + box = QGraphicsRectItem() + box.setPen(self._fit_pen(self._bounds_colour, Qt.PenStyle.DashLine)) + for item in (line, box): + item.setZValue(3) + self._scene.addItem(item) + self._rubber = (line, box) + + # _update_rubber: line from the first click to the pointer, and the box the pair would make, centred halfway + def _update_rubber(self, pos: QPointF) -> None: + if self._first is None or self._rubber is None: + return + line, box = self._rubber + line.setLine(self._first.x(), self._first.y(), pos.x(), pos.y()) + half = math.hypot(pos.x() - self._first.x(), pos.y() - self._first.y()) * (1 + self._padding) / 2 + box.setRect((self._first.x() + pos.x()) / 2 - half, (self._first.y() + pos.y()) / 2 - half, 2 * half, 2 * half) + # _inside: whether a scene position is on the image def _inside(self, pos: QPointF) -> bool: w, h = self.image_size() diff --git a/src/pickmix/gui/components/images.py b/src/pickmix/gui/components/images.py index 825a18c..88d026e 100644 --- a/src/pickmix/gui/components/images.py +++ b/src/pickmix/gui/components/images.py @@ -6,7 +6,7 @@ import math, numpy as np from collections.abc import Callable from PySide6.QtCore import QRect, QSize, Qt -from PySide6.QtGui import QColor, QImage, QPainter, QPixmap +from PySide6.QtGui import QColor, QImage, QPainter, QPen, QPixmap from PySide6.QtWidgets import QLabel, QSizePolicy # Import internal pickmix objects @@ -58,6 +58,19 @@ def to_pixmap(arr: np.ndarray, size: int) -> QPixmap: pixmap = QPixmap.fromImage(to_image(arr)) return pixmap.scaled(size, size, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation) +# draw_box: a copy of a pixmap with a rectangle outlined on it +def draw_box(pixmap: QPixmap, rect: tuple[float, float, float, float], scale: float, colour: str, *, dotted: bool = False) -> QPixmap: + out = QPixmap(pixmap) + painter = QPainter(out) + pen = QPen(QColor(colour)) + pen.setWidth(1) + pen.setStyle(Qt.PenStyle.DotLine if dotted else Qt.PenStyle.SolidLine) + painter.setPen(pen) + left, top, right, bottom = (v * scale for v in rect) + painter.drawRect(QRect(round(left), round(top), round(right - left), round(bottom - top))) + painter.end() + return out + # label_cells: a copy of a montage image with a small translucent box of text in the corner of each cell; cells are grid x grid, row by row, each pad pixels apart (times scale when the image has been resized) def label_cells(image: QImage, labels: list[str], grid: int, pad: int, *, scale: float = 1.0) -> QImage: out = image.convertToFormat(QImage.Format.Format_RGB32) diff --git a/src/pickmix/gui/components/patch.py b/src/pickmix/gui/components/patch.py new file mode 100644 index 0000000..25e64c9 --- /dev/null +++ b/src/pickmix/gui/components/patch.py @@ -0,0 +1,195 @@ +''' +pickmix: zoomed movable crop of pick +''' + +# Import external dependencies +import math, numpy as np +from dataclasses import dataclass +from PySide6.QtCore import QPointF, QRectF, Qt, Signal +from PySide6.QtGui import QBrush, QColor, QMouseEvent, QPainter, QPen, QPixmap, QResizeEvent +from PySide6.QtWidgets import QGraphicsEllipseItem, QGraphicsLineItem, QGraphicsPixmapItem, QGraphicsRectItem, QGraphicsScene, QGraphicsView + +# Import internal pickmix objects +from pickmix.gui.components.images import to_image +from pickmix.gui.style import WELL_BG + +# _HIT_PX: screen distance from the centre dot that counts as grabbing it +_HIT_PX: float = 8.0 + +# _DRAG_PX: screen distance before a press becomes a drag +_DRAG_PX: float = 3.0 + +# _FILL_ALPHA: opacity of the hatching inside the box, out of 255 +_FILL_ALPHA: int = 110 + +# Patch: a crop of one slice and where pick and box sit +@dataclass(frozen=True) +class Patch: + pixels: np.ndarray + # voxel (x, y) of the crop's top-left pixel + origin: tuple[int, int] + pick_id: int + # pick position in voxels, where the dot goes + pick: tuple[float, float] + # box centre in voxels and box edge in pixels + box_centre: tuple[float, float] + box_px: float + colour: str + # tomogram width and height in voxels + bounds: tuple[int, int] + # direction of a filament in degrees from the x axis towards y, drawn through the box centre + psi_deg: float | None = None + +# PatchCanvas: a crop of a slice with pick box as translucent hatched square and pick as a small dot +class PatchCanvas(QGraphicsView): + # move_requested: dot or box dragged and released, pick id and new voxel x, y + move_requested = Signal(int, float, float) + + # __init__: empty scene, no scroll bars + def __init__(self, size: int) -> None: + super().__init__() + self._scene = QGraphicsScene(self) + self.setScene(self._scene) + self._pixmap: QGraphicsPixmapItem = self._scene.addPixmap(QPixmap()) + self._box: QGraphicsRectItem | None = None + self._dot: QGraphicsEllipseItem | None = None + self._axis: QGraphicsLineItem | None = None + self._patch: Patch | None = None + self._drag: QPointF | None = None + self._moved = False + self._offset = QPointF(0, 0) + self.setFixedSize(size, size) + self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.setBackgroundBrush(QColor(WELL_BG)) + self.setRenderHint(QPainter.RenderHint.Antialiasing) + self.setFrameShape(QGraphicsView.Shape.NoFrame) + + # has_patch: whether a crop is showing + @property + def has_patch(self) -> bool: + return self._patch is not None + + # patch: the crop showing, None if none + @property + def patch(self) -> Patch | None: + return self._patch + + # box_rect: the box in scene pixels as (x, y, width, height), None with no crop + def box_rect(self) -> tuple[float, float, float, float] | None: + if self._box is None: + return None + rect = self._box.rect().translated(self._box.pos()) + return rect.x(), rect.y(), rect.width(), rect.height() + + # axis_angle: the direction in degrees of the filament axis drawn, from the x axis towards y, None if there is none + def axis_angle(self) -> float | None: + return None if self._axis is None else math.degrees(math.atan2(self._axis.line().dy(), self._axis.line().dx())) % 180.0 + + # dot_position: the dot in scene pixels, None with no crop + def dot_position(self) -> tuple[float, float] | None: + return None if self._dot is None else (self._dot.pos().x(), self._dot.pos().y()) + + # set_patch: show a crop with box over it and pick as a dot + def set_patch(self, patch: Patch) -> None: + self._patch = patch + self._drag, self._moved, self._offset = None, False, QPointF(0, 0) + self._pixmap.setPixmap(QPixmap.fromImage(to_image(patch.pixels))) + self._scene.setSceneRect(0, 0, patch.pixels.shape[1], patch.pixels.shape[0]) + for item in (self._box, self._dot, self._axis): + if item is not None: + self._scene.removeItem(item) + self._axis = None + colour = QColor(patch.colour) + half = patch.box_px / 2 + self._box = QGraphicsRectItem(-half, -half, 2 * half, 2 * half) + self._box.setBrush(QBrush(QColor(colour.red(), colour.green(), colour.blue(), _FILL_ALPHA), Qt.BrushStyle.BDiagPattern)) + pen = QPen(colour) + pen.setCosmetic(True) + pen.setWidth(1) + self._box.setPen(pen) + self._box.setZValue(1) + self._dot = QGraphicsEllipseItem(-3, -3, 6, 6) + self._dot.setFlag(QGraphicsEllipseItem.GraphicsItemFlag.ItemIgnoresTransformations) + self._dot.setBrush(QColor('white')) + self._dot.setPen(QPen(colour)) + self._dot.setZValue(2) + self._scene.addItem(self._box) + self._scene.addItem(self._dot) + if patch.psi_deg is not None: + reach = patch.box_px / 2 + dx, dy = math.cos(math.radians(patch.psi_deg)) * reach, math.sin(math.radians(patch.psi_deg)) * reach + self._axis = QGraphicsLineItem(-dx, -dy, dx, dy) + axis_pen = QPen(colour) + axis_pen.setCosmetic(True) + axis_pen.setWidth(2) + self._axis.setPen(axis_pen) + self._axis.setZValue(1) + self._scene.addItem(self._axis) + self._place() + self.fitInView(self._scene.sceneRect(), Qt.AspectRatioMode.KeepAspectRatio) + + # clear: remove crop + def clear(self) -> None: + self._patch = None + self._pixmap.setPixmap(QPixmap()) + for item in (self._box, self._dot, self._axis): + if item is not None: + self._scene.removeItem(item) + self._box = self._dot = self._axis = None + + # mousePressEvent: grab dot or box + def mousePressEvent(self, event: QMouseEvent) -> None: + if event.button() == Qt.MouseButton.LeftButton and self._patch is not None and self._hit(self.mapToScene(event.position().toPoint())): + self._drag, self._moved = self.mapToScene(event.position().toPoint()), False + else: + super().mousePressEvent(event) + + # mouseMoveEvent: carry dot and box + def mouseMoveEvent(self, event: QMouseEvent) -> None: + if self._drag is None: + super().mouseMoveEvent(event) + return + delta = self.mapToScene(event.position().toPoint()) - self._drag + if self._moved or math.hypot(delta.x(), delta.y()) * self.transform().m11() > _DRAG_PX: + self._moved, self._offset = True, delta + self._place() + + # mouseReleaseEvent: a drag asks to move the pick; a press without one does nothing + def mouseReleaseEvent(self, event: QMouseEvent) -> None: + if event.button() == Qt.MouseButton.LeftButton and self._drag is not None: + patch, moved, offset = self._patch, self._moved, self._offset + self._drag, self._moved = None, False + if patch is not None and moved: + w, h = patch.bounds + x = min(max(patch.pick[0] + offset.x(), 0.0), max(w - 1, 0)) + y = min(max(patch.pick[1] + offset.y(), 0.0), max(h - 1, 0)) + self.move_requested.emit(patch.pick_id, x, y) + else: + super().mouseReleaseEvent(event) + + # resizeEvent: keep whole crop in view + def resizeEvent(self, event: QResizeEvent) -> None: + super().resizeEvent(event) + if self._patch is not None: + self.fitInView(self._scene.sceneRect(), Qt.AspectRatioMode.KeepAspectRatio) + + # _scene_pos: where a voxel position falls in crop, with half pixel that puts a voxel's centre mid-pixel + def _scene_pos(self, x: float, y: float) -> QPointF: + assert self._patch is not None + return QPointF(x - self._patch.origin[0] + 0.5, y - self._patch.origin[1] + 0.5) + + # _place: put box and dot where patch says, plus any drag in progress + def _place(self) -> None: + assert self._patch is not None and self._box is not None and self._dot is not None + self._box.setPos(self._scene_pos(*self._patch.box_centre) + self._offset) + self._dot.setPos(self._scene_pos(*self._patch.pick) + self._offset) + if self._axis is not None: + self._axis.setPos(self._box.pos()) + + # _hit: whether a scene position is on dot or inside box + def _hit(self, pos: QPointF) -> bool: + assert self._box is not None and self._dot is not None + reach = _HIT_PX / self.transform().m11() + box = QRectF(self._box.rect()).translated(self._box.pos()) + return box.contains(pos) or math.hypot(pos.x() - self._dot.pos().x(), pos.y() - self._dot.pos().y()) <= reach diff --git a/src/pickmix/gui/dialogs/kind_dialog.py b/src/pickmix/gui/dialogs/kind_dialog.py index 62df9b1..12658c8 100644 --- a/src/pickmix/gui/dialogs/kind_dialog.py +++ b/src/pickmix/gui/dialogs/kind_dialog.py @@ -28,7 +28,7 @@ # NO_PARENT: text of the parent choice that means no parent NO_PARENT: str = '(none)' -# KindDialog: sections for the kind's identity, size, estimation and extraction, each row labelled "Title (units) (?):" +# KindDialog: sections for the kind's identity, size, picking, estimation and extraction, each row labelled "Title (units) (?):" class KindDialog(QDialog): # __init__: build the form; name and kind are None when adding, others are the kinds besides this one (so the parent choices and the names this kind cannot take), and check returns why a name and kind cannot be saved, or None def __init__( @@ -48,6 +48,12 @@ def __init__( choose.clicked.connect(self._choose_colour) self.marker_spin = _spin(kind.marker_a, minimum=0.01) self.box_spin = _spin(kind.box_a) + self.mode_box = QComboBox() + self.mode_box.addItems(['point', 'bounds']) + self.mode_box.setCurrentText(kind.pick_mode) + self.padding_spin = _spin(kind.bounds_padding, decimals=3) + self.padding_spin.setEnabled(kind.pick_mode == 'bounds') + self.mode_box.currentTextChanged.connect(lambda mode: self.padding_spin.setEnabled(mode == 'bounds')) self.estimator_box = QComboBox() # keep a name the registry does not know yet, so editing never rewrites it self.estimator_box.addItems(sorted({*ESTIMATORS, kind.estimator})) @@ -93,6 +99,7 @@ def __init__( tidy(layout) layout.addWidget(self._section('General', [('name', self.name_edit), ('colour', colour_row)])) layout.addWidget(self._section('Size', [('marker_a', self.marker_spin), ('box_a', self.box_spin)])) + layout.addWidget(self._section('Picking', [('pick_mode', self.mode_box), ('bounds_padding', self.padding_spin)])) layout.addWidget(self._section('Estimation', [ ('estimator', self.estimator_box), ('parent', self.parent_box), ('parent_tolerance_a', self.tolerance_spin), ])) @@ -108,7 +115,7 @@ def values(self) -> tuple[str, Kind]: colour=self.colour_edit.text().strip(), parent=None if parent == NO_PARENT else parent, parent_tolerance_a=self.tolerance_spin.value(), tilt_prior_deg=self.tilt_spin.value() if self.tilt_box.isChecked() else None, - extract_angpix=self.angpix_spin.value(), + extract_angpix=self.angpix_spin.value(), pick_mode=self.mode_box.currentText(), bounds_padding=self.padding_spin.value(), ) # accept: close only when the entries make a kind the caller can save; otherwise say why diff --git a/src/pickmix/gui/panes/average_pane.py b/src/pickmix/gui/panes/average_pane.py index c097ffa..653dc64 100644 --- a/src/pickmix/gui/panes/average_pane.py +++ b/src/pickmix/gui/panes/average_pane.py @@ -46,6 +46,8 @@ def __init__(self) -> None: self.save_button.setEnabled(False) self.per_tomogram_box = QCheckBox('Include per-tomogram means') self.per_tomogram_box.setToolTip('Also write a mean image for every tomogram in the list') + self.worst_box = QCheckBox('Montage lowest scoring first') + self.worst_box.setToolTip('Show the lowest-scoring picks from kind validation with their scores.') self.results_table = QTableWidget(0, 2) self.results_table.setHorizontalHeaderLabels(['Tomogram', 'Picks']) quiet_table(self.results_table) @@ -76,6 +78,7 @@ def __init__(self) -> None: left_box.addLayout(run_row) left_box.addWidget(self.summary) left_box.addWidget(self.results_table, 1) + left_box.addWidget(self.worst_box) left_box.addLayout(tick_row) left_box.addWidget(self.save_button) mean = QVBoxLayout() @@ -141,7 +144,12 @@ def run(self) -> None: self.run_button.setEnabled(False) self.spinner.set_status('running', f'Averaging {len(items)} picks...') notify(f'Averaging {len(items)} picks of {name}...') - run_in_background(lambda: average_kind(name, config.kinds[name], items, tomos, config), self._done, self._failed) + scores = None + if self.worst_box.isChecked() and self.service is not None: + scores = {p.id: s for p, _ in items if (s := self.service.validation.score(p)) is not None} + if not scores: + notify('No validation scores for this kind yet so montage is spread evenly, validate kind in Review tab.') + run_in_background(lambda: average_kind(name, config.kinds[name], items, tomos, config, scores=scores or None), self._done, self._failed) # save: write the averages of the shown result, and the labelled montage beside them; returns the paths def save(self) -> list[str]: @@ -188,7 +196,8 @@ def _done(self, result: AverageResult) -> None: self.run_button.setEnabled(True) self.save_button.setEnabled(True) self.spinner.set_status(None) - notify(f'Averaged {result.count} boxes of {result.box_px} px (Save to write them)') + turned = '. Filaments are oriented along x, ends are not told apart' if result.aligned else '' + notify(f'Averaged {result.count} boxes of {result.box_px} px (Save to write them){turned}') self.montage_label.set_render(lambda width, height: self._tiled(result, width, height)) rows = [('overall', result.count), *((t, result.counts[t]) for t in self._names)] self.results_table.setRowCount(len(rows)) diff --git a/src/pickmix/gui/panes/kinds_pane.py b/src/pickmix/gui/panes/kinds_pane.py index 25f555d..6a4b202 100644 --- a/src/pickmix/gui/panes/kinds_pane.py +++ b/src/pickmix/gui/panes/kinds_pane.py @@ -184,6 +184,7 @@ def _apply(self, name: str, kind: Kind, *, old: str | None = None) -> None: if old is not None and old != name: if self.service is not None: self.service.store.rename_kind(old, name) + self.service.validation.rename_kind(old, name) if self.session is not None: self.session.store.rename_kind(old, name) self.session.candidates.rename_kind(old, name) @@ -221,10 +222,11 @@ def _saved(self) -> None: # _describe: a kind's values as a vertical list with bold keys def _describe(kind: Kind) -> str: box = 'from estimator' if kind.box_a == 0 else f'{kind.box_a:g} Å' + picking = 'one click' if kind.pick_mode == 'point' else f'two clicks, {kind.bounds_padding:g} padding' parent = 'none' if kind.parent is None else f'{kind.parent} (within {kind.parent_tolerance_a:g} Å)' tilt = 'none' if kind.tilt_prior_deg is None else f'{kind.tilt_prior_deg:g}°' pairs = [ - ('Marker', f'{kind.marker_a:g} Å'), ('Box', box), ('Estimator', kind.estimator), ('Colour', kind.colour), + ('Marker', f'{kind.marker_a:g} Å'), ('Box', box), ('Picking', picking), ('Estimator', kind.estimator), ('Colour', kind.colour), ('Parent', parent), ('Tilt prior', tilt), ('Extract', f'{kind.extract_angpix:g} Å/px'), ] return '
'.join(f'{key}: {html.escape(value)}' for key, value in pairs) diff --git a/src/pickmix/gui/panes/settings_pane.py b/src/pickmix/gui/panes/settings_pane.py index 53ab5ba..3b9dbdd 100644 --- a/src/pickmix/gui/panes/settings_pane.py +++ b/src/pickmix/gui/panes/settings_pane.py @@ -4,11 +4,12 @@ # Import external dependencies from pydantic import BaseModel, ValidationError +from typing import get_args from PySide6.QtCore import Signal from PySide6.QtWidgets import QComboBox, QDoubleSpinBox, QFormLayout, QGroupBox, QHBoxLayout, QLabel, QSpinBox, QVBoxLayout, QWidget # Import internal pickmix objects -from pickmix.config import HOTKEYS, Config, MatchParams, RingParams +from pickmix.config import HOTKEYS, Config, FilamentParams, MatchParams, RingParams, ValidationParams from pickmix.gui.components.collapsible import Collapsible from pickmix.gui.components.toast import notify from pickmix.gui.style import form_label, heading @@ -17,7 +18,7 @@ # NO_KIND: text of the hotkey choice that leaves a key unused NO_KIND: str = '(none)' -# ParamsForm: a form for a flat pydantic model of numbers and number pairs, labelled from the field titles +# ParamsForm: a form for a flat pydantic model of numbers, number pairs and choices between a few words, labelled from the field titles class ParamsForm(QWidget): # changed: a value was committed (arrow, wheel, Enter or focus loss), not set from code changed = Signal() @@ -26,14 +27,14 @@ class ParamsForm(QWidget): def __init__(self, params: BaseModel) -> None: super().__init__() self._cls = type(params) - self._boxes: dict[str, list[QSpinBox | QDoubleSpinBox]] = {} + self._boxes: dict[str, list[QSpinBox | QDoubleSpinBox | QComboBox]] = {} self._setting = False self.labels: dict[str, QLabel] = {} layout = QFormLayout(self) for name, value in params: info = type(params).model_fields[name] values = value if isinstance(value, tuple) else (value,) - boxes = [_spin(v) for v in values] + boxes = [_field(v, info.annotation) for v in values] self._boxes[name] = boxes row = QHBoxLayout() for i, box in enumerate(boxes): @@ -41,8 +42,11 @@ def __init__(self, params: BaseModel) -> None: row.addWidget(QLabel('-')) row.addWidget(box) # no valueChanged per keystroke; it fires when the typed value is committed - box.setKeyboardTracking(False) - box.valueChanged.connect(self._emit) + if isinstance(box, QComboBox): + box.currentTextChanged.connect(self._emit) + else: + box.setKeyboardTracking(False) + box.valueChanged.connect(self._emit) row.addStretch() # "Title (units) (?):" in the label column, then the values head = form_label(info.title or name, info.description or '') @@ -54,19 +58,19 @@ def set(self, params: BaseModel) -> None: self._setting = True for name, value in params: for box, v in zip(self._boxes[name], value if isinstance(value, tuple) else (value,), strict=True): - box.setValue(v) + _write(box, v) self._setting = False # get: a model of the shown values, validated by pydantic def get(self) -> BaseModel: - return self._cls(**{n: tuple(b.value() for b in boxes) if len(boxes) > 1 else boxes[0].value() for n, boxes in self._boxes.items()}) + return self._cls(**{n: tuple(_read(b) for b in boxes) if len(boxes) > 1 else _read(boxes[0]) for n, boxes in self._boxes.items()}) # _emit: announce a committed change - def _emit(self, _value: float) -> None: + def _emit(self, _value: object) -> None: if not self._setting: self.changed.emit() -# SettingsPane: General (volume source and hotkeys) and Estimators, saved as they change +# SettingsPane: General (volume source and hotkeys), Estimators (ring and filament) and Validation, saved as they change class SettingsPane(QWidget): # config_saved: source or estimator parameters were written to config.toml config_saved = Signal() @@ -87,6 +91,8 @@ def __init__(self) -> None: self.hotkey_boxes = [QComboBox() for _ in range(HOTKEYS)] self.ring_form = ParamsForm(RingParams()) self.match_form = ParamsForm(MatchParams()) + self.filament_form = ParamsForm(FilamentParams()) + self.validation_form = ParamsForm(ValidationParams()) general = QGroupBox('General') form = QFormLayout(general) form.addRow('Volume source', self.source_box) @@ -99,22 +105,31 @@ def __init__(self) -> None: estimator_box = QVBoxLayout(estimators) self.ring_section = Collapsible('Ring', self.ring_form) estimator_box.addWidget(self.ring_section) + self.filament_section = Collapsible('Filament', self.filament_form) + estimator_box.addWidget(self.filament_section) matching = QGroupBox('Template matching') matching_box = QVBoxLayout(matching) self.match_section = Collapsible('Scan', self.match_form) matching_box.addWidget(self.match_section) - self.setMinimumWidth(max(self.ring_form.sizeHint().width(), self.match_form.sizeHint().width()) + 48) + validation = QGroupBox('Validation') + validation_box = QVBoxLayout(validation) + self.validation_section = Collapsible('Validation', self.validation_form) + validation_box.addWidget(self.validation_section) + self.setMinimumWidth(max(form.sizeHint().width() for form in (self.ring_form, self.filament_form, self.match_form, self.validation_form)) + 48) layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(heading('Settings')) layout.addWidget(general) layout.addWidget(estimators) layout.addWidget(matching) + layout.addWidget(validation) layout.addStretch() self.source_box.currentTextChanged.connect(self._save) self.cache_spin.valueChanged.connect(self._save) self.ring_form.changed.connect(self._save) self.match_form.changed.connect(self._save) + self.filament_form.changed.connect(self._save) + self.validation_form.changed.connect(self._save) # set_project: show a project's settings without saving them back def set_project(self, project: Project) -> None: @@ -124,6 +139,8 @@ def set_project(self, project: Project) -> None: self.cache_spin.setValue(project.config.cache_mb) self.ring_form.set(project.config.ring) self.match_form.set(project.config.match) + self.filament_form.set(project.config.filament) + self.validation_form.set(project.config.validation) self._loading = False self.refresh_hotkeys() @@ -139,12 +156,12 @@ def refresh_hotkeys(self) -> None: box.setCurrentText(chosen or NO_KIND) self._loading = False - # _save: write source, slice cache and ring & match parameters; a value the config refuses is not written + # _save: write source, slice cache, ring, match, filament and validation parameters; a value the config refuses is not written def _save(self) -> None: if self._loading or self.project is None: return try: - self.project.update(source=self.source_box.currentText(), cache_mb=self.cache_spin.value(), ring=self.ring_form.get(), match=self.match_form.get()) + self.project.update(source=self.source_box.currentText(), cache_mb=self.cache_spin.value(), ring=self.ring_form.get(), match=self.match_form.get(), filament=self.filament_form.get(), validation=self.validation_form.get()) except ValidationError as e: notify(f'Not saved: {e.errors()[0]["msg"]}') return @@ -163,6 +180,23 @@ def _hotkey_changed(self, slot: int, text: str) -> None: self.project.update(hotkeys=['' if k == NO_KIND else k for k in keys]) self.hotkeys_saved.emit() +# _field: the widget for a value: a drop-down for a word, over the choices its annotation allows, else a spin box +def _field(value: object, annotation: object) -> QSpinBox | QDoubleSpinBox | QComboBox: + if isinstance(value, str): + box = QComboBox() + box.addItems(list(get_args(annotation))) + box.setCurrentText(value) + return box + return _spin(value) + +# _read: the value shown by a field +def _read(box: QSpinBox | QDoubleSpinBox | QComboBox) -> float | str: + return box.currentText() if isinstance(box, QComboBox) else box.value() + +# _write: show a value in a field +def _write(box: QSpinBox | QDoubleSpinBox | QComboBox, value: object) -> None: + box.setCurrentText(value) if isinstance(box, QComboBox) else box.setValue(value) + # _spin: an integer or float spin box for a value def _spin(value: float) -> QSpinBox | QDoubleSpinBox: if isinstance(value, int): diff --git a/src/pickmix/gui/panes/welcome_pane.py b/src/pickmix/gui/panes/welcome_pane.py index 8b6db4b..f031187 100644 --- a/src/pickmix/gui/panes/welcome_pane.py +++ b/src/pickmix/gui/panes/welcome_pane.py @@ -3,22 +3,38 @@ ''' # Import external dependencies -from PySide6.QtCore import Qt -from PySide6.QtGui import QKeySequence, QShortcut -from PySide6.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget +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 # Import internal pickmix objects from pickmix import __version__ +from pickmix.gui.components.icons import icon from pickmix.gui.style import big_button, hint, tidy +# _CORNER: gap in pixels between the theme button and the window corner +_CORNER: int = 10 + +# _ICON: edge in pixels of the theme button's icon +_ICON: int = 28 + # WelcomePane: Open project and New project side by side, centred, with the version at the bottom class WelcomePane(QWidget): + # theme_toggled: the user asked for the other colour theme + theme_toggled = Signal() + # __init__: build the buttons and the shortcuts def __init__(self) -> None: super().__init__() self.open_button = big_button('Open project', 'folder_open') self.new_button = big_button('New project', 'create_new_folder') self.version = hint(f'pickmix v{__version__}') + self.theme_button = QPushButton(self) + self.theme_button.setIconSize(QSize(_ICON, _ICON)) + self.theme_button.setStyleSheet('QPushButton { border: none; background: transparent; }') + self.theme_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.update_theme_button() + self.theme_button.clicked.connect(self.theme_toggled) row = QHBoxLayout() row.setSpacing(48) row.addStretch() @@ -36,3 +52,38 @@ def __init__(self) -> None: QShortcut(QKeySequence(keys), self, context=Qt.ShortcutContext.WindowShortcut).activated.connect(button.click) self.open_button.setToolTip('Open an existing project (Ctrl+O)') self.new_button.setToolTip('Create a project from RELION runs (Ctrl+N)') + + # 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 + 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 '') + self.theme_button.setIcon(found or QIcon()) + self.theme_button.setToolTip(f'Switch to {name.lower()}') + self.theme_button.adjustSize() + + # showEvent: put theme theme button in the window's corner + def showEvent(self, event: QShowEvent) -> None: + super().showEvent(event) + self._place() + + # hideEvent: theme button belongs to the window, so hide it with this page + def hideEvent(self, event: QHideEvent) -> None: + super().hideEvent(event) + self.theme_button.hide() + + # resizeEvent: keep the theme button in the corner + def resizeEvent(self, event: QResizeEvent) -> None: + super().resizeEvent(event) + self._place() + + # _place: place theme button relative to window + def _place(self) -> None: + top = self.window() + if self.theme_button.parent() is not top: + self.theme_button.setParent(top) + self.theme_button.adjustSize() + self.theme_button.move(top.width() - self.theme_button.width() - _CORNER, _CORNER) + self.theme_button.raise_() + self.theme_button.show() diff --git a/src/pickmix/gui/style.py b/src/pickmix/gui/style.py index 14aba65..795fdcb 100644 --- a/src/pickmix/gui/style.py +++ b/src/pickmix/gui/style.py @@ -4,8 +4,8 @@ # Import external dependencies from PySide6.QtCore import QSize, Qt -from PySide6.QtGui import QColor, QIcon -from PySide6.QtWidgets import QAbstractItemView, QApplication, QHBoxLayout, QLabel, QLayout, QPushButton, QScrollArea, QTableWidget, QToolButton, QVBoxLayout, QWidget +from PySide6.QtGui import QColor, QIcon, QPalette +from PySide6.QtWidgets import QAbstractButton, QAbstractItemView, QApplication, QHBoxLayout, QLabel, QLayout, QPushButton, QScrollArea, QTableWidget, QToolButton, QVBoxLayout, QWidget # Import internal pickmix objects from pickmix.gui.components.icons import icon, tinted @@ -20,9 +20,6 @@ # RADIUS: corner radius of rounded buttons, pixels RADIUS: int = 16 -# ICON_COLOUR: colour of every action icon -ICON_COLOUR: str = '#ffffff' - # MEDIUM_PAD: pixels added to a medium button's icon edge to get its square size MEDIUM_PAD: int = 16 @@ -177,9 +174,10 @@ def _icon_over_text(text: str, stem: str, icon_px: int, size: tuple[int, int], * inner = QVBoxLayout(button) inner.setSpacing(BIG_GAP) inner.setAlignment(Qt.AlignmentFlag.AlignCenter) - found = tinted(stem, colour='#ffffff', size=icon_px) + found = tinted(stem, colour=icon_colour(), size=icon_px) if found is not None: picture = QLabel() + tint_mark(picture, stem, icon_px) picture.setPixmap(found.pixmap(QSize(icon_px, icon_px))) picture.setAlignment(Qt.AlignmentFlag.AlignCenter) inner.addWidget(picture) @@ -191,9 +189,30 @@ def _icon_over_text(text: str, stem: str, icon_px: int, size: tuple[int, int], * child.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents) return button +# icon_colour: colour of every action icon (theme's text colour so it shows on light and dark buttons) +def icon_colour() -> str: + return QApplication.palette().color(QPalette.ColorRole.ButtonText).name() + +# tint_mark: remember which icon a widget shows, so retint can redraw it when the theme changes +def tint_mark(widget: QWidget, stem: str, size: int) -> None: + widget.setProperty('tint_stem', stem) + widget.setProperty('tint_size', size) + +# retint: redraw every marked icon under a widget in the current theme colour +def retint(root: QWidget) -> None: + for widget in root.findChildren(QWidget): + stem, size = widget.property('tint_stem'), widget.property('tint_size') + found = tinted(stem, icon_colour(), size) if stem else None + if found is None: + continue + if isinstance(widget, QLabel): + widget.setPixmap(found.pixmap(QSize(size, size))) + elif isinstance(widget, QAbstractButton): + widget.setIcon(found) + # white: a bundled icon redrawn in the action colour, or None when its file is not there def white(stem: str, size: int = 16) -> QIcon | None: - return tinted(stem, colour=ICON_COLOUR, size=size) + return tinted(stem, colour=icon_colour(), size=size) # icon_button: an icon-only white button with a tooltip, or a text button when the icon file is missing; size makes it a rounded square of that icon edge plus padding def icon_button(stem: str, text: str, tip: str, *, size: int | None = None) -> QPushButton: @@ -201,6 +220,7 @@ def icon_button(stem: str, text: str, tip: str, *, size: int | None = None) -> Q button = QPushButton() if found is not None else QPushButton(text) if found is not None: button.setIcon(found) + tint_mark(button, stem, size or 16) if size is not None: button.setIconSize(QSize(size, size)) button.setFixedSize(size + MEDIUM_PAD, size + MEDIUM_PAD) diff --git a/src/pickmix/gui/tabs/pick_tab.py b/src/pickmix/gui/tabs/pick_tab.py index 56ee998..e19beab 100644 --- a/src/pickmix/gui/tabs/pick_tab.py +++ b/src/pickmix/gui/tabs/pick_tab.py @@ -3,7 +3,7 @@ ''' # Import external dependencies -import numpy as np +import math, numpy as np from concurrent.futures import Future from PySide6.QtCore import Qt from PySide6.QtGui import QKeySequence, QShortcut @@ -20,8 +20,9 @@ from pickmix.gui.components.status import StatusBadge, fit_status, status_item from pickmix.gui.panes.match_pane import MatchPane from pickmix.gui.panes.tomo_pane import TomoPane +from pickmix.gui.components.toast import notify from pickmix.gui.workers import post -from pickmix.gui.style import CELL_PADDING, bold_safe, eye_toggle, heading, hint, icon_button, quiet_table, tidy, title, view_toggle, white +from pickmix.gui.style import CELL_PADDING, bold_safe, eye_toggle, heading, hint, icon_button, quiet_table, tidy, tint_mark, title, view_toggle, white from pickmix.loader import Loader, Opened from pickmix.matcher import MatchService from pickmix.model import Session @@ -30,6 +31,12 @@ # _STEPS: positions on the contrast sliders _STEPS: int = 1000 +# _HELP: keys that work on any kind +_HELP: str = 'Enter: next tomogram. Shift+Enter: previous tomogram. Up and Down: change slice, with Shift ten at a time.' + +# _BOUNDS_HELP: what a two-click kind asks for +_BOUNDS_HELP: str = ' Two-click kind: click one edge of the structure, then the opposite edge. Esc cancels.' + # PickTab: canvas, kind buttons, z and contrast sliders, and the pick list of the current tomogram class PickTab(QWidget): # __init__: build the layout @@ -52,7 +59,7 @@ def __init__(self) -> None: self._range = (0.0, 1.0) self.canvas = SliceCanvas() self.title = title() - self.help = hint('Enter: next tomogram. Shift+Enter: previous tomogram. Up/Down: change Z slice; Shift+Up/Down: change Z slice by 10.') + self.help = hint(_HELP) self.status = QLabel() self.match_pane = MatchPane() self.tomo = TomoPane() @@ -81,8 +88,8 @@ def __init__(self) -> None: self.invert_box = QCheckBox('Invert') self.fit_button = QPushButton('Fit') self.fill_button = QPushButton('Fill') - self.table = QTableWidget(0, 7) - self.table.setHorizontalHeaderLabels(['', 'Kind', 'x', 'y', 'z', 'SNR', 'Flag']) + self.table = QTableWidget(0, 8) + self.table.setHorizontalHeaderLabels(['', 'Kind', 'x', 'y', 'z', 'SNR', 'Flag', 'Box (Å)']) quiet_table(self.table) self.table.setMaximumHeight(170) # status marker first and fixed so kinds always line up; Kind fits its names, the number columns share the rest @@ -182,6 +189,7 @@ def __init__(self) -> None: self.fill_button.setToolTip('Zoom tomogram to fill') self.delete_button.clicked.connect(self.delete_selected) self.canvas.add_requested.connect(self._add) + self.canvas.bounds_requested.connect(self._add_bounds) self.canvas.move_requested.connect(self._move) self.canvas.marker_clicked.connect(self._clicked) self.canvas.z_scrolled.connect(lambda steps: self.z_slider.setValue(self.z_slider.value() + steps)) @@ -206,6 +214,7 @@ def set_session(self, session: Session, loader: Loader, service: EstimateService matcher.listeners.append(lambda: post(self._on_picks)) # estimates arrive on the service's thread service.store.listeners.append(lambda: post(self._on_picks)) + service.validation.listeners.append(lambda: post(self._on_picks)) session.goto_listeners.append(self._on_goto) self.tomo.set_session(session) self.refresh_kinds() @@ -263,6 +272,7 @@ def refresh_kinds(self) -> None: self._set_active(self.active if self.active in kinds else next(iter(kinds))) else: self.active = None + self._apply_mode() self._on_picks() self.tomo.refresh() @@ -280,11 +290,13 @@ def show_pick(self, pick_id: int) -> None: # set_tomo_visible: show or hide the tomogram pane; the icon is the action the button takes def set_tomo_visible(self, shown: bool) -> None: self.tomo.setVisible(shown) - panel = white('left_panel_close' if shown else 'left_panel_open', 20) + stem = 'left_panel_close' if shown else 'left_panel_open' + panel = white(stem, 20) if panel is None: self.tomo_toggle.setText('<' if shown else '>') else: self.tomo_toggle.setIcon(panel) + tint_mark(self.tomo_toggle, stem, 20) self.tomo_toggle.setToolTip('Hide the tomogram list' if shown else 'Show the tomogram list') # delete_selected: remove selected pick or reject selected candidate @@ -315,6 +327,7 @@ def accept_shown(self) -> None: def _set_active(self, name: str) -> None: self.active = name self.kind_buttons[name].setChecked(True) + self._apply_mode() self._refresh_match() # _scan: scan for active kind's template in every tomogram @@ -327,6 +340,13 @@ def _stop_scan(self) -> None: if self.matcher is not None: self.matcher.stop() + # _apply_mode: a click makes a pick of the active kind in the way that kind asks, and the hint says how + def _apply_mode(self) -> None: + kind = None if self.session is None or self.active is None else self.session.project.config.kinds.get(self.active) + bounds = kind is not None and kind.pick_mode == 'bounds' + self.canvas.set_bounds_mode(bounds, kind.bounds_padding if kind is not None else 0.0, kind.colour if kind is not None else 'yellow') + self.help.setText(_HELP + (_BOUNDS_HELP if bounds else '')) + # _refresh_match: refresh match pane for active kind/tomogram def _refresh_match(self) -> None: if self.session is None: @@ -370,6 +390,7 @@ def _open_done(self, name: str, future: Future[Opened]) -> None: self.opened = future.result() except Exception as e: self.status.setText(f'Could not open {name}: {type(e).__name__}: {e}') + notify(f'Could not open {name}: {type(e).__name__}: {e}') return if self._timer: self._timer.lap('opened and contrast') @@ -416,6 +437,8 @@ def _show_z(self, z: int) -> None: self.z_label.setAlignment(Qt.AlignmentFlag.AlignCenter) self.z_label.setText(f'{z + 1} / {total}') self.canvas.set_z(z) + # both clicks of a pair belong on one slice + self.canvas.cancel_bounds() cached = self.loader.cached(name, z) if cached is not None: self._render(cached) @@ -533,11 +556,13 @@ def _markers(self) -> list[Marker]: continue for p in self.session.store.picks(name, kind_name): fit = self.service.store.get(p) if self.service else None - view = None if fit is None else FitView(fit.x, fit.y, fit.z, fit.radius_a / px if kind.estimator != 'none' else None, fit.box_a / px if fit.box_a > 0 else None, fit.z_lo, fit.z_hi) + # a filament is drawn as its axis + view = None if fit is None else FitView(fit.x, fit.y, fit.z, fit.radius_a / px if kind.estimator != 'none' and fit.psi_deg is None else None, fit.box_a / px if fit.box_a > 0 else None, fit.z_lo, fit.z_hi, fit.psi_deg) parent = self._matched.get(kind_name, {}).get(p.id) unmatched = kind.parent is not None and fit is not None and parent is None + low = self.service is not None and self.service.validation.low(p) normal = None if parent is None else (parent.normal[0], parent.normal[1]) - out.append(Marker(p.id, p.x, p.y, p.z, kind.marker_a / 2 / px, kind.colour, bool(fit and fit.flag) or unmatched, view, normal)) + out.append(Marker(p.id, p.x, p.y, p.z, kind.marker_a / 2 / px, kind.colour, bool(fit and fit.flag) or unmatched or low, view, normal)) for c in self.session.candidates.candidates(name, kind_name, min_score=self.match_pane.min_score()): out.append(Marker(-c.id, c.x, c.y, c.z, kind.marker_a / 2 / px, kind.colour, candidate=True, tip=f'{kind_name} candidate, score {c.score:.2f}')) return out @@ -567,11 +592,15 @@ def _fill_table(self) -> None: snr, flag = ('', '') if fit is None else (f'{fit.snr:.2f}', fit.flag) if fit is not None and kinds[p.kind].parent is not None and p.id not in self._matched.get(p.kind, {}): flag = ','.join(filter(None, [flag, 'noparent'])) + if fit is not None and self.service is not None and self.service.validation.low(p): + flag = ','.join(filter(None, [flag, 'lowcc'])) status = fit_status(self.service.store.state(p) if self.service else 'ok', flag) tip = {'running': 'Estimating...', 'ok': 'Estimate is fine'}.get(status, flag) self.table.setCellWidget(r, 0, StatusBadge(status, tip)) - for c, text in enumerate((p.kind, f'{p.x:.1f}', f'{p.y:.1f}', f'{p.z:.1f}', snr, flag), start=1): + for c, text in enumerate((p.kind, f'{p.x:.1f}', f'{p.y:.1f}', f'{p.z:.1f}', snr, flag, '' if p.box_a is None else f'{p.box_a:.0f}'), start=1): self.table.setItem(r, c, QTableWidgetItem(text)) + # the box column is only worth its room once a pick has a box of its own + self.table.setColumnHidden(7, all(p.box_a is None for p in picks)) self._select(self.canvas.selected_id) # _select: highlight a pick in the canvas and the list @@ -595,6 +624,19 @@ def _add(self, x: float, y: float) -> None: pick = self.session.store.add(self.opened.name, self.active, x, y, float(self.z)) self._select(pick.id) + # _add_bounds: two clicks on opposite sides of a structure make one pick halfway between them, with a box as far across as the clicks plus the kind's padding + def _add_bounds(self, x1: float, y1: float, x2: float, y2: float) -> None: + if self.session is None or self.opened is None or self.active is None: + return + distance = math.hypot(x2 - x1, y2 - y1) + # two clicks on the same voxel say nothing about size + if distance < 1.0: + return + kind = self.session.project.config.kinds[self.active] + box_a = distance * self.session.project.tomos[self.opened.name].pixel_size * (1 + kind.bounds_padding) + pick = self.session.store.add(self.opened.name, self.active, (x1 + x2) / 2, (y1 + y2) / 2, float(self.z), box_a=box_a) + self._select(pick.id) + # _move: pick dragged to a new position, on the same slice it was picked on def _move(self, pick_id: int, x: float, y: float) -> None: if self.session is not None: diff --git a/src/pickmix/gui/tabs/review_tab.py b/src/pickmix/gui/tabs/review_tab.py index ac23383..ce9a05e 100644 --- a/src/pickmix/gui/tabs/review_tab.py +++ b/src/pickmix/gui/tabs/review_tab.py @@ -3,28 +3,32 @@ ''' # Import external dependencies -import numpy as np +import math, numpy as np +from dataclasses import dataclass from PySide6.QtCore import Qt, QTimer, Signal from PySide6.QtWidgets import ( - QComboBox, QDoubleSpinBox, QGridLayout, QHBoxLayout, QHeaderView, QLabel, QMessageBox, - QPushButton, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, + QCheckBox, QComboBox, QDoubleSpinBox, QGridLayout, QHBoxLayout, QHeaderView, QLabel, + QMessageBox, QPushButton, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) # Import internal pickmix objects from pickmix.estimate.registry import Fit -from pickmix.estimates import EstimateService +from pickmix.estimates import EstimateService, effective_box_a from pickmix.export import Item from pickmix.geometry import Parent -from pickmix.gui.components.images import label_image, to_pixmap +from pickmix.gui.components.images import draw_box, label_image, to_pixmap +from pickmix.gui.components.patch import Patch, PatchCanvas from pickmix.gui.components.status import fit_status, status_item -from pickmix.gui.style import image_well, quiet_table, tidy, white +from pickmix.gui.components.toast import notify +from pickmix.gui.style import image_well, quiet_table, tidy, tint_mark, white from pickmix.gui.workers import post, run_in_background from pickmix.items import flagged, items, matched from pickmix.loader import Loader from pickmix.model import Pick, Session +from pickmix.validate import validate_kind # _COLUMNS: pick table headings -_COLUMNS: list[str] = ['Tomogram', 'Kind', 'x', 'y', 'z', 'SNR', 'Flag', 'Estimate'] +_COLUMNS: list[str] = ['Tomogram', 'Kind', 'x', 'y', 'z', 'SNR', 'Flag', 'Estimate', 'Box (Å)', 'Score'] # _CROP: half-width in voxels of the preview crops _CROP: int = 64 @@ -32,6 +36,23 @@ # _PREVIEW: edge in pixels of the preview images _PREVIEW: int = 220 +# _PATCH_SCALE: edge of the editable patch as a multiple of the box edge +_PATCH_SCALE: float = 1.5 + +# _Rect: left, top, right and bottom of a rectangle in the pixels of an array +type _Rect = tuple[float, float, float, float] + +# Preview: what the four panels show for one pick +@dataclass(frozen=True) +class Preview: + xy: np.ndarray + xz: np.ndarray + yz: np.ndarray + patch: Patch + outlines: tuple[_Rect, _Rect, _Rect] + slabs: tuple[_Rect, _Rect] | None + colour: str + # _COLUMN_GAP: pixels between the filters, the buttons and the count _COLUMN_GAP: int = 40 @@ -76,6 +97,14 @@ def __init__(self) -> None: reload_icon = white('cached') if reload_icon is not None: self.reestimate_button.setIcon(reload_icon) + tint_mark(self.reestimate_button, 'cached', 16) + self.validate_button = QPushButton('Validate') + self.validate_button.setToolTip( + 'Score each pick of the chosen kind (every kind if all) against the average of its kind, and flag those far below the rest as lowcc. ' + 'A kind with several distinct views scores low throughout, and a filament needs a good direction.' + ) + self.worst_first_box = QCheckBox('Worst first') + self.worst_first_box.setToolTip('Order the picks by validation score, lowest first, those without a current score last') self.table = QTableWidget(0, len(_COLUMNS)) self.table.setHorizontalHeaderLabels(_COLUMNS) quiet_table(self.table) @@ -91,6 +120,9 @@ def __init__(self) -> None: self.xy_label.setToolTip('The slice through the pick') self.xz_label.setToolTip('The plane through the pick along z, at its y position') self.yz_label.setToolTip('The plane through the pick along z, at its x position') + self.patch_canvas = PatchCanvas(_PREVIEW) + self.patch_canvas.setToolTip('The slice through the pick, close up. Drag the dot or the box to move the pick') + self._previewed: tuple | None = None for label in (self.xy_label, self.xz_label, self.yz_label): image_well(label, _PREVIEW) # controls: filters over two rows, then buttons, then the shown count, all centred on the same line @@ -101,11 +133,13 @@ def __init__(self) -> None: ): filters.addWidget(QLabel(text), row, col) filters.addWidget(widget, row, col + 1) + filters.addWidget(self.worst_first_box, 2, 0, 1, 2) filters.setColumnMinimumWidth(2, 24) buttons = QGridLayout() buttons.addWidget(self.delete_selected_button, 0, 0) buttons.addWidget(self.delete_shown_button, 0, 1) - buttons.addWidget(self.reestimate_button, 1, 0, 1, 2) + buttons.addWidget(self.reestimate_button, 1, 0) + buttons.addWidget(self.validate_button, 1, 1) controls = QHBoxLayout() controls.addLayout(filters) controls.addSpacing(_COLUMN_GAP) @@ -114,14 +148,18 @@ def __init__(self) -> None: controls.addWidget(self.count_label, 1, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) controls.setAlignment(filters, Qt.AlignmentFlag.AlignVCenter) controls.setAlignment(buttons, Qt.AlignmentFlag.AlignVCenter) - previews = QVBoxLayout() - previews.addWidget(self.xy_label) - previews.addWidget(self.xz_label) - previews.addWidget(self.yz_label) - previews.addStretch() + # XY and the editable patch above, XZ and YZ below + self.previews = QGridLayout() + self.previews.addWidget(self.xy_label, 0, 0) + self.previews.addWidget(self.patch_canvas, 0, 1) + self.previews.addWidget(self.xz_label, 1, 0) + self.previews.addWidget(self.yz_label, 1, 1) + preview_column = QVBoxLayout() + preview_column.addLayout(self.previews) + preview_column.addStretch() body = QHBoxLayout() body.addWidget(self.table, 1) - body.addLayout(previews) + body.addLayout(preview_column) layout = QVBoxLayout(self) tidy(layout) layout.addLayout(controls) @@ -129,18 +167,22 @@ def __init__(self) -> None: for combo in (self.kind_filter, self.tomo_filter): combo.currentIndexChanged.connect(self.refresh) self.flag_filter.currentIndexChanged.connect(self.refresh) + self.worst_first_box.toggled.connect(self.refresh) self.snr_spin.valueChanged.connect(self.refresh) self.table.itemSelectionChanged.connect(self._preview) self.table.cellDoubleClicked.connect(self._double_clicked) + self.patch_canvas.move_requested.connect(self._move) self.delete_selected_button.clicked.connect(self.delete_selected) self.delete_shown_button.clicked.connect(self._ask_delete_shown) self.reestimate_button.clicked.connect(self._reestimate) + self.validate_button.clicked.connect(self._validate) # set_session: show a session and follow its picks and estimates def set_session(self, session: Session, loader: Loader, service: EstimateService) -> None: self.session, self.loader, self.service = session, loader, service session.store.listeners.append(self._schedule) service.store.listeners.append(self._schedule) + service.validation.listeners.append(self._schedule) self.refresh_kinds() # refresh_kinds: rebuild the kind and tomogram filters from the config @@ -175,9 +217,18 @@ def refresh(self) -> None: status = fit_status(state, flag) tip = {'running': f'Estimate {state}', 'ok': 'Estimate is fine'}.get(status, flag) self.table.setItem(r, 7, status_item(status, tip)) + self.table.setItem(r, 8, QTableWidgetItem('' if pick.box_a is None else f'{pick.box_a:.0f}')) + score = self.service.validation.score(pick) + self.table.setItem(r, 9, QTableWidgetItem('' if score is None else f'{score:.2f}')) + # the box column is only worth its room once a pick has a box of its own + self.table.setColumnHidden(8, all(p.box_a is None for p in self._shown)) + # the score column is only worth its room once validation has scored a pick shown + self.table.setColumnHidden(9, all(self.service.validation.score(p) is None for p in self._shown)) if selected in [p.id for p in self._shown]: self.table.selectRow([p.id for p in self._shown].index(selected)) self.table.blockSignals(False) + # a moved pick or a new fit changes what the previews show, but the blocked signal will not say so + self._preview(changed_only=True) self.count_label.setText(f'{len(rows)} shown of {self.session.store.total()}') # delete_selected: remove the selected pick; returns how many went @@ -213,7 +264,8 @@ def _matched(self, kind: str) -> dict[int, Parent]: # _flagged: the fit with noparent added to its flags when the pick's kind has a parent and the pick found none def _flagged(self, kind: str, pick: Pick, fit: Fit, parents: dict[int, Parent]) -> Fit: assert self.session is not None - return flagged(self.session, kind, pick, fit, parents) + assert self.service is not None + return flagged(self.session, kind, pick, fit, parents, self.service.validation) # _filtered: picks of known kinds passing the filters, in tomogram then kind order, with their current fit def _filtered(self) -> list[tuple[Pick, Fit | None]]: @@ -237,6 +289,9 @@ def _filtered(self) -> list[tuple[Pick, Fit | None]]: continue out.append((pick, fit)) out.sort(key=lambda pf: (order.get(pf[0].tomogram, len(order)), kinds[pf[0].kind])) + if self.worst_first_box.isChecked(): + # a stable sort, so picks without a score keep their order at the end + out.sort(key=lambda pf: math.inf if (score := self.service.validation.score(pf[0])) is None else score) return out # _ask_delete_shown: confirm, then delete every pick shown @@ -252,44 +307,127 @@ def _reestimate(self) -> None: if self.service is not None: self.service.request_all() + # _validate: score the picks of the chosen kind, or of every kind, off the GUI thread, and say what was found + def _validate(self) -> None: + if self.session is None or self.service is None: + return + chosen = self.kind_filter.currentText() + names = [k for k in self.session.project.config.kinds if chosen in ('(all)', k) and self.session.store.total(k)] + if not names: + notify('No picks to validate') + return + self.validate_button.setEnabled(False) + run_in_background(lambda: self.validate(names), self._validated, self._validate_failed) + + # validate: validate each kind, returning one line about each; a kind that cannot be validated says why in its line + def validate(self, names: list[str]) -> list[str]: + assert self.session is not None and self.service is not None + lines = [] + for name in names: + try: + s = validate_kind(name, self.session, self.service) + except ValueError as e: + lines.append(str(e)) + continue + skipped = f', {s.skipped} without a fit skipped' if s.skipped else '' + lines.append(f'{name}: scored {s.scored}, median {s.median:.2f}, {s.flagged} flagged lowcc{skipped}') + return lines + + # _validated: say what validation found + def _validated(self, lines: list[str]) -> None: + self.validate_button.setEnabled(True) + notify('; '.join(lines)) + + # _validate_failed: say why validation stopped + def _validate_failed(self, message: str) -> None: + self.validate_button.setEnabled(True) + notify(message) + # _double_clicked: open the pick in the Pick tab def _double_clicked(self, row: int, _col: int) -> None: if 0 <= row < len(self._shown): self.open_pick.emit(self._shown[row].tomogram, self._shown[row].id) - # _preview: crops of the selected pick, read off the GUI thread - def _preview(self) -> None: + # _move: the patch was dragged + def _move(self, pick_id: int, x: float, y: float) -> None: + if self.session is not None: + self.session.store.move(pick_id, x, y) + + # _preview: four panels for selected pick, read off GUI thread + def _preview(self, *, changed_only: bool = False) -> None: row = self.table.currentRow() if self.loader is None or self.service is None or not 0 <= row < len(self._shown): return pick = self._shown[row] fit = self.service.store.get(pick) - centre = (fit.x, fit.y, fit.z) if fit else (pick.x, pick.y, pick.z) + key = (pick.id, pick.x, pick.y, pick.z, None if fit is None else fit.model_dump_json()) + if changed_only and key == self._previewed: + return + self._previewed = key self._token += 1 token = self._token run_in_background( - lambda: self.crops(pick.tomogram, centre), - lambda crops: self._show_preview(token, crops), + lambda: self.preview(pick, fit), + lambda result: self._show_preview(token, result), lambda message: self.xy_label.setText(message), ) + # preview: crops, patch and outlines for a pick around its fit centre, or around pick when it has no fit + def preview(self, pick: Pick, fit: Fit | None) -> Preview: + assert self.loader is not None and self.session is not None + project = self.session.project + kind, px = project.config.kinds[pick.kind], project.tomos[pick.tomogram].pixel_size + centre = (fit.x, fit.y, fit.z) if fit else (pick.x, pick.y, pick.z) + xy, xz, yz = self.crops(pick.tomogram, centre) + vol = self.loader.open(pick.tomogram).result().vol + x0, y0, z0 = _starts(centre, vol.shape) + half = effective_box_a(pick, kind, fit) / px / 2 + # voxel centres sit half a pixel in; box is a cube, so z extent is same as width + cx, cy, cz = centre[0] - x0 + 0.5, centre[1] - y0 + 0.5, centre[2] - z0 + 0.5 + outlines = ((cx - half, cy - half, cx + half, cy + half), (cx - half, cz - half, cx + half, cz + half), (cy - half, cz - half, cy + half, cz + half)) + slabs = None if fit is None else ((cx - half, fit.z_lo - z0, cx + half, fit.z_hi + 1 - z0), (cy - half, fit.z_lo - z0, cy + half, fit.z_hi + 1 - z0)) + edge = max(math.ceil(_PATCH_SCALE * 2 * half), 4) + sl = self.loader.slice(pick.tomogram, min(max(round(centre[2]), 0), vol.shape[0] - 1)) + left, top = round(centre[0]) - edge // 2, round(centre[1]) - edge // 2 + patch = Patch(_padded(sl, left, top, edge), (left, top), pick.id, (pick.x, pick.y), (centre[0], centre[1]), 2 * half, kind.colour, (vol.shape[2], vol.shape[1]), None if fit is None else fit.psi_deg) + return Preview(xy, xz, yz, patch, outlines, slabs, kind.colour) + # crops: (xy, xz, yz) arrays around a centre: the slice through it, and the planes through it along z at its y and at its x def crops(self, tomogram: str, centre: tuple[float, float, float]) -> tuple[np.ndarray, np.ndarray, np.ndarray]: assert self.loader is not None vol = self.loader.open(tomogram).result().vol x, y, z = (round(v) for v in centre) z = min(max(z, 0), vol.shape[0] - 1) - xs = slice(max(x - _CROP, 0), x + _CROP) - ys = slice(max(y - _CROP, 0), y + _CROP) - zs = slice(max(z - _CROP, 0), z + _CROP) + xs, ys, zs = (slice(max(c - _CROP, 0), c + _CROP) for c in (x, y, z)) xy = self.loader.slice(tomogram, z)[ys, xs] xz = np.asarray(vol[zs, min(max(y, 0), vol.shape[1] - 1), xs], dtype=np.float32) yz = np.asarray(vol[zs, ys, min(max(x, 0), vol.shape[2] - 1)], dtype=np.float32) return xy, xz, yz - # _show_preview: draw the crops unless a newer selection has been made - def _show_preview(self, token: int, crops: tuple[np.ndarray, np.ndarray, np.ndarray]) -> None: + # _show_preview: draw panels unless a newer selection has been made + def _show_preview(self, token: int, preview: Preview) -> None: if token != self._token: return - for label, crop, name in zip((self.xy_label, self.xz_label, self.yz_label), crops, ('XY', 'XZ', 'YZ'), strict=True): - label.setPixmap(label_image(to_pixmap(crop, _PREVIEW), name)) + crops = (preview.xy, preview.xz, preview.yz) + for i, (label, crop, name) in enumerate(zip((self.xy_label, self.xz_label, self.yz_label), crops, ('XY', 'XZ', 'YZ'), strict=True)): + pixmap = to_pixmap(crop, _PREVIEW) + scale = pixmap.width() / crop.shape[1] + # the z range the fit used goes under the box so the box is still the outermost line + if preview.slabs is not None and i: + pixmap = draw_box(pixmap, preview.slabs[i - 1], scale, preview.colour, dotted=True) + label.setPixmap(label_image(draw_box(pixmap, preview.outlines[i], scale, preview.colour), name)) + self.patch_canvas.set_patch(preview.patch) + +# _starts: first x, y and z voxel of the crops around a centre, as `crops` cuts them +def _starts(centre: tuple[float, float, float], shape: tuple[int, ...]) -> tuple[int, int, int]: + x, y, z = (round(v) for v in centre) + z = min(max(z, 0), shape[0] - 1) + return max(x - _CROP, 0), max(y - _CROP, 0), max(z - _CROP, 0) + +# _padded: an edge x edge crop of a slice with its top-left at voxel (left, top), padded with slice mean where it leaves slice +def _padded(img: np.ndarray, left: int, top: int, edge: int) -> np.ndarray: + out = np.full((edge, edge), img.mean(), dtype=np.float32) + ys, xs = slice(max(top, 0), min(top + edge, img.shape[0])), slice(max(left, 0), min(left + edge, img.shape[1])) + if ys.stop > ys.start and xs.stop > xs.start: + out[ys.start - top : ys.stop - top, xs.start - left : xs.stop - left] = img[ys, xs] + return out diff --git a/src/pickmix/items.py b/src/pickmix/items.py index b64893b..a12f82d 100644 --- a/src/pickmix/items.py +++ b/src/pickmix/items.py @@ -8,23 +8,27 @@ from pickmix.export import Item from pickmix.geometry import Parent, match_parents from pickmix.model import Pick, Session +from pickmix.validation import ValidationStore # matched: parent geometry for every pick of a kind, empty for a kind with no parent def matched(session: Session, service: EstimateService, kind: str) -> dict[int, Parent]: return match_parents(kind, session.project.config, session.store, service.store, session.project.tomos) -# flagged: the fit with noparent added to its flags when the pick's kind has a parent and the pick found none -def flagged(session: Session, kind: str, pick: Pick, fit: Fit, parents: dict[int, Parent]) -> Fit: - if session.project.config.kinds[kind].parent is None or pick.id in parents: - return fit - return fit.model_copy(update={'flag': ','.join(filter(None, [fit.flag, 'noparent']))}) +# flagged: the fit with noparent added to its flags when the pick's kind has a parent and the pick found none, and lowcc when validation scored the pick far below the rest of its kind +def flagged(session: Session, kind: str, pick: Pick, fit: Fit, parents: dict[int, Parent], validation: ValidationStore | None = None) -> Fit: + extra = [] + if session.project.config.kinds[kind].parent is not None and pick.id not in parents: + extra.append('noparent') + if validation is not None and validation.low(pick): + extra.append('lowcc') + return fit.model_copy(update={'flag': ','.join(filter(None, [fit.flag, *extra]))}) if extra else fit -# items: picks of a kind that have a current fit, each fit flagged where its parent is missing +# items: picks of a kind that have a current fit, each fit flagged where its parent is missing or validation scored it low def items(session: Session, service: EstimateService, kind: str) -> list[Item]: parents = matched(session, service, kind) out = [] for pick in session.store.all(kind): fit = service.store.get(pick) if fit is not None: - out.append((pick, flagged(session, kind, pick, fit, parents))) + out.append((pick, flagged(session, kind, pick, fit, parents, service.validation))) return out diff --git a/src/pickmix/model.py b/src/pickmix/model.py index 397c87d..7795c19 100644 --- a/src/pickmix/model.py +++ b/src/pickmix/model.py @@ -7,13 +7,13 @@ from collections.abc import Callable from dataclasses import dataclass from pathlib import Path -from pydantic import BaseModel +from pydantic import BaseModel, field_validator # Import internal pickmix objects from pickmix.candidates import CandidateStore from pickmix.project import Project -# Pick: one hand-picked centre; x, y, z in reconstruction voxels; id lives for the session only +# Pick: one hand-picked centre; x, y, z in reconstruction voxels; id lives for the session only. box_a is the box edge in Angstrom the user measured for this pick, None to take it from the kind or the estimator @dataclass class Pick: id: int @@ -22,8 +22,9 @@ class Pick: x: float y: float z: float + box_a: float | None = None -# _Row: one picks.csv row; a missing kind column is a CaVe file, whose picks were all cages +# _Row: one picks.csv row; a missing kind column is a CaVe file, whose picks were all cages, and a missing or empty box_a column means no box of its own class _Row(BaseModel): tomogram: str kind: str = 'cage' @@ -31,6 +32,13 @@ class _Row(BaseModel): y: float z: float pixel_size_a: float + box_a: float | None = None + + # _blank: an empty csv cell is no box + @field_validator('box_a', mode='before') + @classmethod + def _blank(cls, value: object) -> object: + return None if value == '' else value # Progress: where picking stopped and which tomograms have been opened, saved beside picks.csv class Progress(BaseModel): @@ -58,7 +66,7 @@ def __init__(self, project: Project) -> None: if self.path.exists(): with open(self.path, newline='') as handle: for row in map(_Row.model_validate, csv.DictReader(handle)): - pick = Pick(next(self._ids), row.tomogram, row.kind, row.x, row.y, row.z) + pick = Pick(next(self._ids), row.tomogram, row.kind, row.x, row.y, row.z, row.box_a) self._picks[pick.id] = pick # get: the pick with this id @@ -81,9 +89,9 @@ def count(self, tomogram: str, kind: str | None = None) -> int: def total(self, kind: str | None = None) -> int: return len(self.all(kind)) - # add: new pick; saves and notifies - def add(self, tomogram: str, kind: str, x: float, y: float, z: float) -> Pick: - pick = Pick(next(self._ids), tomogram, kind, x, y, z) + # add: new pick, with its own box edge in Angstrom if it has one; saves and notifies + def add(self, tomogram: str, kind: str, x: float, y: float, z: float, *, box_a: float | None = None) -> Pick: + pick = Pick(next(self._ids), tomogram, kind, x, y, z, box_a) self._picks[pick.id] = pick self._changed() return pick @@ -96,6 +104,11 @@ def move(self, pick_id: int, x: float, y: float, z: float | None = None) -> None pick.z = z self._changed() + # set_box: the pick's own box edge in Angstrom, or None to go back to the kind's; saves and notifies + def set_box(self, pick_id: int, box_a: float | None) -> None: + self._picks[pick_id].box_a = box_a + self._changed() + # remove: delete picks; saves and notifies once def remove(self, *pick_ids: int) -> None: for pick_id in pick_ids: @@ -128,7 +141,7 @@ def save(self) -> None: writer.writeheader() for p in list(self._picks.values()): # unusable tomograms keep their picks; pixel size is only informative - writer.writerow(_Row(tomogram=p.tomogram, kind=p.kind, x=p.x, y=p.y, z=p.z, pixel_size_a=pixel.get(p.tomogram, 0.0)).model_dump()) + writer.writerow(_Row(tomogram=p.tomogram, kind=p.kind, x=p.x, y=p.y, z=p.z, pixel_size_a=pixel.get(p.tomogram, 0.0), box_a=p.box_a).model_dump()) os.replace(tmp, self.path) # _changed: save, then tell listeners diff --git a/src/pickmix/validate.py b/src/pickmix/validate.py new file mode 100644 index 0000000..16e1903 --- /dev/null +++ b/src/pickmix/validate.py @@ -0,0 +1,37 @@ +''' +pickmix: run kind validation over the picks of a kind +''' + +# Import external dependencies +import numpy as np +from collections.abc import Callable +from dataclasses import dataclass + +# Import internal pickmix objects +from pickmix.average import box_images +from pickmix.estimates import EstimateService +from pickmix.items import items +from pickmix.model import Session +from pickmix.validation import low_scores, score_images + +# ValidationSummary: what validating one kind found; skipped picks had no current fit to cut a box at +@dataclass(frozen=True) +class ValidationSummary: + kind: str + scored: int + flagged: int + skipped: int + median: float + +# validate_kind: score the picks of a kind that have a current fit against the average of the kind, store the scores and which are low; ValueError if the kind has too few picks, or picks of more than one pixel size +def validate_kind(name: str, session: Session, service: EstimateService, *, log: Callable[[str], None] = lambda _: None) -> ValidationSummary: + config = session.project.config + got = items(session, service, name) + pairs, _ = box_images(name, config.kinds[name], got, session.project.tomos, config, log=log) + try: + scores = score_images(np.stack([img for _, img in pairs]), config.validation) + except ValueError as e: + raise ValueError(f'kind {name!r}: {e}') from None + low = low_scores(scores, config.validation) + service.validation.put_kind(name, [(p, float(s), bool(flag)) for (p, _), s, flag in zip(pairs, scores, low, strict=True)]) + return ValidationSummary(name, len(pairs), int(low.sum()), session.store.total(name) - len(pairs), float(np.median(scores))) diff --git a/src/pickmix/validation.py b/src/pickmix/validation.py new file mode 100644 index 0000000..4f552fe --- /dev/null +++ b/src/pickmix/validation.py @@ -0,0 +1,148 @@ +''' +pickmix: kind validation, scores of each pick against the average of its kind, saved to out_dir/validation.csv +''' + +# Import external dependencies +import csv, hashlib, json, numpy as np, os, threading +from collections.abc import Callable +from pydantic import BaseModel, field_validator +from typing import Literal + +# Import internal pickmix objects +from pickmix.config import ValidationParams +from pickmix.model import Pick, PickStore +from pickmix.project import Project + +# _MAD_TO_SIGMA: factor that turns a median absolute deviation into the standard deviation of a normal distribution with the same spread +_MAD_TO_SIGMA: float = 1.4826 + +# score_images: for every normalised image (n, h, w), the best normalised cross-correlation with the average of the others, over shifts up to shift_fraction of the box. The average leaves out the trim_fraction of lowest scoring images, found on a first pass, so bad picks do not pull it towards themselves +def score_images(images: np.ndarray, params: ValidationParams) -> np.ndarray: + n = len(images) + if n < params.min_picks: + raise ValueError(f'needs at least {params.min_picks} picks to validate, has {n}') + shift = round(params.shift_fraction * images.shape[1]) + first = _leave_one_out(images, np.ones(n, dtype=bool), shift) + keep = first >= np.quantile(first, params.trim_fraction) + return _leave_one_out(images, keep, shift) + +# deviations: how many robust standard deviations each score sits below the median of the scores, with the spread never less than mad_floor; negative above the median +def deviations(scores: np.ndarray, params: ValidationParams) -> np.ndarray: + median = np.median(scores) + spread = max(_MAD_TO_SIGMA * float(np.median(np.abs(scores - median))), params.mad_floor) + return (median - scores) / spread + +# low_scores: which scores are far enough below the rest to flag, or under the lowest score if one is set +def low_scores(scores: np.ndarray, params: ValidationParams) -> np.ndarray: + return (deviations(scores, params) > params.flag_deviations) | (scores < params.min_score) + +# _leave_one_out: the best normalised cross-correlation of each image with the mean of the images in keep other than itself, over circular shifts up to shift pixels each way +def _leave_one_out(images: np.ndarray, keep: np.ndarray, shift: int) -> np.ndarray: + n, h, w = images.shape + total = images[keep].sum(axis=0) + others = keep.sum() - keep + means = (total[None] - images * keep[:, None, None]) / others[:, None, None] + spread = means.reshape(n, -1).std(axis=1) + 1e-9 + # images have zero mean and unit spread, so the correlation needs only the spread of the average + corr = np.fft.irfft2(np.conj(np.fft.rfft2(images)) * np.fft.rfft2(means), s=(h, w)) / (h * w * spread[:, None, None]) + ys, xs = np.arange(-shift, shift + 1) % h, np.arange(-shift, shift + 1) % w + return corr[:, ys][:, :, xs].reshape(n, -1).max(axis=1) + +# _Row: row from validation.csv (pick score, whether it was low, what score was against) +class _Row(BaseModel): + tomogram: str + kind: str + pick_x: float + pick_y: float + pick_z: float + score: float + low: bool + members: str + digest: str + + # _blank: an empty csv cell reads as a false flag + @field_validator('low', mode='before') + @classmethod + def _blank(cls, value: object) -> object: + return False if value == '' else value + +# _Key: tomogram, kind and rounded coordinates of a pick +type _Key = tuple[str, str, float, float, float] + +# ValidationStore: scores for picks of a kind, valid while settings and all picks are the same as when scored +class ValidationStore: + # __init__: load validation.csv if there is one; digest_of gives the estimate digest of a kind, which the scores depend on through the fits + def __init__(self, project: Project, picks: PickStore, digest_of: Callable[[str], str | None]) -> None: + self.project, self.picks, self._digest_of = project, picks, digest_of + self.path = project.config.out_dir / 'validation.csv' + # called from whichever thread stored a result + self.listeners: list[Callable[[], None]] = [] + self._lock = threading.Lock() + self._rows: dict[_Key, _Row] = {} + if self.path.exists(): + with open(self.path, newline='') as handle: + for row in map(_Row.model_validate, csv.DictReader(handle)): + self._rows[_key(row.tomogram, row.kind, row.pick_x, row.pick_y, row.pick_z)] = row + + # digest: fingerprint of what scores of a kind depend on beside picks + def digest(self, kind: str) -> str | None: + estimate = self._digest_of(kind) + if estimate is None: + return None + blob = json.dumps({'estimate': estimate, 'validation': self.project.config.validation.model_dump()}, sort_keys=True) + return hashlib.sha1(blob.encode()).hexdigest()[:12] + + # members: fingerprint of every pick of a kind and where it is, which changes when one is added, removed or moved + def members(self, kind: str) -> str: + keys = sorted((p.tomogram, round(p.x, 3), round(p.y, 3), round(p.z, 3)) for p in self.picks.all(kind)) + return hashlib.sha1(json.dumps(keys).encode()).hexdigest()[:12] + + # state: ok when score matches pick, settings and picks of kind + def state(self, pick: Pick) -> Literal['ok', 'stale', 'missing']: + row = self._rows.get(_key(pick.tomogram, pick.kind, pick.x, pick.y, pick.z)) + digest = self.digest(pick.kind) + if row is None or digest is None: + return 'missing' + return 'ok' if row.digest == digest and row.members == self.members(pick.kind) else 'stale' + + # score: pick's score if it is current + def score(self, pick: Pick) -> float | None: + return self._rows[_key(pick.tomogram, pick.kind, pick.x, pick.y, pick.z)].score if self.state(pick) == 'ok' else None + + # low: whether pick's score is current and low enough to flag + def low(self, pick: Pick) -> bool: + return self.state(pick) == 'ok' and self._rows[_key(pick.tomogram, pick.kind, pick.x, pick.y, pick.z)].low + + # put_kind: replace scores of a kind with new ones, (pick, score, low) for each, save, and tell listeners + def put_kind(self, kind: str, scored: list[tuple[Pick, float, bool]]) -> None: + digest, members = self.digest(kind), self.members(kind) + if digest is None: + raise KeyError(kind) + with self._lock: + self._rows = {k: r for k, r in self._rows.items() if r.kind != kind} + for pick, score, low in scored: + self._rows[_key(pick.tomogram, kind, pick.x, pick.y, pick.z)] = _Row(tomogram=pick.tomogram, kind=kind, pick_x=pick.x, pick_y=pick.y, pick_z=pick.z, score=score, low=low, members=members, digest=digest) + self._save() + for listener in self.listeners: + listener() + + # rename_kind: keep scores of a renamed kind + def rename_kind(self, old: str, new: str) -> None: + with self._lock: + self._rows = {(_key(r.tomogram, new, r.pick_x, r.pick_y, r.pick_z) if r.kind == old else k): r.model_copy(update={'kind': new}) if r.kind == old else r for k, r in self._rows.items()} + + # _save: atomically write CSV, keeping only rows that belong to a pick now + def _save(self) -> None: + live = {_key(p.tomogram, p.kind, p.x, p.y, p.z) for p in self.picks.all()} + self._rows = {k: r for k, r in self._rows.items() if k in live} + self.path.parent.mkdir(parents=True, exist_ok=True) + tmp = self.path.with_suffix('.csv.tmp') + with open(tmp, 'w', newline='') as handle: + writer = csv.DictWriter(handle, fieldnames=list(_Row.model_fields)) + writer.writeheader() + writer.writerows(r.model_dump() for r in self._rows.values()) + os.replace(tmp, self.path) + +# _key: dictionary key for a pick's position +def _key(tomogram: str, kind: str, x: float, y: float, z: float) -> _Key: + return tomogram, kind, round(x, 3), round(y, 3), round(z, 3) diff --git a/tests/gui/test_components.py b/tests/gui/test_components.py index 05ff2b2..1e38ccb 100644 --- a/tests/gui/test_components.py +++ b/tests/gui/test_components.py @@ -12,7 +12,7 @@ # Import internal pickmix objects from pickmix.gui.components.canvas import FitView, Marker, SliceCanvas from pickmix.gui.components.icons import ICON_DIR, icon, tinted -from pickmix.gui.components.images import FitLabel, label_cells, tile_cells, label_image, to_image, to_pixmap +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 from pickmix.gui.components.status import STATUS_STYLE, StatusBadge, fit_status, status_item from pickmix.gui.components.toast import notify @@ -121,6 +121,79 @@ def test_candidate_marker(self, qtbot: QtBot) -> None: QTest.mouseRelease(canvas.viewport(), Qt.MouseButton.LeftButton, pos=end) assert blocker.args == [-3] and moved == [] and canvas.selected_id == -3 + # test_bounds_two_clicks: in bounds mode the first click places nothing and the second asks for a pair + def test_bounds_two_clicks(self, qtbot: QtBot) -> None: + canvas = _canvas(qtbot) + canvas.set_bounds_mode(True, 0.2) + with qtbot.assertNotEmitted(canvas.add_requested): + QTest.mouseClick(canvas.viewport(), Qt.MouseButton.LeftButton, pos=_view_pos(canvas, 10, 12)) + assert canvas.bounds_pending + with qtbot.waitSignal(canvas.bounds_requested) as blocker: + QTest.mouseClick(canvas.viewport(), Qt.MouseButton.LeftButton, pos=_view_pos(canvas, 30, 12)) + x1, y1, x2, y2 = blocker.args + assert abs(x1 - 10) < 1 and abs(y1 - 12) < 1 and abs(x2 - 30) < 1 and abs(y2 - 12) < 1 + assert not canvas.bounds_pending + + # test_bounds_preview_follows_pointer: after the first click a line and a box follow the pointer, the box padded and centred halfway + def test_bounds_preview_follows_pointer(self, qtbot: QtBot) -> None: + canvas = _canvas(qtbot) + canvas.set_bounds_mode(True, 0.5) + QTest.mouseClick(canvas.viewport(), Qt.MouseButton.LeftButton, pos=_view_pos(canvas, 10, 12)) + QTest.mouseMove(canvas.viewport(), _view_pos(canvas, 30, 12)) + line, box = canvas._rubber + assert abs(line.line().x2() - 30.5) < 1 and abs(box.rect().width() - 20 * 1.5) < 1.5 + assert abs(box.rect().center().x() - 20.5) < 1 + + # test_bounds_cancel: Escape, clearing the canvas and leaving bounds mode all drop a first click + def test_bounds_cancel(self, qtbot: QtBot) -> None: + canvas = _canvas(qtbot) + canvas.set_bounds_mode(True, 0.2) + canvas.setFocus() + QTest.mouseClick(canvas.viewport(), Qt.MouseButton.LeftButton, pos=_view_pos(canvas, 10, 12)) + QTest.keyClick(canvas, Qt.Key.Key_Escape) + assert not canvas.bounds_pending and canvas._rubber is None + QTest.mouseClick(canvas.viewport(), Qt.MouseButton.LeftButton, pos=_view_pos(canvas, 10, 12)) + canvas.set_bounds_mode(False) + assert not canvas.bounds_pending and canvas._rubber is None + canvas.set_bounds_mode(True, 0.2) + QTest.mouseClick(canvas.viewport(), Qt.MouseButton.LeftButton, pos=_view_pos(canvas, 10, 12)) + canvas.clear() + assert not canvas.bounds_pending + + # test_bounds_click_on_marker_selects: in bounds mode a click on a marker still selects it and starts no pair + def test_bounds_click_on_marker_selects(self, qtbot: QtBot) -> None: + canvas = _canvas(qtbot) + canvas.set_markers([Marker(3, 20, 15, 0, 4.0, 'yellow')]) + canvas.set_bounds_mode(True, 0.2) + with qtbot.waitSignal(canvas.marker_clicked): + QTest.mouseClick(canvas.viewport(), Qt.MouseButton.LeftButton, pos=_view_pos(canvas, 20, 15)) + assert not canvas.bounds_pending + + # test_filament_axis: a fit with a direction is drawn as a line along it, only on the slices of the fit and with the rings + def test_filament_axis(self, qtbot: QtBot) -> None: + canvas = _canvas(qtbot) + fit = FitView(20, 15, 5, None, 16.0, 3, 7, 30.0) + canvas.set_markers([Marker(1, 20, 15, 5, 4.0, 'yellow', fit=fit), Marker(2, 5, 5, 5, 4.0, 'yellow', fit=FitView(5, 5, 5, 4.0, 16.0, 3, 7))]) + canvas.set_z(5) + assert canvas.axis_visible(1) and abs(canvas.axis_angle(1) - 30.0) < 1e-6 and canvas.axis_angle(2) is None and not canvas.axis_visible(2) + canvas.set_z(9) + assert not canvas.axis_visible(1) + canvas.set_z(5) + canvas.set_overlay(rings=False, boxes=True) + assert not canvas.axis_visible(1) + canvas.set_overlay(rings=True, boxes=True) + assert canvas.axis_visible(1) + + # test_axis_removed_with_markers: replacing the markers removes the axis items + def test_axis_removed_with_markers(self, qtbot: QtBot) -> None: + canvas = _canvas(qtbot) + canvas.set_markers([Marker(1, 20, 15, 5, 4.0, 'yellow', fit=FitView(20, 15, 5, None, 16.0, 3, 7, 90.0))]) + count = len(canvas.scene().items()) + canvas.set_markers([Marker(1, 20, 15, 5, 4.0, 'yellow', fit=FitView(20, 15, 5, None, 16.0, 3, 7, 90.0))]) + assert len(canvas.scene().items()) == count + canvas.set_markers([]) + assert canvas.axis_angle(1) is None + # test_wheel_scrolls_z: a wheel notch emits one z step def test_wheel_scrolls_z(self, qtbot: QtBot) -> None: canvas = _canvas(qtbot) @@ -261,6 +334,23 @@ def test_tile_cells_fill_a_wide_pane(self, qtbot: QtBot) -> None: tall = tile_cells(base, ['a'] * 5, grid, pad, 120, 600) assert tall.pixelColor(60, 60) != QColor('#141414') and tall.pixelColor(60, 540) != QColor('#141414') + # test_outline_scaled: the rectangle is drawn at the array position times the scale, and the original is untouched + def test_outline_scaled(self) -> None: + base = QPixmap(100, 100) + base.fill(QColor('black')) + out = draw_box(base, (10, 20, 30, 40), 2.0, 'red') + image = out.toImage() + assert image.pixelColor(20, 40) == QColor('red') and image.pixelColor(60, 60) == QColor('red') and image.pixelColor(40, 60) == QColor('black') + assert base.toImage().pixelColor(20, 40) == QColor('black') + + # test_dotted_skips_pixels: a dotted outline leaves gaps along an edge + def test_dotted_skips_pixels(self) -> None: + base = QPixmap(100, 100) + base.fill(QColor('black')) + image = draw_box(base, (10, 10, 90, 50), 1.0, 'red', dotted=True).toImage() + edge = [image.pixelColor(x, 10) == QColor('red') for x in range(10, 90)] + assert any(edge) and not all(edge) + # TestRangeSlider: two-handle slider class TestRangeSlider: # test_solid_handles: an unfocused handle is filled with the highlight colour, like the span diff --git a/tests/gui/test_dialogs.py b/tests/gui/test_dialogs.py index 0daf324..83a1587 100644 --- a/tests/gui/test_dialogs.py +++ b/tests/gui/test_dialogs.py @@ -26,6 +26,15 @@ def test_values_round_trip(self, qtbot: QtBot) -> None: qtbot.addWidget(dialog) assert dialog.values() == ('green', kind) + # test_pick_mode_round_trip: pick mode and padding are shown and padding is only live in bounds mode + def test_pick_mode_round_trip(self, qtbot: QtBot) -> None: + kind = Kind(marker_a=40, pick_mode='bounds', bounds_padding=0.35) + dialog = KindDialog(None, 'tube', kind, [], _ok) + qtbot.addWidget(dialog) + assert dialog.values() == ('tube', kind) and dialog.padding_spin.isEnabled() + dialog.mode_box.setCurrentText('point') + assert not dialog.padding_spin.isEnabled() and dialog.values()[1].pick_mode == 'point' + # test_defaults_when_adding: a new kind starts as an editable passthrough with no tilt prior def test_defaults_when_adding(self, qtbot: QtBot) -> None: dialog = KindDialog(None, None, None, [], _ok) diff --git a/tests/gui/test_panes.py b/tests/gui/test_panes.py index b489f9e..8b9daca 100644 --- a/tests/gui/test_panes.py +++ b/tests/gui/test_panes.py @@ -3,7 +3,7 @@ ''' # Import external dependencies -import numpy as np, pytest +import dataclasses, numpy as np, pytest from collections.abc import Callable, Iterator from pathlib import Path from PySide6.QtGui import QImage, QShortcut @@ -126,6 +126,34 @@ def _ran(self, qtbot: QtBot, pane: tuple[AveragePane, Session, EstimateService]) qtbot.waitUntil(lambda: widget.result is not None, timeout=5000) return widget + # test_montage_lowest_first: with the box ticked and scores stored the montage is labelled with them, and without scores it says so + def test_montage_lowest_first(self, qtbot: QtBot, pane: tuple[AveragePane, Session, EstimateService], capsys) -> None: + widget, session, service = pane + a = session.store.add(NAME, 'yellow', 4.0, 3.0, 2.0) + b = session.store.add(NAME, 'yellow', 5.0, 3.0, 2.0) + qtbot.waitUntil(lambda: all(service.store.state(p) == 'ok' for p in (a, b)), timeout=5000) + widget.refresh_kinds() + widget.worst_box.setChecked(True) + widget.run() + qtbot.waitUntil(lambda: widget.result is not None, timeout=5000) + assert 'No validation scores' in capsys.readouterr().out and not any(label.endswith('0.30') for label in widget.result.labels) + service.validation.put_kind('yellow', [(a, 0.60, False), (b, 0.30, True)]) + widget.result = None + widget.run() + qtbot.waitUntil(lambda: widget.result is not None, timeout=5000) + assert widget.result.labels[0].endswith('0.30') and widget.result.labels[1].endswith('0.60') + + # test_filament_note: an average of turned filaments says so, and one of anything else does not + def test_filament_note(self, qtbot: QtBot, pane: tuple[AveragePane, Session, EstimateService], capsys) -> None: + widget = self._ran(qtbot, pane) + plain = widget.result + assert not plain.aligned + capsys.readouterr() + widget._done(dataclasses.replace(plain, aligned=True)) + assert 'oriented along x' in capsys.readouterr().out + widget._done(plain) + assert 'oriented along x' not in capsys.readouterr().out + # test_list_shows_counts: row 0 is the overall count, each other row a tomogram with its own count, and choosing a row changes the mean def test_list_shows_counts(self, qtbot: QtBot, pane: tuple[AveragePane, Session, EstimateService]) -> None: widget = self._ran(qtbot, pane) @@ -177,7 +205,7 @@ def test_lists_kinds(self, qtbot: QtBot, make_config: Callable[..., Path]) -> No pane, _ = _kinds_pane(qtbot, make_config) assert pane.kind_names() == ['cage'] and 'cage' in pane.edit_buttons text = pane.details['cage'].text() - assert 'Marker: 600 Å' in text and 'Box: from estimator' in text and 'Estimator: ring' in text and 'Parent: none' in text + assert 'Marker: 600 Å' in text and 'Box: from estimator' in text and 'Estimator: ring' in text and 'Picking: one click' in text and 'Parent: none' in text # test_add_kind: a new kind is saved after the others and takes the first free key def test_add_kind(self, qtbot: QtBot, make_config: Callable[..., Path]) -> None: @@ -298,7 +326,7 @@ def test_refused_delete_keeps_picks(self, qtbot: QtBot, make_config: Callable[.. def test_details_are_a_vertical_list_with_bold_keys(self, qtbot: QtBot, make_config: Callable[..., Path]) -> None: pane, _ = _kinds_pane(qtbot, make_config) lines = pane.details['cage'].text().split('
') - assert len(lines) == 7 and all(line.startswith('') and ': ' in line for line in lines) + assert len(lines) == 8 and all(line.startswith('') and ': ' in line for line in lines) # test_kinds_flow_into_columns: a wide block gives one column, a narrow one gives several, filling across then down def test_kinds_flow_into_columns(self, qtbot: QtBot, make_config: Callable[..., Path], monkeypatch) -> None: @@ -374,6 +402,45 @@ def test_match_value_refused(self, qtbot: QtBot, make_config: Callable[..., Path pane.match_form._boxes['min_score'][0].setValue(1.5) assert load_config(path).match.min_score == 0.2 + # test_filament_value_autosaves: a committed filament number is written, the others are kept + def test_filament_value_autosaves(self, qtbot: QtBot, make_config: Callable[..., Path]) -> None: + pane, path = _settings_pane(qtbot, make_config) + with qtbot.waitSignal(pane.config_saved): + pane.filament_form._boxes['search_range_a'][0].setValue(450.0) + config = load_config(path) + assert config.filament.search_range_a == 450.0 and config.filament.width_range_a == (60.0, 300.0) and config.filament.box_from == 'segment' + + # test_box_from_is_a_choice: the box source is a drop-down of its two values, saved when changed, with the trade-off on hover + def test_box_from_is_a_choice(self, qtbot: QtBot, make_config: Callable[..., Path]) -> None: + pane, path = _settings_pane(qtbot, make_config) + [choice] = pane.filament_form._boxes['box_from'] + assert [choice.itemText(i) for i in range(choice.count())] == ['width', 'segment'] and choice.currentText() == 'segment' + assert 'mostly empty' in pane.filament_form.labels['box_from'].toolTip() + with qtbot.waitSignal(pane.config_saved): + choice.setCurrentText('width') + assert load_config(path).filament.box_from == 'width' + pane.set_project(open_project(path)) + assert pane.filament_form.get().box_from == 'width' + + # test_filament_section_collapsed: filament parameters are hidden until the section is opened + def test_filament_section_collapsed(self, qtbot: QtBot) -> None: + pane = SettingsPane() + qtbot.addWidget(pane) + assert pane.filament_form.isHidden() + pane.filament_section.toggle.setChecked(True) + assert not pane.filament_form.isHidden() + + # test_validation_value_autosaves: a committed validation number is written, the others are kept, and the section starts collapsed + def test_validation_value_autosaves(self, qtbot: QtBot, make_config: Callable[..., Path]) -> None: + pane, path = _settings_pane(qtbot, make_config) + assert pane.validation_form.isHidden() + pane.validation_section.toggle.setChecked(True) + assert not pane.validation_form.isHidden() + with qtbot.waitSignal(pane.config_saved): + pane.validation_form._boxes['flag_deviations'][0].setValue(8.0) + config = load_config(path) + assert config.validation.flag_deviations == 8.0 and config.validation.min_picks == 10 and config.validation.trim_fraction == 0.2 + # test_no_save_button: there is nothing to press def test_no_save_button(self, qtbot: QtBot) -> None: pane = SettingsPane() @@ -423,6 +490,8 @@ def test_width_fixed(self, qtbot: QtBot) -> None: qtbot.addWidget(pane) closed = pane.minimumSizeHint().width() pane.ring_section.toggle.setChecked(True) + pane.filament_section.toggle.setChecked(True) + pane.validation_section.toggle.setChecked(True) assert pane.minimumSizeHint().width() == closed # TestTomoPane: tomogram dock diff --git a/tests/gui/test_patch.py b/tests/gui/test_patch.py new file mode 100644 index 0000000..44216c1 --- /dev/null +++ b/tests/gui/test_patch.py @@ -0,0 +1,127 @@ +''' +pickmix: tests for the pick patch canvas +''' + +# Import external dependencies +import numpy as np +from PySide6.QtCore import QPoint, QPointF, Qt +from PySide6.QtTest import QTest +from pytestqt.qtbot import QtBot + +# Import internal pickmix objects +from pickmix.gui.components.patch import Patch, PatchCanvas + +# _patch: a 60 x 60 crop whose top-left pixel is voxel (100, 200), with a pick at (130, 230) and a 20 pixel box centred 2 voxels right of it +def _patch(**changes: object) -> Patch: + base = dict( + pixels=np.random.default_rng(0).random((60, 60)).astype(np.float32), origin=(100, 200), pick_id=7, + pick=(130.0, 230.0), box_centre=(132.0, 230.0), box_px=20.0, colour='yellow', bounds=(500, 500), + ) + return Patch(**{**base, **changes}) + +# _canvas: a shown 240 px canvas with a patch, at 4 screen pixels per voxel +def _canvas(qtbot: QtBot, patch: Patch | None = None) -> PatchCanvas: + canvas = PatchCanvas(240) + qtbot.addWidget(canvas) + canvas.show() + canvas.set_patch(patch or _patch()) + return canvas + +# _view_pos: viewport position of a voxel position +def _view_pos(canvas: PatchCanvas, patch: Patch, x: float, y: float) -> QPoint: + return canvas.mapFromScene(QPointF(x - patch.origin[0] + 0.5, y - patch.origin[1] + 0.5)) + +# TestPatchCanvas: patch canvas tests +class TestPatchCanvas: + # test_geometry: box and dot sit at their voxel positions within the crop + def test_geometry(self, qtbot: QtBot) -> None: + canvas = _canvas(qtbot) + assert canvas.has_patch + assert canvas.box_rect() == (22.5, 20.5, 20.0, 20.0) + assert canvas.dot_position() == (30.5, 30.5) + + # test_drag_dot: dragging the dot asks to move the pick by the dragged distance + def test_drag_dot(self, qtbot: QtBot) -> None: + patch = _patch() + canvas = _canvas(qtbot, patch) + start, end = _view_pos(canvas, patch, 130, 230), _view_pos(canvas, patch, 135, 227) + QTest.mousePress(canvas.viewport(), Qt.MouseButton.LeftButton, pos=start) + QTest.mouseMove(canvas.viewport(), end) + assert abs(canvas.dot_position()[0] - 35.5) < 0.5 and abs(canvas.box_rect()[0] - (37.5 - 10)) < 0.5 + with qtbot.waitSignal(canvas.move_requested) as blocker: + QTest.mouseRelease(canvas.viewport(), Qt.MouseButton.LeftButton, pos=end) + pick_id, x, y = blocker.args + assert pick_id == 7 and abs(x - 135) < 0.5 and abs(y - 227) < 0.5 + + # test_drag_box_body: a press inside the box away from the dot also drags + def test_drag_box_body(self, qtbot: QtBot) -> None: + patch = _patch() + canvas = _canvas(qtbot, patch) + start, end = _view_pos(canvas, patch, 138, 236), _view_pos(canvas, patch, 140, 240) + QTest.mousePress(canvas.viewport(), Qt.MouseButton.LeftButton, pos=start) + QTest.mouseMove(canvas.viewport(), end) + with qtbot.waitSignal(canvas.move_requested) as blocker: + QTest.mouseRelease(canvas.viewport(), Qt.MouseButton.LeftButton, pos=end) + _, x, y = blocker.args + assert abs(x - 132) < 0.5 and abs(y - 234) < 0.5 + + # test_press_outside_does_nothing: a press off the box and dot starts no drag + def test_press_outside_does_nothing(self, qtbot: QtBot) -> None: + patch = _patch() + canvas = _canvas(qtbot, patch) + start, end = _view_pos(canvas, patch, 105, 205), _view_pos(canvas, patch, 110, 210) + with qtbot.assertNotEmitted(canvas.move_requested): + QTest.mousePress(canvas.viewport(), Qt.MouseButton.LeftButton, pos=start) + QTest.mouseMove(canvas.viewport(), end) + QTest.mouseRelease(canvas.viewport(), Qt.MouseButton.LeftButton, pos=end) + assert canvas.dot_position() == (30.5, 30.5) + + # test_click_without_drag: pressing and releasing on the dot asks for nothing + def test_click_without_drag(self, qtbot: QtBot) -> None: + patch = _patch() + canvas = _canvas(qtbot, patch) + pos = _view_pos(canvas, patch, 130, 230) + with qtbot.assertNotEmitted(canvas.move_requested): + QTest.mouseClick(canvas.viewport(), Qt.MouseButton.LeftButton, pos=pos) + + # test_drag_clamps_to_tomogram: a drag past the tomogram edge stops at the edge + def test_drag_clamps_to_tomogram(self, qtbot: QtBot) -> None: + patch = _patch(origin=(0, 0), pick=(5.0, 5.0), box_centre=(5.0, 5.0), bounds=(40, 30)) + canvas = _canvas(qtbot, patch) + start, end = _view_pos(canvas, patch, 5, 5), _view_pos(canvas, patch, -20, 55) + QTest.mousePress(canvas.viewport(), Qt.MouseButton.LeftButton, pos=start) + QTest.mouseMove(canvas.viewport(), end) + with qtbot.waitSignal(canvas.move_requested) as blocker: + QTest.mouseRelease(canvas.viewport(), Qt.MouseButton.LeftButton, pos=end) + _, x, y = blocker.args + assert x == 0.0 and y == 29.0 + + # test_new_patch_replaces_old: setting a patch again leaves one box and one dot, and a drag in progress is dropped + def test_new_patch_replaces_old(self, qtbot: QtBot) -> None: + patch = _patch() + canvas = _canvas(qtbot, patch) + QTest.mousePress(canvas.viewport(), Qt.MouseButton.LeftButton, pos=_view_pos(canvas, patch, 130, 230)) + QTest.mouseMove(canvas.viewport(), _view_pos(canvas, patch, 140, 240)) + canvas.set_patch(_patch(box_px=30.0)) + assert canvas.box_rect()[2] == 30.0 and canvas.dot_position() == (30.5, 30.5) + assert len(canvas.scene().items()) == 3 + + # test_axis_drawn_through_box: a filament direction draws a line along it through the box, which moves with the box + def test_axis_drawn_through_box(self, qtbot: QtBot) -> None: + patch = _patch(psi_deg=45.0) + canvas = _canvas(qtbot, patch) + assert abs(canvas.axis_angle() - 45.0) < 1e-6 and len(canvas.scene().items()) == 4 + start, end = _view_pos(canvas, patch, 130, 230), _view_pos(canvas, patch, 135, 227) + QTest.mousePress(canvas.viewport(), Qt.MouseButton.LeftButton, pos=start) + QTest.mouseMove(canvas.viewport(), end) + assert abs(canvas._axis.pos().x() - canvas._box.pos().x()) < 1e-9 and canvas._axis.pos().x() > 32.5 + QTest.mouseRelease(canvas.viewport(), Qt.MouseButton.LeftButton, pos=end) + canvas.set_patch(_patch()) + assert canvas.axis_angle() is None and len(canvas.scene().items()) == 3 + + # test_clear: clearing removes the box and dot and stops drags + def test_clear(self, qtbot: QtBot) -> None: + canvas = _canvas(qtbot) + canvas.clear() + assert not canvas.has_patch and canvas.box_rect() is None and canvas.dot_position() is None + QTest.mouseClick(canvas.viewport(), Qt.MouseButton.LeftButton, pos=QPoint(100, 100)) diff --git a/tests/gui/test_pick_tab.py b/tests/gui/test_pick_tab.py index 3b903f2..20ffc39 100644 --- a/tests/gui/test_pick_tab.py +++ b/tests/gui/test_pick_tab.py @@ -6,13 +6,15 @@ import pytest from collections.abc import Callable, Iterator from pathlib import Path -from PySide6.QtCore import Qt +from PySide6.QtCore import QPointF, Qt +from PySide6.QtTest import QTest from PySide6.QtWidgets import QHeaderView from pytestqt.qtbot import QtBot # Import internal pickmix objects from pickmix.candidates import Hit from pickmix.config import Kind +from pickmix.estimate.registry import Fit from pickmix.estimates import EstimateService from pickmix.gui.tabs.pick_tab import PickTab from pickmix.loader import Loader @@ -153,6 +155,95 @@ def test_arrow_keys_leave_contrast_slider(self, qtbot: QtBot, setup: Callable[.. qtbot.keyClick(tab.contrast, Qt.Key.Key_Up) assert tab.z == before + # test_bounds_pick: two clicks make one pick halfway between them with a box the distance apart plus the kind's padding + def test_bounds_pick(self, setup: Callable[..., tuple[PickTab, Session]]) -> None: + tab, session = setup() + session.project.update(kinds={**session.project.config.kinds, 'tube': Kind(marker_a=100, pick_mode='bounds', bounds_padding=0.5)}) + tab.refresh_kinds() + tab._set_active('tube') + assert 'Two-click' in tab.help.text() + tab.canvas.bounds_requested.emit(1.0, 2.0, 5.0, 2.0) + [pick] = session.store.all('tube') + px = session.project.tomos[pick.tomogram].pixel_size + assert (pick.x, pick.y, pick.z) == (3.0, 2.0, 2.0) and abs(pick.box_a - 4 * px * 1.5) < 1e-9 + assert tab.canvas.selected_id == pick.id + tab._set_active('cage') + assert 'Two-click' not in tab.help.text() + + # test_bounds_same_voxel_ignored: two clicks on one voxel make no pick + def test_bounds_same_voxel_ignored(self, setup: Callable[..., tuple[PickTab, Session]]) -> None: + tab, session = setup() + session.project.update(kinds={**session.project.config.kinds, 'tube': Kind(marker_a=100, pick_mode='bounds')}) + tab.refresh_kinds() + tab._set_active('tube') + tab.canvas.bounds_requested.emit(2.0, 2.0, 2.4, 2.0) + assert session.store.total() == 0 + + # test_bounds_cancelled_by_kind_and_slice: changing kind or slice between the two clicks drops the first + def test_bounds_cancelled_by_kind_and_slice(self, qtbot: QtBot, setup: Callable[..., tuple[PickTab, Session]]) -> None: + tab, session = setup() + session.project.update(kinds={**session.project.config.kinds, 'tube': Kind(marker_a=100, pick_mode='bounds')}) + tab.refresh_kinds() + tab._set_active('tube') + tab.show() + qtbot.waitExposed(tab) + click = lambda x, y: QTest.mouseClick(tab.canvas.viewport(), Qt.MouseButton.LeftButton, pos=tab.canvas.mapFromScene(QPointF(x + 0.5, y + 0.5))) + click(2, 2) + assert tab.canvas.bounds_pending + tab._step_z(1) + assert not tab.canvas.bounds_pending + click(2, 2) + tab._set_active('cage') + assert not tab.canvas.bounds_pending + + # test_moving_bounds_pick_keeps_box: dragging a bounds pick moves it and keeps its box + def test_moving_bounds_pick_keeps_box(self, setup: Callable[..., tuple[PickTab, Session]]) -> None: + tab, session = setup() + session.project.update(kinds={**session.project.config.kinds, 'tube': Kind(marker_a=100, pick_mode='bounds')}) + tab.refresh_kinds() + tab._set_active('tube') + tab.canvas.bounds_requested.emit(1.0, 2.0, 5.0, 2.0) + [pick] = session.store.all('tube') + box = pick.box_a + tab._move(pick.id, 4.0, 3.0) + assert (session.store.get(pick.id).x, session.store.get(pick.id).box_a) == (4.0, box) + + # test_box_column_only_with_own_boxes: the pick table shows each pick's own box once any pick has one + def test_box_column_only_with_own_boxes(self, setup: Callable[..., tuple[PickTab, Session]]) -> None: + tab, session = setup() + session.store.add('Position_1_2', 'cage', 1.0, 1.0, 1.0) + tab._fill_table() + assert tab.table.isColumnHidden(7) + session.store.add('Position_1_2', 'cage', 2.0, 1.0, 1.0, box_a=412.0) + tab._fill_table() + assert not tab.table.isColumnHidden(7) + assert [tab.table.item(r, 7).text() for r in range(2)] == ['', '412'] + + # test_filament_drawn_as_axis: a fit with a direction shows as an axis line and no ring + def test_filament_drawn_as_axis(self, qtbot: QtBot, setup: Callable[..., tuple[PickTab, Session]]) -> None: + tab, session = setup() + session.project.update(kinds={**session.project.config.kinds, 'rod': Kind(marker_a=100, box_a=100, estimator='filament')}) + tab.refresh_kinds() + pick = session.store.add('Position_1_2', 'rod', 4.0, 3.0, 2.0) + fit = Fit(x=4.0, y=3.0, z=2.0, radius_a=20.0, box_a=100.0, snr=9.0, z_lo=1, z_hi=3, psi_deg=60.0) + # let the service finish its own estimate of this tiny volume first, so it cannot replace this fit + qtbot.waitUntil(lambda: tab.service.pending == 0, timeout=5000) + tab.service.store.put(pick, fit, tab.service.store.digest('rod')) + qtbot.waitUntil(lambda: tab.canvas.axis_angle(pick.id) is not None, timeout=5000) + assert abs(tab.canvas.axis_angle(pick.id) - 60.0) < 1e-6 and tab.canvas.overlay_visible(pick.id)[0] is False + + # test_lowcc_flag_shown: a pick validation scored low is flagged in the table and on the canvas, and loses the flag when the kind's picks change + def test_lowcc_flag_shown(self, qtbot: QtBot, setup: Callable[..., tuple[PickTab, Session]]) -> None: + tab, session = setup() + a = session.store.add('Position_1_2', 'yellow', 1.0, 1.0, 1.0) + b = session.store.add('Position_1_2', 'yellow', 2.0, 1.0, 1.0) + qtbot.waitUntil(lambda: all(tab.service.store.state(p) == 'ok' for p in (a, b)), timeout=5000) + tab.service.validation.put_kind('yellow', [(a, 0.1, True), (b, 0.6, False)]) + qtbot.waitUntil(lambda: 'lowcc' in {tab.table.item(r, 6).text() for r in range(tab.table.rowCount())}, timeout=5000) + assert {m.id: m.flagged for m in tab._markers()}[a.id] and not {m.id: m.flagged for m in tab._markers()}[b.id] + session.store.add('Position_1_2', 'yellow', 3.0, 1.0, 1.0) + qtbot.waitUntil(lambda: 'lowcc' not in {tab.table.item(r, 6).text() for r in range(tab.table.rowCount())}, timeout=5000) + # test_delete_needs_selection: Delete is greyed until a pick is selected and again once it is gone def test_delete_needs_selection(self, setup: Callable[..., tuple[PickTab, Session]]) -> None: tab, _ = setup() diff --git a/tests/gui/test_review_tab.py b/tests/gui/test_review_tab.py index 3cf9730..6631cd2 100644 --- a/tests/gui/test_review_tab.py +++ b/tests/gui/test_review_tab.py @@ -12,6 +12,7 @@ # Import internal pickmix objects from pickmix.config import Kind +from pickmix.estimate.registry import Fit from pickmix.estimates import EstimateService from pickmix.gui.tabs.review_tab import ReviewTab from pickmix.loader import Loader @@ -144,7 +145,7 @@ def test_preview_labels(self, qtbot: QtBot, setup: Callable[[], tuple[ReviewTab, session.store.add(NAME, 'yellow', 4.0, 3.0, 2.0) tab.refresh() tab.table.selectRow(0) - qtbot.waitUntil(lambda: all(not label.pixmap().isNull() for label in (tab.xy_label, tab.xz_label, tab.yz_label)), timeout=5000) + qtbot.waitUntil(lambda: all(not label.pixmap().isNull() for label in (tab.xy_label, tab.xz_label, tab.yz_label)) and tab.patch_canvas.has_patch, timeout=5000) assert tab.yz_label.toolTip() and not tab.reestimate_button.icon().isNull() # test_crops: preview crops are cut around the pick @@ -154,6 +155,130 @@ def test_crops(self, qtbot: QtBot, setup: Callable[[], tuple[ReviewTab, Session, vol = np.arange(4 * 6 * 8, dtype=np.float32).reshape(4, 6, 8) assert np.array_equal(xy, vol[2]) and np.array_equal(xz, vol[:, 3, :]) and np.array_equal(yz, vol[:, :, 4]) + # test_preview_grid: the previews are four panels, XY and the patch above XZ and YZ + def test_preview_grid(self, setup: Callable[[], tuple[ReviewTab, Session, EstimateService]]) -> None: + tab, _, _ = setup() + grid = tab.previews + assert [grid.itemAtPosition(r, c).widget() for r, c in ((0, 0), (0, 1), (1, 0), (1, 1))] == [tab.xy_label, tab.patch_canvas, tab.xz_label, tab.yz_label] + assert tab.patch_canvas.toolTip() + + # test_preview_uses_pick_box: a pick with its box is outlined at that size + def test_preview_uses_pick_box(self, setup: Callable[[], tuple[ReviewTab, Session, EstimateService]]) -> None: + tab, session, _ = setup() + pick = session.store.add(NAME, 'yellow', 4.0, 3.0, 2.0, box_a=10.72) + preview = tab.preview(pick, None) + px = session.project.tomos[NAME].pixel_size + assert preview.patch.box_px == 10.72 / px + + # test_preview_geometry: the patch is 1.5 times the box, centred on the pick, and the outlines surround the pick in each crop + def test_preview_geometry(self, setup: Callable[[], tuple[ReviewTab, Session, EstimateService]]) -> None: + tab, session, _ = setup() + pick = session.store.add(NAME, 'yellow', 4.0, 3.0, 2.0) + px = session.project.tomos[NAME].pixel_size + preview = tab.preview(pick, None) + box = 21.44 / px + assert preview.patch.pixels.shape == (6, 6) and preview.patch.origin == (1, 0) and preview.patch.box_px == box + assert preview.patch.pick == (4.0, 3.0) and preview.patch.bounds == (8, 6) + assert preview.outlines[0] == (4.5 - box / 2, 3.5 - box / 2, 4.5 + box / 2, 3.5 + box / 2) + assert preview.outlines[1] == (4.5 - box / 2, 2.5 - box / 2, 4.5 + box / 2, 2.5 + box / 2) + assert preview.outlines[2][:2] == (3.5 - box / 2, 2.5 - box / 2) and preview.slabs is None + + # test_preview_slab_from_fit: with a fit, the z range it used is outlined in XZ and YZ and the preview centres on the fit + def test_preview_slab_from_fit(self, setup: Callable[[], tuple[ReviewTab, Session, EstimateService]]) -> None: + tab, session, _ = setup() + pick = session.store.add(NAME, 'yellow', 4.0, 3.0, 2.0) + fit = Fit(x=5.0, y=3.0, z=2.0, radius_a=10, box_a=21.44, snr=1, z_lo=1, z_hi=3) + preview = tab.preview(pick, fit) + assert preview.patch.pick == (4.0, 3.0) and preview.patch.box_centre == (5.0, 3.0) + assert preview.slabs is not None and (preview.slabs[0][1], preview.slabs[0][3]) == (1, 4) + + # test_patch_shows_filament_axis: the patch of a pick with a filament fit carries the fit's direction + def test_patch_shows_filament_axis(self, setup: Callable[[], tuple[ReviewTab, Session, EstimateService]]) -> None: + tab, session, _ = setup() + pick = session.store.add(NAME, 'yellow', 4.0, 3.0, 2.0) + fit = Fit(x=4.0, y=3.0, z=2.0, radius_a=10, box_a=21.44, snr=1, z_lo=1, z_hi=3, psi_deg=120.0) + assert tab.preview(pick, fit).patch.psi_deg == 120.0 and tab.preview(pick, None).patch.psi_deg is None + + # test_patch_shown: selecting a pick shows its patch + def test_patch_shown(self, qtbot: QtBot, setup: Callable[[], tuple[ReviewTab, Session, EstimateService]]) -> None: + tab, session, _ = setup() + session.store.add(NAME, 'yellow', 4.0, 3.0, 2.0) + tab.refresh() + tab.table.selectRow(0) + qtbot.waitUntil(lambda: tab.patch_canvas.has_patch, timeout=5000) + assert tab.patch_canvas.box_rect()[2] > 0 + + # test_patch_drag_moves_pick: dragging the patch moves the pick, keeps it selected and refreshes the patch + def test_patch_drag_moves_pick(self, qtbot: QtBot, setup: Callable[[], tuple[ReviewTab, Session, EstimateService]]) -> None: + tab, session, _ = setup() + pick = session.store.add(NAME, 'yellow', 4.0, 3.0, 2.0) + tab.refresh() + tab.table.selectRow(0) + qtbot.waitUntil(lambda: tab.patch_canvas.has_patch, timeout=5000) + tab.patch_canvas.move_requested.emit(pick.id, 5.0, 3.0) + assert (session.store.get(pick.id).x, session.store.get(pick.id).y) == (5.0, 3.0) + qtbot.waitUntil(lambda: tab.patch_canvas.patch is not None and tab.patch_canvas.patch.pick == (5.0, 3.0), timeout=5000) + assert tab.table.currentRow() == 0 + + # test_box_column_only_with_own_boxes: the review table shows each pick's own box once any shown pick has one + def test_box_column_only_with_own_boxes(self, setup: Callable[[], tuple[ReviewTab, Session, EstimateService]]) -> None: + tab, session, _ = setup() + session.store.add(NAME, 'yellow', 4.0, 3.0, 2.0) + tab.refresh() + assert tab.table.isColumnHidden(8) + session.store.add(NAME, 'yellow', 5.0, 3.0, 2.0, box_a=412.0) + tab.refresh() + assert not tab.table.isColumnHidden(8) + assert sorted(tab.table.item(r, 8).text() for r in range(2)) == ['', '412'] + + # test_validate_controls: the tab has a Validate button with an explanation and a Worst first box + def test_validate_controls(self, setup: Callable[[], tuple[ReviewTab, Session, EstimateService]]) -> None: + tab, _, _ = setup() + assert tab.validate_button.text() == 'Validate' and 'lowcc' in tab.validate_button.toolTip() and 'several distinct views' in tab.validate_button.toolTip() + assert tab.worst_first_box.text() == 'Worst first' and not tab.worst_first_box.isChecked() + + # test_score_column_and_worst_first: scores appear once a pick has one, and Worst first puts the lowest first with unscored picks last + def test_score_column_and_worst_first(self, qtbot: QtBot, setup: Callable[[], tuple[ReviewTab, Session, EstimateService]]) -> None: + tab, session, service = setup() + picks = [session.store.add(NAME, 'yellow', float(x), 3.0, 2.0) for x in (1, 2, 3, 4)] + qtbot.waitUntil(lambda: all(service.store.state(p) == 'ok' for p in picks), timeout=5000) + tab.refresh() + assert tab.table.isColumnHidden(9) and [tab.table.item(r, 2).text() for r in range(4)] == ['1.0', '2.0', '3.0', '4.0'] + service.validation.put_kind('yellow', [(picks[0], 0.50, False), (picks[1], 0.10, True), (picks[3], 0.30, False)]) + qtbot.waitUntil(lambda: not tab.table.isColumnHidden(9), timeout=5000) + assert [tab.table.item(r, 9).text() for r in range(4)] == ['0.50', '0.10', '', '0.30'] + assert [tab.table.item(r, 6).text() for r in range(4)] == ['', 'lowcc', '', ''] + tab.worst_first_box.setChecked(True) + assert [tab.table.item(r, 2).text() for r in range(4)] == ['2.0', '4.0', '1.0', '3.0'] + tab.flag_filter.setCurrentIndex(1) + assert tab.table.rowCount() == 1 and tab.table.item(0, 2).text() == '2.0' + + # test_validate_reports: Validate scores the chosen kind in the background and says what it found; a kind with too few picks says so + def test_validate_reports(self, qtbot: QtBot, setup: Callable[[], tuple[ReviewTab, Session, EstimateService]], capsys) -> None: + tab, session, service = setup() + for x in range(12): + session.store.add(NAME, 'yellow', float(x % 8), float(x % 6), float(x % 4)) + session.store.add(NAME, 'bad', 1.0, 1.0, 1.0) + qtbot.waitUntil(lambda: all(service.store.state(p) == 'ok' for p in session.store.all()), timeout=5000) + tab.refresh() + tab.kind_filter.setCurrentText('yellow') + capsys.readouterr() + tab.validate_button.click() + assert not tab.validate_button.isEnabled() + qtbot.waitUntil(lambda: tab.validate_button.isEnabled(), timeout=10000) + assert 'yellow: scored 12' in capsys.readouterr().out + assert all(service.validation.state(p) == 'ok' for p in session.store.all('yellow')) + tab.kind_filter.setCurrentText('(all)') + tab.validate_button.click() + qtbot.waitUntil(lambda: tab.validate_button.isEnabled(), timeout=10000) + assert "kind 'bad': needs at least 10 picks to validate, has 1" in capsys.readouterr().out + + # test_validate_nothing_to_do: with no picks of the chosen kind it says so and starts nothing + def test_validate_nothing_to_do(self, setup: Callable[[], tuple[ReviewTab, Session, EstimateService]], capsys) -> None: + tab, _, _ = setup() + tab.validate_button.click() + assert 'No picks to validate' in capsys.readouterr().out and tab.validate_button.isEnabled() + # test_double_click_opens: double-clicking a row asks to open the pick def test_double_click_opens(self, qtbot: QtBot, setup: Callable[[], tuple[ReviewTab, Session, EstimateService]]) -> None: tab, session, service = setup() diff --git a/tests/test_average.py b/tests/test_average.py index 322a57e..81f5291 100644 --- a/tests/test_average.py +++ b/tests/test_average.py @@ -7,7 +7,7 @@ from pathlib import Path # Import internal pickmix objects -from pickmix.average import average_kind, save_average +from pickmix.average import average_kind, box_images, save_average from pickmix.config import Config, Kind from pickmix.estimate.registry import Fit from pickmix.model import Pick @@ -29,6 +29,29 @@ def _tomogram(path: Path, name: str, centres: list[tuple[int, int, int]], voxel: def _item(i: int, tomogram: str, x: float, y: float, z: float) -> tuple[Pick, Fit]: return Pick(i, tomogram, 'yellow', x, y, z), Fit(x=x, y=y, z=z, radius_a=30.0, box_a=100.0, snr=0, z_lo=round(z), z_hi=round(z)) +# _rod_tomogram: an 80-voxel cube at 5 A with a dark rod through the middle at angle_deg from the x axis towards y, in planes 36 to 44 +def _rod_tomogram(path: Path, name: str, angle_deg: float) -> Tomogram: + rng = np.random.default_rng(7) + vol = rng.normal(0.0, 0.3, (80, 80, 80)).astype(np.float32) + yy, xx = np.mgrid[:80, :80] + ux, uy = np.cos(np.radians(angle_deg)), np.sin(np.radians(angle_deg)) + along = (xx - 40) * ux + (yy - 40) * uy + across = -(xx - 40) * uy + (yy - 40) * ux + vol[36:45] -= 1.0 * np.exp(-0.5 * (across / 2.0) ** 2) * (np.abs(along) <= 22) + with mrcfile.new(path / f'{name}.mrc') as mrc: + mrc.set_data(vol) + mrc.voxel_size = 5.0 + return Tomogram(name, name, path / f'{name}.mrc', None, 5.0, (80, 80, 80), 5.0 / 4, (320, 320, 320)) + +# _rod_items: one pick per rod tomogram with a fit at its middle that has the rod's planes and, unless psi is False, its direction +def _rod_items(angles: dict[str, float], *, psi: bool = True) -> list[tuple[Pick, Fit]]: + return [(Pick(i, name, 'rod', 40, 40, 40), Fit(x=40, y=40, z=40, radius_a=25.0, box_a=250.0, snr=5.0, z_lo=36, z_hi=44, psi_deg=angle if psi else None)) for i, (name, angle) in enumerate(angles.items(), start=1)] + +# _bar_depth: how much darker the middle rows of a mean image are than the rows 8 pixels either side, in units of the image's own spread +def _bar_depth(img: np.ndarray) -> float: + c = img.shape[0] // 2 + return float((img[c - 8 : c - 5].mean() + img[c + 6 : c + 9].mean()) / 2 - img[c - 1 : c + 2].mean()) / float(img.std()) + # TestAverage: mean projections, montage and files class TestAverage: # test_blob_in_centre: the overall mean is brightest in the middle, and averaging alone writes nothing @@ -77,3 +100,110 @@ def test_montage_labels(self, tmp_path: Path) -> None: r = average_kind('yellow', Kind(marker_a=60, box_a=100), items, tomos, config) assert r.labels == ['1 (T)', '2 (T)', '1 (U)'] and r.grid == 2 and r.pad == 2 assert r.montage.shape == (r.grid * (r.box_px + r.pad) + r.pad,) * 2 + + # test_rods_line_up: rods at four different angles average to one bar along x, sharper than the same rods averaged without turning them + def test_rods_line_up(self, tmp_path: Path) -> None: + angles = {'A': 0.0, 'B': 45.0, 'C': 90.0, 'D': 135.0} + tomos = {name: _rod_tomogram(tmp_path, name, angle) for name, angle in angles.items()} + config = Config(raw_dir=tmp_path, tomograms_star=tmp_path / 't.star', out_dir=tmp_path / 'out') + kind = Kind(marker_a=100, box_a=250) + aligned = average_kind('rod', kind, _rod_items(angles), tomos, config).overall + plain = average_kind('rod', kind, _rod_items(angles, psi=False), tomos, config).overall + assert aligned.shape == plain.shape == (50, 50) + assert _bar_depth(aligned) > 2.0 * _bar_depth(plain) + assert average_kind('rod', kind, _rod_items(angles), tomos, config).aligned and not average_kind('rod', kind, _rod_items(angles, psi=False), tomos, config).aligned + # a bar along x is dark across the middle rows end to end, and darker in the middle than at the top of the image + c = aligned.shape[0] // 2 + assert aligned[c - 1 : c + 2, 10:40].mean() < aligned[3:6, 10:40].mean() - 0.3 + + # test_turned_by_its_own_angle: one rod at 30 degrees turned by 30 lies along x, and turned by the wrong angle does not + def test_turned_by_its_own_angle(self, tmp_path: Path) -> None: + tomos = {'A': _rod_tomogram(tmp_path, 'A', 30.0)} + config = Config(raw_dir=tmp_path, tomograms_star=tmp_path / 't.star', out_dir=tmp_path / 'out') + kind = Kind(marker_a=100, box_a=250) + right = average_kind('rod', kind, _rod_items({'A': 30.0}), tomos, config).overall + wrong = average_kind('rod', kind, _rod_items({'A': -30.0}), tomos, config).overall + assert _bar_depth(right) > 2.0 * _bar_depth(wrong) + + # test_slab_follows_fit: a filament takes the planes of its fit, so a fit that misses the rod averages to no bar + def test_slab_follows_fit(self, tmp_path: Path) -> None: + tomos = {'A': _rod_tomogram(tmp_path, 'A', 30.0)} + config = Config(raw_dir=tmp_path, tomograms_star=tmp_path / 't.star', out_dir=tmp_path / 'out') + kind = Kind(marker_a=100, box_a=250) + on = _rod_items({'A': 30.0}) + off = [(p, f.model_copy(update={'z_lo': 10, 'z_hi': 18})) for p, f in on] + assert _bar_depth(average_kind('rod', kind, on, tomos, config).overall) > 3.0 * abs(_bar_depth(average_kind('rod', kind, off, tomos, config).overall)) + + # test_kinds_without_direction_unchanged: a fit with no direction is cut and projected exactly as before + def test_kinds_without_direction_unchanged(self, tmp_path: Path) -> None: + tomos = {'T': _tomogram(tmp_path, 'T', [(12, 20, 20), (28, 20, 20)])} + config = Config(raw_dir=tmp_path, tomograms_star=tmp_path / 't.star', out_dir=tmp_path / 'out') + r = average_kind('yellow', Kind(marker_a=60, box_a=100), [_item(1, 'T', 12, 20, 20), _item(2, 'T', 28, 20, 20)], tomos, config) + from pickmix.extract import crop_box + from pickmix.utils.io import load_volume + vol = load_volume(tomos['T'], source=config.source) + expected = [] + for x in (12, 28): + img = crop_box(vol, (20, 20, x), 20)[10 - 6 : 10 + 6 + 1].mean(axis=0) + expected.append((img - img.mean()) / img.std()) + assert np.allclose(r.overall, np.mean(expected, axis=0)) + + +# _sphere_tomogram: a 60-voxel cube at 5 A with one bright sphere of the given radius in voxels at its middle, in noise +def _sphere_tomogram(path: Path, name: str, radius: float) -> Tomogram: + rng = np.random.default_rng(11) + vol = rng.normal(0.0, 0.1, (60, 60, 60)).astype(np.float32) + zz, yy, xx = np.mgrid[:60, :60, :60] + vol[np.hypot(np.hypot(xx - 30, yy - 30), zz - 30) <= radius] += 1.0 + with mrcfile.new(path / f'{name}.mrc') as mrc: + mrc.set_data(vol) + mrc.voxel_size = 5.0 + return Tomogram(name, name, path / f'{name}.mrc', None, 5.0, (60, 60, 60), 5.0 / 4, (240, 240, 240)) + +# TestAverageLowest: the montage can show the lowest scoring picks first +class TestAverageLowest: + # test_lowest_first: with scores the montage lists the lowest first with their scores in the labels, and the mean is unchanged + def test_lowest_first(self, tmp_path: Path) -> None: + tomos = {'T': _tomogram(tmp_path, 'T', [(12, 20, 20), (28, 20, 20), (20, 12, 20), (20, 28, 20)])} + config = Config(raw_dir=tmp_path, tomograms_star=tmp_path / 't.star', out_dir=tmp_path / 'out') + items = [_item(i, 'T', x, y, 20) for i, (x, y) in enumerate([(12, 20), (28, 20), (20, 12), (20, 28)], start=1)] + kind = Kind(marker_a=60, box_a=100) + plain = average_kind('yellow', kind, items, tomos, config) + ranked = average_kind('yellow', kind, items, tomos, config, scores={1: 0.9, 2: 0.2, 3: 0.5}) + assert [label.split()[0] for label in ranked.labels] == ['2', '3', '1', '4'] + assert ranked.labels[0].endswith('0.20') and ranked.labels[1].endswith('0.50') + # a pick without a score keeps its plain label, and the scores change nothing else + assert ranked.labels[3] == plain.labels[3] and np.array_equal(plain.overall, ranked.overall) + +# TestBoxImages: the normalised box images behind the average +class TestBoxImages: + # test_images_match_average: the images come in the order the average takes them, normalised, and their mean is the average + def test_images_match_average(self, tmp_path: Path) -> None: + tomos = {'T': _tomogram(tmp_path, 'T', [(12, 20, 20), (28, 20, 20)]), 'U': _tomogram(tmp_path, 'U', [(20, 28, 20)])} + config = Config(raw_dir=tmp_path, tomograms_star=tmp_path / 't.star', out_dir=tmp_path / 'out') + items = [_item(1, 'T', 12, 20, 20), _item(3, 'U', 20, 28, 20), _item(2, 'T', 28, 20, 20)] + pairs, box = box_images('yellow', Kind(marker_a=60, box_a=100), items, tomos, config) + assert [p.id for p, _ in pairs] == [1, 2, 3] and box == 20 + assert all(abs(img.mean()) < 1e-5 and abs(img.std() - 1.0) < 1e-4 for _, img in pairs) + assert np.allclose(np.mean([img for _, img in pairs], axis=0), average_kind('yellow', Kind(marker_a=60, box_a=100), items, tomos, config).overall) + + # test_own_box_resampled: a pick with a box of its own is cut at that size and resampled, so a big and a small particle look alike + def test_own_box_resampled(self, tmp_path: Path) -> None: + tomos = {'S': _sphere_tomogram(tmp_path, 'S', 4.0), 'B': _sphere_tomogram(tmp_path, 'B', 8.0)} + config = Config(raw_dir=tmp_path, tomograms_star=tmp_path / 't.star', out_dir=tmp_path / 'out') + kind = Kind(marker_a=100, pick_mode='bounds') + + def items(own: bool) -> list[tuple[Pick, Fit]]: + small = Pick(1, 'S', 'yellow', 30, 30, 30, box_a=100.0 if own else None) + big = Pick(2, 'B', 'yellow', 30, 30, 30, box_a=200.0 if own else None) + return [ + (small, Fit(x=30, y=30, z=30, radius_a=20.0, box_a=100.0, snr=0, z_lo=30, z_hi=30)), + (big, Fit(x=30, y=30, z=30, radius_a=40.0, box_a=200.0, snr=0, z_lo=30, z_hi=30)), + ] + + def agreement(own: bool) -> float: + (_, a), (_, b) = box_images('yellow', kind, items(own), tomos, config)[0] + return float((a * b).mean()) + + assert box_images('yellow', kind, items(True), tomos, config)[1] == 40 + assert agreement(True) > 0.9 and agreement(True) > agreement(False) + 0.2 diff --git a/tests/test_config.py b/tests/test_config.py index 00f104f..42d1e97 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -8,7 +8,7 @@ from pydantic import ValidationError # Import internal pickmix objects -from pickmix.config import Config, Kind, MatchParams, RingParams, load_config, save_config +from pickmix.config import Config, FilamentParams, Kind, MatchParams, RingParams, ValidationParams, load_config, save_config # _config: a config with absolute paths, so it survives a save and load unchanged, and the given kinds def _config(**kinds: Kind) -> Config: @@ -72,6 +72,43 @@ def test_ring_params_documented(self) -> None: for name, field in RingParams.model_fields.items(): assert field.title and field.description, name + # test_filament_params_documented: every filament setting has a title and a description for the settings form + def test_filament_params_documented(self) -> None: + assert all(f.title and f.description for f in FilamentParams.model_fields.values()) + + # test_box_from_tooltip_gives_trade_off: the description of box_from says what each choice costs + def test_box_from_tooltip_gives_trade_off(self) -> None: + text = FilamentParams.model_fields['box_from'].description + assert 'segment' in text and 'width' in text and 'mostly empty' in text and 'runs out of the box' in text + assert FilamentParams().box_from == 'segment' + + # test_filament_round_trip: filament settings survive a save and load + def test_filament_round_trip(self, tmp_path: Path) -> None: + config = _config().replace(filament=FilamentParams(width_range_a=(80.0, 200.0), box_from='width')) + save_config(config, tmp_path / 'config.toml') + assert load_config(tmp_path / 'config.toml').filament == FilamentParams(width_range_a=(80.0, 200.0), box_from='width') + + # test_filament_params_rejected: out of range settings are refused + def test_filament_params_rejected(self) -> None: + with pytest.raises(ValidationError): + FilamentParams(z_fraction=1.5) + with pytest.raises(ValidationError): + FilamentParams(box_from='both') + + # test_validation_params_documented: every validation setting has a title and a description for the settings form + def test_validation_params_documented(self) -> None: + assert all(f.title and f.description for f in ValidationParams.model_fields.values()) + + # test_validation_round_trip: validation settings survive a save and load, and out of range ones are refused + def test_validation_round_trip(self, tmp_path: Path) -> None: + config = _config().replace(validation=ValidationParams(min_picks=20, flag_deviations=4.0)) + save_config(config, tmp_path / 'config.toml') + assert load_config(tmp_path / 'config.toml').validation == ValidationParams(min_picks=20, flag_deviations=4.0) + with pytest.raises(ValidationError): + ValidationParams(trim_fraction=0.6) + with pytest.raises(ValidationError): + ValidationParams(min_picks=1) + # test_match_params_documented: every match setting has a title and a description for the settings form def test_match_params_documented(self) -> None: assert all(f.title and f.description for f in MatchParams.model_fields.values()) @@ -82,6 +119,27 @@ def test_match_round_trip(self, tmp_path: Path) -> None: save_config(config, tmp_path / 'config.toml') assert load_config(tmp_path / 'config.toml').match == MatchParams(template_px=24, min_score=0.3) + # test_pick_mode_defaults_and_round_trip: kinds pick with one click unless set, and mode/padding survive save & load + def test_pick_mode_defaults_and_round_trip(self, tmp_path: Path) -> None: + assert Kind(marker_a=10).pick_mode == 'point' and Kind(marker_a=10).bounds_padding == 0.2 + config = _config(tube=Kind(marker_a=10, pick_mode='bounds', bounds_padding=0.5)) + save_config(config, tmp_path / 'config.toml') + loaded = load_config(tmp_path / 'config.toml').kinds['tube'] + assert (loaded.pick_mode, loaded.bounds_padding) == ('bounds', 0.5) + + # test_bounds_kind_needs_no_box: a passthrough kind with no box is allowed when its picks bring their own + def test_bounds_kind_needs_no_box(self) -> None: + _config(tube=Kind(marker_a=10, pick_mode='bounds')) + with pytest.raises(ValidationError): + _config(tube=Kind(marker_a=10)) + + # test_pick_mode_rejected: unknown mode or negative padding is refused + def test_pick_mode_rejected(self) -> None: + with pytest.raises(ValueError): + Kind(marker_a=10, pick_mode='triple') + with pytest.raises(ValueError): + Kind(marker_a=10, bounds_padding=-0.1) + # test_default_hotkeys: no hotkeys means the first nine kinds in table order, padded with unused keys def test_default_hotkeys(self) -> None: assert _config().hotkeys == ['cage', *[''] * 8] diff --git a/tests/test_estimate.py b/tests/test_estimate.py index 63725bf..a0e2d69 100644 --- a/tests/test_estimate.py +++ b/tests/test_estimate.py @@ -8,6 +8,7 @@ # Import internal pickmix objects from pickmix.config import Config, Kind, RingParams +from pickmix.estimate.common import crop, prepare from pickmix.estimate.registry import ESTIMATORS from pickmix.estimate.ring import ring_snr @@ -75,3 +76,22 @@ def test_ring_fixed_box(self) -> None: kind = Kind(marker_a=600, box_a=900, estimator='ring') fit = ESTIMATORS['ring'](_volume(), (165, 174, 36), kind, PX, _config(cage=kind)) assert fit.box_a == 900 + +# TestEstimateCommon: helpers shared by the slab estimators +class TestEstimateCommon: + # test_crop_pads_and_masks: a crop that leaves the volume is edge padded, the mask marks real voxels, and z is clipped + def test_crop_pads_and_masks(self) -> None: + vol = np.arange(5 * 6 * 7, dtype=np.float32).reshape(5, 6, 7) + sub, valid, zlo = crop(vol, -3, 2, 1, 1, 3) + assert sub.shape == (3, 7, 7) and zlo == 0 + assert valid.shape == (7, 7) and valid.sum() == 5 * 5 and not valid[0].any() + assert np.array_equal(sub[:, 2:, 2:], vol[0:3, 0:5, 0:5]) + assert np.array_equal(sub[:, 0, 3], sub[:, 2, 3]) + + # test_prepare_flattens: a slow ramp is removed away from the edges and a narrow feature stays + def test_prepare_flattens(self) -> None: + yy, xx = np.mgrid[:600, :600] + img = (0.05 * xx).astype(np.float32) + img[295:306, 195:206] += 5.0 + out = prepare(img, 8.0, 500.0, PX) + assert abs(out[300, 400]) < 0.5 and out[300, 200] > out[300, 400] + 1.0 diff --git a/tests/test_estimates.py b/tests/test_estimates.py index 83faeb6..20bc24c 100644 --- a/tests/test_estimates.py +++ b/tests/test_estimates.py @@ -8,10 +8,11 @@ from pathlib import Path # Import internal pickmix objects -from pickmix.config import Kind -from pickmix.estimates import EstimateService, EstimateStore +from pickmix.config import FilamentParams, Kind +from pickmix.estimate.registry import Fit +from pickmix.estimates import EstimateService, EstimateStore, effective_box_a from pickmix.loader import Loader -from pickmix.model import Session +from pickmix.model import Pick, Session from pickmix.project import open_project # NAME: the single tomogram of the fixture project @@ -54,6 +55,24 @@ def test_moved_pick_is_missing_then_refit(self, service: EstimateService) -> Non assert service.store.get(pick).x == 4.0 assert len(service.store.path.read_text().splitlines()) == 2 + # test_pick_mode_keeps_fits: changing how a kind is picked does not make its fits stale + def test_pick_mode_keeps_fits(self, service: EstimateService) -> None: + pick = service.session.store.add(NAME, 'yellow', 3.0, 2.0, 1.0) + _wait(lambda: service.store.state(pick) == 'ok') + service.session.project.update(kinds={**service.session.project.config.kinds, 'yellow': Kind(marker_a=100, box_a=100, pick_mode='bounds', bounds_padding=0.5)}) + assert service.store.state(pick) == 'ok' + + # test_filament_settings_leave_other_kinds_current: editing filament settings makes only filament kinds stale + def test_filament_settings_leave_other_kinds_current(self, service: EstimateService) -> None: + pick = service.session.store.add(NAME, 'yellow', 3.0, 2.0, 1.0) + _wait(lambda: service.store.state(pick) == 'ok') + service.session.project.update(filament=FilamentParams(width_range_a=(80.0, 200.0))) + assert service.store.state(pick) == 'ok' + service.session.project.update(kinds={**service.session.project.config.kinds, 'rod': Kind(marker_a=100, box_a=100, estimator='filament')}) + first = service.store.digest('rod') + service.session.project.update(filament=FilamentParams(width_range_a=(90.0, 200.0))) + assert service.store.digest('rod') != first + # test_settings_change_makes_stale: changing the kind invalidates its fits until they are recomputed def test_settings_change_makes_stale(self, service: EstimateService) -> None: pick = service.session.store.add(NAME, 'yellow', 3.0, 2.0, 1.0) @@ -70,6 +89,28 @@ def test_persists(self, service: EstimateService) -> None: _wait(lambda: service.store.state(pick) == 'ok') assert EstimateStore(service.session.project, service.session.store).state(pick) == 'ok' + # test_direction_round_trip: a fit's direction survives the csv, and fits without one stay without + def test_direction_round_trip(self, service: EstimateService) -> None: + a = service.session.store.add(NAME, 'yellow', 3.0, 2.0, 1.0) + b = service.session.store.add(NAME, 'yellow', 5.0, 2.0, 1.0) + _wait(lambda: service.store.state(a) == 'ok' and service.store.state(b) == 'ok') + digest = service.store.digest('yellow') + fit = Fit.model_validate(service.store.get(a).model_dump(include=set(Fit.model_fields))) + service.store.put(a, fit.model_copy(update={'psi_deg': 37.5}), digest) + again = EstimateStore(service.session.project, service.session.store) + assert again.get(a).psi_deg == 37.5 and again.get(b).psi_deg is None + + # test_old_csv_has_no_direction: an estimates.csv written before fits had a direction still loads + def test_old_csv_has_no_direction(self, service: EstimateService) -> None: + pick = service.session.store.add(NAME, 'yellow', 3.0, 2.0, 1.0) + _wait(lambda: service.store.state(pick) == 'ok') + lines = service.store.path.read_text().splitlines() + col = lines[0].split(',').index('psi_deg') + old = [','.join(v for i, v in enumerate(line.split(',')) if i != col) for line in lines] + service.store.path.write_text(chr(10).join(old) + chr(10)) + again = EstimateStore(service.session.project, service.session.store) + assert again.get(pick).psi_deg is None + # test_failure_is_flagged: an estimator that fails gives a flagged fit and a message, not a retry loop def test_failure_is_flagged(self, service: EstimateService) -> None: pick = service.session.store.add(NAME, 'bad', 3.0, 2.0, 1.0) @@ -101,3 +142,41 @@ def test_rename_kind_keeps_fits(self, service: EstimateService) -> None: service.store.rename_kind('yellow', 'gold') service.session.store.rename_kind('yellow', 'gold') assert pick.kind == 'gold' and service.store.get(pick) is not None and service.pending == 0 + + # test_order: pick's own box, then fit's, then kind's, then marker's + def test_order(self) -> None: + fit = Fit(x=0, y=0, z=0, radius_a=10, box_a=30.0, snr=1, z_lo=0, z_hi=0) + own, plain = Pick(1, NAME, 'k', 0, 0, 0, box_a=45.0), Pick(2, NAME, 'k', 0, 0, 0) + kind = Kind(marker_a=20, box_a=50.0) + assert effective_box_a(own, kind, fit) == 45.0 + assert effective_box_a(plain, kind, fit) == 30.0 + assert effective_box_a(plain, kind, None) == 50.0 + assert effective_box_a(plain, Kind(marker_a=20), None) == 20.0 + assert effective_box_a(plain, Kind(marker_a=20), fit.model_copy(update={'box_a': 0.0})) == 20.0 + + # test_store_get_applies_pick_box: stored fit comes back with pick's box edge, and stored row is unchanged + def test_store_get_applies_pick_box(self, service: EstimateService) -> None: + pick = service.session.store.add(NAME, 'yellow', 3.0, 2.0, 1.0, box_a=250.0) + _wait(lambda: service.store.state(pick) == 'ok') + assert service.store.get(pick).box_a == 250.0 + service.session.store.set_box(pick.id, None) + assert service.store.get(pick).box_a == 100 + + # test_order: pick's own box, then fit's, then kind's, then marker's + def test_order(self) -> None: + fit = Fit(x=0, y=0, z=0, radius_a=10, box_a=30.0, snr=1, z_lo=0, z_hi=0) + own, plain = Pick(1, NAME, 'k', 0, 0, 0, box_a=45.0), Pick(2, NAME, 'k', 0, 0, 0) + kind = Kind(marker_a=20, box_a=50.0) + assert effective_box_a(own, kind, fit) == 45.0 + assert effective_box_a(plain, kind, fit) == 30.0 + assert effective_box_a(plain, kind, None) == 50.0 + assert effective_box_a(plain, Kind(marker_a=20), None) == 20.0 + assert effective_box_a(plain, Kind(marker_a=20), fit.model_copy(update={'box_a': 0.0})) == 20.0 + + # test_store_get_applies_pick_box: stored fit gives pick's own box edge, and stored row is unchanged + def test_store_get_applies_pick_box(self, service: EstimateService) -> None: + pick = service.session.store.add(NAME, 'yellow', 3.0, 2.0, 1.0, box_a=250.0) + _wait(lambda: service.store.state(pick) == 'ok') + assert service.store.get(pick).box_a == 250.0 + service.session.store.set_box(pick.id, None) + assert service.store.get(pick).box_a == 100 diff --git a/tests/test_export.py b/tests/test_export.py index f026d2c..7021cb8 100644 --- a/tests/test_export.py +++ b/tests/test_export.py @@ -89,6 +89,22 @@ def test_no_geometry_columns_without_parent(self, tmp_path: Path) -> None: [row] = read_star_loop(tmp_path / 'relion' / 'yellow' / 'particles.star') assert not any(c.startswith(('rlnTomoSubtomogram', 'rlnAngle')) for c in row) + # test_filament_psi_prior: a filament kind writes each fit's direction as rlnAnglePsiPrior, and a fit with none as zero + def test_filament_psi_prior(self, tmp_path: Path) -> None: + kind = Kind(marker_a=100, estimator='filament') + items = [ + (Pick(1, 'T', 'rod', 4, 3, 2), Fit(x=4, y=3, z=2, radius_a=50.0, box_a=200.0, snr=5.0, z_lo=1, z_hi=3, psi_deg=37.25)), + (Pick(2, 'T', 'rod', 1, 1, 1), Fit(x=1, y=1, z=1, radius_a=50.0, box_a=200.0, snr=0.0, z_lo=1, z_hi=1, flag='error')), + ] + export_kind('rod', kind, items, {'T': TOMO}, tmp_path) + rows = read_star_loop(tmp_path / 'relion' / 'rod' / 'particles.star') + assert [r['rlnAnglePsiPrior'] for r in rows] == ['37.2500', '0.0000'] + + # test_no_psi_prior_for_other_kinds: kinds that are not filaments get no psi prior column + def test_no_psi_prior_for_other_kinds(self, tmp_path: Path) -> None: + export_kind('yellow', KIND, [_item(1, 4, 3, 2, 1.5)], {'T': TOMO}, tmp_path) + assert 'rlnAnglePsiPrior' not in read_star_loop(tmp_path / 'relion' / 'yellow' / 'particles.star')[0] + # test_all_unmatched: a kind whose picks all lack a parent is an error def test_all_unmatched(self, tmp_path: Path) -> None: kind = Kind(marker_a=40, box_a=200, parent='cage') diff --git a/tests/test_filament.py b/tests/test_filament.py new file mode 100644 index 0000000..2404162 --- /dev/null +++ b/tests/test_filament.py @@ -0,0 +1,154 @@ +''' +pickmix: tests for the filament estimator +''' + +# Import external dependencies +import math, numpy as np, pytest +from pathlib import Path + +# Import internal pickmix objects +from pickmix.config import Config, FilamentParams, Kind +from pickmix.estimate.registry import ESTIMATORS, Fit + +# PX: voxel size of the synthetic volumes, so 100 A is 18.7 voxels +PX = 5.36 + +# SHAPE: planes, rows and columns of the synthetic volumes +SHAPE: tuple[int, int, int] = (60, 260, 260) + +# _config: a narrow width ladder, short reach and a modest high-pass to keep the fits fast +def _config(kind: Kind, **settings: object) -> Config: + params = FilamentParams(**{ + 'width_range_a': (80.0, 200.0), 'width_steps': 3, 'max_length_a': 1500.0, 'highpass_sigma_a': 400.0, 'z_max_half_a': 400.0, **settings, + }) + return Config(raw_dir=Path('/r'), tomograms_star=Path('/t.star'), filament=params, kinds={'rod': kind}) + +# _fit: run the estimator on a volume from a pick (x, y, z) with a filament kind +def _fit(vol: np.ndarray, pick: tuple[float, float, float], *, kind: Kind | None = None, **settings: object) -> Fit: + kind = kind or Kind(marker_a=100, estimator='filament') + return ESTIMATORS['filament'](vol, pick, kind, PX, _config(kind, **settings)) + +# _rod: noise with a dark rod through (x, y) = centre at angle_deg from the x axis towards y, present only in planes z_range[0] to z_range[1] - 1; the rod is a gaussian in width_a (full width at half maximum) and a hard length_a long +def _rod( + angle_deg: float, *, width_a: float = 100.0, length_a: float = 1200.0, z_range: tuple[int, int] = (20, 45), + centre: tuple[float, float] = (130.0, 130.0), amp: float = 1.5, seed: int = 1, noise: bool = True, +) -> np.ndarray: + vol = np.random.default_rng(seed).normal(0.0, 1.0, SHAPE).astype(np.float32) if noise else np.zeros(SHAPE, dtype=np.float32) + yy, xx = np.mgrid[: SHAPE[1], : SHAPE[2]] + ux, uy = math.cos(math.radians(angle_deg)), math.sin(math.radians(angle_deg)) + along = (xx - centre[0]) * ux + (yy - centre[1]) * uy + across = -(xx - centre[0]) * uy + (yy - centre[1]) * ux + profile = np.exp(-0.5 * (across / (width_a / 2.355 / PX)) ** 2) * (np.abs(along) <= length_a / 2 / PX) + vol[z_range[0] : z_range[1]] -= amp * profile + return vol + +# _across: distance in voxels of a point from the line through (130, 130) at angle_deg +def _across(x: float, y: float, angle_deg: float) -> float: + return abs(-(x - 130.0) * math.sin(math.radians(angle_deg)) + (y - 130.0) * math.cos(math.radians(angle_deg))) + +# _turn: smallest difference in degrees between two directions that are only defined up to a half turn +def _turn(a: float, b: float) -> float: + d = (a - b) % 180.0 + return min(d, 180.0 - d) + +# _offset_pick: a pick shifted from the rod centre by along and across, in Angstrom, at plane z +def _offset_pick(angle_deg: float, along_a: float, across_a: float, z: float) -> tuple[float, float, float]: + ux, uy = math.cos(math.radians(angle_deg)), math.sin(math.radians(angle_deg)) + a, c = along_a / PX, across_a / PX + return 130.0 + a * ux - c * uy, 130.0 + a * uy + c * ux, z + +# TestFilament: filament estimator tests +class TestFilament: + # test_registered: the estimator is available by name + def test_registered(self) -> None: + assert 'filament' in ESTIMATORS + + # test_rods_at_angles: an off-axis pick is snapped onto the axis, with its direction, width and z extent found + @pytest.mark.parametrize('angle', [0.0, 35.0, 90.0, 150.0]) + def test_rods_at_angles(self, angle: float) -> None: + fit = _fit(_rod(angle), _offset_pick(angle, 150.0, 60.0, 30.0)) + assert _across(fit.x, fit.y, angle) < 1.0 + assert _turn(fit.psi_deg, angle) < 3.0 and 0.0 <= fit.psi_deg < 180.0 + assert 2 * fit.radius_a == pytest.approx(100.0, rel=0.15) + assert fit.z == pytest.approx(32.0, abs=2.0) and abs(fit.z_lo - 20) <= 3 and abs(fit.z_hi - 44) <= 3 + assert fit.snr > 10.0 and fit.flag == '' + + # test_widths: widths across the range are measured + @pytest.mark.parametrize('width', [70.0, 150.0, 260.0]) + def test_widths(self, width: float) -> None: + fit = _fit(_rod(60.0, width_a=width), _offset_pick(60.0, 0.0, 30.0, 30.0), width_range_a=(60.0, 320.0), width_steps=4) + assert 2 * fit.radius_a == pytest.approx(width, rel=0.15) + + # test_z_extent_follows_filament: the z extent and its middle come from the filament and not from where the pick was made + @pytest.mark.parametrize('pick_z', [22.0, 32.0, 42.0]) + def test_z_extent_follows_filament(self, pick_z: float) -> None: + fit = _fit(_rod(20.0, z_range=(20, 45)), _offset_pick(20.0, 0.0, 0.0, pick_z)) + assert fit.z == pytest.approx(32.0, abs=2.0) and abs(fit.z_lo - 20) <= 3 and abs(fit.z_hi - 44) <= 3 + + # test_pick_snaps_back: a pick as far from the axis as the search allows still finds it, flagged moved + def test_pick_snaps_back(self) -> None: + fit = _fit(_rod(70.0), _offset_pick(70.0, 0.0, 250.0, 30.0)) + assert _across(fit.x, fit.y, 70.0) < 1.5 and 'moved' in fit.flag.split(',') + + # test_pick_in_noise_is_weak: a pick where there is no filament gets a low SNR and the weak flag, and nothing raises + def test_pick_in_noise_is_weak(self) -> None: + fit = _fit(np.random.default_rng(5).normal(0.0, 1.0, SHAPE).astype(np.float32), (130.0, 130.0, 30.0)) + assert 'weak' in fit.flag.split(',') and fit.snr < 3.0 + + # test_faint_filament_is_found: a filament well under the noise in a single voxel is still found by the slab + def test_faint_filament_is_found(self) -> None: + fit = _fit(_rod(40.0, amp=0.4), _offset_pick(40.0, 0.0, 30.0, 30.0)) + assert _across(fit.x, fit.y, 40.0) < 1.5 and _turn(fit.psi_deg, 40.0) < 5.0 and 'weak' not in fit.flag.split(',') + + # test_nearer_filament_wins: of two parallel filaments the one nearer the pick is fitted + def test_nearer_filament_wins(self) -> None: + a, b = _rod(90.0, centre=(70.0, 130.0), seed=1), _rod(90.0, centre=(190.0, 130.0), seed=2, noise=False) + vol = a + b + near_a, near_b = _fit(vol, (85.0, 130.0, 30.0)), _fit(vol, (175.0, 130.0, 30.0)) + assert near_a.x == pytest.approx(70.0, abs=1.5) and near_b.x == pytest.approx(190.0, abs=1.5) + + # test_edge_flagged: a filament running off the volume is flagged and its fit stays inside + def test_edge_flagged(self) -> None: + fit = _fit(_rod(0.0, centre=(25.0, 130.0), length_a=800.0), (25.0, 130.0, 30.0)) + assert 'edge' in fit.flag.split(',') and 0 <= fit.x < SHAPE[2] + + # test_z_edge_flagged: a filament reaching the first plane is flagged zedge + def test_z_edge_flagged(self) -> None: + fit = _fit(_rod(70.0, z_range=(0, 18)), (130.0, 130.0, 8.0)) + assert 'zedge' in fit.flag.split(',') and fit.z_lo == 0 + + # test_spot_is_short: a round spot is traced as a stretch no longer than it is wide and flagged short + def test_spot_is_short(self) -> None: + fit = _fit(_rod(0.0, length_a=110.0, width_a=110.0, amp=2.0), (130.0, 130.0, 30.0)) + assert 'short' in fit.flag.split(',') + + # test_box_from_segment: the default box holds the measured length of filament, and the width box is smaller + def test_box_from_segment(self) -> None: + vol, pick = _rod(35.0), _offset_pick(35.0, 100.0, 20.0, 30.0) + assert _fit(vol, pick).box_a == pytest.approx(1200.0, rel=0.15) + assert _fit(vol, pick, box_from='width').box_a == pytest.approx(1.25 * 100.0, rel=0.2) + + # test_segment_is_capped: a filament longer than the longest stretch gets a box of that length + def test_segment_is_capped(self) -> None: + fit = _fit(_rod(0.0, length_a=3000.0), (130.0, 130.0, 30.0), max_length_a=1000.0) + assert fit.box_a == pytest.approx(1000.0, rel=0.1) + + # test_segment_centres_on_stretch: with the segment box the fit sits at the middle of the stretch, however far along it the pick was + def test_segment_centres_on_stretch(self) -> None: + fit = _fit(_rod(0.0, length_a=800.0), _offset_pick(0.0, 250.0, 0.0, 30.0)) + assert fit.x == pytest.approx(130.0, abs=6.0) + + # test_width_box_keeps_position_along_axis: with the width box the fit stays level with the pick along the filament + def test_width_box_keeps_position_along_axis(self) -> None: + fit = _fit(_rod(0.0), _offset_pick(0.0, 250.0, 40.0, 30.0), box_from='width') + assert fit.x == pytest.approx(130.0 + 250.0 / PX, abs=1.5) and _across(fit.x, fit.y, 0.0) < 1.0 + + # test_kind_box_wins: a kind with its own box keeps it + def test_kind_box_wins(self) -> None: + fit = _fit(_rod(35.0), _offset_pick(35.0, 0.0, 20.0, 30.0), kind=Kind(marker_a=100, box_a=333.0, estimator='filament')) + assert fit.box_a == 333.0 + + # test_minimum_box: a thin short filament still gets the smallest box + def test_minimum_box(self) -> None: + fit = _fit(_rod(35.0, width_a=60.0, length_a=200.0), (130.0, 130.0, 30.0), box_from='width', min_box_a=250.0, width_range_a=(50.0, 200.0)) + assert fit.box_a == 250.0 diff --git a/tests/test_items.py b/tests/test_items.py index 9eb4346..fa151f3 100644 --- a/tests/test_items.py +++ b/tests/test_items.py @@ -11,6 +11,8 @@ # Import internal pickmix objects from pickmix.config import Kind from pickmix.estimates import EstimateService +from pickmix.export import recommend_box +from pickmix.extract import box_pixels from pickmix.items import flagged, items, matched from pickmix.loader import Loader from pickmix.model import Session @@ -37,6 +39,19 @@ def test_no_parent_kind(self, parts: tuple[Session, EstimateService]) -> None: session, service = parts assert matched(session, service, 'cage') == {} + # test_flagged_adds_lowcc: a pick validation scored low gets lowcc beside its other flags, and one it scored well does not + def test_flagged_adds_lowcc(self, qtbot: QtBot, parts: tuple[Session, EstimateService]) -> None: + session, service = parts + a = session.store.add(NAME, 'cage', 10.0, 10.0, 10.0) + b = session.store.add(NAME, 'cage', 20.0, 10.0, 10.0) + qtbot.waitUntil(lambda: all(service.store.state(p) == 'ok' for p in session.store.all()), timeout=5000) + assert all('lowcc' not in f.flag for _, f in items(session, service, 'cage')) + service.validation.put_kind('cage', [(a, 0.1, True), (b, 0.6, False)]) + got = {p.id: f.flag for p, f in items(session, service, 'cage')} + assert got[a.id] == 'lowcc' and got[b.id] == '' + session.store.add(NAME, 'cage', 30.0, 10.0, 10.0) + assert all('lowcc' not in f.flag for _, f in items(session, service, 'cage')) + # test_flagged_adds_noparent: a pick with no parent in reach gets noparent, others do not def test_flagged_adds_noparent(self, qtbot: QtBot, parts: tuple[Session, EstimateService]) -> None: session, service = parts @@ -54,3 +69,17 @@ def test_items_skip_missing_fits(self, parts: tuple[Session, EstimateService]) - service.shutdown() session.store.add(NAME, 'cage', 10.0, 10.0, 10.0) assert items(session, service, 'cage') == [] + + # test_own_boxes_reach_export_and_extraction: a kind with no box of its own takes its box from the picks' boxes, at the 95th percentile + def test_own_boxes_reach_export_and_extraction(self, qtbot: QtBot, parts: tuple[Session, EstimateService]) -> None: + session, service = parts + session.project.update(kinds={'tube': Kind(marker_a=100, pick_mode='bounds', extract_angpix=5.36)}) + for i, box in enumerate((100.0, 200.0, 300.0)): + session.store.add(NAME, 'tube', 1.0 + i, 2.0, 1.0, box_a=box) + qtbot.waitUntil(lambda: all(service.store.state(p) == 'ok' for p in session.store.all()), timeout=5000) + got = items(session, service, 'tube') + assert sorted(f.box_a for _, f in got) == [100.0, 200.0, 300.0] + box_a, box_px = recommend_box(session.project.config.kinds['tube'], got) + assert abs(box_a - 290.0) < 1e-6 and box_px % 2 == 0 + # extraction cuts at the tomogram's own sampling and rounds to the nearest even edge + assert box_pixels(session.project.config.kinds['tube'], got, session.project.tomos[NAME].pixel_size) == 54 diff --git a/tests/test_model.py b/tests/test_model.py index b0d38a1..2efac57 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -61,6 +61,35 @@ def test_unknown_kind_kept(self, make_config: Callable[..., Path]) -> None: store.add('Position_1_2', 'cage', 0.0, 0.0, 0.0) assert sorted(p.kind for p in PickStore(project).all()) == ['cage', 'gone'] + # test_box_round_trip: a pick's own box edge survives a save, and picks without one stay without + def test_box_round_trip(self, make_config: Callable[..., Path]) -> None: + path = make_config() + store = PickStore(open_project(path)) + store.add('Position_1_2', 'cage', 1.0, 2.0, 3.0, box_a=412.5) + store.add('Position_1_2', 'cage', 4.0, 5.0, 6.0) + assert [p.box_a for p in PickStore(open_project(path)).all()] == [412.5, None] + + # test_old_csv_has_no_box: a picks.csv written before boxes existed loads with none + def test_old_csv_has_no_box(self, make_config: Callable[..., Path]) -> None: + project = open_project(make_config()) + out = project.config.out_dir + out.mkdir(parents=True) + (out / 'picks.csv').write_text('tomogram,kind,x,y,z,pixel_size_a\nPosition_1_2,cage,1.0,2.0,3.0,5.36\n') + [pick] = PickStore(project).all() + assert pick.box_a is None + + # test_set_box_and_move: set_box edits the box and notifies; moving a pick keeps its box + def test_set_box_and_move(self, make_config: Callable[..., Path]) -> None: + store = _store(make_config) + heard: list[int] = [] + pick = store.add('Position_1_2', 'cage', 1.0, 2.0, 3.0) + store.listeners.append(lambda: heard.append(1)) + store.set_box(pick.id, 300.0) + store.move(pick.id, 5.0, 6.0) + assert store.get(pick.id).box_a == 300.0 and len(heard) == 2 + store.set_box(pick.id, None) + assert store.get(pick.id).box_a is None + # test_navigation_clamps: stepping stops at both ends def test_navigation_clamps(self, make_config: Callable[..., Path]) -> None: session = Session(open_project(make_config(names=THREE))) diff --git a/tests/test_validate.py b/tests/test_validate.py new file mode 100644 index 0000000..e08426b --- /dev/null +++ b/tests/test_validate.py @@ -0,0 +1,95 @@ +''' +pickmix: tests for running kind validation +''' + +# Import external dependencies +import numpy as np, pytest +from collections.abc import Callable, Iterator +from pathlib import Path +from pytestqt.qtbot import QtBot + +# Import internal pickmix objects +from pickmix.config import Kind +from pickmix.estimates import EstimateService, _key +from pickmix.items import items +from pickmix.loader import Loader +from pickmix.model import Session +from pickmix.project import open_project +from pickmix.validate import validate_kind + +# NAME: the single tomogram of the fixture project +NAME: str = 'Position_1_2' + +# SIZE: edge in pixels of the crafted box images +SIZE: int = 24 + +# parts: a session over a yellow kind, with its service, shut down afterwards +@pytest.fixture +def parts(make_config: Callable[..., Path]) -> Iterator[tuple[Session, EstimateService]]: + project = open_project(make_config()) + project.update(kinds={'yellow': Kind(marker_a=100, box_a=100)}) + session, loader = Session(project), Loader(project) + service = EstimateService(session, loader) + yield session, service + service.shutdown() + loader.shutdown() + +# _picks: n picks of kind yellow in the one tomogram, waited for until every one has a current fit +def _picks(qtbot: QtBot, session: Session, service: EstimateService, n: int) -> None: + for i in range(n): + session.store.add(NAME, 'yellow', float(i % 8), float(i % 6), float(i % 4)) + qtbot.waitUntil(lambda: all(service.store.state(p) == 'ok' for p in session.store.all()), timeout=5000) + +# _crafted: box_images standing in for the real one: n images of a gaussian blob with noise, the last `bad` of them noise only +def _crafted(n: int, bad: int) -> Callable[..., tuple[list, int]]: + def box_images(name: str, kind: Kind, got: list, tomos: dict, config: object, *, log: Callable[[str], None] = lambda _: None) -> tuple[list, int]: + rng = np.random.default_rng(8) + yy, xx = np.mgrid[:SIZE, :SIZE] + blob = np.exp(-0.5 * (np.hypot(yy - SIZE // 2, xx - SIZE // 2) / 3.0) ** 2) + out = [] + for i, (pick, _) in enumerate(got): + img = rng.normal(0.0, 1.0, (SIZE, SIZE)) if i >= n - bad else blob + rng.normal(0.0, 0.3, (SIZE, SIZE)) + out.append((pick, ((img - img.mean()) / img.std()).astype(np.float32))) + return out, SIZE + return box_images + +# TestValidate: validating a kind +class TestValidate: + # test_scores_stored_and_flagged: outliers among the images are flagged lowcc in the items, and every scored pick has a current score + def test_scores_stored_and_flagged(self, qtbot: QtBot, parts: tuple[Session, EstimateService], monkeypatch: pytest.MonkeyPatch) -> None: + session, service = parts + _picks(qtbot, session, service, 20) + monkeypatch.setattr('pickmix.validate.box_images', _crafted(20, 2)) + summary = validate_kind('yellow', session, service) + assert (summary.scored, summary.flagged, summary.skipped) == (20, 2, 0) and 0.0 < summary.median < 1.0 + assert all(service.validation.state(p) == 'ok' for p in session.store.all()) + flagged = [p.id for p, f in items(session, service, 'yellow') if 'lowcc' in f.flag] + assert len(flagged) == 2 and flagged == [p.id for p in session.store.all()][-2:] + + # test_runs_on_real_boxes: with nothing mocked, boxes are cut from the tomogram and every pick gets a score + def test_runs_on_real_boxes(self, qtbot: QtBot, parts: tuple[Session, EstimateService]) -> None: + session, service = parts + _picks(qtbot, session, service, 12) + summary = validate_kind('yellow', session, service) + assert summary.scored == 12 + assert all(np.isfinite(service.validation.score(p)) for p in session.store.all()) + + # test_too_few_picks_says_which_kind: fewer picks than the setting is a ValueError naming the kind + def test_too_few_picks_says_which_kind(self, qtbot: QtBot, parts: tuple[Session, EstimateService]) -> None: + session, service = parts + _picks(qtbot, session, service, 5) + with pytest.raises(ValueError, match="kind 'yellow': needs at least 10 picks to validate, has 5"): + validate_kind('yellow', session, service) + + # test_picks_without_fit_skipped: a pick with no current fit has no box to cut, is counted as skipped and gets no score + def test_picks_without_fit_skipped(self, qtbot: QtBot, parts: tuple[Session, EstimateService], monkeypatch: pytest.MonkeyPatch) -> None: + session, service = parts + _picks(qtbot, session, service, 14) + service.shutdown() + lost = session.store.all()[:2] + for p in lost: + service.store._rows.pop(_key(p.tomogram, p.kind, p.x, p.y, p.z)) + monkeypatch.setattr('pickmix.validate.box_images', _crafted(12, 0)) + summary = validate_kind('yellow', session, service) + assert (summary.scored, summary.skipped) == (12, 2) + assert all(service.validation.score(p) is None for p in lost) diff --git a/tests/test_validation.py b/tests/test_validation.py new file mode 100644 index 0000000..15f9f4c --- /dev/null +++ b/tests/test_validation.py @@ -0,0 +1,224 @@ +''' +pickmix: tests for kind validation +''' + +# Import external dependencies +import numpy as np, pytest +from collections.abc import Callable +from pathlib import Path + +# Import internal pickmix objects +from pickmix.config import Kind, ValidationParams +from pickmix.model import PickStore +from pickmix.project import open_project +from pickmix.validation import ValidationStore, deviations, low_scores, score_images + +# SIZE: edge in pixels of the synthetic box images +SIZE: int = 24 + +# _norm: an image with zero mean and unit spread, as box_images makes them +def _norm(img: np.ndarray) -> np.ndarray: + return (img - img.mean()) / (img.std() or 1.0) + +# _blob: a normalised gaussian blob with noise, optionally shifted by (dy, dx) pixels +def _blob(rng: np.random.Generator, *, dy: int = 0, dx: int = 0, noise: float = 0.3) -> np.ndarray: + yy, xx = np.mgrid[:SIZE, :SIZE] + img = np.exp(-0.5 * (((yy - SIZE // 2 - dy) ** 2 + (xx - SIZE // 2 - dx) ** 2) / 3.0**2)) + rng.normal(0.0, noise, (SIZE, SIZE)) + return _norm(img) + +# _noise: a normalised image of noise only +def _noise(rng: np.random.Generator) -> np.ndarray: + return _norm(rng.normal(0.0, 1.0, (SIZE, SIZE))) + +# _ring: a normalised ring with noise, a different shape from the blob +def _ring(rng: np.random.Generator) -> np.ndarray: + yy, xx = np.mgrid[:SIZE, :SIZE] + return _norm(np.exp(-0.5 * ((np.hypot(yy - SIZE // 2, xx - SIZE // 2) - 8.0) / 1.5) ** 2) + rng.normal(0.0, 0.3, (SIZE, SIZE))) + +# _brute: the same scores worked out one image and one shift at a time +def _brute(images: np.ndarray, shift: int) -> np.ndarray: + out = [] + for i in range(len(images)): + mean = np.delete(images, i, axis=0).mean(axis=0) + best = -1.0 + for dy in range(-shift, shift + 1): + for dx in range(-shift, shift + 1): + moved = np.roll(images[i], (dy, dx), axis=(0, 1)) + best = max(best, float((moved * (mean - mean.mean())).mean() / (moved.std() * mean.std()))) + out.append(best) + return np.array(out) + +# TestValidation: scoring and flagging +class TestValidation: + # test_matches_brute_force: the fast scores are the best correlation with the mean of the others over the shifts, worked out directly + def test_matches_brute_force(self) -> None: + rng = np.random.default_rng(0) + images = np.stack([_blob(rng, dy=int(rng.integers(-1, 2)), dx=int(rng.integers(-1, 2))) for _ in range(10)]) + params = ValidationParams(min_picks=3, trim_fraction=0.0, shift_fraction=2 / SIZE) + assert np.allclose(score_images(images, params), _brute(images, 2), atol=1e-6) + + # test_outliers_score_lowest_and_are_flagged: noise and a different shape among clean blobs score lowest and are the only ones flagged + def test_outliers_score_lowest_and_are_flagged(self) -> None: + rng = np.random.default_rng(1) + images = np.stack([*(_blob(rng) for _ in range(30)), _noise(rng), _noise(rng), _ring(rng)]) + scores = score_images(images, ValidationParams()) + assert set(np.argsort(scores)[:3]) == {30, 31, 32} + assert list(np.nonzero(low_scores(scores, ValidationParams()))[0]) == [30, 31, 32] + + # test_clean_kind_flags_nothing: however many picks there are, a kind of good picks has none flagged + @pytest.mark.parametrize('count', [12, 25, 60]) + def test_clean_kind_flags_nothing(self, count: int) -> None: + rng = np.random.default_rng(count) + scores = score_images(np.stack([_blob(rng) for _ in range(count)]), ValidationParams()) + assert not low_scores(scores, ValidationParams()).any() + + # test_shift_tolerance: a box a couple of pixels off keeps its score, and one far off loses it + def test_shift_tolerance(self) -> None: + rng = np.random.default_rng(2) + images = np.stack([*(_blob(rng) for _ in range(20)), _blob(rng, dy=2, dx=-2), _blob(rng, dy=9, dx=9)]) + scores = score_images(images, ValidationParams()) + assert scores[20] > np.median(scores[:20]) - 0.1 and scores[21] < scores[20] - 0.2 + + # test_trimming_sharpens_the_average: a cluster of picks all off the same way props up its own scores unless the lowest scoring are left out of the average + def test_trimming_sharpens_the_average(self) -> None: + rng = np.random.default_rng(3) + images = np.stack([*(_blob(rng) for _ in range(20)), *(_blob(rng, dy=8, dx=8) for _ in range(8))]) + trimmed = score_images(images, ValidationParams(trim_fraction=0.3)) + plain = score_images(images, ValidationParams(trim_fraction=0.0)) + assert trimmed[20:].mean() < plain[20:].mean() - 0.05 and trimmed[:20].mean() > plain[:20].mean() + 0.03 + + # test_default_cut_off_clears_clean_kinds: across many clean kinds of different sizes the default flags none, and still flags planted outliers + def test_default_cut_off_clears_clean_kinds(self) -> None: + params = ValidationParams() + for seed in range(40): + rng = np.random.default_rng(1000 + seed) + n = int(rng.choice([12, 20, 30, 60, 100])) + assert not low_scores(score_images(np.stack([_blob(rng) for _ in range(n)]), params), params).any() + + # test_too_few_picks: fewer picks than the setting is refused + def test_too_few_picks(self) -> None: + rng = np.random.default_rng(4) + with pytest.raises(ValueError, match='at least 10 picks'): + score_images(np.stack([_blob(rng) for _ in range(9)]), ValidationParams()) + + # test_identical_images_flag_nothing: scores with no spread at all do not divide by zero or flag anything + def test_identical_images_flag_nothing(self) -> None: + rng = np.random.default_rng(5) + scores = score_images(np.stack([_blob(rng, noise=0.0)] * 12), ValidationParams()) + assert np.isfinite(deviations(scores, ValidationParams())).all() and not low_scores(scores, ValidationParams()).any() + + # test_spread_floor: tiny differences in a very uniform kind are not flagged, but a big drop still is + def test_spread_floor(self) -> None: + params = ValidationParams() + scores = np.array([0.90, 0.9001, 0.8999, 0.9002, 0.8998, 0.9, 0.9001, 0.8999, 0.9002, 0.8995, 0.85, 0.3]) + flags = low_scores(scores, params) + assert not flags[:11].any() and flags[11] + + # test_only_low_scores_flag: a score far above the rest is not flagged + def test_only_low_scores_flag(self) -> None: + scores = np.array([0.5] * 11 + [0.99]) + assert not low_scores(scores + np.linspace(-0.01, 0.01, 12) * 0, ValidationParams()).any() + + # test_absolute_floor: a lowest score flags picks under it, whatever the rest do + def test_absolute_floor(self) -> None: + scores = np.array([0.2, 0.22, 0.21, 0.19, 0.2, 0.23, 0.21, 0.2, 0.22, 0.18]) + assert not low_scores(scores, ValidationParams()).any() + assert low_scores(scores, ValidationParams(min_score=0.21)).sum() == 5 + + +# NAME: the single tomogram of the fixture project +NAME: str = 'Position_1_2' + +# _store: a validation store over a project with two kinds, a few yellow picks, and the estimate digests it is told, which a test can change +def _store(make_config: Callable[..., Path], count: int = 4) -> tuple[ValidationStore, PickStore, dict[str, str]]: + project = open_project(make_config()) + project.update(kinds={'yellow': Kind(marker_a=100, box_a=100), 'green': Kind(marker_a=100, box_a=100)}) + picks = PickStore(project) + for i in range(count): + picks.add(NAME, 'yellow', float(i), 1.0, 1.0) + digests = {'yellow': 'd1', 'green': 'g1'} + return ValidationStore(project, picks, digests.get), picks, digests + +# TestValidationStore: saved scores and when they stop applying +class TestValidationStore: + # test_put_and_read: scores and low flags come back for the picks they were stored for + def test_put_and_read(self, make_config: Callable[..., Path]) -> None: + store, picks, _ = _store(make_config) + heard: list[int] = [] + store.listeners.append(lambda: heard.append(1)) + mine = picks.all('yellow') + assert store.state(mine[0]) == 'missing' and store.score(mine[0]) is None and not store.low(mine[0]) + store.put_kind('yellow', [(p, 0.5 + 0.1 * i, i == 3) for i, p in enumerate(mine)]) + assert [store.state(p) for p in mine] == ['ok'] * 4 and heard == [1] + assert store.score(mine[1]) == pytest.approx(0.6) and [store.low(p) for p in mine] == [False, False, False, True] + + # test_reload: a new store reads back what was saved, including the flag + def test_reload(self, make_config: Callable[..., Path]) -> None: + store, picks, digests = _store(make_config) + mine = picks.all('yellow') + store.put_kind('yellow', [(p, 0.5, i == 0) for i, p in enumerate(mine)]) + again = ValidationStore(store.project, picks, digests.get) + assert again.state(mine[0]) == 'ok' and again.low(mine[0]) and not again.low(mine[1]) + + # test_new_pick_makes_stale: adding, moving or removing a pick of the kind makes every score of the kind stale, and no flag shows + def test_new_pick_makes_stale(self, make_config: Callable[..., Path]) -> None: + store, picks, _ = _store(make_config) + mine = picks.all('yellow') + store.put_kind('yellow', [(p, 0.5, True) for p in mine]) + picks.add(NAME, 'yellow', 9.0, 9.0, 1.0) + assert [store.state(p) for p in mine] == ['stale'] * 4 and not store.low(mine[0]) and store.score(mine[0]) is None + store.put_kind('yellow', [(p, 0.5, True) for p in picks.all('yellow')]) + assert store.state(mine[0]) == 'ok' + picks.move(mine[1].id, 5.0, 5.0) + assert store.state(mine[0]) == 'stale' and store.state(mine[1]) == 'missing' + store.put_kind('yellow', [(p, 0.5, False) for p in picks.all('yellow')]) + picks.remove(mine[2].id) + assert store.state(mine[0]) == 'stale' + + # test_other_kinds_unaffected: scores of a kind stay while picks of another kind change + def test_other_kinds_unaffected(self, make_config: Callable[..., Path]) -> None: + store, picks, _ = _store(make_config) + mine = picks.all('yellow') + store.put_kind('yellow', [(p, 0.5, False) for p in mine]) + picks.add(NAME, 'green', 3.0, 3.0, 3.0) + assert store.state(mine[0]) == 'ok' + + # test_settings_make_stale: a change to the kind's fits or to the validation settings makes its scores stale + def test_settings_make_stale(self, make_config: Callable[..., Path]) -> None: + store, picks, digests = _store(make_config) + mine = picks.all('yellow') + store.put_kind('yellow', [(p, 0.5, False) for p in mine]) + digests['yellow'] = 'd2' + assert store.state(mine[0]) == 'stale' + digests['yellow'] = 'd1' + assert store.state(mine[0]) == 'ok' + store.project.update(validation=ValidationParams(flag_deviations=8.0)) + assert store.state(mine[0]) == 'stale' + + # test_unknown_kind: a kind the config does not have cannot be stored, and its picks have no score + def test_unknown_kind(self, make_config: Callable[..., Path]) -> None: + store, picks, digests = _store(make_config) + digests.pop('green') + extra = picks.add(NAME, 'green', 3.0, 3.0, 3.0) + assert store.state(extra) == 'missing' + with pytest.raises(KeyError): + store.put_kind('green', [(extra, 0.5, False)]) + + # test_deleted_picks_dropped_on_save: rows of picks that no longer exist are not kept + def test_deleted_picks_dropped_on_save(self, make_config: Callable[..., Path]) -> None: + store, picks, _ = _store(make_config) + mine = picks.all('yellow') + store.put_kind('yellow', [(p, 0.5, False) for p in mine]) + picks.remove(mine[0].id) + store.put_kind('yellow', [(p, 0.5, False) for p in picks.all('yellow')]) + assert len(store.path.read_text().splitlines()) == 4 + + # test_rename_keeps_scores: a renamed kind keeps its scores + def test_rename_keeps_scores(self, make_config: Callable[..., Path]) -> None: + store, picks, digests = _store(make_config) + mine = picks.all('yellow') + store.put_kind('yellow', [(p, 0.5, True) for p in mine]) + digests['gold'] = digests['yellow'] + store.rename_kind('yellow', 'gold') + picks.rename_kind('yellow', 'gold') + assert store.state(mine[0]) == 'ok' and store.low(mine[0]) diff --git a/uv.lock b/uv.lock index 9050010..d2599ef 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.14" [[package]] @@ -137,7 +137,7 @@ wheels = [ [[package]] name = "pickmix" -version = "0.4.1" +version = "0.5.0" source = { editable = "." } dependencies = [ { name = "imageio" },