Spaces:
Sleeping
Sleeping
Download classfix_harmonic_comb.py from akshit2603/fabric-api: direct link, hf CLI and curl.
- Browser
- Download file 13.6 kB
-
https://huggingface.co/spaces/akshit2603/fabric-api/resolve/main/classfix_harmonic_comb.py
- Command line
-
hf download hf://spaces/akshit2603/fabric-api/classfix_harmonic_comb.py
-
curl -L -o classfix_harmonic_comb.py https://huggingface.co/spaces/akshit2603/fabric-api/resolve/main/classfix_harmonic_comb.py
13.6 kB
| """ | |
| Harmonic-comb period disambiguation EPI corrector (CLASSICAL signal processing). | |
| Problem | |
| ------- | |
| On dense mixed-yarn (cotton+spandex / ply) DOBBY/SATIN warp fabrics, the float / | |
| yarn-colour MOTIF injects a strong low-frequency component into the warp-axis | |
| (column) power spectrum. A plain FFT thread counter locks onto that motif (or a | |
| clean sub-multiple of it) and reports a warp period that is an INTEGER MULTIPLE of | |
| the true thread period -- i.e. the reported fundamental frequency f is a | |
| SUB-HARMONIC of the true thread frequency. Result: EPI is read as truth/2, /3, /4. | |
| Idea | |
| ---- | |
| The true thread frequency is one of the harmonics {1f, 2f, 3f, 4f} of the FFT | |
| fundamental f = fft_epi / px_per_inch. A real thread train is near-periodic, so | |
| its OWN harmonic comb (f0, 2f0, 3f0, ...) lines up with sharp spectral peaks, | |
| whereas a motif sub-harmonic does not generate a clean comb of its own. | |
| The corrector: | |
| 1. Builds warp-axis power spectra at several resolutions: a single column-mean | |
| periodogram (sharp, isolated lines for coherent fabrics) and strip-averaged | |
| periodograms (Welch-like, robust to slow skew, recovers weak high harmonics). | |
| 2. LOCK DETECTOR: it only overrides FFT when the FFT fundamental (N=1) shows | |
| strong harmonic support ABOVE itself (energy at 2f, 3f, 4f) -- the signature | |
| of a sub-harmonic lock. Otherwise it defers to FFT, so the 14 easy/borderline | |
| FFT-correct cases are left completely untouched. | |
| 3. PERIOD DISAMBIGUATION: for each candidate N in {2,3,4} with N*fft_epi in a | |
| plausible EPI band, a harmonic-product-style (HPS) search slides a candidate | |
| fundamental over a window around N*f and scores its full harmonic comb. The | |
| chosen harmonic is the *finest* (highest N) whose comb is still well-supported | |
| (within COMB_FRAC of the best comb) -- climbing past intermediate motif | |
| harmonics toward the genuine, well-combed thread frequency. | |
| 4. The chosen harmonic's period is refined with a multi-resolution HPS search | |
| that keeps the estimate whose line has the sharpest local prominence -> EPI. | |
| Public API | |
| ---------- | |
| correct_epi(crop, px_per_inch, fft_epi) -> dict(epi, used_fft, N, ...) | |
| """ | |
| import numpy as np | |
| # ---- tuned constants (grid-searched on the 21-image shared set) ------------ | |
| EPI_LO = 55.0 # plausible warp EPI band (lower) | |
| EPI_HI = 195.0 # plausible warp EPI band (upper) | |
| LOCK_SUPPORT = 0.06 # min harmonic-support-above N=1 to suspect a sub-harmonic lock | |
| COMB_FLOOR = 0.008 # min mean-comb score for a higher harmonic to be credible | |
| COMB_FRAC = 0.5 # accept a finer harmonic if its comb >= this frac of the best | |
| PERIOD_MIN_PX = 4.5 # ignore spectrum above this frequency (period < 4.5 px) | |
| SEARCH_HALF = 0.05 # +/- fractional window for the HPS fundamental search | |
| SEARCH_NSTRIPS = 8 # strips for the period-accurate HPS comb search | |
| # --------------------------------------------------------------------------- | |
| def _detrend(x, deg=1): | |
| t = np.arange(len(x)) | |
| return x - np.polyval(np.polyfit(t, x, deg), t) | |
| def warp_spectrum(crop, pad=16, nstrips=1): | |
| """Column-axis (warp) power spectrum. | |
| nstrips == 1 : single periodogram of the column-mean profile. | |
| nstrips > 1 : incoherent average of per-row-band periodograms (Welch-like), | |
| which suppresses skew smearing and recovers weak harmonics. | |
| Returns (freqs [cycles/px], power). | |
| """ | |
| img = np.asarray(crop, dtype=np.float64) | |
| h, w = img.shape | |
| N = 1 << int(np.ceil(np.log2(w * pad))) | |
| win = np.hanning(w) | |
| freqs = np.fft.rfftfreq(N, d=1.0) | |
| P = np.zeros(len(freqs)) | |
| if nstrips <= 1: | |
| P = np.abs(np.fft.rfft(_detrend(img.mean(0)) * win, N)) ** 2 | |
| return freqs, P | |
| bh = max(1, h // nstrips) | |
| used = 0 | |
| for s in range(nstrips): | |
| band = img[s * bh:(s + 1) * bh] | |
| if band.shape[0] < 4: | |
| continue | |
| P += np.abs(np.fft.rfft(_detrend(band.mean(0)) * win, N)) ** 2 | |
| used += 1 | |
| return freqs, P / max(used, 1) | |
| def _peak(freqs, P, fc, bw): | |
| if fc <= 0: | |
| return 0.0 | |
| sel = (freqs >= fc - bw) & (freqs <= fc + bw) | |
| return P[sel].max() if sel.any() else 0.0 | |
| def _refine(freqs, P, fc, rel=0.02): | |
| """Parabolic-interpolated peak location near fc; returns (freq, power).""" | |
| if fc <= 0: | |
| return fc, 0.0 | |
| bw = max(fc * rel, 3 * (freqs[1] - freqs[0])) | |
| sel = (freqs >= fc - bw) & (freqs <= fc + bw) | |
| if not sel.any(): | |
| return fc, 0.0 | |
| idx = np.where(sel)[0] | |
| j = idx[int(np.argmax(P[idx]))] | |
| if 0 < j < len(P) - 1: | |
| y0, y1, y2 = P[j - 1], P[j], P[j + 1] | |
| den = (y0 - 2 * y1 + y2) | |
| d = 0.5 * (y0 - y2) / den if den != 0 else 0.0 | |
| d = float(np.clip(d, -1, 1)) | |
| else: | |
| d = 0.0 | |
| return freqs[j] + (freqs[1] - freqs[0]) * d, P[j] | |
| def _comb_support_above(freqs, P, fc, df, fband_hi): | |
| """Sum of the relative power at 2fc and 3fc (the candidate's own harmonics).""" | |
| s = 0.0 | |
| for m in (2, 3): | |
| fm = m * fc | |
| if fm > fband_hi: | |
| break | |
| s += _peak(freqs, P, fm, max(fm * 0.02, 3 * df)) | |
| return s | |
| def _hps_search(freqs, P, df, f0_guess, fband_hi, half=SEARCH_HALF, ngrid=161, | |
| maxh=8): | |
| """Harmonic-product-style fundamental search. | |
| Slide a candidate fundamental f0 over +/-`half` around `f0_guess` on a fine | |
| grid; for each, average the spectral-peak power over its harmonic comb | |
| (1f0..maxh*f0). Returns (best_freq, mean_comb_score, total_comb_energy). | |
| Because the comb averages several harmonics, the located fundamental is | |
| period-accurate even when the FFT anchor is a few percent off. | |
| """ | |
| cand = np.linspace(f0_guess * (1 - half), f0_guess * (1 + half), ngrid) | |
| best_sc, best_f = -1.0, f0_guess | |
| for fc in cand: | |
| sc = 0.0 | |
| nh = 0 | |
| m = 1 | |
| while m * fc <= fband_hi and m <= maxh: | |
| sc += _peak(freqs, P, m * fc, max(m * fc * 0.008, 2 * df)) | |
| nh += 1 | |
| m += 1 | |
| sc /= max(nh, 1) | |
| if sc > best_sc: | |
| best_sc, best_f = sc, fc | |
| total = 0.0 | |
| m = 1 | |
| while m * best_f <= fband_hi and m <= maxh: | |
| total += _peak(freqs, P, m * best_f, max(m * best_f * 0.008, 2 * df)) | |
| m += 1 | |
| return best_f, best_sc, total | |
| def _local_snr(freqs, P, fc, df): | |
| """Prominence of the line at fc vs the local spectral floor around it.""" | |
| if fc <= 0: | |
| return 0.0 | |
| bw = max(fc * 0.012, 2 * df) | |
| sel = (freqs >= fc - bw) & (freqs <= fc + bw) | |
| if not sel.any(): | |
| return 0.0 | |
| pkv = P[sel].max() | |
| nb = max(fc * 0.10, 12 * df) | |
| selN = (freqs >= fc - nb) & (freqs <= fc + nb) & (~sel) | |
| floor = np.median(P[selN]) if selN.any() else 1e-9 | |
| return pkv / max(floor, 1e-9) | |
| def _multires_period(crop, ppi, f0_guess, fband_hi, df, strip_set=(1, 4, 8)): | |
| """Period-accurate EPI for a chosen harmonic. | |
| Runs the HPS comb search at several strip resolutions (full-crop coherent vs | |
| skew-robust averaged) and keeps the estimate whose located line has the | |
| sharpest local prominence. Different dense fabrics resolve the true thread | |
| line best at different resolutions, so this multi-resolution pick maximises | |
| accuracy once the harmonic N is fixed. | |
| """ | |
| best_snr, best_epi = -1.0, ppi * f0_guess | |
| for ns in strip_set: | |
| f, P = warp_spectrum(crop, nstrips=ns) | |
| P = P / (P[f > 0.005].max() or 1.0) | |
| bf, _, _ = _hps_search(f, P, df, f0_guess, fband_hi, half=0.06, | |
| ngrid=241, maxh=8) | |
| snr = _local_snr(f, P, bf, df) | |
| if snr > best_snr: | |
| best_snr, best_epi = snr, ppi * bf | |
| return best_epi, best_snr | |
| def correct_epi(crop, px_per_inch, fft_epi): | |
| """Return a corrected warp EPI for a single crop. | |
| Parameters | |
| ---------- | |
| crop : 2D float array (warp threads vertical -> period along X/columns) | |
| px_per_inch : float, calibrated pixels per inch | |
| fft_epi : float, the production FFT counter's EPI reading (anchor / fallback) | |
| Returns | |
| ------- | |
| dict with keys: | |
| epi : corrected EPI (float) | |
| used_fft : True if we deferred to FFT, False if we overrode | |
| N : chosen harmonic multiple of the FFT fundamental | |
| lock_score : harmonic-support-above measure that drove the detector | |
| candidates : per-N diagnostics | |
| """ | |
| ppi = float(px_per_inch) | |
| fe = float(fft_epi) | |
| if fe <= 0 or ppi <= 0: | |
| return dict(epi=fe, used_fft=True, N=1, lock_score=0.0, candidates={}) | |
| f1, P1 = warp_spectrum(crop, nstrips=1) | |
| f16, P16 = warp_spectrum(crop, nstrips=16) | |
| f8, P8 = warp_spectrum(crop, nstrips=SEARCH_NSTRIPS) | |
| m1 = P1[f1 > 0.005].max() or 1.0 | |
| m16 = P16[f16 > 0.005].max() or 1.0 | |
| m8 = P8[f8 > 0.005].max() or 1.0 | |
| p1 = P1 / m1 | |
| p16 = P16 / m16 | |
| p8 = P8 / m8 | |
| df = f1[1] - f1[0] | |
| f_fft = fe / ppi | |
| fband_hi = 1.0 / PERIOD_MIN_PX | |
| # ---- LOCK DETECTOR: does the FFT fundamental have a comb above it? -------- | |
| # A sub-harmonic lock means the *true* threads show up as 2f/3f/4f of f. | |
| lock_above = _comb_support_above(f1, p1, f_fft, df, fband_hi) \ | |
| + _comb_support_above(f16, p16, f_fft, df, fband_hi) | |
| candidates = {} | |
| for N in (1, 2, 3, 4): | |
| epiN = N * fe | |
| f0 = N * f_fft | |
| self1 = _peak(f1, p1, f0, max(f0 * 0.02, 3 * df)) | |
| self16 = _peak(f16, p16, f0, max(f0 * 0.02, 3 * df)) | |
| # period-accurate harmonic-comb (HPS) search around the N-th harmonic | |
| best_f, comb_mean, comb_tot = _hps_search(f8, p8, df, f0, fband_hi) | |
| candidates[N] = dict( | |
| epi_naive=epiN, | |
| epi_search=ppi * best_f, | |
| self=max(self1, self16), | |
| comb=comb_mean, | |
| comb_total=comb_tot, | |
| ) | |
| # ---- DECISION ------------------------------------------------------------ | |
| # Default: defer to FFT. | |
| if lock_above < LOCK_SUPPORT: | |
| return dict(epi=fe, used_fft=True, N=1, lock_score=lock_above, | |
| candidates=candidates) | |
| # Sub-harmonic lock suspected. Period-disambiguation step: among the higher | |
| # harmonics {2f,3f,4f} that fall in a plausible EPI band and carry credible | |
| # comb energy, choose the *highest* (finest) one whose harmonic comb is still | |
| # well-supported -- i.e. within COMB_FRAC of the strongest comb. Threads are | |
| # near-periodic so a true thread fundamental's whole comb lines up; preferring | |
| # the finest well-supported comb climbs past intermediate motif harmonics | |
| # toward the actual thread frequency, exactly the spec's "highest plausible". | |
| eligible = {} | |
| for N in (2, 3, 4): | |
| c = candidates[N] | |
| if not (EPI_LO <= c["epi_search"] <= EPI_HI): | |
| continue | |
| if c["comb"] < COMB_FLOOR: | |
| continue | |
| eligible[N] = c["comb"] | |
| chosen_N = 1 | |
| if eligible: | |
| best_comb = max(eligible.values()) | |
| chosen_N = max(N for N, cb in eligible.items() | |
| if cb >= COMB_FRAC * best_comb) | |
| if chosen_N == 1: | |
| # detector fired but no credible higher harmonic -> stay with FFT. | |
| return dict(epi=fe, used_fft=True, N=1, lock_score=lock_above, | |
| candidates=candidates) | |
| # Period-accurate, multi-resolution EPI for the chosen harmonic. | |
| chosen_epi, snr = _multires_period(crop, ppi, chosen_N * f_fft, fband_hi, df) | |
| return dict(epi=chosen_epi, used_fft=False, N=chosen_N, lock_score=lock_above, | |
| snr=snr, candidates=candidates) | |
| # --------------------------------------------------------------------------- | |
| # Self-test / evaluation on the shared data set when run directly. | |
| # --------------------------------------------------------------------------- | |
| if __name__ == "__main__": | |
| Z = np.load("/scratch/user/uqabeniw/fabric/thread_counter/hardwarp_eval.npz") | |
| IDS = sorted({k.split("__")[0] for k in Z.files}, key=int) | |
| HARD = {"42", "44", "46", "48", "49", "50", "52"} | |
| n_ok_overall = n_ok_hard = n_ok_easy = 0 | |
| n_hard = n_easy = 0 | |
| fft_ok_overall = fft_ok_hard = 0 | |
| regressions = [] | |
| print(f'{"id":>3} {"kind":>12} {"truth":>5} {"fft":>4} {"pred":>6} ' | |
| f'{"N":>2} {"src":>4} {"|e|":>4} {"lock":>5}') | |
| 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"]) | |
| kind = str(Z[f"{i}__kind"]) | |
| r = correct_epi(crop, ppi, fe) | |
| pred = r["epi"] | |
| err = abs(pred - te) | |
| fft_err = abs(fe - te) | |
| ok = err <= 2 | |
| fft_ok = fft_err <= 2 | |
| is_hard = i in HARD | |
| if is_hard: | |
| n_hard += 1 | |
| n_ok_hard += ok | |
| fft_ok_hard += fft_ok | |
| else: | |
| n_easy += 1 | |
| n_ok_easy += ok | |
| if fft_ok and not ok: | |
| regressions.append((i, te, fe, pred)) | |
| n_ok_overall += ok | |
| fft_ok_overall += fft_ok | |
| print(f'{i:>3} {kind:>12} {te:>5.0f} {fe:>4.0f} {pred:>6.1f} ' | |
| f'{r["N"]:>2} {("FFT" if r["used_fft"] else "COMB"):>4} ' | |
| f'{err:>4.1f} {r["lock_score"]:>5.2f}') | |
| print("\n--- SUMMARY ---") | |
| print(f"overall within +-2 : {n_ok_overall}/21 (FFT alone: {fft_ok_overall}/21)") | |
| print(f"HARD within +-2 : {n_ok_hard}/{n_hard} (FFT alone: {fft_ok_hard}/{n_hard})") | |
| print(f"easy within +-2 : {n_ok_easy}/{n_easy}") | |
| print(f"regressions (FFT was right, we broke it): {regressions if regressions else 'NONE'}") | |