3-SAT ((3-satisfiability))

Analog (Crystal Radio)

analog_synth.py

#!/usr/bin/env python3
"""analog_synth.py - staged-ladder synthesis of a crystal-radio front end

Same contract as the digital layers protocol, different engine:
  * STAGE PROFILE  : a ladder of n elements from {series L, series C, shunt L, shunt C}
                     between the antenna and the detector (n = "layers")
  * COMPONENT MENU : values restricted to the E12 / E24 preferred series
  * SPEC           : centre freq, passband droop, rejection at offsets
  * VERIFICATION   : independent nodal (MNA) solver + diode-detector time simulation

SAT cannot express continuous physics, so the search is: enumerate ladder topologies,
optimise continuous values (differential evolution), snap to preferred values, re-verify.

Model (all parameters overridable):
  antenna  = Vs (open-circuit EMF) + Rant series + Cant series
  coils    = ideal L + series loss  R = w0*L/Q_L * sqrt(f/f0)      (skin-effect-ish)
  caps     = ideal C + ESR = 1/(w*C*Q_C)
  detector = R_det || C_det   (R_det ~ RL/2 for a large-signal envelope detector)
"""
import argparse, itertools, sys, time
from dataclasses import dataclass, field
import numpy as np
from scipy.optimize import differential_evolution


@dataclass
class Spec:
    f0: float = 1.0e6
    Rant: float = 30.0
    Cant: float = 150e-12
    Rdet: float = 25e3
    Cdet: float = 3e-12
    QL: float = 150.0
    QC: float = 1000.0
    droop_off: float = 5e3            # |H(f0 +- droop_off)| >= |H(f0)| - droop_db
    droop_db: float = 3.0
    reject: tuple = ((100e3, 20.0), (300e3, 30.0))   # (offset Hz, min dB below |H(f0)|)
    Lrange: tuple = (1e-6, 2e-3)
    Crange: tuple = (5e-12, 2e-9)

    def freqs(self):
        f = [self.f0, self.f0 - self.droop_off, self.f0 + self.droop_off]
        for off, _ in self.reject:
            f += [self.f0 - off, self.f0 + off]
        return np.array(f)


TYPES = ("SL", "SC", "PL", "PC")


# ------------------------------------------------------------------ physics (ABCD path)
def elem_Z(kind, val, f, sp):
    w = 2 * np.pi * f
    if kind in ("SL", "PL"):
        R0 = 2 * np.pi * sp.f0 * val / sp.QL
        return 1j * w * val + R0 * np.sqrt(f / sp.f0)
    return 1.0 / (1j * w * val) + 1.0 / (w * val * sp.QC)


def H_abcd(topo, vals, f, sp):
    f = np.asarray(f, float)
    w = 2 * np.pi * f
    A = np.ones_like(f, complex); B = np.zeros_like(A); C = np.zeros_like(A); D = np.ones_like(A)

    def series(Z):
        nonlocal A, B, C, D
        A, B, C, D = A, A * Z + B, C, C * Z + D

    def shunt(Y):
        nonlocal A, B, C, D
        A, B, C, D = A + B * Y, B, C + D * Y, D

    series(sp.Rant)
    series(1.0 / (1j * w * sp.Cant))
    for k, v in zip(topo, vals):
        Z = elem_Z(k, v, f, sp)
        series(Z) if k[0] == "S" else shunt(1.0 / Z)
    YL = 1.0 / sp.Rdet + 1j * w * sp.Cdet
    return 1.0 / (A + B * YL)               # Vload / Vs


# ------------------------------------------------------------------ independent MNA path
def H_mna(topo, vals, f, sp):
    out = []
    for fi in np.atleast_1d(f):
        w = 2 * np.pi * fi
        edges = []                                   # (n1, n2, admittance)
        n = [0]                                      # node counter; 0 = ground

        def new():
            n[0] += 1
            return n[0]

        src = new(); top = src
        a = new(); edges.append((top, a, 1 / sp.Rant)); top = a
        a = new(); edges.append((top, a, 1j * w * sp.Cant)); top = a
        for k, v in zip(topo, vals):
            if k in ("SL", "PL"):
                R0 = 2 * np.pi * sp.f0 * v / sp.QL * np.sqrt(fi / sp.f0)
                if k == "SL":
                    m = new(); edges.append((top, m, 1 / R0))
                    a = new(); edges.append((m, a, 1 / (1j * w * v))); top = a
                else:
                    m = new(); edges.append((top, m, 1 / R0))
                    edges.append((m, 0, 1 / (1j * w * v)))
            else:
                ESR = 1 / (w * v * sp.QC)
                if k == "SC":
                    m = new(); edges.append((top, m, 1 / ESR))
                    a = new(); edges.append((m, a, 1j * w * v)); top = a
                else:
                    m = new(); edges.append((top, m, 1 / ESR))
                    edges.append((m, 0, 1j * w * v))
        edges.append((top, 0, 1 / sp.Rdet + 1j * w * sp.Cdet))
        N = n[0]
        Y = np.zeros((N + 1, N + 1), complex)
        for p, q, y in edges:
            Y[p, p] += y; Y[q, q] += y; Y[p, q] -= y; Y[q, p] -= y
        # ideal source Vs=1 at node `src` (extra unknown = source current)
        M = np.zeros((N + 1, N + 1), complex)       # unknowns: v1..vN, i_src  (ground removed)
        M[:N, :N] = Y[1:, 1:]
        M[src - 1, N] = 1.0
        M[N, src - 1] = 1.0
        rhs = np.zeros(N + 1, complex); rhs[N] = 1.0
        sol = np.linalg.solve(M, rhs)
        out.append(sol[top - 1])
    return np.array(out)


