#!/usr/bin/env python """referee_fold — spatial thread-counting referee (fold/peak-count v2). Decides which integer multiple k of the counter's raw reading f_raw is the true thread frequency, by DIRECTLY counting thread crests in the spatial domain: * strips perpendicular to the counting axis (skew-tolerant, keeps local structure that a whole-crop average washes out) * per strip: detrend, smooth to the finest plausible thread scale, detect peaks (bright yarns) AND valleys (dark inter-yarn gaps) with adaptive prominence; rate = peaks per inch, counted not inferred from spacing (robust to uneven pair spacing) * channel estimates vote; a phase-fold mode count confirms; a yarn-width (peak FWHM) physical bound vetoes impossible densities. Abstains unless the evidence for k>1 is clear. Interface shared by all referees: score_k(crop, px_per_inch, f_raw, axis, kmax=4) -> {'best_k', 'abstain', 'confidence', 'scores', 'diag'} """ import numpy as np from scipy import ndimage, signal STRIP_PX = 16 # strip thickness (perpendicular to counting axis) MIN_PERIODS = 6 # need at least this many raw periods along the axis PROMOTE_AT = 1.30 # min(channel ratios) >= this proves k >= 2 (controls <= 1.11) CONT_MIN = 0.50 # strip-to-strip crest persistence needed to trust crests WIDTH_SLACK = 1.20 # threads/inch may exceed 1/width by at most this factor # v3 semantics: spatial peak counting SATURATES on tight pairs / dense goods # (measured: k=2 pair cases resolve to only 1.34-1.56x f_raw; dense controls # under-count at 0.52-0.79x). So the referee is ONE-SIDED: # ratio >= PROMOTE_AT -> k >= 2 is PROVEN (some pairs split; count can only # under-estimate, never over-estimate at these gates) # ratio ~ 1 or < 1 -> NO information (merged pairs and correct reads look # identical) -> best_k=1 is non-binding, never a veto. def _strip_profiles(crop, axis): """Yield 1-D profiles along the counting axis, one per strip.""" a = crop if axis == "epi" else crop.T # periodicity along columns H, W = a.shape for y0 in range(0, H - STRIP_PX + 1, STRIP_PX): yield a[y0:y0 + STRIP_PX].mean(axis=0) def _channel_rate(prof, P_raw, px_per_inch, invert): """Count crests (or valleys) in one strip profile. Returns (n, length_px, widths_px, coherence) or None if the strip is unusable. coherence = how periodically the detected peaks repeat at the raw period P_raw (max over harmonics m=1..4 of the circular moment |mean(exp(2pi*i*m*phase))|): real thread/pair crests are period-locked (high), intra-yarn slub texture is aperiodic (low).""" p = -prof if invert else prof # detrend at ~1.5 raw periods; smooth to finest plausible thread scale p = p - ndimage.gaussian_filter1d(p, max(3.0, 1.5 * P_raw)) p = ndimage.gaussian_filter1d(p, max(1.0, P_raw / 24.0)) s = float(p.std()) if s <= 1e-9: return None dist = max(2, int(round(P_raw / 6.0))) # finest sep ~ P/6 (k=4 + slack) pk, props = signal.find_peaks(p, distance=dist, prominence=0.55 * s) if len(pk) < 3: return None widths = signal.peak_widths(p, pk, rel_height=0.5)[0] return len(pk), len(p), widths, pk def _continuity(peak_lists, tol): """A true thread is a continuous line: its crest position persists from one strip to the next. Local slub/texture blobs do not. Score = mean fraction of peaks in strip s that have a peak within tol px in strip s+1.""" fr = [] for a, b in zip(peak_lists[:-1], peak_lists[1:]): if len(a) == 0 or len(b) == 0: continue d = np.min(np.abs(a[:, None] - b[None, :]), axis=1) fr.append(float(np.mean(d <= tol))) return float(np.median(fr)) if fr else 0.0 def _fold_modes(profiles, P, nbins=48): """Phase-fold all strip profiles at period P; count modes in the folded mean (confirmation channel). Returns (n_modes, mode_strength).""" acc = np.zeros(nbins) wts = np.zeros(nbins) for prof in profiles: p = prof - ndimage.gaussian_filter1d(prof, max(3.0, 1.5 * P)) x = np.arange(len(p)) b = np.minimum(((x / P) % 1.0 * nbins).astype(int), nbins - 1) acc += np.bincount(b, weights=p, minlength=nbins) wts += np.bincount(b, minlength=nbins) folded = acc / np.maximum(wts, 1) folded -= folded.mean() fs = ndimage.gaussian_filter1d(np.tile(folded, 3), 1.2)[nbins:2 * nbins] rng = float(fs.max() - fs.min()) if rng <= 1e-9: return 1, 0.0 ext = np.tile(fs, 3) pk, props = signal.find_peaks(ext, prominence=0.30 * rng) pk = pk[(pk >= nbins) & (pk < 2 * nbins)] strength = float(np.median(props["prominences"])) / rng if len(pk) else 0.0 return max(1, len(pk)), strength def score_k(crop, px_per_inch, f_raw, axis, kmax=4): diag = {} f_raw = float(f_raw) if not np.isfinite(f_raw) or f_raw <= 0: return {"best_k": 1, "abstain": True, "confidence": 0.0, "scores": {}, "diag": {"why": "bad_f_raw"}} P_raw = px_per_inch / f_raw # raw period in px profiles = list(_strip_profiles(crop, axis)) if not profiles or len(profiles[0]) < MIN_PERIODS * P_raw: return {"best_k": 1, "abstain": True, "confidence": 0.0, "scores": {}, "diag": {"why": "too_few_periods"}} # --- channel A: bright crests; channel B: dark valleys ----------------- votes = {} for name, invert in (("peaks", False), ("valleys", True)): counts, length, widths, plists = 0, 0, [], [] used = 0 for prof in profiles: r = _channel_rate(prof, P_raw, px_per_inch, invert) if r is None: continue c, l, w, pk = r counts += c; length += l; widths.extend(w) plists.append(np.asarray(pk, float)) used += 1 if used < 3 or length == 0: continue rate = counts / (length / px_per_inch) # threads/inch ratio = rate / f_raw k_hat = int(round(ratio)) ok = 1 <= k_hat <= kmax and abs(ratio - k_hat) <= 0.30 # diag only med_w = float(np.median(widths)) if widths else float("nan") cont = _continuity(plists, tol=max(2.0, P_raw / 10.0)) votes[name] = {"rate": round(rate, 1), "ratio": round(ratio, 2), "k": k_hat if ok else None, "n_strips": used, "yarn_px": round(med_w, 1), "cont": round(cont, 2)} diag["channels"] = votes # --- confirmation: fold-mode count at the raw period -------------------- n_modes, strength = _fold_modes(profiles, P_raw) diag["fold_modes"] = n_modes diag["fold_strength"] = round(strength, 3) # --- combine (v3: one-sided lower-bound promotion) ----------------------- ratios = [v["ratio"] for v in votes.values()] if len(ratios) < 2: return {"best_k": 1, "abstain": True, "confidence": 0.0, "scores": {}, "diag": {**diag, "why": "lt2_channels"}} r_min = min(ratios) diag["r_min"] = round(r_min, 2) if r_min < PROMOTE_AT: # no promotion evidence; k=1 is NON-BINDING (saturation indistinguishable # from a correct read) -> abstain so other referees decide freely. return {"best_k": 1, "abstain": True, "confidence": 0.0, "scores": {1: 0.0}, "diag": {**diag, "why": "no_promotion_evidence"}} # continuity guard: real threads are continuous lines whose crest positions # persist across strips; intra-yarn slub texture is local blobs that do not. cont_min = min(v.get("cont", 0.0) for v in votes.values()) if cont_min < CONT_MIN: return {"best_k": 1, "abstain": True, "confidence": 0.0, "scores": {}, "diag": {**diag, "why": "low_continuity"}} # promotion proven: choose the smallest k consistent with the (lower-bound) # measured rate; exact-resolution case maps ratio -> nearest integer. if r_min >= 3.4: k_best = 4 elif r_min >= 2.5: k_best = 3 else: k_best = 2 lower_bound = abs(r_min - k_best) > 0.25 # saturated: true k may be higher # yarn-width physical veto on the promoted density (thinnest detected yarn) widths = [v["yarn_px"] for v in votes.values() if np.isfinite(v.get("yarn_px", np.nan))] if widths: max_density = WIDTH_SLACK * px_per_inch / max(min(widths), 1e-9) diag["max_density"] = round(max_density, 1) if k_best * f_raw > max_density: return {"best_k": 1, "abstain": True, "confidence": 0.0, "scores": {}, "diag": {**diag, "why": "width_veto"}} conf = round(min(1.0, 0.5 + (r_min - PROMOTE_AT)), 2) return {"best_k": int(k_best), "abstain": False, "confidence": conf, "lower_bound": bool(lower_bound), "scores": {int(k_best): 1.0}, "diag": diag} # --------------------------------------------------------------------------- #