seglint 0.2.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.
seglint/calibrate.py ADDED
@@ -0,0 +1,270 @@
1
+ """`seglint calibrate`: write seglint.toml with proposed thresholds and frozen reference statistics.
2
+
3
+ File layout (the design decision, also in docs/checks.md):
4
+
5
+ * the UPPER part is the user's: free text and keys (`[thresholds]`, ...) that survive a re-run;
6
+ * everything from `MARKER` down is generated (`[calibrated]`, `[calibrated.options]`,
7
+ `[calibrated.thresholds]`, `[calibrated.stats.<measure>.<global|class_N>]`) and rewritten on
8
+ every `seglint calibrate`;
9
+ * precedence when `check` reads it: CLI flags > user keys > `[calibrated]` > built-in defaults;
10
+ * with `[calibrated.stats.*]` present, `check` judges the scanned data against these frozen
11
+ statistics instead of recomputing them from the scanned data (checking a new batch against a
12
+ reference set).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from collections.abc import Sequence
19
+ from pathlib import Path
20
+
21
+ from seglint import __version__
22
+ from seglint.checks.relative import _fmt, shown_range
23
+ from seglint.config import SENSITIVITY_K, Config
24
+ from seglint.models import SampleRecord
25
+ from seglint.relative import MEASURES, PERCENTILES, RobustStats, dataset_stats, k_for
26
+
27
+ MARKER = "# ===== generated by `seglint calibrate` (re-run it to regenerate; edit above) ====="
28
+
29
+ USER_HEAD = """\
30
+ # seglint.toml
31
+ #
32
+ # Your own settings go in this upper part; they survive `seglint calibrate -o <this file>`.
33
+ # Precedence: CLI flags > keys in this upper part > [calibrated] values below > built-in defaults.
34
+ # `seglint check --explain-config` shows which layer every effective value comes from.
35
+ #
36
+ # Uncomment and edit to override a calibrated value, for example:
37
+ #
38
+ # [thresholds]
39
+ # relative_k = 4.0 # one knob for all relative checks (see the notes below)
40
+ # relative_k_object_count = 6.0 # per-check override (0 = use relative_k)
41
+
42
+ """
43
+
44
+ NAMES = {
45
+ "area_frac": "Area-fraction",
46
+ "position": "Position",
47
+ "shape": "Shape",
48
+ "object_count": "Object-count",
49
+ "holes": "Small-hole",
50
+ "speckles": "Speckle-count",
51
+ }
52
+
53
+ # group -> (check, what it measures, measures, when to adjust)
54
+ GROUPS = {
55
+ "area_frac": (
56
+ "R001",
57
+ "the share of the image a class covers (judged on a logit scale, so the normal range "
58
+ "stays inside 0-100%)",
59
+ ["area_frac"],
60
+ "Raise it if your objects legitimately vary a lot in size; lower it to catch every size "
61
+ "outlier.",
62
+ ),
63
+ "position": (
64
+ "R002",
65
+ "where the centre of a class sits in the image (x and y, 0-1)",
66
+ ["centroid_x", "centroid_y"],
67
+ "Raise it if objects can appear anywhere in your images; lower it if they are always "
68
+ "centred.",
69
+ ),
70
+ "shape": (
71
+ "R003",
72
+ "how compact (solidity, low is extreme) and how elongated the largest object is",
73
+ ["solidity", "elongation"],
74
+ "Raise it if your objects have irregular or very elongated shapes by nature.",
75
+ ),
76
+ "object_count": (
77
+ "R004",
78
+ "how many separate objects a class has in one mask",
79
+ ["object_count"],
80
+ "Raise it if you label many small objects per image.",
81
+ ),
82
+ "holes": (
83
+ "G003 relative tier",
84
+ "the share of a class area taken by small holes",
85
+ ["hole_share"],
86
+ "Raise it if your masks legitimately contain holes (rings, hollow objects).",
87
+ ),
88
+ "speckles": (
89
+ "G002 relative tier",
90
+ "the number of tiny specks (components of speckle size) per class",
91
+ ["speck_count"],
92
+ "Raise it if your data has genuine tiny objects.",
93
+ ),
94
+ }
95
+
96
+ # fixed absolute thresholds: key -> comment
97
+ FIXED = {
98
+ "near_empty_info_frac": "T005: a mask covering less than this share of the image is "
99
+ "reported (INFO).",
100
+ "near_empty_warn_frac": "T005: below this share the finding is a WARNING.",
101
+ "full_mask_info_frac": "T006: a mask covering at least this share of the image is reported "
102
+ "(INFO).",
103
+ "full_mask_warn_frac": "T006: from this share the finding is a WARNING.",
104
+ "speckle_max_area_frac": "G002: a component up to this share of the class/image area (and "
105
+ "at least 4 px) counts as a speck.",
106
+ "small_hole_max_area_frac": "G003: a hole up to this share of the area counts as a small hole.",
107
+ "small_hole_warn_area_frac": "G003: small holes covering this share of a class are a WARNING.",
108
+ "max_components_per_class": "G001: more than this many components of one class is reported.",
109
+ }
110
+
111
+
112
+ def _f(x: float) -> str:
113
+ return repr(float(x))
114
+
115
+
116
+ def _s(x: str) -> str:
117
+ return json.dumps(x)
118
+
119
+
120
+ def _range_text(measure: str, st: RobustStats, k: float) -> str:
121
+ lo, hi = shown_range(measure, st, k)
122
+ return f"{_fmt(measure, lo)}-{_fmt(measure, hi)} (median {_fmt(measure, st.median)}, n={st.n})"
123
+
124
+
125
+ def _group_comment(group: str, stats, cfg: Config, k: float) -> list[str]:
126
+ check, what, measures, when = GROUPS[group]
127
+ out = [
128
+ f"# {NAMES[group]} threshold ({check}), k = {k:g}: flags a mask when {what} is",
129
+ "# extreme relative to this dataset.",
130
+ ]
131
+ if not any(stats.get(m) for m in measures):
132
+ out.append("# no normal range: too few samples of this measure in this dataset.")
133
+ for m in measures:
134
+ per = stats.get(m)
135
+ if not per:
136
+ continue
137
+ lab = MEASURES[m].label
138
+ out.append(f"# normal {lab}, all classes: {_range_text(m, per[None], k)}")
139
+ for cls, st in sorted((c, s) for c, s in per.items() if c is not None):
140
+ if st.source == "class" and st.n < per[None].n:
141
+ out.append(f"# normal {lab}, class {cls}: {_range_text(m, st, k)}")
142
+ n_fb = [c for c, s in per.items() if c is not None and s.source != "class"]
143
+ if n_fb:
144
+ out.append(
145
+ f"# class(es) {', '.join(map(str, sorted(n_fb)))} have fewer than "
146
+ f"{cfg.thresholds.min_class_samples} samples: they use the all-class range"
147
+ )
148
+ hi_only = group in ("object_count", "holes", "speckles")
149
+ if hi_only and stats.get(measures[0]):
150
+ lim = shown_range(measures[0], stats[measures[0]][None], k)[1]
151
+ out.append(
152
+ f"# so a mask with a {MEASURES[measures[0]].label} above {_fmt(measures[0], lim)} "
153
+ "is flagged."
154
+ )
155
+ out.append("# Raise k to flag fewer (only the most extreme masks); lower it to flag more.")
156
+ out.append(f"# {when}")
157
+ return out
158
+
159
+
160
+ def render(
161
+ cfg: Config,
162
+ records: Sequence[SampleRecord],
163
+ n_samples: int,
164
+ sensitivity: str,
165
+ user_head: str | None = None,
166
+ ) -> tuple[str, dict]:
167
+ """The file text and a small summary (n_valid, reference usable, notes)."""
168
+ cfg.reference = None # statistics come from the scanned data, never from an older file
169
+ valid = [r for r in records if r.valid_labels]
170
+ stats = dataset_stats(valid, cfg)
171
+ k = cfg.thresholds.relative_k
172
+ th = cfg.thresholds
173
+ notes = []
174
+ if not any(stats.values()):
175
+ notes.append(
176
+ f"only {len(valid)} samples with usable masks: no statistics written (at least "
177
+ f"{th.min_class_samples} are needed, {th.min_relative_samples} for relative checks)"
178
+ )
179
+ elif len(valid) < th.min_relative_samples:
180
+ notes.append(
181
+ f"only {len(valid)} samples with usable masks: statistics written, but `check` skips "
182
+ f"the relative checks until the reference has {th.min_relative_samples} (R000 notice)"
183
+ )
184
+ lines = [
185
+ (user_head if user_head is not None else USER_HEAD).rstrip("\n") + "\n",
186
+ MARKER,
187
+ "# Frozen statistics of the scanned dataset. With these present, `seglint check` judges",
188
+ "# the data it scans against THESE statistics instead of recomputing them (use it to",
189
+ "# check a new batch against a reference set). Remove [calibrated.stats.*] to go back",
190
+ "# to judging a dataset against itself.",
191
+ "[calibrated]",
192
+ "version = 1",
193
+ f"seglint_version = {_s(__version__)}",
194
+ f"n_samples = {n_samples}",
195
+ f"n_valid = {len(valid)}",
196
+ f"sensitivity = {_s(sensitivity)}",
197
+ "",
198
+ ]
199
+ opts = []
200
+ if cfg.mask_suffix:
201
+ opts.append(f"mask_suffix = {_s(cfg.mask_suffix)}")
202
+ if cfg.binary:
203
+ opts.append("binary = true")
204
+ opts += [f"ignore_index = {cfg.ignore_index}", f"background_index = {cfg.background_index}"]
205
+ lines += ["# Dataset options used for the scan (can be overridden by CLI flags).",
206
+ "[calibrated.options]", *opts, ""] # fmt: skip
207
+ lines += [
208
+ "[calibrated.thresholds]",
209
+ f"# Sensitivity '{sensitivity}': k = {k:g} (strict {SENSITIVITY_K['strict']:g}, balanced "
210
+ f"{SENSITIVITY_K['balanced']:g}, relaxed {SENSITIVITY_K['relaxed']:g}).",
211
+ "# relative_k is the number of scaled MADs around the median that still counts as normal",
212
+ "# (normal range = median +- k * scaled MAD). It is the one knob for all relative checks:",
213
+ "# a larger k widens every normal range and flags fewer masks. A finding means 'extreme",
214
+ "# relative to this dataset', not 'wrong'.",
215
+ f"relative_k = {_f(k)}",
216
+ "",
217
+ ]
218
+ for group in GROUPS:
219
+ lines += _group_comment(group, stats, cfg, k)
220
+ lines += [
221
+ f"# relative_k_{group} = 0 # 0 = use relative_k; copy to [thresholds] to override",
222
+ "",
223
+ ]
224
+ lines.append("# Absolute checks: fixed, not calibrated (they do not depend on this dataset).")
225
+ for key, text in FIXED.items():
226
+ v = getattr(th, key)
227
+ lines += [f"# {text}", f"{key} = {_f(v) if isinstance(v, float) else v}"]
228
+ lines += [
229
+ "# Majority notice: if one relative check (R001-R004, relative tiers of G002/G003) flags",
230
+ "# more than this share of the samples, `check` warns that the dataset's 'normal' may",
231
+ "# differ or that a defect may be in the majority. Notice only: findings and exit code",
232
+ "# do not change. Raise it if your data legitimately has many extreme masks.",
233
+ f"majority_warn_fraction = {_f(th.majority_warn_fraction)}",
234
+ "",
235
+ ]
236
+ for m, per in stats.items():
237
+ if not per:
238
+ continue
239
+ spec = MEASURES[m]
240
+ lines.append(
241
+ f"# {spec.label} ({m}); transform {spec.transform}, extreme tail: {spec.side}."
242
+ )
243
+ for cls, st in sorted(per.items(), key=lambda kv: (kv[0] is not None, kv[0] or 0)):
244
+ if cls is not None and st.source != "class":
245
+ continue
246
+ lo, hi = shown_range(m, st, k_for(cfg, spec, cls))
247
+ name = "global" if cls is None else f"class_{cls}"
248
+ lines += [
249
+ f"[calibrated.stats.{m}.{name}]",
250
+ f"n = {st.n}",
251
+ f"median = {_f(st.median)}",
252
+ f"scaled_mad = {_f(st.scaled_mad)}",
253
+ f"scale = {_f(st.scale)}",
254
+ f"scale_rule = {_s(st.scale_rule)}",
255
+ f"transform = {_s(st.transform)}",
256
+ *[f"p{p} = {_f(st.percentiles[p])}" for p in PERCENTILES if p in st.percentiles],
257
+ f"normal_lo = {_f(lo)} # informational: median +- k*scale at k = {k:g}",
258
+ f"normal_hi = {_f(hi)}",
259
+ "",
260
+ ]
261
+ return "\n".join(lines).rstrip("\n") + "\n", {"n_valid": len(valid), "notes": notes}
262
+
263
+
264
+ def split_head(path: Path) -> str | None:
265
+ """User part of an existing file (text above MARKER), None when absent or not ours."""
266
+ try:
267
+ text = path.read_text(encoding="utf-8")
268
+ except OSError:
269
+ return None
270
+ return text.split(MARKER)[0] if MARKER in text else None
File without changes
@@ -0,0 +1,41 @@
1
+ """Area limits shared by the geometric checks and the pipeline's true-resolution confirmation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ SPECKLE_MIN_AREA = 4 # px floor of the G002 limit
6
+
7
+
8
+ def speckle_limit(cfg, cls: int, area: float) -> float:
9
+ """Largest component area (px) of class `cls` counted as a speckle on a grid of `area` px."""
10
+ return max(SPECKLE_MIN_AREA, cfg.thresholds.for_class(cls, "speckle_max_area_frac") * area)
11
+
12
+
13
+ def hole_limit(cfg, cls: int, area: float) -> float:
14
+ """Largest hole area (px) that counts as a small hole on a grid of `area` px."""
15
+ return max(1.0, cfg.thresholds.for_class(cls, "small_hole_max_area_frac") * area)
16
+
17
+
18
+ def has_small_features(cfg, components, area: float) -> bool:
19
+ """True when any class has a speckle-sized component or a small hole (G002/G003 candidate)."""
20
+ for cls, comps in components.items():
21
+ if cls == cfg.background_index:
22
+ continue
23
+ s, h = speckle_limit(cfg, cls, area), hole_limit(cfg, cls, area)
24
+ for c in comps:
25
+ if c.area <= s or any(a <= h for a in c.hole_areas):
26
+ return True
27
+ return False
28
+
29
+
30
+ def small_view(record):
31
+ """(components, area, height, width) used for the speckle/hole checks G002 and G003 and their
32
+ relative measures: the true-resolution confirmation when the pipeline made one, else the
33
+ analysis grid."""
34
+ if record.fine_components is not None:
35
+ return record.fine_components, record.fine_area, record.height, record.width
36
+ return (
37
+ record.components,
38
+ record.grid_area,
39
+ record.comp_height or record.height,
40
+ record.comp_width or record.width,
41
+ )
@@ -0,0 +1,30 @@
1
+ """Robust statistics shared by the dataset-scope checks (median/MAD based)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ MAD_TO_SIGMA = 1.4826 # MAD -> standard deviation for normal data
8
+ MEAN_AD_TO_SIGMA = 1.2533 # mean absolute deviation -> standard deviation for normal data
9
+
10
+
11
+ def robust_z(values: np.ndarray) -> np.ndarray:
12
+ """Signed robust z-scores: (x - median) / (1.4826 * MAD).
13
+
14
+ When more than half of the values equal the median, MAD is 0. The scale then falls back to
15
+ the mean absolute deviation (so a handful of odd values in an otherwise constant set still
16
+ stand out, while a 40% minority does not). All zeros if the values do not vary at all.
17
+ """
18
+ x = np.asarray(values, dtype=np.float64)
19
+ if x.size == 0:
20
+ return x
21
+ dev = x - np.median(x)
22
+ mad = float(np.median(np.abs(dev)))
23
+ if mad > 0:
24
+ scale = MAD_TO_SIGMA * mad
25
+ else:
26
+ mean_ad = float(np.mean(np.abs(dev)))
27
+ if mean_ad == 0:
28
+ return np.zeros_like(x)
29
+ scale = MEAN_AD_TO_SIGMA * mean_ad
30
+ return dev / scale
seglint/checks/base.py ADDED
@@ -0,0 +1,174 @@
1
+ """Check interface and registry.
2
+
3
+ Writing a check::
4
+
5
+ from seglint.checks.base import BaseCheck, register
6
+ from seglint.models import Severity
7
+
8
+ @register
9
+ class S001(BaseCheck):
10
+ id = "S001"
11
+ default_severity = Severity.ERROR
12
+ run_on_incomplete = True # also run when image or mask is None/unreadable
13
+
14
+ def run_sample(self, ctx, sample, image, mask):
15
+ return [self.issue(sample, "image has no mask", score=1.0)]
16
+
17
+ `image` is HxWx3 uint8 RGB (or None), `mask` is HxW ints (HxWxC when the file is
18
+ multichannel and no palette is configured; or None). `ctx` is a `CheckContext`.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import importlib
24
+ from dataclasses import dataclass, field
25
+ from typing import Literal, Protocol
26
+
27
+ from seglint.config import Config
28
+ from seglint.models import Issue, Sample, SampleRecord, Severity
29
+
30
+ # Modules that may define checks; missing ones are skipped (they arrive phase by phase).
31
+ CHECK_MODULES = ("structural", "statistical", "geometric", "relative", "leakage", "alignment")
32
+
33
+
34
+ @dataclass
35
+ class CheckContext:
36
+ config: Config
37
+ # sample_id -> error message for files that failed to load (pipeline emits S004 itself)
38
+ load_errors: dict[str, str] = field(default_factory=dict)
39
+ cache: dict = field(default_factory=dict) # per-run scratch shared by the checks
40
+
41
+
42
+ class Check(Protocol):
43
+ id: str
44
+ default_severity: Severity
45
+ scope: Literal["sample", "dataset"]
46
+ experimental: bool
47
+ profile: bool
48
+ run_on_incomplete: bool
49
+
50
+ def run_sample(self, ctx: CheckContext, sample: Sample, image, mask) -> list[Issue]: ...
51
+
52
+ def run_dataset(self, ctx: CheckContext, records: list[SampleRecord]) -> list[Issue]: ...
53
+
54
+ def run_record(self, ctx: CheckContext, record: SampleRecord) -> list[Issue]: ...
55
+
56
+
57
+ class BaseCheck:
58
+ """Convenience base with defaults; subclass and override one of the run_* methods."""
59
+
60
+ id: str = ""
61
+ default_severity: Severity = Severity.WARNING
62
+ scope: Literal["sample", "dataset"] = "sample"
63
+ experimental: bool = False
64
+ # Profile checks describe the dataset (e.g. border contact, resolution spread) instead of
65
+ # judging mask quality: off by default, shown in the dataset profile, never in the budget.
66
+ profile: bool = False
67
+ run_on_incomplete: bool = False # run even if image/mask missing or unreadable
68
+
69
+ def run_sample(self, ctx: CheckContext, sample: Sample, image, mask) -> list[Issue]:
70
+ return []
71
+
72
+ def run_dataset(self, ctx: CheckContext, records: list[SampleRecord]) -> list[Issue]:
73
+ return []
74
+
75
+ def run_record(self, ctx: CheckContext, record: SampleRecord) -> list[Issue]:
76
+ """Per-sample check on the extracted features (no image/mask access). Pass 1, in the
77
+ worker, after the record is built; only called when the sample loaded completely."""
78
+ return []
79
+
80
+ def issue(
81
+ self,
82
+ sample: Sample | SampleRecord,
83
+ message: str,
84
+ score: float = 1.0,
85
+ severity: Severity | None = None,
86
+ **data,
87
+ ) -> Issue:
88
+ sid = sample.id if isinstance(sample, Sample) else sample.sample_id
89
+ return Issue(
90
+ self.id,
91
+ severity if severity is not None else self.default_severity,
92
+ sid,
93
+ sample.split,
94
+ message,
95
+ max(0.0, min(1.0, score)),
96
+ data,
97
+ )
98
+
99
+
100
+ _REGISTRY: dict[str, Check] = {}
101
+
102
+
103
+ def register(cls):
104
+ """Class decorator: instantiate and register a check under `cls.id`."""
105
+ inst = cls()
106
+ if not inst.id:
107
+ raise ValueError(f"{cls.__name__} has no id")
108
+ _REGISTRY[inst.id] = inst
109
+ return cls
110
+
111
+
112
+ def unregister(check_id: str) -> None:
113
+ _REGISTRY.pop(check_id, None)
114
+
115
+
116
+ def load_builtin_checks() -> None:
117
+ """Import seglint.checks.* modules so their @register decorators run."""
118
+ for name in CHECK_MODULES:
119
+ full = f"seglint.checks.{name}"
120
+ try:
121
+ importlib.import_module(full)
122
+ except ModuleNotFoundError as e:
123
+ if e.name != full:
124
+ raise
125
+
126
+
127
+ def checks_by_id(ids: list[str]) -> list[Check]:
128
+ """Registered checks with exactly these ids (used by worker processes)."""
129
+ load_builtin_checks()
130
+ missing = [i for i in ids if i not in _REGISTRY]
131
+ if missing:
132
+ raise KeyError(f"checks not registered in this process: {missing}")
133
+ return [_REGISTRY[i] for i in ids]
134
+
135
+
136
+ def _matches(check_id: str, patterns: set[str]) -> bool:
137
+ return any(check_id.startswith(p) for p in patterns)
138
+
139
+
140
+ def id_selected(check_id: str, select: list[str] | None, ignore: list[str] | None) -> bool:
141
+ """Whether `check_id` passes --select / --ignore filters."""
142
+ sel = {s.strip().upper() for s in select or [] if s.strip()}
143
+ ign = {s.strip().upper() for s in ignore or [] if s.strip()}
144
+ return (not sel or _matches(check_id, sel)) and not (ign and _matches(check_id, ign))
145
+
146
+
147
+ def get_checks(
148
+ select: list[str] | None = None,
149
+ ignore: list[str] | None = None,
150
+ experimental: bool = False,
151
+ include_profile: bool = False,
152
+ ) -> list[Check]:
153
+ """Registered checks filtered by --select / --ignore (exact id or prefix like "S").
154
+
155
+ Experimental checks need ``experimental``. Profile checks need ``include_profile`` or an
156
+ exact id in ``select`` (``--select G004``).
157
+ """
158
+ load_builtin_checks()
159
+ out = []
160
+ for cid in sorted(_REGISTRY):
161
+ c = _REGISTRY[cid]
162
+ if c.experimental and not experimental:
163
+ continue
164
+ if getattr(c, "profile", False) and not (include_profile or cid in (select or ())):
165
+ continue
166
+ if not id_selected(cid, select, ignore):
167
+ continue
168
+ out.append(c)
169
+ return out
170
+
171
+
172
+ def profile_check_ids() -> set[str]:
173
+ load_builtin_checks()
174
+ return {cid for cid, c in _REGISTRY.items() if getattr(c, "profile", False)}