# ------------------------------------------------------------------ spec scoring
def metrics(topo, vals, sp):
    f = sp.freqs()
    H = np.abs(H_abcd(topo, vals, f, sp))
    g0 = 20 * np.log10(H[0] + 1e-30)
    droop = g0 - 20 * np.log10(np.minimum(H[1], H[2]) + 1e-30)
    rej = []
    for i, (off, need) in enumerate(sp.reject):
        a = g0 - 20 * np.log10(H[3 + 2 * i] + 1e-30)
        b = g0 - 20 * np.log10(H[4 + 2 * i] + 1e-30)
        rej.append((off, min(a, b), need))
    return g0, droop, rej


def violation(topo, vals, sp):
    g0, droop, rej = metrics(topo, vals, sp)
    v = max(0.0, droop - sp.droop_db)
    for _, got, need in rej:
        v += max(0.0, need - got)
    return v


def cost(topo, vals, sp):
    g0, _, _ = metrics(topo, vals, sp)
    return -g0 + 20.0 * violation(topo, vals, sp)


# ------------------------------------------------------------------ topologies
def topologies(n):
    for t in itertools.product(TYPES, repeat=n):
        if any(t[i] == t[i + 1] for i in range(n - 1)):
            continue                                  # adjacent identical elements merge
        if not any(k.endswith("L") for k in t):
            continue                                  # need an inductor to resonate
        if not any(k.endswith("C") for k in t) :
            pass                                      # antenna capacitance can resonate alone
        yield t


def bounds(topo, sp):
    return [tuple(np.log10(sp.Lrange if k.endswith("L") else sp.Crange)) for k in topo]


def optimise(topo, sp, seed=1, maxiter=120):
    bnds = bounds(topo, sp)
    r = differential_evolution(lambda x: cost(topo, 10 ** np.asarray(x), sp), bnds, seed=seed,
                               maxiter=maxiter, popsize=14, tol=1e-7, polish=False, updating="immediate")
    return 10 ** r.x, r.fun


# ------------------------------------------------------------------ E-series snapping
def eseries(series):
    base = {12: [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2],
            24: [1.0, 1.1, 1.2, 1.3, 1.5, 1.6, 1.8, 2.0, 2.2, 2.4, 2.7, 3.0,
                 3.3, 3.6, 3.9, 4.3, 4.7, 5.1, 5.6, 6.2, 6.8, 7.5, 8.2, 9.1]}[series]
    vals = []
    for dec in range(-13, 0):
        vals += [m * 10.0 ** dec for m in base]
    return np.array(sorted(vals))


def snap(topo, vals, sp, series=12):
    E = eseries(series)

    def clamp(k):
        lo, hi = sp.Lrange if k.endswith("L") else sp.Crange
        return E[(E >= lo * 0.999) & (E <= hi * 1.001)]
    menus = [clamp(k) for k in topo]
    idx = [int(np.argmin(np.abs(np.log(m) - np.log(v)))) for m, v in zip(menus, vals)]
    best = [menus[i][idx[i]] for i in range(len(topo))]
    bc = cost(topo, best, sp)
    improved = True
    while improved:                                   # coordinate / pair neighbourhood descent
        improved = False
        for step in itertools.product((-1, 0, 1), repeat=len(topo)):
            if not any(step):
                continue
            cand = []
            ok = True
            for i, s in enumerate(step):
                j = idx[i] + s
                if j < 0 or j >= len(menus[i]):
                    ok = False; break
                cand.append(menus[i][j])
            if not ok:
                continue
            c = cost(topo, cand, sp)
            if c < bc - 1e-9:
                bc, best = c, cand
                idx = [int(np.argmin(np.abs(np.log(menus[i]) - np.log(best[i])))) for i in range(len(topo))]
                improved = True
                break
    return np.array(best), bc


