maskfits 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- maskfits/__init__.py +15 -0
- maskfits/assets/icon.ico +0 -0
- maskfits/assets/icon.png +0 -0
- maskfits/automask.py +179 -0
- maskfits/automask_window.py +498 -0
- maskfits/binning.py +57 -0
- maskfits/cli.py +95 -0
- maskfits/colormaps.py +204 -0
- maskfits/custom_themes.py +106 -0
- maskfits/cuts_histogram.py +375 -0
- maskfits/gui.py +2099 -0
- maskfits/imagedata.py +229 -0
- maskfits/layouts.py +126 -0
- maskfits/masking.py +177 -0
- maskfits/settings.py +103 -0
- maskfits/settings_window.py +445 -0
- maskfits/theme.py +540 -0
- maskfits/theme_editor_window.py +221 -0
- maskfits/update_check.py +202 -0
- maskfits/update_dialog.py +85 -0
- maskfits/widgets.py +426 -0
- maskfits-1.0.0.dist-info/METADATA +59 -0
- maskfits-1.0.0.dist-info/RECORD +26 -0
- maskfits-1.0.0.dist-info/WHEEL +4 -0
- maskfits-1.0.0.dist-info/entry_points.txt +2 -0
- maskfits-1.0.0.dist-info/licenses/LICENSE +21 -0
maskfits/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""maskfits package version - resolved from installed package metadata
|
|
2
|
+
(itself generated from pyproject.toml's `version` at install time), so this
|
|
3
|
+
never has to be hand-kept in sync with pyproject.toml. After bumping the
|
|
4
|
+
version there, re-run `pip install -e .` for this to pick it up - normal for
|
|
5
|
+
any Python package, not something maskfits-specific.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
__version__ = version("maskfits")
|
|
12
|
+
except PackageNotFoundError:
|
|
13
|
+
# Running from source without an install (e.g. a plain git clone that
|
|
14
|
+
# was never `pip install -e .`'d) - fall back rather than crash import.
|
|
15
|
+
__version__ = "0.0.0+unknown"
|
maskfits/assets/icon.ico
ADDED
|
Binary file
|
maskfits/assets/icon.png
ADDED
|
Binary file
|
maskfits/automask.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Threshold-based automatic source masking: background level + iterative
|
|
2
|
+
sigma-clipping to isolate background-only pixels, then a kappa-sigma cut
|
|
3
|
+
above that background flags source pixels for masking.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from scipy.ndimage import binary_closing, binary_dilation, label
|
|
10
|
+
from scipy.optimize import curve_fit
|
|
11
|
+
|
|
12
|
+
ERROR_METHODS = ["sigma", "sem"]
|
|
13
|
+
BG_METHODS = ["constant"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def valid_pixels(data: np.ndarray) -> np.ndarray:
|
|
17
|
+
"""Boolean mask of pixels eligible for background/threshold work at all -
|
|
18
|
+
excludes NaN and exact-zero (no-data/padding) pixels."""
|
|
19
|
+
return np.isfinite(data) & (data != 0)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def sigma_clip_mask(data: np.ndarray, valid: np.ndarray, kappa: float, max_iter: int = 10) -> np.ndarray:
|
|
23
|
+
"""Iteratively sigma-clip `data` (restricted to `valid`) at `kappa` sigma
|
|
24
|
+
around the surviving set's mean, converging (or stopping at max_iter) once
|
|
25
|
+
a pass removes nothing more - this is the "clean up" clip that strips
|
|
26
|
+
bright source pixels out so only background-like pixels remain.
|
|
27
|
+
|
|
28
|
+
Returns a boolean mask of the surviving ("background candidate") pixels.
|
|
29
|
+
"""
|
|
30
|
+
kept = valid.copy()
|
|
31
|
+
if kappa <= 0:
|
|
32
|
+
return kept
|
|
33
|
+
for _ in range(max_iter):
|
|
34
|
+
vals = data[kept]
|
|
35
|
+
if vals.size == 0:
|
|
36
|
+
break
|
|
37
|
+
mean = float(vals.mean())
|
|
38
|
+
std = float(vals.std())
|
|
39
|
+
if std == 0:
|
|
40
|
+
break
|
|
41
|
+
lo, hi = mean - kappa * std, mean + kappa * std
|
|
42
|
+
new_kept = valid & (data >= lo) & (data <= hi)
|
|
43
|
+
if int(new_kept.sum()) == int(kept.sum()):
|
|
44
|
+
kept = new_kept
|
|
45
|
+
break
|
|
46
|
+
kept = new_kept
|
|
47
|
+
return kept
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def background_stats(data: np.ndarray, kept: np.ndarray, error_method: str) -> tuple[float, float]:
|
|
51
|
+
"""Mean background level and its error (plain sigma, or the standard
|
|
52
|
+
error of the mean = sigma / sqrt(n)) over the surviving `kept` pixels."""
|
|
53
|
+
vals = data[kept]
|
|
54
|
+
if vals.size == 0:
|
|
55
|
+
return 0.0, 0.0
|
|
56
|
+
bg = float(vals.mean())
|
|
57
|
+
sigma = float(vals.std())
|
|
58
|
+
if error_method == "sem":
|
|
59
|
+
err = sigma / np.sqrt(vals.size) if vals.size > 0 else 0.0
|
|
60
|
+
else:
|
|
61
|
+
err = sigma
|
|
62
|
+
return bg, err
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _gaussian(x: np.ndarray, amplitude: float, mu: float, sigma: float) -> np.ndarray:
|
|
66
|
+
return amplitude * np.exp(-0.5 * ((x - mu) / sigma) ** 2)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def fit_gaussian_to_histogram(
|
|
70
|
+
values: np.ndarray, bins: int, hist_range: tuple[float, float]
|
|
71
|
+
) -> Optional[tuple[float, float, float]]:
|
|
72
|
+
"""Least-squares gaussian fit (amplitude, mu, sigma) to a histogram of
|
|
73
|
+
`values` binned over `hist_range` - for overlaying a fitted curve on the
|
|
74
|
+
auto-mask background histogram.
|
|
75
|
+
|
|
76
|
+
Falls back to the sample mean/std (a cruder, but still valid, gaussian
|
|
77
|
+
estimate via moment-matching) if the least-squares fit fails to
|
|
78
|
+
converge or lands on a degenerate result; returns None only when there's
|
|
79
|
+
nothing at all to fit.
|
|
80
|
+
"""
|
|
81
|
+
if values.size < 3:
|
|
82
|
+
return None
|
|
83
|
+
counts, edges = np.histogram(values, bins=bins, range=hist_range)
|
|
84
|
+
centers = (edges[:-1] + edges[1:]) / 2.0
|
|
85
|
+
mean = float(values.mean())
|
|
86
|
+
std = float(values.std()) or 1.0
|
|
87
|
+
try:
|
|
88
|
+
popt, _ = curve_fit(
|
|
89
|
+
_gaussian, centers, counts.astype(np.float64),
|
|
90
|
+
p0=[float(counts.max()), mean, std], maxfev=2000,
|
|
91
|
+
)
|
|
92
|
+
amplitude, mu, sigma = float(popt[0]), float(popt[1]), abs(float(popt[2]))
|
|
93
|
+
if sigma <= 0 or not np.isfinite(amplitude) or not np.isfinite(mu):
|
|
94
|
+
raise ValueError("degenerate gaussian fit")
|
|
95
|
+
except Exception:
|
|
96
|
+
amplitude, mu, sigma = float(counts.max()), mean, std
|
|
97
|
+
return amplitude, mu, sigma
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def auto_mask_preview(data: np.ndarray, valid: np.ndarray, bg: float, bg_err: float, kappa: float) -> np.ndarray:
|
|
101
|
+
"""Boolean mask of pixels to flag: `valid` pixels whose value exceeds
|
|
102
|
+
bg + kappa * bg_err. `valid` decides what's even eligible to be flagged -
|
|
103
|
+
pass valid_pixels(data) intersected with anything else that should be
|
|
104
|
+
excluded (e.g. pixels already masked manually - see AutoMaskWindow)."""
|
|
105
|
+
threshold = bg + kappa * bg_err
|
|
106
|
+
return valid & (data > threshold)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _disk_footprint(radius: int) -> np.ndarray:
|
|
110
|
+
yy, xx = np.mgrid[-radius:radius + 1, -radius:radius + 1]
|
|
111
|
+
return (xx ** 2 + yy ** 2) <= radius ** 2 + 1e-9
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# How far apart (in pixels) two flagged specks can be and still count as
|
|
115
|
+
# "the same object" for group-size filtering - see filter_by_group_size.
|
|
116
|
+
# Not user-facing: it's just large enough to bridge the sub-threshold noise
|
|
117
|
+
# gaps a real, noisy extended source leaves in its own thresholding, while
|
|
118
|
+
# staying far too small to merge genuinely separate point sources.
|
|
119
|
+
GROUP_BRIDGE_RADIUS = 4
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def filter_by_group_size(mask: np.ndarray, max_size: int) -> np.ndarray:
|
|
123
|
+
"""Drop any connected group of flagged pixels larger than `max_size` -
|
|
124
|
+
keeps compact, point-like detections (small background sources) while
|
|
125
|
+
dropping extended ones (satellite trails, big galaxies, artifacts).
|
|
126
|
+
Applied to the RAW threshold flags, before expand_mask pads whatever
|
|
127
|
+
survives - padding first would inflate every group's size and defeat the
|
|
128
|
+
point of this filter. max_size <= 0 disables filtering (nothing dropped).
|
|
129
|
+
|
|
130
|
+
Group membership is measured on a version of `mask` with small gaps
|
|
131
|
+
closed (binary_closing, radius=GROUP_BRIDGE_RADIUS) first, NOT on the raw
|
|
132
|
+
mask directly. A real extended source (a galaxy, a trail) practically
|
|
133
|
+
never thresholds into one solid blob - sky noise pushes individual
|
|
134
|
+
pixels within it below the cut too, fragmenting it into many small,
|
|
135
|
+
disconnected specks that would each individually slip under any size
|
|
136
|
+
limit on their own. Closing small gaps first recognizes that scattered
|
|
137
|
+
cluster of specks as the one big object it actually is, without merging
|
|
138
|
+
genuinely separate, well-spaced point sources (which stay distinct
|
|
139
|
+
groups, since they're farther apart than the bridging radius).
|
|
140
|
+
"""
|
|
141
|
+
if max_size <= 0 or not mask.any():
|
|
142
|
+
return mask
|
|
143
|
+
structure = np.ones((3, 3), dtype=bool)
|
|
144
|
+
bridged = binary_closing(mask, structure=_disk_footprint(GROUP_BRIDGE_RADIUS))
|
|
145
|
+
labeled, num = label(bridged, structure=structure)
|
|
146
|
+
if num == 0:
|
|
147
|
+
return mask
|
|
148
|
+
sizes = np.bincount(labeled.ravel())
|
|
149
|
+
too_big = np.nonzero(sizes > max_size)[0]
|
|
150
|
+
if too_big.size == 0:
|
|
151
|
+
return mask
|
|
152
|
+
return mask & ~np.isin(labeled, too_big)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def expand_mask(mask: np.ndarray, radius: float) -> np.ndarray:
|
|
156
|
+
"""Pad each flagged region out by `radius` pixels (a disk-shaped dilation)
|
|
157
|
+
so a thin/eroded detection still covers a source's faint wings. radius <=
|
|
158
|
+
0 leaves the mask unchanged."""
|
|
159
|
+
r = int(round(radius))
|
|
160
|
+
if r <= 0:
|
|
161
|
+
return mask
|
|
162
|
+
return binary_dilation(mask, structure=_disk_footprint(r))
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def neural_network_mask(data: np.ndarray, model_path: str) -> np.ndarray:
|
|
166
|
+
"""Placeholder interface for a future neural-network-based source/
|
|
167
|
+
satellite masker (e.g. a model trained to flag sources or satellite
|
|
168
|
+
trails directly from pixel data). Not implemented yet - deliberately not
|
|
169
|
+
wired to any inference framework here, so this project doesn't pick up a
|
|
170
|
+
heavy ML dependency just for a stub. Fixing the interface now (a model
|
|
171
|
+
path in, a boolean mask matching `data`'s shape out) means a real
|
|
172
|
+
implementation can be dropped in later - by this project or another user
|
|
173
|
+
- without any GUI-side changes: AutoMaskWindow already calls this and
|
|
174
|
+
handles the NotImplementedError gracefully.
|
|
175
|
+
"""
|
|
176
|
+
raise NotImplementedError(
|
|
177
|
+
"Neural network masking is not implemented yet - this is a placeholder interface "
|
|
178
|
+
"for a future model."
|
|
179
|
+
)
|
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
"""A non-modal window for interactively building a threshold-based auto mask.
|
|
2
|
+
|
|
3
|
+
Computes an iterative sigma-clipped background level (+ error) from the
|
|
4
|
+
current entry's displayed data (whatever resolution/smoothing is currently
|
|
5
|
+
active - same as manual painting), then flags pixels above bg + kappa *
|
|
6
|
+
bg_err as a translucent preview overlay drawn on the main canvas by the app.
|
|
7
|
+
Nothing touches the real mask until the user clicks Confirm.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import TYPE_CHECKING, Optional
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
from PySide6.QtCore import QRectF, Qt
|
|
16
|
+
from PySide6.QtGui import QCloseEvent, QColor, QKeyEvent, QPainter, QPainterPath, QPen
|
|
17
|
+
from PySide6.QtWidgets import (
|
|
18
|
+
QCheckBox,
|
|
19
|
+
QDialog,
|
|
20
|
+
QFileDialog,
|
|
21
|
+
QFrame,
|
|
22
|
+
QHBoxLayout,
|
|
23
|
+
QLabel,
|
|
24
|
+
QLineEdit,
|
|
25
|
+
QVBoxLayout,
|
|
26
|
+
QWidget,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
from maskfits.automask import (
|
|
30
|
+
BG_METHODS,
|
|
31
|
+
auto_mask_preview,
|
|
32
|
+
background_stats,
|
|
33
|
+
expand_mask,
|
|
34
|
+
filter_by_group_size,
|
|
35
|
+
fit_gaussian_to_histogram,
|
|
36
|
+
neural_network_mask,
|
|
37
|
+
sigma_clip_mask,
|
|
38
|
+
valid_pixels,
|
|
39
|
+
)
|
|
40
|
+
from maskfits.theme import current_theme, theme_manager
|
|
41
|
+
from maskfits.widgets import RoundButton, RoundSlider, SegmentedControl
|
|
42
|
+
|
|
43
|
+
if TYPE_CHECKING:
|
|
44
|
+
from maskfits.gui import Entry, MaskFitsApp
|
|
45
|
+
|
|
46
|
+
HIST_W = 420
|
|
47
|
+
HIST_H = 140
|
|
48
|
+
HIST_BINS = 60
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class _AutoMaskHistCanvas(QWidget):
|
|
52
|
+
"""Histogram of only the pixels that survived clean-up clipping, with the
|
|
53
|
+
Gaussian-fit curve and background/threshold marker lines overlaid."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, parent: Optional[QWidget] = None):
|
|
56
|
+
super().__init__(parent)
|
|
57
|
+
self.setFixedSize(HIST_W, HIST_H)
|
|
58
|
+
self._vals: Optional[np.ndarray] = None
|
|
59
|
+
self._bg = 0.0
|
|
60
|
+
self._threshold = 0.0
|
|
61
|
+
theme_manager().theme_changed.connect(lambda _t: self.update())
|
|
62
|
+
|
|
63
|
+
def set_data(self, vals: np.ndarray, bg: float, threshold: float) -> None:
|
|
64
|
+
self._vals = vals
|
|
65
|
+
self._bg = bg
|
|
66
|
+
self._threshold = threshold
|
|
67
|
+
self.update()
|
|
68
|
+
|
|
69
|
+
def paintEvent(self, _event) -> None: # noqa: N802
|
|
70
|
+
theme = current_theme()
|
|
71
|
+
painter = QPainter(self)
|
|
72
|
+
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
|
73
|
+
painter.fillRect(self.rect(), QColor(theme.panel_bg))
|
|
74
|
+
painter.setPen(QPen(QColor(theme.panel_border), 1))
|
|
75
|
+
painter.drawRect(QRectF(0.5, 0.5, self.width() - 1, self.height() - 1))
|
|
76
|
+
|
|
77
|
+
vals = self._vals
|
|
78
|
+
if vals is None or vals.size == 0:
|
|
79
|
+
return
|
|
80
|
+
|
|
81
|
+
mean = float(vals.mean())
|
|
82
|
+
std = float(vals.std()) or 1.0
|
|
83
|
+
lo, hi = mean - 8 * std, mean + 8 * std
|
|
84
|
+
if hi <= lo:
|
|
85
|
+
hi = lo + 1.0
|
|
86
|
+
|
|
87
|
+
pad = 10
|
|
88
|
+
pad_left = 10
|
|
89
|
+
w, h = HIST_W, HIST_H
|
|
90
|
+
plot_w = w - pad_left - pad
|
|
91
|
+
plot_h = h - 2 * pad
|
|
92
|
+
y_bottom = h - pad
|
|
93
|
+
|
|
94
|
+
counts, _edges = np.histogram(vals, bins=HIST_BINS, range=(lo, hi))
|
|
95
|
+
heights = np.log1p(counts.astype(np.float64))
|
|
96
|
+
max_h = heights.max() or 1.0
|
|
97
|
+
bar_w = plot_w / HIST_BINS
|
|
98
|
+
|
|
99
|
+
painter.setPen(Qt.PenStyle.NoPen)
|
|
100
|
+
painter.setBrush(QColor(theme.text_dim))
|
|
101
|
+
for i in range(HIST_BINS):
|
|
102
|
+
if counts[i] == 0:
|
|
103
|
+
continue
|
|
104
|
+
x0 = pad_left + i * bar_w
|
|
105
|
+
bar_h = (heights[i] / max_h) * plot_h
|
|
106
|
+
painter.drawRect(QRectF(x0, y_bottom - bar_h, bar_w, bar_h))
|
|
107
|
+
|
|
108
|
+
def x_of(v: float) -> float:
|
|
109
|
+
frac = (v - lo) / (hi - lo) if hi > lo else 0.0
|
|
110
|
+
frac = min(max(frac, 0.0), 1.0)
|
|
111
|
+
return pad_left + frac * plot_w
|
|
112
|
+
|
|
113
|
+
fit = fit_gaussian_to_histogram(vals, HIST_BINS, (lo, hi))
|
|
114
|
+
if fit is not None:
|
|
115
|
+
amplitude, mu, sigma = fit
|
|
116
|
+
xs = np.linspace(lo, hi, 150)
|
|
117
|
+
predicted = np.clip(amplitude * np.exp(-0.5 * ((xs - mu) / sigma) ** 2), 0, None)
|
|
118
|
+
fit_heights = np.log1p(predicted)
|
|
119
|
+
path = QPainterPath()
|
|
120
|
+
for i, (x, fh) in enumerate(zip(xs, fit_heights)):
|
|
121
|
+
px = pad_left + ((x - lo) / (hi - lo)) * plot_w
|
|
122
|
+
py = y_bottom - (fh / max_h) * plot_h
|
|
123
|
+
if i == 0:
|
|
124
|
+
path.moveTo(px, py)
|
|
125
|
+
else:
|
|
126
|
+
path.lineTo(px, py)
|
|
127
|
+
pen = QPen(QColor(theme.blue), 2)
|
|
128
|
+
pen.setDashPattern([5, 3])
|
|
129
|
+
painter.setPen(pen)
|
|
130
|
+
painter.drawPath(path)
|
|
131
|
+
|
|
132
|
+
bg_x = x_of(self._bg)
|
|
133
|
+
painter.setPen(QPen(QColor(theme.green), 2))
|
|
134
|
+
painter.drawLine(int(bg_x), pad, int(bg_x), h - pad)
|
|
135
|
+
th_x = x_of(self._threshold)
|
|
136
|
+
painter.setPen(QPen(QColor(theme.warning), 2))
|
|
137
|
+
painter.drawLine(int(th_x), pad, int(th_x), h - pad)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class AutoMaskWindow(QDialog):
|
|
141
|
+
def __init__(self, app: "MaskFitsApp", entry: "Entry"):
|
|
142
|
+
super().__init__(app)
|
|
143
|
+
self.app = app
|
|
144
|
+
self.entry = entry
|
|
145
|
+
# A snapshot reference to whatever's currently displayed (binned/
|
|
146
|
+
# smoothed or not) - matches how manual painting already treats
|
|
147
|
+
# "the current image state" as the thing to operate on. Pixels the
|
|
148
|
+
# user already masked manually (or with a previously-confirmed auto
|
|
149
|
+
# mask) are excluded from background stats AND from being (re-)
|
|
150
|
+
# flagged here - see _apply()'s `valid` computation.
|
|
151
|
+
self.data = entry.image.data
|
|
152
|
+
self.existing_mask = entry.image.mask.copy()
|
|
153
|
+
self.setWindowTitle("Auto Mask")
|
|
154
|
+
self.setModal(False)
|
|
155
|
+
|
|
156
|
+
self.bg_method = "constant"
|
|
157
|
+
self.error_method = "sigma"
|
|
158
|
+
self.cleanup_kappa = 4.0
|
|
159
|
+
self.cleanup_iterations = 10
|
|
160
|
+
self.kappa = 5.0
|
|
161
|
+
self.max_group_size_enabled = True
|
|
162
|
+
self.max_group_size = 50
|
|
163
|
+
self.expand_px = 5
|
|
164
|
+
|
|
165
|
+
self._preview: Optional[np.ndarray] = None
|
|
166
|
+
self.nn_model_path: Optional[str] = None
|
|
167
|
+
self._resolved = False
|
|
168
|
+
|
|
169
|
+
self._build()
|
|
170
|
+
self._apply()
|
|
171
|
+
theme_manager().theme_changed.connect(lambda _t: self._style_confirm_button())
|
|
172
|
+
|
|
173
|
+
self._center_on_parent()
|
|
174
|
+
|
|
175
|
+
# ---------------------------------------------------------------- build
|
|
176
|
+
|
|
177
|
+
def _center_on_parent(self) -> None:
|
|
178
|
+
parent = self.app
|
|
179
|
+
self.adjustSize()
|
|
180
|
+
geo = parent.frameGeometry()
|
|
181
|
+
x = max(geo.x() + (geo.width() - self.width()) // 2, 0)
|
|
182
|
+
y = max(geo.y() + (geo.height() - self.height()) // 2, 0)
|
|
183
|
+
self.move(x, y)
|
|
184
|
+
|
|
185
|
+
def _build(self) -> None:
|
|
186
|
+
layout = QVBoxLayout(self)
|
|
187
|
+
layout.setContentsMargins(16, 12, 16, 16)
|
|
188
|
+
layout.setSpacing(0)
|
|
189
|
+
|
|
190
|
+
title = QLabel("Auto Mask")
|
|
191
|
+
layout.addWidget(title)
|
|
192
|
+
desc = QLabel(
|
|
193
|
+
"Flags pixels above background + κ × background error as a preview "
|
|
194
|
+
"overlay, updated live as the sliders below change - nothing is written "
|
|
195
|
+
"to the real mask until Confirm."
|
|
196
|
+
)
|
|
197
|
+
desc.setWordWrap(True)
|
|
198
|
+
desc.setProperty("dim", True)
|
|
199
|
+
desc.setFixedWidth(HIST_W)
|
|
200
|
+
layout.addSpacing(2)
|
|
201
|
+
layout.addWidget(desc)
|
|
202
|
+
|
|
203
|
+
self._method_row(layout, "background method", [(m, m.capitalize()) for m in BG_METHODS],
|
|
204
|
+
self.bg_method, self._on_bg_method_changed)
|
|
205
|
+
self._method_row(layout, "background error", [("sigma", "Sigma"), ("sem", "SEM")],
|
|
206
|
+
self.error_method, self._on_error_method_changed)
|
|
207
|
+
self._slider_row(layout, "clean-up κ (background isolation)", self.cleanup_kappa, 0.5, 10.0,
|
|
208
|
+
on_change=self._on_cleanup_kappa_changed)
|
|
209
|
+
self._slider_row(layout, "clean-up iterations", self.cleanup_iterations, 1, 20, integer=True,
|
|
210
|
+
on_change=self._on_cleanup_iterations_changed)
|
|
211
|
+
|
|
212
|
+
self.hist_canvas = _AutoMaskHistCanvas(self)
|
|
213
|
+
hist_row = QHBoxLayout()
|
|
214
|
+
hist_row.addWidget(self.hist_canvas)
|
|
215
|
+
hist_row.addStretch(1)
|
|
216
|
+
layout.addSpacing(10)
|
|
217
|
+
layout.addLayout(hist_row)
|
|
218
|
+
|
|
219
|
+
legend = QHBoxLayout()
|
|
220
|
+
legend.setSpacing(0)
|
|
221
|
+
theme = current_theme()
|
|
222
|
+
self._legend_swatch(legend, theme.text_dim, "background (kept after clipping)")
|
|
223
|
+
self._legend_swatch(legend, theme.blue, "gaussian fit")
|
|
224
|
+
self._legend_swatch(legend, theme.green, "background")
|
|
225
|
+
self._legend_swatch(legend, theme.warning, "mask threshold")
|
|
226
|
+
legend.addStretch(1)
|
|
227
|
+
layout.addLayout(legend)
|
|
228
|
+
|
|
229
|
+
# The threshold/expand knobs live below the histogram, separate from
|
|
230
|
+
# the clean-up block above it - they shape the FINAL flagged mask,
|
|
231
|
+
# not the background estimate the histogram is showing.
|
|
232
|
+
self._slider_row(layout, "mask κ (threshold above background)", self.kappa, 0.5, 20.0,
|
|
233
|
+
on_change=self._on_kappa_changed)
|
|
234
|
+
self._slider_row(layout, "max group size (px, drops larger flagged regions)", self.max_group_size,
|
|
235
|
+
1, 500, integer=True, enabled_checkbox=True, on_change=self._on_max_group_size_changed)
|
|
236
|
+
self._slider_row(layout, "expand (pad each flagged region, px)", self.expand_px, 0, 20, integer=True,
|
|
237
|
+
on_change=self._on_expand_changed)
|
|
238
|
+
|
|
239
|
+
self.stats_label = QLabel()
|
|
240
|
+
self.stats_label.setWordWrap(True)
|
|
241
|
+
layout.addSpacing(8)
|
|
242
|
+
layout.addWidget(self.stats_label)
|
|
243
|
+
|
|
244
|
+
self._build_nn_section(layout)
|
|
245
|
+
|
|
246
|
+
layout.addSpacing(4)
|
|
247
|
+
btn_row = QHBoxLayout()
|
|
248
|
+
btn_row.addStretch(1)
|
|
249
|
+
confirm_btn = RoundButton("confirm")
|
|
250
|
+
confirm_btn.clicked.connect(self._confirm)
|
|
251
|
+
discard_btn = RoundButton("discard", danger=True)
|
|
252
|
+
discard_btn.clicked.connect(self._discard)
|
|
253
|
+
btn_row.addWidget(confirm_btn)
|
|
254
|
+
btn_row.addWidget(discard_btn)
|
|
255
|
+
layout.addLayout(btn_row)
|
|
256
|
+
self._confirm_btn = confirm_btn
|
|
257
|
+
self._style_confirm_button()
|
|
258
|
+
|
|
259
|
+
def _style_confirm_button(self) -> None:
|
|
260
|
+
theme = current_theme()
|
|
261
|
+
self._confirm_btn.setStyleSheet(
|
|
262
|
+
f"QPushButton {{ background-color: {theme.green}; color: white; }}"
|
|
263
|
+
f"QPushButton:hover {{ background-color: {theme.green}; }}"
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
def _build_nn_section(self, layout: QVBoxLayout) -> None:
|
|
267
|
+
"""Forward-looking hook, not functional yet: lets a model file be
|
|
268
|
+
picked and wires an "apply" button through to
|
|
269
|
+
automask.neural_network_mask, which currently just raises
|
|
270
|
+
NotImplementedError - so the interface (pick a model, apply it, merge
|
|
271
|
+
its output the same way as the threshold preview) is in place for a
|
|
272
|
+
real model to be dropped into later without any GUI changes."""
|
|
273
|
+
divider = QFrame()
|
|
274
|
+
divider.setFrameShape(QFrame.Shape.HLine)
|
|
275
|
+
layout.addSpacing(2)
|
|
276
|
+
layout.addWidget(divider)
|
|
277
|
+
layout.addSpacing(8)
|
|
278
|
+
|
|
279
|
+
caption = QLabel("Neural network masking (future / experimental):")
|
|
280
|
+
caption.setProperty("dim", True)
|
|
281
|
+
layout.addWidget(caption)
|
|
282
|
+
|
|
283
|
+
row = QHBoxLayout()
|
|
284
|
+
self.nn_model_label = QLabel("no model loaded")
|
|
285
|
+
self.nn_model_label.setProperty("dim", True)
|
|
286
|
+
row.addWidget(self.nn_model_label, 1)
|
|
287
|
+
load_btn = RoundButton("load model...")
|
|
288
|
+
load_btn.clicked.connect(self._load_nn_model)
|
|
289
|
+
row.addWidget(load_btn)
|
|
290
|
+
layout.addSpacing(4)
|
|
291
|
+
layout.addLayout(row)
|
|
292
|
+
|
|
293
|
+
nn_btn_row = QHBoxLayout()
|
|
294
|
+
apply_btn = RoundButton("apply nn mask")
|
|
295
|
+
apply_btn.clicked.connect(self._apply_nn)
|
|
296
|
+
nn_btn_row.addWidget(apply_btn)
|
|
297
|
+
nn_btn_row.addStretch(1)
|
|
298
|
+
layout.addSpacing(6)
|
|
299
|
+
layout.addLayout(nn_btn_row)
|
|
300
|
+
|
|
301
|
+
self.nn_status_label = QLabel()
|
|
302
|
+
self.nn_status_label.setWordWrap(True)
|
|
303
|
+
self.nn_status_label.setFixedWidth(HIST_W)
|
|
304
|
+
self.nn_status_label.setProperty("dim", True)
|
|
305
|
+
layout.addSpacing(4)
|
|
306
|
+
layout.addWidget(self.nn_status_label)
|
|
307
|
+
|
|
308
|
+
def _load_nn_model(self) -> None:
|
|
309
|
+
path, _filter = QFileDialog.getOpenFileName(self, "Load a masking model")
|
|
310
|
+
if not path:
|
|
311
|
+
return
|
|
312
|
+
self.nn_model_path = path
|
|
313
|
+
self.nn_model_label.setText(path.rsplit("/", 1)[-1])
|
|
314
|
+
|
|
315
|
+
def _apply_nn(self) -> None:
|
|
316
|
+
if not self.nn_model_path:
|
|
317
|
+
self.nn_status_label.setText("Load a model file first.")
|
|
318
|
+
return
|
|
319
|
+
try:
|
|
320
|
+
preview = neural_network_mask(self.data, self.nn_model_path)
|
|
321
|
+
except NotImplementedError as exc:
|
|
322
|
+
self.nn_status_label.setText(str(exc))
|
|
323
|
+
return
|
|
324
|
+
self._preview = preview
|
|
325
|
+
self.app.set_auto_mask_preview(self.entry, preview)
|
|
326
|
+
self.nn_status_label.setText(f"NN mask applied: {int(preview.sum()):,} px flagged.")
|
|
327
|
+
|
|
328
|
+
@staticmethod
|
|
329
|
+
def _legend_swatch(layout: QHBoxLayout, color: str, label: str) -> None:
|
|
330
|
+
box = QHBoxLayout()
|
|
331
|
+
box.setSpacing(4)
|
|
332
|
+
swatch = QLabel()
|
|
333
|
+
swatch.setFixedSize(10, 10)
|
|
334
|
+
swatch.setStyleSheet(f"background-color: {color}; border-radius: 2px;")
|
|
335
|
+
box.addWidget(swatch)
|
|
336
|
+
text = QLabel(label)
|
|
337
|
+
text.setProperty("dim", True)
|
|
338
|
+
box.addWidget(text)
|
|
339
|
+
wrapper = QWidget()
|
|
340
|
+
wrapper.setLayout(box)
|
|
341
|
+
layout.addWidget(wrapper)
|
|
342
|
+
layout.setSpacing(12)
|
|
343
|
+
|
|
344
|
+
def _method_row(self, layout: QVBoxLayout, label: str, options: list[tuple[str, str]], value: str,
|
|
345
|
+
on_change) -> None:
|
|
346
|
+
row = QHBoxLayout()
|
|
347
|
+
lbl = QLabel(f"{label}:")
|
|
348
|
+
lbl.setProperty("dim", True)
|
|
349
|
+
row.addWidget(lbl)
|
|
350
|
+
row.addStretch(1)
|
|
351
|
+
control = SegmentedControl(options, value)
|
|
352
|
+
control.valueChanged.connect(on_change)
|
|
353
|
+
row.addWidget(control)
|
|
354
|
+
layout.addSpacing(10)
|
|
355
|
+
layout.addLayout(row)
|
|
356
|
+
|
|
357
|
+
def _slider_row(self, layout: QVBoxLayout, label: str, value: float, lo: float, hi: float, *,
|
|
358
|
+
integer: bool = False, enabled_checkbox: bool = False, on_change=None) -> None:
|
|
359
|
+
row = QHBoxLayout()
|
|
360
|
+
checkbox: Optional[QCheckBox] = None
|
|
361
|
+
if enabled_checkbox:
|
|
362
|
+
# An optional on/off switch for this parameter - the constraint
|
|
363
|
+
# only applies while checked (see _apply()); the slider/entry
|
|
364
|
+
# stay interactive either way, they just have no effect while
|
|
365
|
+
# unchecked.
|
|
366
|
+
checkbox = QCheckBox()
|
|
367
|
+
checkbox.setChecked(self.max_group_size_enabled)
|
|
368
|
+
checkbox.toggled.connect(self._on_max_group_size_enabled_changed)
|
|
369
|
+
row.addWidget(checkbox)
|
|
370
|
+
lbl = QLabel(f"{label}:")
|
|
371
|
+
lbl.setProperty("dim", True)
|
|
372
|
+
row.addWidget(lbl)
|
|
373
|
+
row.addStretch(1)
|
|
374
|
+
entry = QLineEdit(f"{value:.3g}")
|
|
375
|
+
entry.setFixedWidth(56)
|
|
376
|
+
entry.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
|
377
|
+
row.addWidget(entry)
|
|
378
|
+
layout.addSpacing(10)
|
|
379
|
+
layout.addLayout(row)
|
|
380
|
+
|
|
381
|
+
slider = RoundSlider(lo, hi, value, integer=integer)
|
|
382
|
+
slider.setFixedWidth(HIST_W)
|
|
383
|
+
layout.addSpacing(0)
|
|
384
|
+
layout.addWidget(slider)
|
|
385
|
+
|
|
386
|
+
def apply_entry() -> None:
|
|
387
|
+
try:
|
|
388
|
+
v = float(entry.text())
|
|
389
|
+
except ValueError:
|
|
390
|
+
entry.setText(f"{slider.value():.3g}")
|
|
391
|
+
return
|
|
392
|
+
v = max(lo, min(v, hi))
|
|
393
|
+
slider.setValue(v)
|
|
394
|
+
entry.setText(f"{slider.value():.3g}")
|
|
395
|
+
if on_change is not None:
|
|
396
|
+
on_change(slider.value())
|
|
397
|
+
|
|
398
|
+
def sync_entry(v: float) -> None:
|
|
399
|
+
entry.setText(f"{v:.3g}")
|
|
400
|
+
if on_change is not None:
|
|
401
|
+
on_change(v)
|
|
402
|
+
|
|
403
|
+
entry.editingFinished.connect(apply_entry)
|
|
404
|
+
slider.valueChanged.connect(sync_entry)
|
|
405
|
+
|
|
406
|
+
# ------------------------------------------------------- param setters
|
|
407
|
+
|
|
408
|
+
def _on_bg_method_changed(self, v: str) -> None:
|
|
409
|
+
self.bg_method = v
|
|
410
|
+
self._apply()
|
|
411
|
+
|
|
412
|
+
def _on_error_method_changed(self, v: str) -> None:
|
|
413
|
+
self.error_method = v
|
|
414
|
+
self._apply()
|
|
415
|
+
|
|
416
|
+
def _on_cleanup_kappa_changed(self, v: float) -> None:
|
|
417
|
+
self.cleanup_kappa = v
|
|
418
|
+
self._apply()
|
|
419
|
+
|
|
420
|
+
def _on_cleanup_iterations_changed(self, v: float) -> None:
|
|
421
|
+
self.cleanup_iterations = int(v)
|
|
422
|
+
self._apply()
|
|
423
|
+
|
|
424
|
+
def _on_kappa_changed(self, v: float) -> None:
|
|
425
|
+
self.kappa = v
|
|
426
|
+
self._apply()
|
|
427
|
+
|
|
428
|
+
def _on_max_group_size_changed(self, v: float) -> None:
|
|
429
|
+
self.max_group_size = int(v)
|
|
430
|
+
self._apply()
|
|
431
|
+
|
|
432
|
+
def _on_max_group_size_enabled_changed(self, checked: bool) -> None:
|
|
433
|
+
self.max_group_size_enabled = checked
|
|
434
|
+
self._apply()
|
|
435
|
+
|
|
436
|
+
def _on_expand_changed(self, v: float) -> None:
|
|
437
|
+
self.expand_px = int(v)
|
|
438
|
+
self._apply()
|
|
439
|
+
|
|
440
|
+
# ---------------------------------------------------------------- logic
|
|
441
|
+
|
|
442
|
+
def _apply(self) -> None:
|
|
443
|
+
data = self.data
|
|
444
|
+
# Already-masked pixels (manually painted, or a previously-confirmed
|
|
445
|
+
# auto mask) are excluded from background stats and can never be
|
|
446
|
+
# (re-)flagged - as far as this tool is concerned they don't exist
|
|
447
|
+
# in the image.
|
|
448
|
+
valid = valid_pixels(data) & ~self.existing_mask
|
|
449
|
+
kept = sigma_clip_mask(data, valid, self.cleanup_kappa, max_iter=self.cleanup_iterations)
|
|
450
|
+
bg, bg_err = background_stats(data, kept, self.error_method)
|
|
451
|
+
preview = auto_mask_preview(data, valid, bg, bg_err, self.kappa)
|
|
452
|
+
threshold = bg + self.kappa * bg_err
|
|
453
|
+
# Group-size filtering runs on the RAW flagged regions, before expand
|
|
454
|
+
# pads them - padding first would inflate every group's size and
|
|
455
|
+
# defeat the point of keeping only compact, point-like sources.
|
|
456
|
+
max_group_size = self.max_group_size if self.max_group_size_enabled else 0
|
|
457
|
+
preview = filter_by_group_size(preview, max_group_size)
|
|
458
|
+
# Expansion only pads the FINAL flagged regions - it has no bearing
|
|
459
|
+
# on background isolation, so it's applied after everything the
|
|
460
|
+
# histogram/stats below are about.
|
|
461
|
+
preview = expand_mask(preview, self.expand_px)
|
|
462
|
+
|
|
463
|
+
self._preview = preview
|
|
464
|
+
|
|
465
|
+
flagged = int(preview.sum())
|
|
466
|
+
total = data.size
|
|
467
|
+
pct = 100.0 * flagged / total if total else 0.0
|
|
468
|
+
self.stats_label.setText(
|
|
469
|
+
f"background: {bg:.4g} error: {bg_err:.4g} threshold: {threshold:.4g}\n"
|
|
470
|
+
f"flagged: {flagged:,} px ({pct:.2f}%) background pixels used: {int(kept.sum()):,}"
|
|
471
|
+
)
|
|
472
|
+
self.hist_canvas.set_data(data[kept], bg, threshold)
|
|
473
|
+
self.app.set_auto_mask_preview(self.entry, preview)
|
|
474
|
+
|
|
475
|
+
def _confirm(self) -> None:
|
|
476
|
+
self._resolved = True
|
|
477
|
+
if self._preview is not None:
|
|
478
|
+
self.app.confirm_auto_mask(self.entry, self._preview)
|
|
479
|
+
else:
|
|
480
|
+
self.app.discard_auto_mask(self.entry)
|
|
481
|
+
self.close()
|
|
482
|
+
|
|
483
|
+
def _discard(self) -> None:
|
|
484
|
+
self._resolved = True
|
|
485
|
+
self.app.discard_auto_mask(self.entry)
|
|
486
|
+
self.close()
|
|
487
|
+
|
|
488
|
+
def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802
|
|
489
|
+
if not self._resolved:
|
|
490
|
+
self._resolved = True
|
|
491
|
+
self.app.discard_auto_mask(self.entry)
|
|
492
|
+
super().closeEvent(event)
|
|
493
|
+
|
|
494
|
+
def keyPressEvent(self, event: QKeyEvent) -> None: # noqa: N802
|
|
495
|
+
if event.key() == Qt.Key.Key_Escape:
|
|
496
|
+
self._discard()
|
|
497
|
+
return
|
|
498
|
+
super().keyPressEvent(event)
|