"""First-principles MEEF teaching experiments and figure generation.

From the article's asset directory:
    python3 simulate.py
"""

# /// script
# requires-python = ">=3.11"
# dependencies = ["numpy>=2.0", "matplotlib>=3.9"]
# ///

import json
import math
from pathlib import Path

import matplotlib
import numpy as np

matplotlib.use("Agg")
import matplotlib.pyplot as plt

OUTPUT = Path(__file__).resolve().parent

# Consistent visual palette matching site style
BLUE = "#24559b"
RUST = "#9d4b1f"
TEAL = "#086960"
PURPLE = "#6c3f8a"
AMBER = "#b87a00"
RED = "#b8292f"
INK = "#263647"
MUTED = "#6d7b88"


def configure_matplotlib():
    plt.rcParams.update({
        "font.family": "DejaVu Sans",
        "font.size": 12.2,
        "axes.spines.top": False,
        "axes.spines.right": False,
        "axes.labelcolor": INK,
        "axes.titlecolor": INK,
        "axes.edgecolor": "#9faebc",
        "text.color": INK,
        "xtick.color": INK,
        "ytick.color": INK,
        "axes.grid": True,
        "grid.color": "#e4eaed",
        "axes.axisbelow": True,
        "figure.facecolor": "white",
        "legend.frameon": False,
    })


# ---------------------------------------------------------------------------
# 2D circular-pupil partially coherent imaging engine (Abbe source integration)
# All lateral lengths in units of lambda / NA; defocus in lambda / NA^2.
# ---------------------------------------------------------------------------