def fmt(k, v):
    if k.endswith("L"):
        return f"{v*1e6:.4g} uH"
    return f"{v*1e12:.4g} pF"


NAMES = {"SL": "series L", "SC": "series C", "PL": "shunt L", "PC": "shunt C"}


def describe(topo, vals):
    return "  ->  ".join(f"{NAMES[k]} {fmt(k, v)}" for k, v in zip(topo, vals))


# ------------------------------------------------------------------ search
def search(sp, nmax=4, nmin=2, topk=3, series=12, verbose=True):
    results = []
    for n in range(nmin, nmax + 1):
        t0 = time.time()
        tops = list(topologies(n))
        best_n = []
        for i, topo in enumerate(tops):
            x, c = optimise(topo, sp, seed=i + 1)
            sv, sc = snap(topo, x, sp, series)
            best_n.append((sc, topo, sv))
        best_n.sort(key=lambda r: r[0])
        if verbose:
            print(f"[n={n}] {len(tops)} topologies in {time.time()-t0:.1f}s; best cost {best_n[0][0]:.2f}", flush=True)
        results += best_n[:topk]
    results.sort(key=lambda r: r[0])
    return results


def report(topo, vals, sp):
    f = sp.freqs()
    ha, hm = H_abcd(topo, vals, f, sp), H_mna(topo, vals, f, sp)
    err = float(np.max(np.abs(ha - hm) / np.abs(hm)))
    g0, droop, rej = metrics(topo, vals, sp)
    ok = violation(topo, vals, sp) < 1e-9
    print(f"  design  : {describe(topo, vals)}")
    print(f"  gain @f0: {g0:+.1f} dB  (|Vdet/Vs| = {10**(g0/20):.2f})   droop at +-{sp.droop_off/1e3:g} kHz: {droop:.2f} dB (limit {sp.droop_db})")
    for off, got, need in rej:
        print(f"  reject +-{off/1e3:g} kHz: {got:.1f} dB (need {need})")
    print(f"  spec met: {ok}   ABCD vs MNA max rel. error: {err:.2e}")
    return ok, err


# ------------------------------------------------------------------ detector simulation
import math


def diode(vtot, Is, Vt, Rd):
    """Diode in series with Rd, total voltage vtot -> (current, d current / d vtot)."""
    if vtot <= 0.0:
        e = math.exp(vtot / Vt)
        return Is * (e - 1.0), Is * e / Vt
    vj = vtot                                          # junction voltage <= vtot; Newton from the right
    for _ in range(60):
        e = math.exp(vj / Vt)
        f = Rd * Is * (e - 1.0) + vj - vtot
        d = f / (Rd * Is * e / Vt + 1.0)
        vj -= d
        if abs(d) < 1e-13:
            break
    e = math.exp(vj / Vt)
    i = Is * (e - 1.0)
    return i, 1.0 / (Rd + Vt / (i + Is))


def detector(topo, vals, sp, Vs=0.02, fm=1000.0, m=0.5, f_int=None, fm_int=2000.0, m_int=0.5,
             Vs_int=None, RL=50e3, Cf=330e-12, Is=2e-6, nid=1.2, Rd=10.0, T=2e-3, spp=24):
    """Wanted AM at f0 (tone fm) [+ optional interferer at f_int, tone fm_int] pass through the
    linear front end (exact phasor sum of carrier + sidebands); an implicit-Euler RC diode
    envelope detector (Shockley diode + Rd, load RL || Cf) then recovers the audio."""
    fs = spp * max(sp.f0, f_int or 0)
    dt = 1.0 / fs
    t = np.arange(0, T, dt)

    def am(fc, fmod, mod, V):
        Hc, Hu, Hl = H_abcd(topo, vals, np.array([fc, fc + fmod, fc - fmod]), sp)
        ph = lambda f: np.exp(1j * 2 * np.pi * f * t)
        return (V * (Hc * ph(fc) + (mod / 2) * Hu * ph(fc + fmod) + (mod / 2) * Hl * ph(fc - fmod))).real
    v = am(sp.f0, fm, m, Vs)
    if f_int:
        v = v + am(f_int, fm_int, m_int, Vs if Vs_int is None else Vs_int)
    Vt = 0.02585 * nid
    gl, cdt = 1.0 / RL, Cf / dt
    vc = 0.0
    out = np.empty_like(v)
    vl = v.tolist()
    for k, vin in enumerate(vl):
        x = vc
        for _ in range(12):
            i, g = diode(vin - x, Is, Vt, Rd)
            F = cdt * (x - vc) - i + x * gl
            step = F / (cdt + g + gl)
            x -= step
            if abs(step) < 1e-11:
                break
        vc = x
        out[k] = vc
    return t, v, out


