#!/usr/bin/env python3
"""fractal_synth.py - first cell of the analog fractal library: self-similar RC ladder -> CPE

Family  : "power-law spectrum" fractals (Brownian / fBm / Levy / percolation ...) realised as a
          geometric ladder: stage k = series R0*rho^k, shunt C0*gamma^k  (k=0..n-1), open end.
Theory  : Z(s)=R0+1/(sC0+1/(rho*Z(s*gamma*rho)))  has the power-law fixed point Z ~ s^-alpha with
              alpha = ln(rho) / ln(rho*gamma)                       (closed form, tested below)
          and discrete scale invariance => log-periodic ripple of period ln(rho*gamma) in ln(f).
Verify  : (1) ladder recursion  (2) independent nodal (MNA) solve; slope fitted from the data.
Equivalence group (analog 'NPN'):  impedance scaling Z->kZ, frequency scaling f->kf, i.e. (R0,C0) free;
          class = (rho,gamma,n).  Only the ratios matter, so the synthesis search is over (rho,gamma,n).
Bound   : n RC sections have n poles; ripple-limited power-law span is ~ n*ln(rho*gamma) nepers of
          frequency, so the minimal n for a D-decade band is ceil(D*ln10/ln(rho*gamma)) (+ edge margin).
"""
import itertools, math, sys
import numpy as np

PHI = (1 + 5 ** 0.5) / 2

def ladder_RC(n, rho, gam, R0=1.0, C0=1.0):
    k = np.arange(n)
    return R0 * rho ** k, C0 * gam ** k

def Zin(f, R, C):
    """input impedance, order: R0, C0, R1, C1, ... (series R then shunt C), open end"""
    s = 2j * np.pi * np.asarray(f, float)
    Y = s * C[-1]
    Z = R[-1] + 1.0 / Y
    for k in range(len(R) - 2, -1, -1):
        Y = s * C[k] + 1.0 / Z
        Z = R[k] + 1.0 / Y
    return Z

def Zin_mna(f, R, C):
    out = []
    n = len(R)
    for fi in np.atleast_1d(f):
        s = 2j * np.pi * fi
        N = n                                   # nodes 1..n, node k = after R_{k-1}; node0 = port (current source)
        Y = np.zeros((N + 1, N + 1), complex)   # include port node 0 as index 0, no ground row
        def stamp(a, b, y):
            Y[a, a] += y
            if b is not None:
                Y[b, b] += y; Y[a, b] -= y; Y[b, a] -= y
        for k in range(n):
            stamp(k, k + 1, 1.0 / R[k])        # series R between node k and k+1
            stamp(k + 1, None, s * C[k])       # shunt C at node k+1 to ground
        # port node 0 driven by 1 A; solve with ground = implicit
        I = np.zeros(N + 1, complex); I[0] = 1.0
        out.append(np.linalg.solve(Y, I)[0])
    return np.array(out)

def fit(n, rho, gam, ppd=40):
    R, C = ladder_RC(n, rho, gam)
    tau0, g = R[0] * C[0], rho * gam
    w_hi = 0.15 / tau0                          # above this the first R dominates
    w_lo = 6.0 / (tau0 * g ** (n - 1))          # below this the open end dominates
    if w_lo >= w_hi:
        return None
    dec = math.log10(w_hi / w_lo)
    f = np.logspace(math.log10(w_lo / 2 / np.pi), math.log10(w_hi / 2 / np.pi), max(8, int(ppd * dec)))
    Z = Zin(f, R, C)
    Zm = Zin_mna(f[::max(1, len(f) // 12)], R, C)
    err = float(np.max(np.abs(Z[::max(1, len(f) // 12)] - Zm) / np.abs(Zm)))
    x, y = np.log(f), np.log(np.abs(Z))
    A = np.vstack([x, np.ones_like(x)]).T
    (m, b), *_ = np.linalg.lstsq(A, y, rcond=None)
    res = y - (m * x + b)
    ripple_db = 20 / math.log(10) * (res.max() - res.min())
    ph = np.degrees(np.angle(Z))
    return dict(alpha_fit=-m, dec=dec, ripple_db=ripple_db, phase_mean=ph.mean(),
                phase_pp=ph.max() - ph.min(), mna_err=err)

def alpha_pred(rho, gam): return math.log(rho) / math.log(rho * gam)

def min_n(rho, gam, decades, ripple_db, nmax=40):
    for n in range(2, nmax):
        r = fit(n, rho, gam)
        if r and r["dec"] >= decades and r["ripple_db"] <= ripple_db:
            return n, r
    return None, None

if __name__ == "__main__":
    print("== closed-form exponent check: alpha_fit vs alpha = ln(rho)/ln(rho*gamma), n=24 ==")
    print(f"{'rho':>6} {'gamma':>6} {'alpha_pred':>10} {'alpha_fit':>9} {'phase deg (pred)':>17} {'ripple dB':>9} {'decades':>7} {'MNA err':>8}")
    for rho, gam in [(2, 2), (PHI, PHI), (2, 1.5), (3, 2), (1.5, 3), (PHI, PHI ** 2), (PHI ** 2, PHI), (4, 2), (2, 4)]:
        r = fit(24, rho, gam)
        a = alpha_pred(rho, gam)
        print(f"{rho:6.3f} {gam:6.3f} {a:10.4f} {r['alpha_fit']:9.4f} {-90*a:8.1f} ({r['phase_mean']:6.1f}) {r['ripple_db']:9.3f} {r['dec']:7.2f} {r['mna_err']:8.1e}")
    print("\n== minimal n for a 3-decade power-law band, ripple <= 1 dB (by ratio class) ==")
    print(f"{'rho':>6} {'gamma':>6} {'alpha':>6} {'ln(rho*gam)':>11} {'n_min':>5} {'bound ceil(D ln10/ln rg)':>25}")
    for rho, gam in [(2, 2), (PHI, PHI), (3, 3), (1.5, 1.5), (2, 1.5), (3, 2), (PHI, PHI**2)]:
        n, r = min_n(rho, gam, 3.0, 1.0)
        lg = math.log(rho * gam)
        print(f"{rho:6.3f} {gam:6.3f} {alpha_pred(rho,gam):6.3f} {lg:11.3f} {str(n):>5} {math.ceil(3*math.log(10)/lg):25d}")