def make_circular_source(sigma_out, sigma_in=0.0, n_r=18, n_theta=36, first_quadrant_only=False):
    """Gauss-Legendre radial + uniform azimuthal quadrature on an annulus/disk."""
    u, wu = np.polynomial.legendre.leggauss(n_r)
    t0, t1 = sigma_in**2, sigma_out**2
    t = 0.5 * (t1 - t0) * u + 0.5 * (t1 + t0)
    wt = 0.5 * (t1 - t0) * wu
    r = np.sqrt(t)
    if first_quadrant_only:
        n_q = max(4, n_theta // 4)
        thetas = (np.arange(n_q) + 0.5) * (0.5 * np.pi / n_q)
        denom = n_q
    else:
        thetas = (np.arange(n_theta) + 0.5) * (2.0 * np.pi / n_theta)
        denom = n_theta
    rr, tt = np.meshgrid(r, thetas, indexing="ij")
    ww = np.broadcast_to(wt[:, None], rr.shape) * (1.0 / denom)
    sx = (rr * np.cos(tt)).ravel()
    sy = (rr * np.sin(tt)).ravel()
    w = ww.ravel()
    w = w / np.sum(w)
    return sx, sy, w


def aerial_1d_periodic_grid(pitch, coeffs, orders, n_x, sx, sy, sw, focus=0.0, blur_sigma=0.0):
    """1D periodic intensity on uniform grid x in [-pitch/2, pitch/2) with optional Gaussian resist blur."""
    x = np.linspace(-pitch / 2.0, pitch / 2.0, n_x, endpoint=False)
    fx = orders / pitch
    gx = sx[:, None] + fx[None, :]
    gy = sy[:, None]
    r2 = gx**2 + gy**2
    pupil = (r2 <= 1.0 + 1e-12) * np.exp(-1j * np.pi * focus * r2)
    exp_mat = np.exp(2j * np.pi * fx[:, None] * x[None, :])
    fields = (pupil * coeffs[None, :]) @ exp_mat
    intensity = np.einsum("s,sx->x", sw, np.abs(fields) ** 2)
    if blur_sigma > 0.0:
        freqs = np.fft.fftfreq(n_x, d=pitch / n_x)
        filt = np.exp(-2.0 * (np.pi * blur_sigma * freqs) ** 2)
        intensity = np.fft.ifft(np.fft.fft(intensity) * filt).real
    return x, intensity


def binary_space_coeffs(w, orders, pitch, bg_amp=0.0):
    """Fourier coefficients of bright opening width w (amp=1) in background bg_amp."""
    fx = orders / pitch
    c = (1.0 - bg_amp) * (w / pitch) * np.sinc(w * fx)
    zero_idx = np.where(orders == 0)[0][0]
    c[zero_idx] += bg_amp
    return c


def binary_dark_line_coeffs(w, orders, pitch, line_amp=0.0):
    """Fourier coefficients of dark line width w (amp=line_amp) in clear background (amp=1)."""
    fx = orders / pitch
    c = -(1.0 - line_amp) * (w / pitch) * np.sinc(w * fx)
    zero_idx = np.where(orders == 0)[0][0]
    c[zero_idx] += 1.0
    return c


def aerial_2d_contact(pitch, w_x, w_y, sx_q, sy_q, sw_q, n_grid=128, focus=0.0, blur_sigma=0.0):
    """2D periodic rectangular bright contact hole in dark field using 4-fold symmetry of source & mask."""
    s_max = float(np.max(np.hypot(sx_q, sy_q)))
    k_max = int(np.floor((1.0 + s_max) * pitch)) + 1
    assert 2 * k_max + 1 < n_grid
    orders = np.arange(-k_max, k_max + 1)
    fx = orders / pitch
    fy = orders / pitch
    mx = (w_x / pitch) * np.sinc(w_x * fx)
    my = (w_y / pitch) * np.sinc(w_y * fy)
    M = np.outer(mx, my)
    idx = orders % n_grid
    FX, FY = np.meshgrid(fx, fy, indexing="ij")

    I_q = np.zeros((n_grid, n_grid), dtype=np.float64)
    for sxi, syi, wi in zip(sx_q, sy_q, sw_q):
        r2 = (FX + sxi) ** 2 + (FY + syi) ** 2
        inside = r2 <= 1.0 + 1e-12
        if not np.any(inside):
            continue
        spec = np.zeros((n_grid, n_grid), dtype=np.complex128)
        pupil_val = np.where(inside, np.exp(-1j * np.pi * focus * r2), 0.0)
        spec[np.ix_(idx, idx)] = M * pupil_val
        field = np.fft.ifft2(spec) * (n_grid * n_grid)
        I_q += wi * (field.real**2 + field.imag**2)

    # Symmetrize over the 4 quadrants (valid for even mask M(-fx,-fy)=M(fx,fy) and circular/annular source)
    # In unshifted FFT grid: x -> -x maps index i -> (-i) % n_grid
    rev = (-np.arange(n_grid)) % n_grid
    I_acc = 0.25 * (I_q + I_q[rev, :] + I_q[:, rev] + I_q[np.ix_(rev, rev)])
    I_2d = np.fft.fftshift(I_acc)
    if blur_sigma > 0.0:
        freqs = np.fft.fftfreq(n_grid, d=pitch / n_grid)
        KX, KY = np.meshgrid(freqs, freqs, indexing="ij")
        filt = np.exp(-2.0 * (np.pi * blur_sigma) ** 2 * (KX**2 + KY**2))
        I_2d = np.fft.ifft2(np.fft.fft2(I_2d) * filt).real
    coords = (np.arange(n_grid) - n_grid // 2) * (pitch / n_grid)
    return coords, I_2d


def find_edge_1d(x, prof, threshold, bright_center=True):
    """Find positive edge x_e > 0 where profile crosses threshold."""
    mask_pos = x >= 0.0
    xp = x[mask_pos]
    yp = prof[mask_pos]
    if bright_center:
        if yp[0] <= threshold:
            return np.nan
        below = np.flatnonzero(yp < threshold)
        if len(below) == 0:
            return np.nan
        i = below[0]
    else:
        if yp[0] >= threshold:
            return np.nan
        above = np.flatnonzero(yp > threshold)
        if len(above) == 0:
            return np.nan
        i = above[0]
    if i == 0:
        return np.nan
    y0, y1 = yp[i - 1], yp[i]
    t = (threshold - y0) / (y1 - y0)
    return float(xp[i - 1] + t * (xp[i] - xp[i - 1]))


def eval_slope_at_x(x, prof, x_e):
    dx = x[1] - x[0]
    dI = np.gradient(prof, dx)
    return float(np.interp(x_e, x, dI))


def solve_mask_for_target_1d(pitch, target_cd, threshold, sx, sy, sw, bright_center=True,
                              focus=0.0, blur_sigma=0.0, bg_amp=0.0, n_x=2048):
    """Scan to bracket, then bisect mask width w_m so printed wafer CD hits target_cd."""
    s_max = float(np.max(np.hypot(sx, sy)))
    k_max = int(np.floor((1.0 + s_max) * pitch)) + 1
    orders = np.arange(-k_max, k_max + 1)

    def printed_cd(w):
        if bright_center:
            coeffs = binary_space_coeffs(w, orders, pitch, bg_amp=bg_amp)
        else:
            coeffs = binary_dark_line_coeffs(w, orders, pitch, line_amp=bg_amp)
        x, prof = aerial_1d_periodic_grid(pitch, coeffs, orders, n_x, sx, sy, sw, focus, blur_sigma)
        xe = find_edge_1d(x, prof, threshold, bright_center=bright_center)
        return 2.0 * xe, x, prof

    lo_scan = max(0.05, target_cd * 0.45)
    hi_scan = min(pitch * 0.90, target_cd * 1.95)
    ws = np.linspace(lo_scan, hi_scan, 35)
    vals = [printed_cd(w)[0] for w in ws]
    bracket = None
    for i in range(len(ws) - 1):
        if np.isfinite(vals[i]) and np.isfinite(vals[i + 1]):
            if vals[i] <= target_cd <= vals[i + 1]:
                bracket = (ws[i], ws[i + 1])
                break
    if bracket is None:
        return np.nan, np.nan, np.nan

    lo, hi = bracket
    for _ in range(34):
        mid = 0.5 * (lo + hi)
        cd_mid, _, _ = printed_cd(mid)
        if np.isnan(cd_mid) or cd_mid < target_cd:
            lo = mid
        else:
            hi = mid
    w_star = 0.5 * (lo + hi)
    dw = 1e-4
    cd_p, _, _ = printed_cd(w_star + dw)
    cd_m, _, _ = printed_cd(w_star - dw)
    meef = (cd_p - cd_m) / (2.0 * dw)

    _, x, prof = printed_cd(w_star)
    slope = eval_slope_at_x(x, prof, target_cd / 2.0)
    nils = target_cd * abs(slope) / threshold
    return float(w_star), float(meef), float(nils)


def solve_mask_for_target_2d_contact(pitch, target_cd, threshold, sx_q, sy_q, sw_q,
                                     focus=0.0, blur_sigma=0.0, n_grid=128):
    """Bracket and bisect square contact mask width w_m so x-slice printed CD hits target_cd."""
    mid_idx = n_grid // 2

    def printed_cd_xy(wx, wy):
        coords, I_2d = aerial_2d_contact(pitch, wx, wy, sx_q, sy_q, sw_q, n_grid, focus, blur_sigma)
        prof = I_2d[:, mid_idx]
        xe = find_edge_1d(coords, prof, threshold, bright_center=True)
        return 2.0 * xe, coords, prof

    lo_scan = max(0.10, target_cd * 0.65)
    hi_scan = min(pitch * 0.90, target_cd * 1.85)
    ws = np.linspace(lo_scan, hi_scan, 26)
    vals = [printed_cd_xy(w, w)[0] for w in ws]
    bracket = None
    for i in range(len(ws) - 1):
        if np.isfinite(vals[i]) and np.isfinite(vals[i + 1]):
            if vals[i] <= target_cd <= vals[i + 1]:
                bracket = (ws[i], ws[i + 1])
                break
    if bracket is None:
        return np.nan, np.nan, np.nan, np.nan, np.nan

    lo, hi = bracket
    for _ in range(28):
        mid = 0.5 * (lo + hi)
        cd_mid, _, _ = printed_cd_xy(mid, mid)
        if np.isnan(cd_mid) or cd_mid < target_cd:
            lo = mid
        else:
            hi = mid
    w_star = 0.5 * (lo + hi)
    dw = 5e-4
    cd_p, _, _ = printed_cd_xy(w_star + dw, w_star + dw)
    cd_m, _, _ = printed_cd_xy(w_star - dw, w_star - dw)
    meef_total = (cd_p - cd_m) / (2.0 * dw)

    cd_xp, _, _ = printed_cd_xy(w_star + dw, w_star)
    cd_xm, _, _ = printed_cd_xy(w_star - dw, w_star)
    meef_x = (cd_xp - cd_xm) / (2.0 * dw)

    cd_yp, _, _ = printed_cd_xy(w_star, w_star + dw)
    cd_ym, _, _ = printed_cd_xy(w_star, w_star - dw)
    meef_y = (cd_yp - cd_ym) / (2.0 * dw)

    _, coords, prof = printed_cd_xy(w_star, w_star)
    slope = eval_slope_at_x(coords, prof, target_cd / 2.0)
    nils = target_cd * abs(slope) / threshold
    return float(w_star), float(meef_total), float(nils), float(meef_x), float(meef_y)


# ---------------------------------------------------------------------------
# Experiment 1: Same source, same resist -> 5 feature types across k1
# ---------------------------------------------------------------------------

def run_experiment_1():
    print("Running Experiment 1: Feature-type MEEF comparison...")
    sx, sy, sw = make_circular_source(sigma_out=0.65, sigma_in=0.0, n_r=22, n_theta=48, first_quadrant_only=False)
    sx_q, sy_q, sw_q = make_circular_source(sigma_out=0.65, sigma_in=0.0, n_r=22, n_theta=48, first_quadrant_only=True)
    threshold = 0.30
    blur_resist = 0.075  # Same resist Gaussian diffusion length in lambda/NA

    k1_grid = np.array([0.38, 0.41, 0.44, 0.48, 0.52, 0.58, 0.65, 0.75])
    iso_pitch_1d = 6.0
    iso_pitch_2d = 3.2

    # Convergence check at k1 = 0.48 (both source refinement and FFT grid refinement)
    sx_f, sy_f, sw_f = make_circular_source(sigma_out=0.65, sigma_in=0.0, n_r=32, n_theta=72, first_quadrant_only=False)
    sx_qf, sy_qf, sw_qf = make_circular_source(sigma_out=0.65, sigma_in=0.0, n_r=32, n_theta=72, first_quadrant_only=True)
    _, m_1d_c, _ = solve_mask_for_target_1d(2 * 0.48, 0.48, threshold, sx, sy, sw, True, 0.0, 0.0)
    _, m_1d_f, _ = solve_mask_for_target_1d(2 * 0.48, 0.48, threshold, sx_f, sy_f, sw_f, True, 0.0, 0.0)
    _, m_2d_c, _, _, _ = solve_mask_for_target_2d_contact(2 * 0.48, 0.48, threshold, sx_q, sy_q, sw_q, 0.0, 0.0, n_grid=128)
    _, m_2d_f, _, _, _ = solve_mask_for_target_2d_contact(2 * 0.48, 0.48, threshold, sx_qf, sy_qf, sw_qf, 0.0, 0.0, n_grid=192)
    print(f"  Convergence check @ k1=0.48: 1D dense diff={abs(m_1d_c - m_1d_f):.2e}, 2D dense diff={abs(m_2d_c - m_2d_f):.2e}")

    features = [
        "1D Dense L/S (1:1)",
        "1D Isolated Dark Line",
        "1D Isolated Bright Space",
        "2D Isolated Contact",
        "2D Dense Contact (1:1)",
    ]
    res = {
        "k1": k1_grid.tolist(),
        "threshold": threshold,
        "sigma": 0.65,
        "blur_resist": blur_resist,
        "convergence": {
            "1d_dense_k1_0.48_diff": abs(m_1d_c - m_1d_f),
            "2d_dense_k1_0.48_diff": abs(m_2d_c - m_2d_f),
        },
        "aerial": {f: {"meef": [], "nils": [], "mask_w": []} for f in features},
        "resist": {f: {"meef": [], "nils": [], "mask_w": []} for f in features},
        "contact_decomposition_k1_0.48": {},
    }

    for mode, blur in [("aerial", 0.0), ("resist", blur_resist)]:
        for k1 in k1_grid:
            w, m, nils = solve_mask_for_target_1d(2 * k1, k1, threshold, sx, sy, sw, True, 0.0, blur)
            res[mode]["1D Dense L/S (1:1)"]["mask_w"].append(w)
            res[mode]["1D Dense L/S (1:1)"]["meef"].append(m)
            res[mode]["1D Dense L/S (1:1)"]["nils"].append(nils)

            w, m, nils = solve_mask_for_target_1d(iso_pitch_1d, k1, threshold, sx, sy, sw, False, 0.0, blur)
            res[mode]["1D Isolated Dark Line"]["mask_w"].append(w)
            res[mode]["1D Isolated Dark Line"]["meef"].append(m)
            res[mode]["1D Isolated Dark Line"]["nils"].append(nils)

            w, m, nils = solve_mask_for_target_1d(iso_pitch_1d, k1, threshold, sx, sy, sw, True, 0.0, blur)
            res[mode]["1D Isolated Bright Space"]["mask_w"].append(w)
            res[mode]["1D Isolated Bright Space"]["meef"].append(m)
            res[mode]["1D Isolated Bright Space"]["nils"].append(nils)

            w, m, nils, mx, my = solve_mask_for_target_2d_contact(iso_pitch_2d, k1, threshold, sx_q, sy_q, sw_q, 0.0, blur, n_grid=128)
            res[mode]["2D Isolated Contact"]["mask_w"].append(w)
            res[mode]["2D Isolated Contact"]["meef"].append(m)
            res[mode]["2D Isolated Contact"]["nils"].append(nils)
            if mode == "aerial" and np.isclose(k1, 0.48):
                res["contact_decomposition_k1_0.48"]["2D Isolated Contact"] = {
                    "meef_total": m, "meef_x": mx, "meef_y": my, "nils": nils, "mask_w": w
                }

            w, m, nils, mx, my = solve_mask_for_target_2d_contact(2 * k1, k1, threshold, sx_q, sy_q, sw_q, 0.0, blur, n_grid=128)
            res[mode]["2D Dense Contact (1:1)"]["mask_w"].append(w)
            res[mode]["2D Dense Contact (1:1)"]["meef"].append(m)
            res[mode]["2D Dense Contact (1:1)"]["nils"].append(nils)
            if mode == "aerial" and np.isclose(k1, 0.48):
                res["contact_decomposition_k1_0.48"]["2D Dense Contact (1:1)"] = {
                    "meef_total": m, "meef_x": mx, "meef_y": my, "nils": nils, "mask_w": w
                }

    return res


# ---------------------------------------------------------------------------
# Experiment 2: Analytical 1/gamma law, defocus, and 6% Att-PSM
# ---------------------------------------------------------------------------

def run_experiment_2():
    print("Running Experiment 2: 1/gamma analytical law, defocus, and Att-PSM...")
    sx, sy, sw = make_circular_source(sigma_out=0.85, sigma_in=0.50, n_r=22, n_theta=60)
    pitches = np.linspace(0.62, 1.35, 30)

    meef_bim_f0 = []
    meef_bim_f30 = []
    meef_1_over_gamma = []
    gamma_vals = []

    meef_bim_fixed_th = []
    meef_att_fixed_th = []
    nils_bim_fixed_th = []
    nils_att_fixed_th = []

    for p in pitches:
        f1 = 1.0 / p
        pass_p1 = (sx + f1) ** 2 + sy**2 <= 1.0 + 1e-12
        pass_m1 = (sx - f1) ** 2 + sy**2 <= 1.0 + 1e-12
        # In the two-beam regime the two sets of source points are disjoint.
        gamma = float(np.sum(sw[pass_p1 | pass_m1])) if p <= 1.0 else np.nan
        gamma_vals.append(gamma)
        meef_1_over_gamma.append(1.0 / gamma if gamma > 1e-6 else np.nan)

        k_max = int(np.floor((1.0 + 0.85) * p)) + 1
        orders = np.arange(-k_max, k_max + 1)

        def calc_meef_at_half_pitch(focus_val):
            w0 = p / 2.0
            c0 = binary_space_coeffs(w0, orders, p, bg_amp=0.0)
            x, prof0 = aerial_1d_periodic_grid(p, c0, orders, 2048, sx, sy, sw, focus=0.0)
            th = float(np.interp(p / 4.0, x, prof0))
            dw = 1e-4
            cp = binary_space_coeffs(w0 + dw, orders, p, bg_amp=0.0)
            cm = binary_space_coeffs(w0 - dw, orders, p, bg_amp=0.0)
            _, prof_p = aerial_1d_periodic_grid(p, cp, orders, 2048, sx, sy, sw, focus=focus_val)
            _, prof_m = aerial_1d_periodic_grid(p, cm, orders, 2048, sx, sy, sw, focus=focus_val)
            xe_p = find_edge_1d(x, prof_p, th, bright_center=True)
            xe_m = find_edge_1d(x, prof_m, th, bright_center=True)
            return float(2.0 * (xe_p - xe_m) / (2.0 * dw))

        meef_bim_f0.append(calc_meef_at_half_pitch(0.0))
        meef_bim_f30.append(calc_meef_at_half_pitch(0.30))

        # Fixed threshold = 0.25 (standard dose-to-size regime where both BIM and 6% Att-PSM print cleanly)
        _, m_b, n_b = solve_mask_for_target_1d(p, p / 2.0, 0.25, sx, sy, sw, True, 0.0, 0.0, bg_amp=0.0)
        _, m_a, n_a = solve_mask_for_target_1d(p, p / 2.0, 0.25, sx, sy, sw, True, 0.0, 0.0, bg_amp=-np.sqrt(0.06))
        meef_bim_fixed_th.append(m_b)
        meef_att_fixed_th.append(m_a)
        nils_bim_fixed_th.append(n_b)
        nils_att_fixed_th.append(n_a)

    # Check exact agreement of 1/gamma in 2-beam regime (k1 <= 0.50)
    k1_arr = pitches / 2.0
    two_beam = k1_arr <= 0.50
    max_2beam_diff = float(np.max(np.abs(np.array(meef_bim_f0)[two_beam] - np.array(meef_1_over_gamma)[two_beam])))
    print(f"  2-beam 1/gamma exactness check (k1 <= 0.50): max diff = {max_2beam_diff:.2e}")

    return {
        "pitches": pitches.tolist(),
        "k1": k1_arr.tolist(),
        "gamma_eff": gamma_vals,
        "meef_1_over_gamma": meef_1_over_gamma,
        "meef_bim_f0_exact_1to1": meef_bim_f0,
        "meef_bim_f030_exact_1to1": meef_bim_f30,
        "max_2beam_1_over_gamma_diff": max_2beam_diff,
        "fixed_threshold": 0.25,
        "meef_bim_fixed_th": meef_bim_fixed_th,
        "meef_att6_fixed_th": meef_att_fixed_th,
        "nils_bim_fixed_th": nils_bim_fixed_th,
        "nils_att6_fixed_th": nils_att_fixed_th,
    }


# ---------------------------------------------------------------------------
# Experiment 3: Negative MEEF (periodic CPL grating and cross-MEEF oscillation)
# ---------------------------------------------------------------------------

def run_experiment_3():
    print("Running Experiment 3: Negative MEEF (CPL grating and cross-MEEF)...")
    # Part A: Periodic 180-deg CPL grating (pitch = 0.90 lambda/NA, annular sigma 0.50-0.85, threshold = 0.18)
    sx_c, sy_c, sw_c = make_circular_source(sigma_out=0.85, sigma_in=0.50, n_r=18, n_theta=48)
    pitch_cpl = 0.90
    k_max = int(np.floor((1.0 + 0.85) * pitch_cpl)) + 1
    orders = np.arange(-k_max, k_max + 1)
    th_cpl = 0.18

    wm_cpl = np.linspace(0.17, 0.39, 89)
    cd_cpl = []
    i0_cpl = []
    meef_cpl = []
    dw = 2e-4
    for w in wm_cpl:
        coeffs = binary_dark_line_coeffs(w, orders, pitch_cpl, line_amp=-1.0)
        x, prof = aerial_1d_periodic_grid(pitch_cpl, coeffs, orders, 2048, sx_c, sy_c, sw_c, focus=0.0)
        i_center = float(np.interp(0.0, x, prof))
        i0_cpl.append(i_center)
        xe = find_edge_1d(x, prof, th_cpl, bright_center=False)
        cd_val = 2.0 * xe
        cd_cpl.append(cd_val)

        cp = binary_dark_line_coeffs(w + dw, orders, pitch_cpl, line_amp=-1.0)
        cm = binary_dark_line_coeffs(w - dw, orders, pitch_cpl, line_amp=-1.0)
        _, pp = aerial_1d_periodic_grid(pitch_cpl, cp, orders, 2048, sx_c, sy_c, sw_c, focus=0.0)
        _, pm = aerial_1d_periodic_grid(pitch_cpl, cm, orders, 2048, sx_c, sy_c, sw_c, focus=0.0)
        cdp = 2.0 * find_edge_1d(x, pp, th_cpl, bright_center=False)
        cdm = 2.0 * find_edge_1d(x, pm, th_cpl, bright_center=False)
        meef_cpl.append(float((cdp - cdm) / (2.0 * dw)))

    cd_arr = np.array(cd_cpl)
    meef_arr = np.array(meef_cpl)
    valid_neg = np.flatnonzero(np.isfinite(meef_arr) & (meef_arr < 0))
    peak_idx = int(np.nanargmax(cd_arr))
    neg_summary = {
        "pitch": pitch_cpl,
        "threshold": th_cpl,
        "peak_wm_zero_meef": float(wm_cpl[peak_idx]),
        "peak_cd": float(cd_arr[peak_idx]),
        "wm_range_negative": [float(wm_cpl[valid_neg[0]]), float(wm_cpl[valid_neg[-1]])],
        "meef_at_wm_0.34": float(np.interp(0.34, wm_cpl, meef_arr)),
        "meef_at_wm_0.36": float(np.interp(0.36, wm_cpl, meef_arr)),
    }
    print(f"  CPL Negative MEEF: peak CD={neg_summary['peak_cd']:.4f} at wm={neg_summary['peak_wm_zero_meef']:.3f}; "
          f"MEEF(0.34)={neg_summary['meef_at_wm_0.34']:.2f}, MEEF(0.36)={neg_summary['meef_at_wm_0.36']:.2f}")

    # Part B: Cross-MEEF of symmetric neighboring bars vs distance d
    pitch_sb = 10.0
    th_sb = 0.30
    w_main = 0.45
    w_sb = 0.14
    distances = np.linspace(0.58, 2.35, 72)
    cross_meef_results = {}
    for sig_label, sig_val in [("sigma=0.35", 0.35), ("sigma=0.65", 0.65)]:
        sx_s, sy_s, sw_s = make_circular_source(sigma_out=sig_val, sigma_in=0.0, n_r=14, n_theta=28)
        km = int(np.floor((1.0 + sig_val) * pitch_sb)) + 1
        ords = np.arange(-km, km + 1)
        fx = ords / pitch_sb

        def get_main_cd(d_val, ws_val):
            c = -(w_main / pitch_sb) * np.sinc(w_main * fx) - 2.0 * (ws_val / pitch_sb) * np.sinc(ws_val * fx) * np.cos(2.0 * np.pi * d_val * fx)
            c[np.where(ords == 0)[0][0]] += 1.0
            x, prof = aerial_1d_periodic_grid(pitch_sb, c, ords, 4096, sx_s, sy_s, sw_s, focus=0.0)
            xe = find_edge_1d(x, prof, th_sb, bright_center=False)
            return 2.0 * xe

        dw_s = 1e-4
        cmeef = []
        for d_val in distances:
            cdp = get_main_cd(d_val, w_sb + dw_s)
            cdm = get_main_cd(d_val, w_sb - dw_s)
            cmeef.append(float((cdp - cdm) / (2.0 * dw_s)))
        cross_meef_results[sig_label] = cmeef
        min_i = int(np.nanargmin(cmeef))
        print(f"  Cross-MEEF ({sig_label}): min={cmeef[min_i]:.3f} @ d={distances[min_i]:.2f}, max={np.nanmax(cmeef):.3f}")

    return {
        "cpl": {
            "wm": wm_cpl.tolist(),
            "cd": [float(v) if np.isfinite(v) else None for v in cd_arr],
            "meef": [float(v) if np.isfinite(v) else None for v in meef_arr],
            "i_center": i0_cpl,
            "summary": neg_summary,
        },
        "cross_meef": {
            "distances": distances.tolist(),
            "w_main": w_main,
            "w_sb": w_sb,
            "values": cross_meef_results,
        },
    }


# ---------------------------------------------------------------------------
# Experiment 4: OPC convergence with fixed damping vs MEEF-scaled vs Matrix OPC
# ---------------------------------------------------------------------------

def run_experiment_4():
    print("Running Experiment 4: OPC convergence & MEEF matrix...")
    n_iter = 10
    alpha_fixed = 0.65
    e0 = 5.0  # initial EPE = 5.0 nm

    cases_scalar = {
        "M = 1.0 (fixed α=0.65)": (1.0, alpha_fixed),
        "M = 3.4 (fixed α=0.65)": (3.4, alpha_fixed),
        "M = -0.8 (fixed α=0.65)": (-0.8, alpha_fixed),
        "M = 3.4 (MEEF-scaled α=0.65/M)": (3.4, 0.65 / 3.4),
    }
    trajs_a = {}
    for label, (M, a) in cases_scalar.items():
        e = [e0]
        for _ in range(n_iter):
            e.append(e[-1] * (1.0 - a * M))
        trajs_a[label] = e

    # Panel B: Tight coupled 2-line optical pair (sep = 0.66 lambda/NA, annular 0.50-0.85, th = 0.30)
    sx, sy, sw = make_circular_source(sigma_out=0.85, sigma_in=0.50, n_r=16, n_theta=36)
    pitch_pair = 6.0
    km = int(np.floor((1.0 + 0.85) * pitch_pair)) + 1
    ords = np.arange(-km, km + 1)
    fx = ords / pitch_pair
    th = 0.30
    sep = 0.66

    def eval_pair_cds(w1, w2):
        c = (
            -(w1 / pitch_pair) * np.sinc(w1 * fx) * np.exp(2j * np.pi * (sep / 2.0) * fx)
            - (w2 / pitch_pair) * np.sinc(w2 * fx) * np.exp(-2j * np.pi * (sep / 2.0) * fx)
        )
        c[np.where(ords == 0)[0][0]] += 1.0
        x, prof = aerial_1d_periodic_grid(pitch_pair, c, ords, 4096, sx, sy, sw, focus=0.0)
        out = []
        for x_center in (-sep / 2.0, sep / 2.0):
            m = np.abs(x - x_center) <= sep * 0.49
            xl, yl = x[m], prof[m]
            ic = int(np.argmin(yl))
            if yl[ic] >= th:
                out.append(np.nan)
                continue
            left = np.flatnonzero(yl[:ic] > th)
            right = np.flatnonzero(yl[ic:] > th)
            if len(left) == 0 or len(right) == 0:
                out.append(np.nan)
                continue
            iL = left[-1]
            xL = xl[iL] + (th - yl[iL]) / (yl[iL + 1] - yl[iL]) * (xl[iL + 1] - xl[iL])
            iR = ic + right[0]
            xR = xl[iR - 1] + (th - yl[iR - 1]) / (yl[iR] - yl[iR - 1]) * (xl[iR] - xl[iR - 1])
            out.append(float(xR - xL))
        return np.array(out)

    target_pair = np.array([0.34, 0.28])
    w_init = np.array([0.34, 0.28])
    dw = 1e-4
    J0 = np.zeros((2, 2))
    J0[:, 0] = (eval_pair_cds(w_init[0] + dw, w_init[1]) - eval_pair_cds(w_init[0] - dw, w_init[1])) / (2 * dw)
    J0[:, 1] = (eval_pair_cds(w_init[0], w_init[1] + dw) - eval_pair_cds(w_init[0], w_init[1] - dw)) / (2 * dw)
    print(f"  Tight 2-line optical MEEF matrix J0 =\n{J0}")

    def run_nonlinear_opc(method, n_steps=10):
        w = w_init.copy()
        errs = []
        for _ in range(n_steps + 1):
            cd = eval_pair_cds(*w)
            if not np.all(np.isfinite(cd)):
                errs.extend([np.nan] * (n_steps + 1 - len(errs)))
                break
            e = cd - target_pair
            errs.append(float(np.max(np.abs(e))))
            if method == "fixed_diag":
                w = w - 0.85 * e
            elif method == "self_meef":
                d1 = (eval_pair_cds(w[0] + dw, w[1])[0] - eval_pair_cds(w[0] - dw, w[1])[0]) / (2 * dw)
                d2 = (eval_pair_cds(w[0], w[1] + dw)[1] - eval_pair_cds(w[0], w[1] - dw)[1]) / (2 * dw)
                w = w - 0.85 * e / np.array([d1, d2])
            elif method == "matrix_opc":
                Jm = np.zeros((2, 2))
                Jm[:, 0] = (eval_pair_cds(w[0] + dw, w[1]) - eval_pair_cds(w[0] - dw, w[1])) / (2 * dw)
                Jm[:, 1] = (eval_pair_cds(w[0], w[1] + dw) - eval_pair_cds(w[0], w[1] - dw)) / (2 * dw)
                lam = 0.01
                step = np.linalg.solve(Jm.T @ Jm + lam * np.eye(2), Jm.T @ e)
                w = w - 0.90 * step
        return errs, w.tolist()

    e_fixed, w_fixed = run_nonlinear_opc("fixed_diag")
    e_self, w_self = run_nonlinear_opc("self_meef")
    e_mat, w_mat = run_nonlinear_opc("matrix_opc")
    print(f"  Pair OPC max|err| @ iter 5: fixed={e_fixed[5]:.5f}, self_meef={e_self[5]:.5f}, matrix={e_mat[5]:.5f}")
    print(f"  Pair OPC max|err| @ iter 10: fixed={e_fixed[10]:.5f}, self_meef={e_self[10]:.5f}, matrix={e_mat[10]:.5f}")

    return {
        "scalar": {
            "iterations": list(range(n_iter + 1)),
            "trajectories": trajs_a,
        },
        "nonlinear_pair": {
            "separation": sep,
            "target_cds": target_pair.tolist(),
            "initial_jacobian": J0.tolist(),
            "iterations": list(range(11)),
            "max_err_fixed_diag": e_fixed,
            "max_err_self_meef": e_self,
            "max_err_matrix_opc": e_mat,
            "final_w_matrix": w_mat,
        },
    }


# ---------------------------------------------------------------------------
# Plotting
# ---------------------------------------------------------------------------

def plot_all(r1, r2, r3, r4):
    configure_matplotlib()
    plt.rcParams.update({"axes.titlesize": 12.2, "font.size": 11.5})

    def save(fig, name):
        fig.savefig(OUTPUT / name, dpi=180, bbox_inches="tight", pad_inches=0.14)
        plt.close(fig)

    # --- Figure 1: Feature-type MEEF comparison ---
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.7), layout="constrained")
    k1 = np.array(r1["k1"])
    styles = [
        ("1D Dense L/S (1:1)", BLUE, "-", "o"),
        ("1D Isolated Dark Line", TEAL, "--", "s"),
        ("1D Isolated Bright Space", AMBER, "-.", "^"),
        ("2D Isolated Contact", PURPLE, ":", "D"),
        ("2D Dense Contact (1:1)", RUST, "-", "v"),
    ]
    for name, color, ls, mk in styles:
        y = np.array(r1["aerial"][name]["meef"], dtype=float)
        ax1.plot(k1, y, color=color, ls=ls, marker=mk, ms=5.2, lw=2.1, label=name)
    ax1.axhline(1.0, color=MUTED, ls=":", lw=1.2)
    ax1.text(0.755, 0.72, "Ideal MEEF = 1", ha="right", va="top", fontsize=9.5, color=MUTED)
    ax1.set(
        title="Same source (σ = 0.65), aerial threshold",
        xlabel="Normalized target CD  k₁ = CD / (λ/NA)",
        ylabel="MEEF = ∂CD_wafer / ∂(CD_mask / R)",
        xlim=(0.36, 0.77),
        ylim=(0.5, 8.5),
    )
    ax1.legend(loc="upper right", fontsize=9.4)

    idx48 = int(np.argmin(np.abs(k1 - 0.48)))
    short_names = ["1D Dense\nL/S", "1D Iso\nDark Line", "1D Iso\nSpace", "2D Iso\nContact", "2D Dense\nContact"]
    full_names = [s[0] for s in styles]
    m_aer = [r1["aerial"][n]["meef"][idx48] for n in full_names]
    m_res = [r1["resist"][n]["meef"][idx48] for n in full_names]
    x_pos = np.arange(len(short_names))
    bw = 0.36
    b1 = ax2.bar(x_pos - bw / 2, m_aer, width=bw, color=BLUE, alpha=0.88, label="Aerial image (L_D = 0)")
    b2 = ax2.bar(x_pos + bw / 2, m_res, width=bw, color=RUST, alpha=0.88, label="Same resist blur (L_D = 0.075 λ/NA)")
    ax2.axhline(1.0, color=MUTED, ls=":", lw=1.2)
    for bar in list(b1) + list(b2):
        h = bar.get_height()
        if np.isfinite(h):
            ax2.text(bar.get_x() + bar.get_width() / 2, h + 0.06, f"{h:.2f}", ha="center", va="bottom", fontsize=9.0, color=INK)
    ax2.set(
        title="Same resist blur at k₁ = 0.48",
        ylabel="MEEF",
        ylim=(0, np.nanmax(m_res) * 1.24),
    )
    ax2.set_xticks(x_pos)
    ax2.set_xticklabels(short_names, fontsize=9.6)
    ax2.legend(loc="upper left", fontsize=9.4)
    save(fig, "meef-feature-types.png")

    # --- Figure 2: 1/gamma law, defocus, and 6% Att-PSM ---
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.7), layout="constrained")
    k1_2 = np.array(r2["k1"])
    ax1.plot(k1_2, r2["meef_bim_f0_exact_1to1"], color=BLUE, lw=2.4, label="Source-sampled model (f = 0)")
    ax1.plot(k1_2, r2["meef_1_over_gamma"], color=RUST, lw=2.0, ls="--", label="Two-beam result: 1/γ")
    ax1.plot(k1_2, r2["meef_bim_f030_exact_1to1"], color=TEAL, lw=2.0, ls="-.", label="Defocus f = 0.30 λ/NA²")
    ax1.axvline(0.50, color=MUTED, ls=":", lw=1.1)
    ax1.text(0.492, 3.15, "2-beam exact\n(k₁ ≤ 0.50)", ha="right", va="top", fontsize=9.2, color=MUTED)
    ax1.axhline(1.0, color=MUTED, ls=":", lw=1.0)
    ax1.set(
        title="1:1 Dense L/S, annular σ = 0.50–0.85",
        xlabel="Half-pitch  k₁ = p / (2λ/NA)",
        ylabel="MEEF",
        xlim=(0.30, 0.68),
        ylim=(0.4, 6.0),
    )
    ax1.legend(loc="upper right", fontsize=9.2)

    ax2.plot(k1_2, r2["meef_bim_fixed_th"], color=RUST, lw=2.3, label="Binary mask (BIM), MEEF")
    ax2.plot(k1_2, r2["meef_att6_fixed_th"], color=TEAL, lw=2.3, label="6% Att-PSM, MEEF")
    ax2_r = ax2.twinx()
    ax2_r.spines["top"].set_visible(False)
    ax2_r.spines["right"].set_color("#9faebc")
    ax2_r.plot(k1_2, r2["nils_bim_fixed_th"], color=RUST, lw=1.6, ls=":", alpha=0.85, label="BIM NILS (right)")
    ax2_r.plot(k1_2, r2["nils_att6_fixed_th"], color=TEAL, lw=1.6, ls=":", alpha=0.85, label="6% Att-PSM NILS (right)")
    ax2.set(
        title="6% Att-PSM vs BIM at fixed th = 0.25",
        xlabel="Half-pitch  k₁ = p / (2λ/NA)",
        ylabel="MEEF (solid)",
        xlim=(0.30, 0.68),
    )
    ax2_r.set_ylabel("NILS (dotted)", color=INK)
    ax2_r.set_ylim(0.5, 4.5)
    h1, l1 = ax2.get_legend_handles_labels()
    h2, l2 = ax2_r.get_legend_handles_labels()
    ax2.legend(h1 + h2, l1 + l2, loc="upper center", fontsize=9.0)
    save(fig, "meef-pitch-mechanism.png")

    # --- Figure 3: Negative MEEF in the CPL grating and neighboring bars ---
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.7), layout="constrained")
    wm = np.array(r3["cpl"]["wm"])
    cd = np.array([np.nan if v is None else v for v in r3["cpl"]["cd"]])
    meef_c = np.array([np.nan if v is None else v for v in r3["cpl"]["meef"]])
    neg_rng = r3["cpl"]["summary"]["wm_range_negative"]

    ax1.axvspan(neg_rng[0], neg_rng[1], color="#f8dede", alpha=0.75, label="Negative MEEF zone")
    ax1.plot(wm, meef_c, color=RED, lw=2.3, label="MEEF = ∂CD_w / ∂w_m")
    ax1.axhline(0.0, color=INK, lw=1.1, ls="--")
    ax1_r = ax1.twinx()
    ax1_r.spines["top"].set_visible(False)
    ax1_r.spines["right"].set_color("#9faebc")
    ax1_r.plot(wm, cd, color=BLUE, lw=2.1, ls="-.", label="Printed dark CD (right)")
    ax1.set(
        title="180° CPL grating (p = 0.90, th = 0.18)",
        xlabel="Mask 180° phase width  w_m (λ/NA)",
        ylabel="MEEF (solid red)",
        xlim=(0.17, 0.39),
        ylim=(-10.5, 10.5),
    )
    ax1_r.set_ylabel("Wafer dark-line CD (λ/NA, blue)", color=BLUE)
    ax1_r.set_ylim(0.0, 0.36)
    h1, l1 = ax1.get_legend_handles_labels()
    h2, l2 = ax1_r.get_legend_handles_labels()
    ax1.legend(h1 + h2, l1 + l2, loc="lower left", fontsize=9.0, frameon=True, facecolor="white")

    dists = np.array(r3["cross_meef"]["distances"])
    cm35 = np.array(r3["cross_meef"]["values"]["sigma=0.35"], dtype=float)
    cm65 = np.array(r3["cross_meef"]["values"]["sigma=0.65"], dtype=float)
    ax2.axhline(0.0, color=INK, lw=1.1, ls="--")
    ax2.fill_between(dists, cm35, 0.0, where=cm35 < 0, color="#dce8f7", alpha=0.70, label="Negative cross-MEEF (σ = 0.35)")
    ax2.plot(dists, cm35, color=BLUE, lw=2.2, label="σ = 0.35 (higher coherence)")
    ax2.plot(dists, cm65, color=TEAL, lw=2.2, ls="--", label="σ = 0.65 (lower coherence)")
    ax2.set(
        title="Cross-MEEF of symmetric neighbor bars",
        xlabel="Center-to-center distance  d (λ/NA)",
        ylabel="Cross-MEEF  ∂CD_main / ∂w_neighbor",
        xlim=(0.58, 2.35),
        ylim=(-0.55, 3.0),
    )
    ax2.legend(loc="upper right", fontsize=9.2)
    save(fig, "negative-meef.png")

    # --- Figure 4: OPC convergence & Matrix OPC ---
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.7), layout="constrained")
    it_a = np.array(r4["scalar"]["iterations"])
    trajs = r4["scalar"]["trajectories"]
    plot_cfg = [
        ("M = 1.0 (fixed α=0.65)", BLUE, "-", "o", 6.2, 2.8),
        ("M = 3.4 (fixed α=0.65)", RUST, "--", "s", 4.8, 2.1),
        ("M = -0.8 (fixed α=0.65)", RED, ":", "^", 5.2, 2.1),
        ("M = 3.4 (MEEF-scaled α=0.65/M)", TEAL, "--", "D", 4.0, 1.9),
    ]
    for label, color, ls, mk, ms, lw in plot_cfg:
        y = np.array(trajs[label])
        ax1.plot(it_a, y, color=color, ls=ls, marker=mk, ms=ms, lw=lw, label=label)
    ax1.axhline(0.0, color=MUTED, lw=1.0, ls=":")
    ax1.set(
        title="Fixed damping fails at high or negative MEEF",
        xlabel="OPC iteration",
        ylabel="Signed EPE residual (nm, symlog)",
        xlim=(0, 10),
    )
    ax1.set_yscale("symlog", linthresh=1.0)
    ax1.legend(loc="lower left", fontsize=9.0, frameon=True, facecolor="white")

    it_b = np.array(r4["nonlinear_pair"]["iterations"])
    ax2.semilogy(it_b, np.array(r4["nonlinear_pair"]["max_err_fixed_diag"], dtype=float),
                 color=RUST, ls="--", marker="s", ms=4.8, lw=2.1, label="Fixed diagonal step (α = 0.85)")
    ax2.semilogy(it_b, np.array(r4["nonlinear_pair"]["max_err_self_meef"], dtype=float),
                 color=BLUE, ls="-.", marker="o", ms=4.8, lw=2.1, label="Self-MEEF damped step")
    ax2.semilogy(it_b, np.array(r4["nonlinear_pair"]["max_err_matrix_opc"], dtype=float),
                 color=TEAL, ls="-", marker="D", ms=4.8, lw=2.2, label="Regularized MEEF-matrix OPC")
    ax2.set(
        title="Coupled two-line optical OPC (sep = 0.66)",
        xlabel="OPC iteration",
        ylabel="Max |CD error| (λ/NA, log scale)",
        xlim=(0, 10),
    )
    ax2.legend(loc="upper right", fontsize=9.2)
    save(fig, "opc-meef-convergence.png")