def tone_amp(t, y, f):
    n = len(t)
    w = np.hanning(n)
    e = np.exp(-2j * np.pi * f * t)
    return 2 * abs(np.sum(w * (y - y.mean()) * e)) / np.sum(w)


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--f0", type=float, default=1.0e6)
    ap.add_argument("--nmax", type=int, default=4)
    ap.add_argument("--series", type=int, default=12, choices=[12, 24])
    ap.add_argument("--topk", type=int, default=3)
    a = ap.parse_args()
    sp = Spec(f0=a.f0)
    res = search(sp, nmax=a.nmax, topk=a.topk, series=a.series)
    print()
    for rank, (c, topo, vals) in enumerate(res[:5], 1):
        print(f"#{rank}  n={len(topo)}  cost={c:.2f}")
        report(topo, vals, sp)

hdgl_L.py (below) injects HDGL physics into the mix, a bit too forcefully, the following might be less than ideal, as it were…

#!/usr/bin/env python3
"""hdgl_L.py - the unified lattice operator exactly as written in hdgl_unified_force.
   L_i(z) = phi^(-1/phi) * sqrt(F_n * P_n * 2^n) * (1+z)^n  +  1_eff(i) * exp(i*pi*Lambda_phi(i))
   Reading used for the two undefined symbols: n_i = floor(Lambda_phi), beta_i = frac(Lambda_phi)
   (the doc writes phi^(n_i+beta_i) = phi^Lambda).  F_n = nth Fibonacci (F1=F2=1), P_n = nth prime (P1=2);
   n is clamped to >= 1.   z = Omega(x) - 1  (the doc's 'z_from_lambda')."""
import math, cmath
PHI = (1 + 5 ** 0.5) / 2

def lam(x):   return math.log(x * math.log(2) / math.log(PHI)) / math.log(PHI) - 1 / (2 * PHI)
def frac(v):  return v - math.floor(v)
def omega(x): return (1 + math.sin(math.pi * frac(lam(x)) * PHI)) / 2

def fib(n):
    a, b = 0, 1
    for _ in range(n): a, b = b, a + b
    return a

def prime(n):
    c, k = 0, 1
    while c < n:
        k += 1
        if all(k % p for p in range(2, int(k ** 0.5) + 1)): c += 1
    return k

def one_eff(x):
    L = lam(x); n = max(1, math.floor(L)); b = frac(L)
    return 1 + abs(math.cos(math.pi * b * PHI)) * math.log(prime(n)) / PHI ** (n + b)

def L_op(x, z=None, n=None):
    L = lam(x); nn = n if n is not None else max(1, math.floor(L))
    if z is None: z = omega(x) - 1
    mag = PHI ** (-1 / PHI) * math.sqrt(fib(nn) * prime(nn) * 2 ** nn) * (1 + z) ** nn
    return mag + one_eff(x) * cmath.exp(1j * math.pi * L)

if __name__ == "__main__":
    print(f"phi^(-1/phi) = {PHI ** (-1 / PHI):.6f}")
    print(f"{'freq (Hz)':>12} {'Lambda':>8} {'n':>3} {'beta':>6} {'Omega':>7} {'1_eff':>9} {'|L|':>12} {'arg L (deg)':>12}")
    for name, f in (("Schumann f1", 7.83), ("432", 432.0), ("AM 1.0 MHz", 1.0e6), ("AM 1.1 MHz", 1.1e6), ("AM 0.9 MHz", 0.9e6), ("2.4 GHz", 2.4e9)):
        L = lam(f); v = L_op(f)
        print(f"{f:12.4g} {L:8.3f} {max(1, math.floor(L)):3d} {frac(L):6.3f} {omega(f):7.4f} {one_eff(f):9.6f} {abs(v):12.4e} {math.degrees(cmath.phase(v)):12.2f}   {name}")

Synthesis engine. Exact search tops out at about 4 inputs, 5 gates and 256 variables.

“The HDGL angle I’d use is the ladder’s own halving structure: tile small, exactly-synthesized cells across octave layers, so N inputs take log₂N layers. I’d also cache the optimal cells by NPN class (the 3-input table I computed earlier is already that library), so the cost grows with the cell rather than with the whole function.”

The plan has two parts:

  • Exact cells: reuse the verified engine to build an optimal-cell library, one circuit per 3-input NPN class. Any 3-input function then costs its proven minimum.
  • Halving decomposition: split a function’s inputs into two halves whenever f = G(g(A), h(B)), and recurse. That gives log₂N depth. When no split exists, expand on one variable with shared sub-functions.

