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/relative.py ADDED
@@ -0,0 +1,274 @@
1
+ """Dataset-relative statistics for the R checks (reusable, e.g. by `seglint calibrate`).
2
+
3
+ A measure is judged against the robust distribution of the same measure over the dataset:
4
+ median and scaled MAD (1.4826 * MAD) of the (optionally log-transformed) values. The normal range
5
+ is `median +- k * scale` in the transformed space, mapped back to the measure's own unit.
6
+
7
+ Scale rule (never divides by zero):
8
+ 1. scaled MAD when it is > 0;
9
+ 2. else (more than half of the values equal the median) 1.2533 * mean absolute deviation, so a few
10
+ odd values in an otherwise constant set still stand out;
11
+ 3. the result is never below `min_scale` (an effect-size floor per transform, from the config):
12
+ values within a factor ~exp(k * min_scale) of the median are never "extreme", however tight the
13
+ rest of the dataset is. When all values are identical, the floor alone defines the range.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+ from collections.abc import Callable, Sequence
20
+ from dataclasses import dataclass, field, replace
21
+
22
+ import numpy as np
23
+
24
+ from seglint.checks._limits import hole_limit, small_view, speckle_limit
25
+ from seglint.checks._robust import MAD_TO_SIGMA, MEAN_AD_TO_SIGMA
26
+ from seglint.models import SampleRecord
27
+
28
+ PERCENTILES = (1, 5, 25, 50, 75, 95, 99)
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class MeasureSpec:
33
+ name: str # key in stats / Issue.data["measure"]
34
+ group: str # check family: area_frac | position | shape | object_count
35
+ attr: str # ClassFeatures attribute
36
+ transform: str # "identity" | "log" | "log1p" | "logit"
37
+ side: str # which tail is "extreme": "both" | "low" | "high"
38
+ label: str # human readable
39
+ # optional (record, cfg) -> {class id: value}; replaces the ClassFeatures lookup (G002/G003)
40
+ getter: Callable | None = None
41
+
42
+
43
+ HOLE_FLOOR = 1e-6 # hole share of a class without small holes (zero cannot be log-transformed);
44
+ # about 3x below the smallest hole share seen on ISIC (docs/checks.md, G003 score)
45
+
46
+
47
+ def _hole_shares(r: SampleRecord, cfg) -> dict[int, float]:
48
+ """class -> small-hole area / class area for every foreground class present (G003 rule)."""
49
+ comps_by_cls, area, _, _ = small_view(r)
50
+ out = {}
51
+ for cls, comps in comps_by_cls.items():
52
+ if cls == cfg.background_index or not comps:
53
+ continue
54
+ lim = hole_limit(cfg, cls, area)
55
+ small = sum(a for c in comps for a in c.hole_areas if a <= lim)
56
+ class_area = sum(c.area for c in comps)
57
+ out[cls] = max(HOLE_FLOOR, small / class_area) if class_area else HOLE_FLOOR
58
+ return out
59
+
60
+
61
+ def _speck_counts(r: SampleRecord, cfg) -> dict[int, float]:
62
+ """class -> number of speckle components for every foreground class present (G002 rule)."""
63
+ comps_by_cls, area, _, _ = small_view(r)
64
+
65
+ def specks(cls, comps):
66
+ lim = speckle_limit(cfg, cls, area)
67
+ return float(sum(1 for c in comps if c.area <= lim and not c.touches_ignore))
68
+
69
+ return {
70
+ cls: specks(cls, comps)
71
+ for cls, comps in comps_by_cls.items()
72
+ if cls != cfg.background_index and comps
73
+ }
74
+
75
+
76
+ MEASURES: dict[str, MeasureSpec] = {
77
+ m.name: m
78
+ for m in (
79
+ MeasureSpec("area_frac", "area_frac", "area_frac", "logit", "both", "area fraction"),
80
+ MeasureSpec("centroid_x", "position", "cx", "identity", "both", "centroid x"),
81
+ MeasureSpec("centroid_y", "position", "cy", "identity", "both", "centroid y"),
82
+ MeasureSpec("solidity", "shape", "solidity", "identity", "low", "solidity"),
83
+ MeasureSpec("elongation", "shape", "elongation", "log", "both", "elongation"),
84
+ MeasureSpec("object_count", "object_count", "n_objects", "log", "both", "object count"),
85
+ MeasureSpec("hole_share", "holes", "", "log", "high", "small-hole share", _hole_shares),
86
+ MeasureSpec("speck_count", "speckles", "", "log1p", "high", "speckle count", _speck_counts),
87
+ )
88
+ }
89
+
90
+
91
+ @dataclass(frozen=True)
92
+ class RobustStats:
93
+ """Robust summary of one measure. `median` and `percentiles` are in the measure's own unit;
94
+ `scaled_mad` (raw 1.4826 * MAD, may be 0) and `scale` (effective, after the rule above) are in
95
+ the transformed space."""
96
+
97
+ n: int
98
+ median: float
99
+ scaled_mad: float
100
+ scale: float
101
+ scale_rule: str # "mad" | "mean_ad" | "floor"
102
+ transform: str
103
+ percentiles: dict[int, float] = field(default_factory=dict) # p1..p99, own unit
104
+ source: str = "class" # "class" | "global" | "global_fallback"
105
+
106
+ def center(self) -> float:
107
+ """Median in the transformed space."""
108
+ return float(_fwd(np.array([self.median]), self.transform)[0])
109
+
110
+
111
+ # logit: shares in [0, 1] are clipped to [LOGIT_EPS, 1 - LOGIT_EPS] before log(p / (1 - p)), so
112
+ # 0 and 1 stay finite; the inverse maps any value back into (0, 1).
113
+ LOGIT_EPS = 1e-4
114
+
115
+
116
+ def _fwd(x: np.ndarray, transform: str) -> np.ndarray:
117
+ if transform == "log1p":
118
+ return np.log1p(np.maximum(x, 0.0))
119
+ if transform == "logit":
120
+ p = np.clip(x, LOGIT_EPS, 1.0 - LOGIT_EPS)
121
+ return np.log(p / (1.0 - p))
122
+ return np.log(np.maximum(x, 1e-12)) if transform == "log" else x
123
+
124
+
125
+ def _inv(t: float, transform: str) -> float:
126
+ if transform == "log1p":
127
+ return math.expm1(t)
128
+ if transform == "logit": # numerically stable sigmoid
129
+ if t >= 0:
130
+ return 1.0 / (1.0 + math.exp(-t))
131
+ e = math.exp(t)
132
+ return e / (1.0 + e)
133
+ return math.exp(t) if transform == "log" else t
134
+
135
+
136
+ def robust_stats(
137
+ values: Sequence[float] | np.ndarray,
138
+ transform: str = "identity",
139
+ min_scale: float = 0.0,
140
+ source: str = "class",
141
+ ) -> RobustStats | None:
142
+ """Median / scaled MAD / percentiles of `values`; None for an empty input. `transform` is
143
+ "identity", "log", "log1p" or "logit"."""
144
+ x = np.asarray(values, dtype=np.float64)
145
+ if x.size == 0:
146
+ return None
147
+ t = _fwd(x, transform)
148
+ med_t = float(np.median(t))
149
+ dev = np.abs(t - med_t)
150
+ smad = MAD_TO_SIGMA * float(np.median(dev))
151
+ if smad > 0:
152
+ scale, rule = smad, "mad"
153
+ else:
154
+ scale, rule = MEAN_AD_TO_SIGMA * float(np.mean(dev)), "mean_ad"
155
+ if scale < min_scale or scale <= 0:
156
+ scale, rule = max(min_scale, 1e-12), "floor"
157
+ pct = {p: float(np.percentile(x, p)) for p in PERCENTILES}
158
+ median = _inv(med_t, transform)
159
+ return RobustStats(int(x.size), median, smad, scale, rule, transform, pct, source)
160
+
161
+
162
+ def normal_range(stats: RobustStats, k: float) -> tuple[float, float]:
163
+ """[lo, hi] in the measure's own unit: median +- k * scale in the transformed space."""
164
+ c = stats.center()
165
+ lo, hi = c - k * stats.scale, c + k * stats.scale
166
+ return _inv(lo, stats.transform), _inv(hi, stats.transform)
167
+
168
+
169
+ def deviation(stats: RobustStats, value: float) -> float:
170
+ """Signed distance of `value` from the median in units of `scale` (transformed space)."""
171
+ v = float(_fwd(np.array([value]), stats.transform)[0])
172
+ return (v - stats.center()) / stats.scale
173
+
174
+
175
+ def min_scale_for(cfg, spec: MeasureSpec) -> float:
176
+ th = cfg.thresholds
177
+ # logit behaves like log for small shares, so it shares the log floor
178
+ log_like = spec.transform in ("log", "log1p", "logit")
179
+ return th.relative_min_scale_log if log_like else th.relative_min_scale_unit
180
+
181
+
182
+ def k_for(cfg, spec: MeasureSpec, cls: int | None = None) -> float:
183
+ """k of a measure: per-check override (`relative_k_<group>`), else `relative_k`; both can be
184
+ overridden per class through `thresholds.per_class`."""
185
+ th = cfg.thresholds
186
+ name = f"relative_k_{spec.group}"
187
+ own = th.for_class(cls, name) if cls is not None else getattr(th, name)
188
+ if own:
189
+ return float(own)
190
+ return float(th.for_class(cls, "relative_k") if cls is not None else th.relative_k)
191
+
192
+
193
+ def collect_values(
194
+ records: Sequence[SampleRecord], measure: str, cfg=None
195
+ ) -> dict[int, list[tuple[SampleRecord, float]]]:
196
+ """class id -> [(record, value)] of a measure over foreground classes with a value.
197
+ `cfg` is needed for the measures that have a getter (hole_share, speck_count)."""
198
+ spec = MEASURES[measure]
199
+ out: dict[int, list[tuple[SampleRecord, float]]] = {}
200
+ for r in records:
201
+ if not r.valid_labels:
202
+ continue
203
+ if spec.getter is not None:
204
+ for cls, v in spec.getter(r, cfg).items():
205
+ out.setdefault(cls, []).append((r, float(v)))
206
+ continue
207
+ for cls, f in r.class_features.items():
208
+ v = getattr(f, spec.attr)
209
+ if v is not None and (spec.attr != "n_objects" or v > 0):
210
+ out.setdefault(cls, []).append((r, float(v)))
211
+ return out
212
+
213
+
214
+ def measure_stats(
215
+ records: Sequence[SampleRecord], cfg, measure: str
216
+ ) -> dict[int | None, RobustStats]:
217
+ """Statistics a check uses for one measure: {class id: stats, None: global}.
218
+
219
+ A class with fewer than `min_class_samples` values gets the global (all-class) statistics with
220
+ source "global_fallback"; the global entry (key None) exists when it has at least
221
+ `min_class_samples` values (otherwise the dict is empty: not enough data to judge).
222
+ """
223
+ spec = MEASURES[measure]
224
+ th = cfg.thresholds
225
+ ms = min_scale_for(cfg, spec)
226
+ by_cls = collect_values(records, measure, cfg)
227
+ ref = getattr(cfg, "reference", None)
228
+ if ref is not None: # frozen statistics of a calibration run replace the scanned dataset's
229
+ rs = ref.stats.get(measure, {})
230
+ if None not in rs:
231
+ return {}
232
+ out_ref: dict[int | None, RobustStats] = {None: rs[None]}
233
+ fb = replace(rs[None], source="global_fallback")
234
+ for cls in by_cls:
235
+ out_ref[cls] = rs.get(cls, fb)
236
+ return out_ref
237
+ pooled = [v for items in by_cls.values() for _, v in items]
238
+ glob = robust_stats(pooled, spec.transform, ms, "global")
239
+ if glob is None or glob.n < th.min_class_samples:
240
+ return {}
241
+ out: dict[int | None, RobustStats] = {None: glob}
242
+ fallback = robust_stats(pooled, spec.transform, ms, "global_fallback")
243
+ for cls, items in by_cls.items():
244
+ if len(items) >= th.min_class_samples:
245
+ out[cls] = robust_stats([v for _, v in items], spec.transform, ms, "class")
246
+ else:
247
+ out[cls] = fallback
248
+ return out
249
+
250
+
251
+ def skip_reason(cfg, n_valid: int) -> str | None:
252
+ """Why relative checks cannot run (None: they can). With a calibrated reference the size of
253
+ the reference set counts, not the size of the scanned batch."""
254
+ need = cfg.thresholds.min_relative_samples
255
+ ref = getattr(cfg, "reference", None)
256
+ if ref is not None:
257
+ if ref.n_samples < need:
258
+ return (
259
+ f"the calibrated reference has only {ref.n_samples} samples with usable masks, "
260
+ f"at least {need} are needed for dataset statistics (min_relative_samples); "
261
+ "re-run `seglint calibrate` on a larger dataset"
262
+ )
263
+ return None
264
+ if n_valid < need:
265
+ return (
266
+ f"{n_valid} samples with usable masks, at least {need} are needed for dataset "
267
+ "statistics (min_relative_samples)"
268
+ )
269
+ return None
270
+
271
+
272
+ def dataset_stats(records: Sequence[SampleRecord], cfg) -> dict[str, dict[int | None, RobustStats]]:
273
+ """measure name -> measure_stats(...) for every measure (what `seglint calibrate` needs)."""
274
+ return {m: measure_stats(records, cfg, m) for m in MEASURES}
File without changes