def json_ready(value):
    """Serialize missing contour measurements as JSON null."""
    if isinstance(value, dict):
        return {key: json_ready(item) for key, item in value.items()}
    if isinstance(value, list):
        return [json_ready(item) for item in value]
    if isinstance(value, float) and not math.isfinite(value):
        return None
    return value


def main():
    import sys
    if "--plot-only" in sys.argv and (OUTPUT / "results.json").exists():
        report = json.loads((OUTPUT / "results.json").read_text())
        plot_all(
            report["experiment_1_feature_types"],
            report["experiment_2_pitch_and_attpsm"],
            report["experiment_3_negative_meef"],
            report["experiment_4_opc_convergence"],
        )
        print("Re-plotted all figures from results.json.")
        return
    r1 = run_experiment_1()
    r2 = run_experiment_2()
    r3 = run_experiment_3()
    r4 = run_experiment_4()
    report = {
        "experiment_1_feature_types": r1,
        "experiment_2_pitch_and_attpsm": r2,
        "experiment_3_negative_meef": r3,
        "experiment_4_opc_convergence": r4,
    }
    (OUTPUT / "results.json").write_text(json.dumps(json_ready(report), indent=2, allow_nan=False) + "\n")
    plot_all(r1, r2, r3, r4)
    print("All figures and results.json generated successfully.")


if __name__ == "__main__":
    main()