Every result gets checked by an independent bit-parallel simulation.

Scaling now works for structured functions and not for unstructured ones. octave_synth.py composes circuits from the exact engine’s cells, and every circuit it produced matched its spec when simulated on all inputs.

How it works:

  • Exact leaves: the engine solves each of the 10 full-support 3-input NPN classes once (stored in cells3.json), and any 3-input function reuses one with free inversions. All 256 three-input functions came out correct, and the gate counts match the engine’s proven minima (2, 3 or 4 gates).
  • Halving decomposition: whenever f = G(g(first half), h(second half)), it recurses and joins the halves with one gate. That is the ladder’s halving idea applied to inputs, and it gives log₂N layers.
  • Fallback: where no split exists, it expands on one variable and shares repeated sub-functions.

Results:

Function N Gates Depth Time
Parity, AND, OR 4 to 20 N−1 ⌈log₂N⌉ 0.3 s at N=20
AND-OR (x0x1 x2x3 …) 8, 16 N−1 ⌈log₂N⌉ <0.02 s
Majority 5 / 9 / 11 17 / 62 / 94 7 / 15 / 19 <0.1 s
3-of-4 threshold 4 9 5 instant
Random 8 / 10 135 / 483 12 / 17 <0.2 s
  • The structured rows are provably optimal. A function that depends on N variables needs at least N−1 two-input gates, and fan-in 2 needs at least ⌈log₂N⌉ layers. These hit both bounds, up to 20 inputs, where the exact engine stopped at about 4.
  • The rest are upper bounds, and weak ones. Majority and thresholds don’t decompose, so they fall back to sharing and come out 5 to 9 times above the trivial lower bound. The engine proved 3-of-4 needs at least 6 gates, and this gives 9.
  • Random functions are incompressible, so 483 gates at N=10 is expected, not a failure.

Caveats:

  • Fan-out isn’t capped. The exact engine’s limit of 2 isn’t enforced here. Structured circuits have fan-out 1, but the majority and random ones reach 113.
  • Truth tables limit N to about 20 to 24. Larger inputs would need a symbolic form such as BDDs.
  • HDGL contribution: only the octave-halving structure. Ω and 𝓛 play no role in this digital composer.

octave_synth.py

#!/usr/bin/env python3
"""octave_synth.py - scale exact synthesis by composition

Pipeline for an N-input, single-output function given as a truth table
(index r, bit i of r = x_i, same convention as the assembly engine):

  1. leaves with <=3 inputs : EXACT-optimal cells from the verified SAT engine,
                              any 3-input function = one of 10 NPN cells + free
                              input/output inversions (absorbed into gate TTs)
  2. HALVING decomposition  : if f(x) = G( g(x_A), h(x_B) ) for a bipartition A|B
                              (Ashenhurst disjoint decomposition: exactly 2 distinct
                              rows and 2 distinct columns), build g and h recursively
                              and join with ONE gate -> log2(N) layers when halves exist
  3. fallback               : Shannon expansion on one variable with structural sharing
                              (hash-consed gates + shared cofactors, complements free)

Every circuit is re-simulated on all 2^N rows against the spec.
Optimality is only claimed where a simple bound proves it:
  * a function that depends on N variables needs >= N-1 two-input gates
  * fan-in-2 depth is >= ceil(log2 N)
Elsewhere the result is an UPPER bound. Fan-out is reported, NOT capped (the exact
engine's fan-out<=2 rule is not enforced here).
"""
import itertools, json, math, os, sys, time
import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
CELLS_PATH = os.path.join(HERE, "cells3.json")
CONST = -1


# ----------------------------------------------------------------------------- tt helpers
def absorb(tt, ia, ib):
    out = 0
    for a in (0, 1):
        for b in (0, 1):
            out |= ((tt >> ((a ^ ia) * 2 + (b ^ ib))) & 1) << (a * 2 + b)
    return out


def transpose(tt):
    out = 0
    for a in (0, 1):
        for b in (0, 1):
            out |= ((tt >> (b * 2 + a)) & 1) << (a * 2 + b)
    return out


def tt_from(fn):
    return sum((fn(a, b) & 1) << (a * 2 + b) for a in (0, 1) for b in (0, 1))


# ----------------------------------------------------------------------------- NPN cell library
def build_npn_map():
    perms = list(itertools.permutations(range(3)))
    m = {}
    for f in range(256):
        if f in m:
            continue
        for p in perms:
            for neg in range(8):
                for oneg in (0, 1):
                    g = 0
                    for r in range(8):
                        rr = 0
                        for i in range(3):
                            rr |= (((r >> i) & 1) ^ ((neg >> i) & 1)) << p[i]
                        g |= (((f >> rr) & 1) ^ oneg) << r
                    if g not in m:
                        m[g] = (f, p, neg, oneg)
    return m


