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.
@@ -0,0 +1,306 @@
1
+ """Plain-language description of every check: the single source for the report's check table.
2
+
3
+ Each entry says what the check looks for, what a finding means, which settings change it
4
+ (`seglint.toml` keys, as `--explain-config` prints them) and its known weak spot. The weak spots
5
+ follow the "False-positive risk" lines of docs/checks.md; tests/test_report_ui.py checks that
6
+ every check id in docs/checks.md and in the registry has an entry here.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class CheckInfo:
16
+ name: str # short plain name, e.g. "Fragmented mask"
17
+ looks_for: str # what the check looks for
18
+ means: str # what a finding means for the user
19
+ settings: tuple[str, ...] # config keys that change it (as in --explain-config)
20
+ weakness: str # known false-alarm risk / weak spot
21
+ # "definite", "definite_warning" (T005/T006: only the WARNING level is definite),
22
+ # "uncertain", "hygiene", "profile", "notice" or "experimental"
23
+ kind: str
24
+
25
+
26
+ _T = "thresholds."
27
+
28
+ CHECK_INFO: dict[str, CheckInfo] = {
29
+ # --- structure (S) ------------------------------------------------------------------------
30
+ "S001": CheckInfo(
31
+ "Image without a mask",
32
+ "An image file with no mask of the same name.",
33
+ "This image cannot be used for training or evaluation until it gets a mask.",
34
+ ("mask_suffix",),
35
+ "Images left unlabelled on purpose, or a mask naming scheme seglint does not know "
36
+ "(set mask_suffix).",
37
+ "definite",
38
+ ),
39
+ "S002": CheckInfo(
40
+ "Mask without an image",
41
+ "A mask file with no image of the same name.",
42
+ "The mask is orphaned: its image is missing or named differently.",
43
+ ("mask_suffix",),
44
+ "Same naming caveat as S001; images stored outside the scanned folder.",
45
+ "definite",
46
+ ),
47
+ "S003": CheckInfo(
48
+ "Image and mask sizes differ",
49
+ "Image and mask with different pixel sizes.",
50
+ "The mask cannot line up with its image pixel for pixel.",
51
+ (),
52
+ "Datasets that store masks at a lower resolution on purpose are flagged on every sample.",
53
+ "definite",
54
+ ),
55
+ "S004": CheckInfo(
56
+ "Unreadable file",
57
+ "An image or mask that cannot be decoded.",
58
+ "The file is corrupt or in a format that cannot be read; the other checks skip it.",
59
+ (),
60
+ "Rare formats the image library does not support (some TIFF variants).",
61
+ "definite",
62
+ ),
63
+ "S005": CheckInfo(
64
+ "Unknown class value",
65
+ "Mask pixels whose value is not in the declared class list (nor the ignore index).",
66
+ "A label outside your class list: a typo in the labels, or an incomplete class list.",
67
+ ("classes", "ignore_index"),
68
+ "An incomplete classes list, or masks that store instance ids instead of classes. "
69
+ "A single stray pixel is enough.",
70
+ "definite",
71
+ ),
72
+ "S006": CheckInfo(
73
+ "Unexpected mask format",
74
+ "A mask that is not single-channel or palette-indexed (for example RGB).",
75
+ "Class ids may not be read correctly from this mask.",
76
+ (),
77
+ "Colour-coded masks that are intended; pass the palette with --palette.",
78
+ "definite",
79
+ ),
80
+ "S007": CheckInfo(
81
+ "Photo rotation may not match the mask",
82
+ "An image rotated by its EXIF tag (width and height swap) whose mask has the unrotated "
83
+ "size.",
84
+ "Depending on how your loader reads the image, the mask may be rotated against it.",
85
+ (),
86
+ "Pipelines that ignore EXIF for both image and mask are consistent, but still flagged.",
87
+ "definite",
88
+ ),
89
+ "S008": CheckInfo(
90
+ "Mask saved as JPEG",
91
+ "A mask stored in a lossy format (JPEG).",
92
+ "Compression changes pixel values near edges, so class ids are no longer exact.",
93
+ (),
94
+ "Very low: a JPEG mask is only harmless if its pixel values are never read as classes.",
95
+ "definite",
96
+ ),
97
+ # --- statistics (T) -----------------------------------------------------------------------
98
+ "T001": CheckInfo(
99
+ "Empty mask",
100
+ "A mask with no labelled object (only background or ignore pixels).",
101
+ "The object was not annotated, or the mask was not saved.",
102
+ ("allow_empty_masks", "background_index"),
103
+ "Datasets with intentional negative (empty) samples; set allow_empty_masks = true.",
104
+ "definite",
105
+ ),
106
+ "T002": CheckInfo(
107
+ "Missing or very rare class in a split",
108
+ "A class with no pixels, or very few pixels, in one split (or never seen at all).",
109
+ "A model trained or tested on this split barely sees the class.",
110
+ (_T + "rare_class_pixel_frac",),
111
+ "Classes that are rare by nature, and small splits that miss a class by chance.",
112
+ "uncertain",
113
+ ),
114
+ "T003": CheckInfo(
115
+ "Unusual image size",
116
+ "Images whose size or aspect ratio is far from the rest of the dataset.",
117
+ "Information about the dataset, not about mask quality.",
118
+ ("include_profile_checks", _T + "resolution_mad_z", _T + "resolution_min_rel_dev"),
119
+ "Datasets that mix resolutions on purpose. Off by default (dataset profile).",
120
+ "profile",
121
+ ),
122
+ "T004": CheckInfo(
123
+ "Class mix differs between splits",
124
+ "A split whose class proportions differ clearly from train.",
125
+ "Evaluation on this split may not reflect training conditions.",
126
+ (_T + "split_drift_z", _T + "split_drift_min_tv", _T + "min_split_samples"),
127
+ "Splits that are small or stratified differently on purpose (for example a test set from "
128
+ "another site).",
129
+ "uncertain",
130
+ ),
131
+ "T005": CheckInfo(
132
+ "Almost empty mask",
133
+ "A mask whose object covers a tiny share of the image.",
134
+ "Often a stray click or a truncated annotation instead of a real object.",
135
+ (_T + "near_empty_info_frac", _T + "near_empty_warn_frac"),
136
+ "Datasets of tiny objects (cells, stars, small defects). Only the WARNING level counts "
137
+ "as a definite defect.",
138
+ "definite_warning",
139
+ ),
140
+ "T006": CheckInfo(
141
+ "Mask covers (almost) the whole image",
142
+ "A mask whose object covers 95% or more of the image.",
143
+ "Often an inverted mask (background labelled as object) or a filled placeholder.",
144
+ (_T + "full_mask_info_frac", _T + "full_mask_warn_frac"),
145
+ "Close-ups where the object really fills the frame; datasets where class 0 is not "
146
+ "background. Only the WARNING level counts as a definite defect.",
147
+ "definite_warning",
148
+ ),
149
+ # --- geometry (G) -------------------------------------------------------------------------
150
+ "G001": CheckInfo(
151
+ "Fragmented mask",
152
+ "A class split into more separate parts than the limit (tiny specks not counted).",
153
+ "The annotation may be broken into pieces, or several objects were merged into one class.",
154
+ (_T + "max_components_per_class",),
155
+ "Datasets with many small instances per class (cells, crowds); raise the limit per class.",
156
+ "uncertain",
157
+ ),
158
+ "G002": CheckInfo(
159
+ "Speckles",
160
+ "Tiny isolated blobs of a class (a few pixels).",
161
+ "Usually brush noise left by the annotation tool.",
162
+ (_T + "speckle_max_area_frac", _T + "speckle_warn_count", _T + "relative_k_speckles"),
163
+ "Tiny objects that are real; a class whose only object is tiny is still reported.",
164
+ "uncertain",
165
+ ),
166
+ "G003": CheckInfo(
167
+ "Small holes",
168
+ "Small holes inside a class region.",
169
+ "Usually gaps the annotator's brush missed.",
170
+ (
171
+ _T + "small_hole_max_area_frac",
172
+ _T + "small_hole_warn_area_frac",
173
+ _T + "relative_k_holes",
174
+ ),
175
+ "Objects with real holes (rings) and the pockets of very detailed outlines. The 0.2% "
176
+ "WARNING floor was chosen on one dataset (ISIC) and is provisional.",
177
+ "uncertain",
178
+ ),
179
+ "G004": CheckInfo(
180
+ "Mask touches the image border",
181
+ "An object cut by the image edge.",
182
+ "Information about framing (the object may be cropped), not about mask quality.",
183
+ ("include_profile_checks",),
184
+ "High wherever objects are routinely cropped or fill the frame. Off by default (dataset "
185
+ "profile).",
186
+ "profile",
187
+ ),
188
+ "G005": CheckInfo(
189
+ "Jagged outline (experimental)",
190
+ "An outline much rougher than the rest of the dataset.",
191
+ "Possibly a careless or noisy annotation.",
192
+ ("experimental", _T + "jagged_mad_z"),
193
+ "Measured at chance level in the benchmark; experimental and off by default.",
194
+ "experimental",
195
+ ),
196
+ # --- relative to this dataset (R) ---------------------------------------------------------
197
+ "R000": CheckInfo(
198
+ "Relative checks skipped",
199
+ "A dataset with too few usable samples to define what is normal.",
200
+ "R001-R004 and the relative tiers of G002/G003 did not run. Not a defect.",
201
+ (_T + "min_relative_samples",),
202
+ "None; it is a notice.",
203
+ "notice",
204
+ ),
205
+ "R001": CheckInfo(
206
+ "Unusual object size for this dataset",
207
+ "A class area (share of the image) far from what is normal in this dataset.",
208
+ "The mask is much smaller or larger than the others: possibly truncated, a wrong class "
209
+ "or a wrong crop.",
210
+ (_T + "relative_k", _T + "relative_k_area_frac", _T + "relative_warn_factor"),
211
+ "Datasets whose object sizes vary a lot; there it stays quiet on purpose.",
212
+ "uncertain",
213
+ ),
214
+ "R002": CheckInfo(
215
+ "Unusual object position for this dataset",
216
+ "A class centre far from where this dataset normally puts it.",
217
+ "The mask may be shifted or placed on the wrong spot.",
218
+ (_T + "relative_k", _T + "relative_k_position", _T + "relative_warn_factor"),
219
+ "Off-centre objects that are correct, and datasets whose composition varies by design. "
220
+ "It cannot see the image, so it cannot tell which one it is.",
221
+ "uncertain",
222
+ ),
223
+ "R003": CheckInfo(
224
+ "Unusual shape for this dataset",
225
+ "A largest part far more concave or stretched than the rest of the dataset.",
226
+ "Possibly a bad polygon, or objects merged or cut.",
227
+ (_T + "relative_k", _T + "relative_k_shape", _T + "relative_warn_factor"),
228
+ "Datasets with legitimately varied shapes (vessels, roads, cracks).",
229
+ "uncertain",
230
+ ),
231
+ "R004": CheckInfo(
232
+ "Unusual number of objects for this dataset",
233
+ "Many more separate parts of a class than usual in this dataset.",
234
+ "Possibly a fragmented annotation or extra objects.",
235
+ (_T + "relative_k", _T + "relative_k_object_count", _T + "relative_warn_factor"),
236
+ "Datasets that mix single-object and multi-object images.",
237
+ "uncertain",
238
+ ),
239
+ # --- dataset hygiene (L) ------------------------------------------------------------------
240
+ "L001": CheckInfo(
241
+ "Identical image file",
242
+ "Image files that are byte-for-byte the same.",
243
+ "The same picture is in the dataset twice; across splits it leaks test data into training.",
244
+ (),
245
+ "Datasets that repeat images on purpose (augmented copies saved to disk).",
246
+ "hygiene",
247
+ ),
248
+ "L002": CheckInfo(
249
+ "Near-duplicate image in the same split",
250
+ "Images that look the same after resizing, re-encoding, brightness change, mirroring or "
251
+ "rotation, inside one split.",
252
+ "Repeated content; the model sees it more often than the rest.",
253
+ (
254
+ _T + "near_dup_hamming",
255
+ _T + "near_dup_dhash_hamming",
256
+ _T + "near_identical_hamming",
257
+ _T + "near_identical_dhash_hamming",
258
+ ),
259
+ "Augmented copies saved on purpose, and photos that are similar by nature. Cropped copies "
260
+ "are mostly missed.",
261
+ "hygiene",
262
+ ),
263
+ "L003": CheckInfo(
264
+ "Near-duplicate image across splits (leakage)",
265
+ "The same image (or a lightly changed copy) in two different splits.",
266
+ "Test or validation data leaks into training, so evaluation scores look better than they "
267
+ "are.",
268
+ (
269
+ _T + "near_dup_hamming",
270
+ _T + "near_dup_dhash_hamming",
271
+ _T + "near_identical_hamming",
272
+ _T + "near_identical_dhash_hamming",
273
+ ),
274
+ "Photos that are similar by nature can match at the 'similar' level. Cropped copies are "
275
+ "mostly missed.",
276
+ "hygiene",
277
+ ),
278
+ "L004": CheckInfo(
279
+ "Duplicate images with different masks",
280
+ "A duplicate pair whose two masks disagree (low overlap, IoU).",
281
+ "The same picture was annotated twice in different ways; at least one mask may be wrong.",
282
+ (_T + "mask_iou_warn", _T + "mask_iou_info"),
283
+ "Two annotators drawing the same object slightly differently; the IoU limits are "
284
+ "provisional.",
285
+ "uncertain",
286
+ ),
287
+ }
288
+
289
+ KIND_LABELS = {
290
+ "definite": "definite defect",
291
+ "definite_warning": "definite at WARNING, to review at INFO",
292
+ "uncertain": "to review",
293
+ "hygiene": "dataset hygiene",
294
+ "profile": "dataset profile",
295
+ "notice": "notice",
296
+ "experimental": "experimental",
297
+ }
298
+
299
+
300
+ def check_info(check_id: str) -> CheckInfo | None:
301
+ return CHECK_INFO.get(check_id)
302
+
303
+
304
+ def check_name(check_id: str) -> str:
305
+ info = CHECK_INFO.get(check_id)
306
+ return info.name if info else check_id
@@ -0,0 +1,309 @@
1
+ """Geometric checks G001-G005, computed from SampleRecord.components (no disk access).
2
+
3
+ Components are measured on the analysis grid (see Config.analysis_max_side), so every area limit
4
+ is relative to the grid area; the absolute floor of 4 px is in grid pixels. The background class
5
+ (Config.background_index) has no components and is not examined. Speckles (<= the G002 limit)
6
+ are excluded from G001, G004 and G005 so each check reports one phenomenon.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+
13
+ import numpy as np
14
+
15
+ from seglint.checks._limits import SPECKLE_MIN_AREA, hole_limit, small_view
16
+ from seglint.checks._limits import speckle_limit as _speckle_limit
17
+ from seglint.checks._robust import robust_z
18
+ from seglint.checks.base import BaseCheck, register
19
+ from seglint.checks.relative import describe, relative_findings, skip_notice
20
+ from seglint.models import Severity
21
+ from seglint.relative import skip_reason
22
+
23
+ __all__ = ["SPECKLE_MIN_AREA", "speckle_limit"]
24
+
25
+
26
+ def speckle_limit(cfg, record, cls: int) -> float:
27
+ """G002 limit on the record's analysis grid."""
28
+ return _speckle_limit(cfg, cls, record.grid_area)
29
+
30
+
31
+ _small_view = small_view
32
+
33
+
34
+ def _fg_components(cfg, record):
35
+ """(class, [components]) for non-background classes."""
36
+ for cls, comps in sorted(record.components.items()):
37
+ if cls != cfg.background_index:
38
+ yield cls, comps
39
+
40
+
41
+ class _RelativeTier:
42
+ """G002/G003: absolute floor plus a dataset-relative tier (scope: dataset).
43
+
44
+ `run_record` yields the candidates of the absolute rule (all tiers). `run_dataset` keeps the
45
+ WARNING candidates (the fixed floor: they stay WARNING whatever the dataset looks like) and
46
+ turns an INFO candidate into a finding only when its measure is extreme relative to this
47
+ dataset (median +- k * scaled MAD, shared mechanism of the R checks); otherwise it is dropped.
48
+ """
49
+
50
+ group = ""
51
+ scope = "dataset"
52
+
53
+ def run_dataset(self, ctx, records):
54
+ valid = [r for r in records if r.valid_labels]
55
+ if skip_reason(ctx.config, len(valid)):
56
+ out = skip_notice(ctx, len(valid))
57
+ relative = {}
58
+ else:
59
+ out, relative = [], relative_findings(ctx.config, valid, self.group)
60
+ for r in valid:
61
+ for issue in self.run_record(ctx, r):
62
+ if issue.severity >= Severity.WARNING:
63
+ out.append(issue)
64
+ continue
65
+ hit = relative.get((r.sample_id, issue.data["cls"]))
66
+ if hit is None:
67
+ continue
68
+ top = {k: v for k, v in hit[1][0].items() if k != "_warn_at"}
69
+ issue.message = describe(top, issue.data["cls"])
70
+ issue.data = {**issue.data, **top, "tier": "relative"}
71
+ out.append(issue)
72
+ return out
73
+
74
+
75
+ @register
76
+ class G001(BaseCheck):
77
+ id = "G001"
78
+ default_severity = Severity.WARNING
79
+
80
+ def run_record(self, ctx, record):
81
+ cfg, out = ctx.config, []
82
+ for cls, comps in _fg_components(cfg, record):
83
+ lim = speckle_limit(cfg, record, cls)
84
+ n = sum(1 for c in comps if c.area > lim)
85
+ cap = cfg.thresholds.for_class(cls, "max_components_per_class")
86
+ if n > cap:
87
+ out.append(
88
+ self.issue(
89
+ record,
90
+ f"class {cls} is split into {n} components (limit {cap}); "
91
+ "fragmented mask (suspicious)",
92
+ n / (2 * cap),
93
+ cls=cls,
94
+ n_components=n,
95
+ limit=cap,
96
+ threshold=cap,
97
+ )
98
+ )
99
+ return out
100
+
101
+
102
+ @register
103
+ class G002(_RelativeTier, BaseCheck):
104
+ """Absolute floor: WARNING from `speckle_warn_count` specks in a class. Below it a finding
105
+ (INFO) only when the speck count is extreme relative to this dataset (log1p scale,
106
+ `relative_k_speckles`)."""
107
+
108
+ group = "speckles"
109
+ id = "G002"
110
+ default_severity = Severity.WARNING
111
+
112
+ def run_record(self, ctx, record):
113
+ cfg, out = ctx.config, []
114
+ comps_by_cls, area, h, w = _small_view(record)
115
+ for cls, comps in sorted(comps_by_cls.items()):
116
+ if cls == cfg.background_index:
117
+ continue
118
+ lim = _speckle_limit(cfg, cls, area)
119
+ # a piece next to ignore pixels was cut off by the ignore band: not a speck
120
+ areas = sorted(c.area for c in comps if c.area <= lim and not c.touches_ignore)
121
+ if areas:
122
+ warn = cfg.thresholds.for_class(cls, "speckle_warn_count")
123
+ out.append(
124
+ self.issue(
125
+ record,
126
+ f"class {cls} has {len(areas)} tiny component(s) (<= {lim:.0f} px on the "
127
+ f"{w}x{h} grid); possible speckle noise (suspicious)",
128
+ len(areas) / (len(areas) + 3),
129
+ severity=Severity.WARNING if len(areas) >= warn else Severity.INFO,
130
+ cls=cls,
131
+ n_specks=len(areas),
132
+ areas=areas[:20],
133
+ limit=lim,
134
+ threshold=lim, # speck size limit (grid px)
135
+ warn_threshold=warn, # specks per class for WARNING
136
+ )
137
+ )
138
+ return out
139
+
140
+
141
+ HOLE_SCORE_LO = 1e-5 # hole_area_frac mapped to score 0 (about 3x below the smallest ISIC value)
142
+ HOLE_SCORE_HI = 1e-1 # ... to score 1 (3x above the largest ISIC value: not a small gap any more)
143
+
144
+
145
+ def hole_score(frac: float) -> float:
146
+ """G003 suspicion score: log10 of the small-hole area share, scaled to 0..1 over
147
+ [HOLE_SCORE_LO, HOLE_SCORE_HI]. Replaces n / (n + 3), which saturated at ~1.00 for any mask
148
+ with a few hundred ragged-boundary pockets."""
149
+ if frac <= HOLE_SCORE_LO:
150
+ return 0.0
151
+ return min(1.0, math.log10(frac / HOLE_SCORE_LO) / math.log10(HOLE_SCORE_HI / HOLE_SCORE_LO))
152
+
153
+
154
+ @register
155
+ class G003(_RelativeTier, BaseCheck):
156
+ """Absolute floor: WARNING when the small holes cover at least `small_hole_warn_area_frac` of
157
+ the class area (resolution independent). Below it a finding (INFO) only when the hole share
158
+ is extreme relative to this dataset (log scale, `relative_k_holes`). Raw measures stay in
159
+ `data`."""
160
+
161
+ group = "holes"
162
+ id = "G003"
163
+ default_severity = Severity.INFO
164
+
165
+ def run_record(self, ctx, record):
166
+ cfg, out = ctx.config, []
167
+ comps_by_cls, area, _, _ = _small_view(record)
168
+ for cls, comps in sorted(comps_by_cls.items()):
169
+ if cls == cfg.background_index:
170
+ continue
171
+ lim = hole_limit(cfg, cls, area)
172
+ small = sorted(a for c in comps for a in c.hole_areas if a <= lim)
173
+ if small:
174
+ warn = cfg.thresholds.for_class(cls, "small_hole_warn_area_frac")
175
+ class_area = sum(c.area for c in comps)
176
+ hole_area = sum(small)
177
+ frac = hole_area / class_area if class_area else 0.0
178
+ mpx = record.height * record.width / 1e6
179
+ out.append(
180
+ self.issue(
181
+ record,
182
+ f"class {cls} has {len(small)} small hole(s) (<= {lim:.0f} px); "
183
+ "possible annotation gaps (suspicious)",
184
+ hole_score(frac),
185
+ severity=Severity.WARNING if frac >= warn else Severity.INFO,
186
+ cls=cls,
187
+ n_holes=len(small),
188
+ hole_area_px=hole_area,
189
+ class_area_px=class_area,
190
+ hole_area_frac=frac, # the tier measure: small-hole area / class area
191
+ megapixels=mpx,
192
+ holes_per_mpx=len(small) / mpx if mpx else 0.0,
193
+ areas=small[:20],
194
+ limit=lim,
195
+ threshold=lim, # hole size limit (grid px)
196
+ warn_threshold=warn, # hole share of the class for WARNING
197
+ )
198
+ )
199
+ return out
200
+
201
+
202
+ def border_touch(cfg, record) -> tuple[dict[int, int], float]:
203
+ """Per class, how many non-speckle components touch the image border, and the largest share
204
+ of a touching component's outline that lies on the border (0..1)."""
205
+ gw, gh = record.comp_width or record.width, record.comp_height or record.height
206
+ touching: dict[int, int] = {}
207
+ worst = 0.0
208
+ for cls, comps in _fg_components(cfg, record):
209
+ lim = speckle_limit(cfg, record, cls)
210
+ for c in comps:
211
+ if c.area <= lim:
212
+ continue
213
+ x, y, w, h = c.bbox
214
+ if x == 0 or y == 0 or x + w >= gw or y + h >= gh:
215
+ touching[cls] = touching.get(cls, 0) + 1
216
+ if c.perimeter > 0:
217
+ worst = max(worst, c.border_perimeter / c.perimeter)
218
+ return touching, worst
219
+
220
+
221
+ @register
222
+ class G004(BaseCheck):
223
+ """Border contact. A PROFILE check: off by default (see docs/checks.md, "Dataset profile");
224
+ border contact is reported as a dataset-profile fact instead."""
225
+
226
+ id = "G004"
227
+ default_severity = Severity.INFO
228
+ profile = True
229
+
230
+ def run_record(self, ctx, record):
231
+ touching, worst = border_touch(ctx.config, record)
232
+ if not touching:
233
+ return []
234
+ return [
235
+ self.issue(
236
+ record,
237
+ f"mask touches the image border (classes {sorted(touching)}); the object may be "
238
+ "cropped (suspicious, often harmless)",
239
+ worst,
240
+ classes=sorted(touching),
241
+ n_components=sum(touching.values()),
242
+ )
243
+ ]
244
+
245
+
246
+ @register
247
+ class G005(BaseCheck):
248
+ """Jagged boundary. EXPERIMENTAL, off by default: in the controlled perturbation benchmark
249
+ (smooth, hole-free boundary roughening) it scored at chance level: AUROC 0.49-0.53 in the
250
+ "rough boundary v2" run and 0.48-0.52 in the final benchmark with G005 on (docs/benchmarks.md,
251
+ "Which run each G005 AUROC range comes from")."""
252
+
253
+ id = "G005"
254
+ default_severity = Severity.WARNING
255
+ scope = "dataset"
256
+ experimental = True
257
+
258
+ def run_dataset(self, ctx, records):
259
+ cfg = ctx.config
260
+ per_class: dict[int, list[tuple[object, float]]] = {}
261
+ for r in records:
262
+ if not r.valid_labels:
263
+ continue
264
+ for cls, comps in _fg_components(cfg, r):
265
+ if not comps:
266
+ continue
267
+ # only the largest component per class: a fragment's perimeter/sqrt(area) says
268
+ # "fragmented" (G001/G002), not "ragged outline"
269
+ c = max(comps, key=lambda k: k.area)
270
+ if c.area > speckle_limit(cfg, r, cls) and c.perimeter > 0:
271
+ per_class.setdefault(cls, []).append((r, c.perimeter / math.sqrt(c.area)))
272
+ out = []
273
+ for cls, items in sorted(per_class.items()):
274
+ if len(items) < MIN_COMPONENTS:
275
+ continue
276
+ ratios = np.array([v for _, v in items])
277
+ z = robust_z(ratios)
278
+ thr = cfg.thresholds.for_class(cls, "jagged_mad_z")
279
+ med = float(np.median(ratios))
280
+ worst: dict[str, int] = {}
281
+ for i in np.flatnonzero(z > thr):
282
+ sid = items[int(i)][0].sample_id
283
+ if sid not in worst or z[i] > z[worst[sid]]:
284
+ worst[sid] = int(i)
285
+ for i in (worst[k] for k in sorted(worst)):
286
+ rec = items[i][0]
287
+ out.append(
288
+ self.issue(
289
+ rec,
290
+ f"class {cls} boundary is extreme relative to this dataset (jagged): "
291
+ f"perimeter/sqrt(area) = {ratios[i]:.2f} vs class median {med:.2f} "
292
+ f"(robust z {z[i]:.1f}) (unusual for this dataset)",
293
+ float(z[i]) / (2 * thr),
294
+ cls=cls,
295
+ ratio=float(ratios[i]),
296
+ class_median=med,
297
+ robust_z=float(z[i]),
298
+ # same fields as the R checks (the threshold here is robust z > k)
299
+ measure="roughness",
300
+ value=float(ratios[i]),
301
+ median=med,
302
+ k=thr,
303
+ stats_source="class",
304
+ )
305
+ )
306
+ return out
307
+
308
+
309
+ MIN_COMPONENTS = 20 # fewer components per class: the median/MAD estimate is not meaningful