Spaces:
Sleeping

fabric-api / classfix_combined.py
Akshit Beniwal (qris-uq)
Deploy fabric analyzer API
d47fb92
Raw History Blame Contribute Delete
12.9 kB
"""
classfix_combined.py
====================
COMBINED selective dense-warp EPI corrector for the fabric thread counter.
It synthesises the five independent classical correctors that were each measured
on hardwarp_eval.npz:
classfix_harmonic_comb.py (HPS harmonic-comb period disambiguation)
classfix_motif_removal.py (float-motif removal + spatial thread count)
classfix_autocorr_cepstrum.py(block-averaged periodogram comb / ACF)
classfix_gradient_edge.py (X-gradient edge-density spectrum)
classfix_local_bandpass.py (band-limited harmonic promotion, px/thread gate)
WHY A COMBINATION
-----------------
The production FFT counter (epi_ppi_v5) sub-harmonic-locks on dense mixed-yarn
DOBBY/SATIN *warp* EPI cases: the float / yarn-colour MOTIF injects a strong low
frequency and the FFT locks onto a clean sub-multiple of the true thread comb, so
the truth period is an INTEGER MULTIPLE k of the FFT period (k = 2,3,4) for the
recoverable hard cases. Every individual corrector therefore reduces to two
decisions: (1) DOES this image have a sub-harmonic lock? and (2) WHICH integer
multiple k of the FFT period is the true thread comb?
Measured on the 21-image shared set, the five methods are UNANIMOUS on decision
(1): all five defer (k = 1) on every one of the 14 easy/borderline cases and on
id42 (a non-integer ~1.2x over-count, not a sub-harmonic lock) and id52 (FFT
already correct). They DISAGREE only on decision (2) -- the multiple k -- for the
five recoverable hard cases (44,46,48,49,50), and no single method gets all five
right (e.g. harmonic_comb picks k=3 for id49 truth k=4 and k=2 for id50 truth k=3;
local_bandpass picks k=2 for id48 truth k=3). But the MAJORITY VOTE over the
methods' chosen k is correct on ALL FIVE:
id true k votes (firing methods) majority
44 2 [2,2,2,2,2] 2 OK
46 2 [2,2,2,2] (gradient defers) 2 OK
48 3 [3,3,3,3,2] 3 OK
49 4 [3,4,4,4] (gradient defers) 4 OK
50 3 [2,3,3,3] (gradient defers->3) 3 OK
So the combined corrector is a DETECTOR-CASCADE + PERIOD-VOTE ENSEMBLE:
CASCADE GATE : fire only if at least MIN_FIRE of the five base correctors
independently declare a lock for this image. (Measured: the 14
easy/borderline + id42 + id52 get ZERO fires, so the gate never
opens on them -> zero regressions, structurally guaranteed.)
PERIOD VOTE : among the firing methods, take the MAJORITY of the chosen integer
multiple k (ties broken toward the FINER / higher k, since a
motif lock can only make the FFT too COARSE, never too fine).
REFINE : once k is fixed, compute a precise sub-pixel warp period by a
multi-resolution harmonic-product-style (HPS) comb search around
k * fft_freq (re-using the harmonic_comb refinement, which gave
the tightest within-+-2 reads), and return EPI = ppi / period.
PPI (weft) is already accurate from the FFT counter and is passed through
unchanged (count_ppi), exactly as in the base correctors.
PUBLIC API
----------
correct_epi(crop, px_per_inch, fft_epi, weave=None) -> dict
count_ppi(crop, px_per_inch, fft_ppi) -> float
"""
from __future__ import annotations
import os
from collections import Counter
import numpy as np
# Import the five base correctors as the ensemble members. They live in the same
# tmp/ directory as this file.
import classfix_harmonic_comb as HC
import classfix_motif_removal as MR
import classfix_autocorr_cepstrum as AC
import classfix_gradient_edge as GE
import classfix_local_bandpass as LB
# --------------------------------------------------------------------------- #
# Tuning (deliberately coarse / robust, NOT knife-edge fit to 7 points).
# --------------------------------------------------------------------------- #
MIN_FIRE = 2 # >= this many base methods must declare a lock to fire.
# The 14 easy + id42 + id52 get 0 fires, so any value >=1
# gives zero regressions; 2 adds robustness margin.
EPI_LO = 55.0 # plausible warp EPI band (defensive bound on the result)
EPI_HI = 200.0
PPTH_LO = 9.0 # plausible thread resolution band (px/thread) for the
PPTH_HI = 22.0 # refined result (real fabric here is ~10-20 px/thread).
# --------------------------------------------------------------------------- #
# Helpers: poll each base method for (fired, chosen_k).
# --------------------------------------------------------------------------- #
def _poll_members(crop, ppi, fe, weave):
"""Run all five base correctors; return a list of (name, fired, k) where k is
the integer multiple of the FFT period each method chose (1 == deferred)."""
out = []
# 1) harmonic comb (HPS)
try:
r = HC.correct_epi(crop, ppi, fe)
out.append(("comb", (not r["used_fft"]), int(r["N"]) if not r["used_fft"] else 1))
except Exception:
out.append(("comb", False, 1))
# 2) motif removal + spatial count
try:
r = MR.correct_epi(crop, ppi, fe)
fired = r["used"] == "corrected"
out.append(("motif", fired, int(r["k"]) if fired else 1))
except Exception:
out.append(("motif", False, 1))
# 3) autocorr / block periodogram comb
try:
_, info = AC.correct_epi(crop, ppi, fe, return_info=True)
fired = bool(info["locked"])
out.append(("autocorr", fired, int(info["k"]) if fired else 1))
except Exception:
out.append(("autocorr", False, 1))
# 4) gradient edge density
try:
r = GE.correct_epi(crop, ppi, fe)
fired = bool(r["locked"])
out.append(("gradient", fired, int(r.get("k", 1)) if fired else 1))
except Exception:
out.append(("gradient", False, 1))
# 5) band-limited harmonic promotion (px/thread gate)
try:
r = LB.correct_epi(crop, ppi, fe, weave=weave)
out.append(("bandpass", bool(r.fired), int(r.pick_k) if r.fired else 1))
except Exception:
out.append(("bandpass", False, 1))
return out
def _vote_k(members):
"""Majority vote over the integer multiple k chosen by the FIRING members.
Ties are broken toward the FINER (higher) k: a motif sub-harmonic lock can
only make the FFT period too COARSE, so when the evidence is split the higher
multiple is the safer correction. Returns the winning k (>=2) or 1 if none."""
ks = [k for (_n, fired, k) in members if fired and k >= 2]
if not ks:
return 1
counts = Counter(ks)
best = max(counts.values())
winners = [k for k, c in counts.items() if c == best]
return max(winners) # finer-k tie-break
def _refine_epi(crop, ppi, fe, k):
"""Precise sub-pixel EPI for the chosen multiple k, via the harmonic-comb
module's multi-resolution HPS refinement around k * fft_freq. This re-uses
the most period-accurate of the base methods so the final value is not a
coarse integer k*fft_epi but a sub-pixel comb-locked estimate."""
f_fft = fe / ppi
fband_hi = 1.0 / HC.PERIOD_MIN_PX
# df from a single full-resolution spectrum (used for window widths)
f1, _ = HC.warp_spectrum(crop, nstrips=1)
df = f1[1] - f1[0]
epi, snr = HC._multires_period(crop, ppi, k * f_fft, fband_hi, df)
return float(epi), float(snr)
# --------------------------------------------------------------------------- #
# Public corrector
# --------------------------------------------------------------------------- #
def correct_epi(crop, px_per_inch, fft_epi, weave=None, return_info=False):
"""Combined selective dense-warp EPI corrector.
Parameters
----------
crop : 2-D float array, calibrated flat-fielded central crop
(warp threads vertical -> warp period is along X / columns).
px_per_inch : float, calibrated pixels per inch for this crop.
fft_epi : float, the production FFT counter's EPI reading (anchor/fallback).
weave : optional weave label (used by the band-limited member's gate;
pass None to leave that gate open).
Returns
-------
dict with keys: epi, used ('fft' | 'combined'), k, n_fire, votes, members.
"""
ppi = float(px_per_inch)
fe = float(fft_epi)
if fe <= 0 or ppi <= 0 or not np.isfinite(fe):
info = dict(epi=fe, used="fft", k=1, n_fire=0, votes={}, members=[])
return (fe, info) if return_info else info
members = _poll_members(crop, ppi, fe, weave)
n_fire = sum(1 for (_n, fired, _k) in members if fired)
# ---- CASCADE GATE: require a quorum of independent lock detections. -------
if n_fire < MIN_FIRE:
info = dict(epi=fe, used="fft", k=1, n_fire=n_fire,
votes={}, members=members)
return (fe, info) if return_info else info
# ---- PERIOD VOTE: majority integer multiple k of the FFT period. ----------
k = _vote_k(members)
votes = dict(Counter(k for (_n, fired, k) in members if fired and k >= 2))
if k < 2:
info = dict(epi=fe, used="fft", k=1, n_fire=n_fire,
votes=votes, members=members)
return (fe, info) if return_info else info
# ---- REFINE: sub-pixel comb-locked period for the chosen k. ---------------
epi, snr = _refine_epi(crop, ppi, fe, k)
# Defensive plausibility checks; if the refined value is implausible fall back
# to the coarse integer multiple, and if THAT is implausible defer to FFT.
ppth = ppi / max(epi, 1e-9)
if not (EPI_LO <= epi <= EPI_HI and PPTH_LO <= ppth <= PPTH_HI):
coarse = k * fe
if EPI_LO <= coarse <= EPI_HI:
epi = float(coarse)
else:
info = dict(epi=fe, used="fft", k=1, n_fire=n_fire,
votes=votes, members=members)
return (fe, info) if return_info else info
info = dict(epi=float(epi), used="combined", k=int(k), n_fire=n_fire,
votes=votes, members=members, snr=snr)
return (float(epi), info) if return_info else info
def count_ppi(crop, px_per_inch, fft_ppi):
"""PPI (weft) is already accurate from the production FFT counter; pass it
through unchanged (every base corrector measured a regression when this warp
corrector was applied to the transposed crop)."""
return float(fft_ppi)
# --------------------------------------------------------------------------- #
# Self-evaluation on the shared data set.
# --------------------------------------------------------------------------- #
if __name__ == "__main__":
NPZ = "/scratch/user/uqabeniw/fabric/thread_counter/hardwarp_eval.npz"
z = np.load(NPZ)
ids = sorted({k.split("__")[0] for k in z.files}, key=int)
HARD = {"42", "44", "46", "48", "49", "50", "52"}
n_all = n_all_fft = 0
n_hard = n_hard_fft = 0
n_easy = n_easy_fft = n_easy_n = 0
regress = []
hard_abserr = hard_abserr_fft = 0.0
rows = []
for i in ids:
crop = z[f"{i}__crop"]
ppi = float(z[f"{i}__ppi"])
te = float(z[f"{i}__truth_epi"])
fe = float(z[f"{i}__fft_epi"])
weave = str(z[f"{i}__weave"])
kind = str(z[f"{i}__kind"])
pred, info = correct_epi(crop, ppi, fe, weave=weave, return_info=True)
err = pred - te
ferr = fe - te
ok = abs(err) <= 2
okf = abs(ferr) <= 2
n_all += ok
n_all_fft += okf
if i in HARD:
n_hard += ok
n_hard_fft += okf
hard_abserr += abs(err)
hard_abserr_fft += abs(ferr)
else:
n_easy_n += 1
n_easy += ok
n_easy_fft += okf
if okf and not ok:
regress.append(i)
rows.append((i, kind, te, fe, pred, err, info["used"], info["k"],
info["n_fire"], info.get("votes", {})))
print(f"{'id':>3} {'kind':<13} {'truth':>5} {'fft':>4} {'pred':>7} "
f"{'err':>6} {'used':>8} {'k':>2} {'nfire':>5} votes")
for (i, kind, te, fe, pred, err, used, k, nf, votes) in rows:
mark = " *HARD" if i in HARD else ""
print(f"{i:>3} {kind:<13} {te:5.0f} {fe:4.0f} {pred:7.2f} "
f"{err:+6.2f} {used:>8} {k:>2} {nf:>5} {dict(votes)}{mark}")
print()
print(f"EPI within +-2 OVERALL : FFT {n_all_fft}/21 -> combined {n_all}/21")
print(f"EPI within +-2 HARD(7) : FFT {n_hard_fft}/7 -> combined {n_hard}/7")
print(f"EPI within +-2 EASY/BL : FFT {n_easy_fft}/{n_easy_n} -> combined {n_easy}/{n_easy_n}")
print(f"HARD mean-abs-err : FFT {hard_abserr_fft/7:.1f} -> combined {hard_abserr/7:.1f}")
print(f"REGRESSIONS (FFT ok, combined broke): {regress if regress else 'NONE'}")