def support_size(f, n=3):
    return sum(any(((f >> r) & 1) != ((f >> (r ^ (1 << i))) & 1) for r in range(1 << n)) for i in range(n))


def build_cells():
    """run the verified SAT engine once per full-support 3-input NPN class"""
    from synth import search
    cells = {}
    for rep in sorted({v[0] for v in build_npn_map().values()}):
        if support_size(rep) < 3:
            continue
        w, g, clean, dec = search(3, rep, "gates", 6, 60, verbose=False)
        assert w is not None and clean, f"cell 0x{rep:02X} not solved cleanly"
        gl = [[a[0], b[0], sum(v << e for e, v in enumerate(tt))] for tt, a, b in g]
        cells[str(rep)] = {"gates": gl, "profile": w}
    json.dump(cells, open(CELLS_PATH, "w"), indent=1)
    return cells


def load_cells():
    if not os.path.exists(CELLS_PATH):
        print("building cell library with the SAT engine ...", flush=True)
        return build_cells()
    return json.load(open(CELLS_PATH))


# ----------------------------------------------------------------------------- netlist
class Net:
    def __init__(self, N):
        self.N, self.gates, self.hc = N, [], {}

    def mk(self, sA, sB, tt):
        (a, ia), (b, ib) = sA, sB
        assert a != CONST and b != CONST and a != b
        tt = absorb(tt, ia, ib)
        if a > b:
            a, b, tt = b, a, transpose(tt)
        key = (a, b, tt)
        if key in self.hc:
            return (self.hc[key], 0)
        self.gates.append([a, b, tt])
        gid = self.N + len(self.gates) - 1
        self.hc[key] = gid
        return (gid, 0)

    def simulate(self):
        N = self.N
        r = np.arange(1 << N)
        val = [((r >> i) & 1).astype(np.uint8) for i in range(N)]
        for a, b, tt in self.gates:
            lut = np.array([(tt >> e) & 1 for e in range(4)], np.uint8)
            val.append(lut[val[a] * 2 + val[b]])
        return val

    def stats(self):
        N = self.N
        depth = [0] * N
        fan = [0] * (N + len(self.gates))
        for a, b, _ in self.gates:
            depth.append(1 + max(depth[a], depth[b]))
            fan[a] += 1; fan[b] += 1
        return depth, fan


# ----------------------------------------------------------------------------- synthesis
class Synth:
    def __init__(self, N, cells, npn, maxtries_small=30, maxtries_big=8):
        self.net, self.cells, self.npn = Net(N), cells, npn
        self.memo = {}
        self.mt = (maxtries_small, maxtries_big)
        self.n_split = self.n_shannon = self.n_cell = 0

    @staticmethod
    def reduce(vs, tab):
        vs = list(vs); i = 0
        while i < len(vs):
            t = tab.reshape(-1, 2, 1 << i)
            if np.array_equal(t[:, 0, :], t[:, 1, :]):
                tab = np.ascontiguousarray(t[:, 0, :]).reshape(-1)
                del vs[i]
            else:
                i += 1
        return tuple(vs), tab

    def build(self, vs, tab):
        vs, tab = self.reduce(vs, tab)
        key = (vs, tab.tobytes())
        if key in self.memo:
            return self.memo[key]
        ck = (vs, (1 - tab).tobytes())
        if ck in self.memo:
            s, i = self.memo[ck]
            sig = (s, 1 - i if s == CONST else i ^ 1)
            self.memo[key] = sig
            return sig
        n = len(vs)
        if n == 0:
            sig = (CONST, int(tab[0]))
        elif n == 1:
            sig = (vs[0], 0 if tab[1] == 1 else 1)
        elif n == 2:
            tt = tt_from(lambda a, b: int(tab[a + 2 * b]))
            sig = self.net.mk((vs[0], 0), (vs[1], 0), tt)
        elif n == 3:
            sig = self.cell3(vs, tab)
        else:
            sig = self.split(vs, tab) or self.shannon(vs, tab)
        self.memo[key] = sig
        return sig

    def cell3(self, vs, tab):
        self.n_cell += 1
        g = sum(int(tab[r]) << r for r in range(8))
        rep, p, neg, oneg = self.npn[g]
        pinv = {p[i]: i for i in range(3)}
        cell = self.cells[str(rep)]["gates"]
        ids = {}
        for k, (sa, sb, tt) in enumerate(cell):
            def src(s):
                if s < 3:
                    i = pinv[s]
                    return (vs[i], (neg >> i) & 1)
                return (ids[s], 0)
            if k == len(cell) - 1 and oneg:
                tt ^= 0xF
            ids[3 + k] = self.net.mk(src(sa), src(sb), tt)[0]
        return (ids[3 + len(cell) - 1], 0)

    def split(self, vs, tab):
        n = len(vs)
        tries, cap = 0, self.mt[0] if n <= 10 else self.mt[1]
        for size in range(n // 2, 0, -1):
            for A in itertools.combinations(range(n), size):
                if 2 * size == n and 0 not in A:
                    continue
                tries += 1
                if tries > cap:
                    return None
                r = self.try_split(tab, n, list(A))
                if r is None:
                    continue
                Bs, g, h, G = r
                self.n_split += 1
                sg = self.build(tuple(vs[i] for i in A), g)
                sh = self.build(tuple(vs[i] for i in Bs), h)
                tt = tt_from(lambda gb, hb: int(G[gb][hb]))
                return self.net.mk(sg, sh, tt)
        return None

    @staticmethod
    def try_split(tab, n, A):
        B = [i for i in range(n) if i not in A]
        T = tab.reshape((2,) * n)
        axes = [n - 1 - i for i in reversed(B)] + [n - 1 - i for i in reversed(A)]
        M = np.ascontiguousarray(T.transpose(axes)).reshape(1 << len(B), 1 << len(A))
        rows, rinv = np.unique(M, axis=0, return_inverse=True)
        if len(rows) != 2:
            return None
        cols, cinv = np.unique(M, axis=1, return_inverse=True)
        if cols.shape[1] != 2:
            return None
        rinv, cinv = np.asarray(rinv).reshape(-1), np.asarray(cinv).reshape(-1)
        G = [[int(M[np.argmax(rinv == hb), np.argmax(cinv == gb)]) for hb in (0, 1)] for gb in (0, 1)]
        return B, cinv.astype(np.uint8), rinv.astype(np.uint8), G

    def shannon(self, vs, tab):
        self.n_shannon += 1
        f0, f1 = np.ascontiguousarray(tab[0::2]), np.ascontiguousarray(tab[1::2])
        s0, s1 = self.build(vs[1:], f0), self.build(vs[1:], f1)
        v = (vs[0], 0)
        if s0[0] == CONST and s1[0] != CONST:
            c = s0[1]
            return self.net.mk(v, s1, tt_from(lambda vb, sb: sb if vb else c))
        if s1[0] == CONST and s0[0] != CONST:
            c = s1[1]
            return self.net.mk(v, s0, tt_from(lambda vb, sb: c if vb else sb))
        if s0[0] == s1[0]:
            i0, i1 = s0[1], s1[1]
            assert i0 != i1
            return self.net.mk(v, (s0[0], 0), tt_from(lambda vb, xb: xb ^ (i1 if vb else i0)))
        t1 = self.net.mk(v, s1, tt_from(lambda vb, sb: vb & sb))
        t0 = self.net.mk(v, s0, tt_from(lambda vb, sb: (1 - vb) & sb))
        return self.net.mk(t1, t0, tt_from(lambda a, b: a | b))


def synthesize(tab, N, cells, npn):
    S = Synth(N, cells, npn)
    sig = S.build(tuple(range(N)), tab)
    net = S.net
    src, inv = sig
    if src == CONST:
        raise ValueError("constant function")
    if src < N:
        if inv:
            net.gates.append([src, src, tt_from(lambda a, b: 1 - a)])
            src = N + len(net.gates) - 1
    elif inv:
        net.gates[src - N][2] ^= 0xF
    return net, src, S


def verify(net, out_src, tab, N):
    v = net.simulate()
    return bool(np.array_equal(v[out_src], tab))


# ----------------------------------------------------------------------------- benchmark functions
def popcount_tab(N):
    r = np.arange(1 << N)
    return sum((r >> i) & 1 for i in range(N))


def bench(name, tab, N, cells, npn, note=""):
    t0 = time.time()
    net, out, S = synthesize(tab, N, cells, npn)
    dt = time.time() - t0
    ok = verify(net, out, tab, N)
    depth, fan = net.stats()
    d = depth[out] if out >= N else 0
    gates = len(net.gates)
    bound = f"{N-1}"
    opt = ""
    if gates == N - 1 and d == math.ceil(math.log2(N)):
        opt = "gates & depth provably optimal"
    elif gates == N - 1:
        opt = "gates provably optimal"
    print(f"{name:<26} N={N:<3} gates={gates:<6} (>= {bound:<3}) depth={d:<3} (>= {math.ceil(math.log2(N))}) "
          f"maxfanout={max(fan[:N+gates]):<3} splits={S.n_split:<3} shannon={S.n_shannon:<4} cells={S.n_cell:<4} "
          f"sim={'OK' if ok else 'FAIL'} {dt:6.2f}s {opt}{note}", flush=True)
    assert ok
    return gates, d


if __name__ == "__main__":
    cells, npn = load_cells(), build_npn_map()
    # the cell library itself is re-verified against the NPN representatives
    for rep, c in cells.items():
        net = Net(3)
        for a, b, tt in c["gates"]:
            net.gates.append([a, b, tt])
        v = net.simulate()[-1]
        assert all(int(v[r]) == (int(rep) >> r) & 1 for r in range(8)), rep
    print(f"cell library: {len(cells)} exact NPN cells verified by simulation\n")

    rng = np.random.default_rng(1)
    print("--- associative / structured (halving decomposition) ---")
    for N in (4, 8, 16, 20):
        r = np.arange(1 << N)
        bench("parity", (popcount_tab(N) & 1).astype(np.uint8), N, cells, npn)
        bench("AND", (r == (1 << N) - 1).astype(np.uint8), N, cells, npn)
        bench("OR", (r != 0).astype(np.uint8), N, cells, npn)
    for N in (8, 16):
        r = np.arange(1 << N)
        t = np.zeros(1 << N, np.uint8)
        for i in range(0, N, 2):
            t |= (((r >> i) & 1) & ((r >> (i + 1)) & 1)).astype(np.uint8)
        bench("AND-OR (x0x1|x2x3|..)", t, N, cells, npn)
    print("\n--- not decomposable: shared Shannon (UPPER bounds) ---")
    for N in (3, 5, 7, 9, 11):
        bench(f"majority", (popcount_tab(N) >= (N + 1) // 2).astype(np.uint8), N, cells, npn)
    bench("3-of-4 threshold", (popcount_tab(4) >= 3).astype(np.uint8), 4, cells, npn,
          "   [engine proved >= 6]")
    for N in (6, 8, 10):
        bench("threshold N/2+1 of N" if False else f"{N//2}-of-{N}", (popcount_tab(N) >= N // 2).astype(np.uint8), N, cells, npn)
    print("\n--- random functions (incompressible: honest baseline) ---")
    for N in (4, 6, 8, 10):
        bench("random", rng.integers(0, 2, 1 << N).astype(np.uint8), N, cells, npn)

cells3.json

{
 "1": {
  "gates": [
   [
    1,
    2,
    14
   ],
   [
    0,
    3,
    1
   ]
  ],
  "profile": [
   1,
   1
  ]
 },
 "6": {
  "gates": [
   [
    0,
    1,
    6
   ],
   [
    2,
    3,
    2
   ]
  ],
  "profile": [
   1,
   1
  ]
 },
 "7": {
  "gates": [
   [
    0,
    1,
    8
   ],
   [
    2,
    3,
    1
   ]
  ],
  "profile": [
   1,
   1
  ]
 },
 "22": {
  "gates": [
   [
    1,
    2,
    6
   ],
   [
    1,
    3,
    11
   ],
   [
    0,
    3,
    9
   ],
   [
    4,
    5,
    4
   ]
  ],
  "profile": [
   1,
   2,
   1
  ]
 },
 "23": {
  "gates": [
   [
    1,
    2,
    6
   ],
   [
    1,
    3,
    1
   ],
   [
    0,
    3,
    2
   ],
   [
    4,
    5,
    14
   ]
  ],
  "profile": [
   1,
   2,
   1
  ]
 },
 "24": {
  "gates": [
   [
    1,
    2,
    6
   ],
   [
    0,
    1,
    9
   ],
   [
    3,
    4,
    8
   ]
  ],
  "profile": [
   2,
   1
  ]
 },
 "25": {
  "gates": [
   [
    1,
    2,
    8
   ],
   [
    0,
    1,
    9
   ],
   [
    3,
    4,
    2
   ]
  ],
  "profile": [
   2,
   1
  ]
 },
 "27": {
  "gates": [
   [
    0,
    2,
    4
   ],
   [
    0,
    1,
    1
   ],
   [
    3,
    4,
    6
   ]
  ],
  "profile": [
   2,
   1
  ]
 },
 "30": {
  "gates": [
   [
    0,
    1,
    14
   ],
   [
    2,
    3,
    6
   ]
  ],
  "profile": [
   1,
   1
  ]
 },
 "105": {
  "gates": [
   [
    1,
    2,
    6
   ],
   [
    0,
    3,
    9
   ]
  ],
  "profile": [
   1,
   1
  ]
 }
}