"""Optimal nonlinearity of the unconventional photon blockade at large coupling.

Two coupled cavities, each with a Kerr term, the first one driven coherently:

    H = sum_i [ Delta a_i^+ a_i + U a_i^+ a_i^+ a_i a_i ] + J (a_1^+ a_2 + h.c.) + F (a_1^+ + a_1)

in the frame of the drive (Delta = cavity frequency - drive frequency), with a loss rate
kappa per cavity (full linewidth). Note the Kerr convention: U a^+ a^+ a a, with no 1/2.

Method A, analytic. To lowest order in F the amplitude of two photons in the driven
cavity vanishes when (Bamba et al., Phys. Rev. A 83, 021802(R) (2011))

    2 E^2 (E + U) + J^2 U = 0,      E = Delta - i kappa / 2.

For J >> kappa this gives Delta = kappa / (2 sqrt 3) and U = (2 / (3 sqrt 3)) kappa^3 / J^2.
The closed-form solution is Eqs. (27)-(28) of Flayac and Savona, Phys. Rev. A 96, 053810
(2017); the script checks that it solves the condition above.

Method B, numerical and independent of A. Steady state of the full master equation in a
truncated Fock space; the nonlinearity that minimises g2(0) of the driven cavity is read
from a parabola fitted around the minimum, and the calculation is repeated with a larger
Fock space and a weaker drive to check that the answer has stopped moving.

Copyright (c) 2026 Hugo Flayac. All rights reserved. You may download and run this script,
modified or not, for the sole purpose of checking the result. Do not redistribute it.

Run:  python upb-optimal-nonlinearity.py [figure.json]
Needs numpy and scipy only. Takes about half a minute.
"""

import json
import sys

import numpy as np
from scipy.optimize import brentq

PREFACTOR = 2 / (3 * np.sqrt(3))


def optimum_from_amplitudes(J, kappa):
    """Method A: real (Delta, U) solving 2 E^2 (E + U) + J^2 U = 0."""

    def u_of(delta):
        e = delta - 0.5j * kappa
        return -2 * e**3 / (2 * e**2 + J**2)

    # U must be real: find the detuning where its imaginary part crosses zero.
    delta = brentq(lambda d: u_of(d).imag, 0.05 * kappa, 0.5 * kappa, xtol=1e-14)
    return delta, u_of(delta).real


def optimum_closed_form(J, kappa):
    """Eqs. (27) and (28) of Flayac and Savona, Phys. Rev. A 96, 053810 (2017)."""
    delta = 0.5 * np.sqrt(np.sqrt(9 * J**4 + 8 * kappa**2 * J**2) - kappa**2 - 3 * J**2)
    return delta, delta * (4 * delta**2 + 5 * kappa**2) / (2 * (2 * J**2 - kappa**2))


def g2_master_equation(J, kappa, delta, U, F, cutoff):
    """Method B: g2(0) of the driven cavity from the steady state of the master equation."""
    a = np.diag(np.sqrt(np.arange(1, cutoff)), 1)
    one = np.eye(cutoff)
    a1, a2 = np.kron(a, one), np.kron(one, a)
    dim = cutoff**2
    eye = np.eye(dim)

    def kerr(op):
        n = op.conj().T @ op
        return delta * n + U * (n @ n - n)

    H = kerr(a1) + kerr(a2) + J * (a1.conj().T @ a2 + a2.conj().T @ a1) + F * (a1 + a1.conj().T)

    # Row-major vectorisation: vec(A rho B) = (A kron B^T) vec(rho).
    L = -1j * (np.kron(H, eye) - np.kron(eye, H.T))
    for c in (a1, a2):
        n = c.conj().T @ c
        L += kappa * (np.kron(c, c.conj()) - 0.5 * np.kron(n, eye) - 0.5 * np.kron(eye, n.T))

    # Replace one redundant equation by the normalisation Tr(rho) = 1.
    L[0, :] = eye.reshape(-1)
    rhs = np.zeros(dim * dim, dtype=complex)
    rhs[0] = 1
    rho = np.linalg.solve(L, rhs).reshape(dim, dim)

    n1 = a1.conj().T @ a1
    population = np.trace(n1 @ rho).real
    pairs = np.trace(a1.conj().T @ a1.conj().T @ a1 @ a1 @ rho).real
    return pairs / population**2


def optimum_from_master_equation(J, kappa, F, cutoff, window=2e-3, samples=21):
    """The U that minimises g2(0), at the detuning given by method A.

    g2 is a smooth parabola near its minimum, so the minimum is read from a least-squares
    parabola through `samples` points within +-`window` (relative) of the analytic value.
    A scalar minimiser stalls here: the parabola is too flat for it at double precision.
    """
    delta, u_a = optimum_from_amplitudes(J, kappa)
    offsets = np.linspace(-window, window, samples)
    g2 = [g2_master_equation(J, kappa, delta, u_a * (1 + x), F, cutoff) for x in offsets]
    c2, c1, c0 = np.polyfit(offsets, g2, 2)
    vertex = -c1 / (2 * c2)
    return u_a * (1 + vertex), c0 - c1**2 / (4 * c2)


def main():
    # 1. Large-coupling limit of method A, in units of kappa.
    print("J/kappa   Delta/kappa   U J^2/kappa^3   deviation from 2/(3 sqrt 3)")
    for ratio in (1, 3, 10, 30, 100, 1000):
        delta, u = optimum_from_amplitudes(ratio, 1.0)
        print(f"{ratio:7.0f}   {delta:.6f}      {u * ratio**2:.6f}        {u * ratio**2 / PREFACTOR - 1:+.2e}")
    print(f"limits:   {1 / (2 * np.sqrt(3)):.6f}      {PREFACTOR:.6f}")

    print("\nMethod A against Eqs. (27)-(28) of the 2017 review: relative difference in U")
    for ratio in (1, 3, 10, 100):
        u_root, u_review = optimum_from_amplitudes(ratio, 1.0)[1], optimum_closed_form(ratio, 1.0)[1]
        print(f"  J = {ratio:<4} kappa   {u_root / u_review - 1:+.1e}")

    # 2. Convergence of method B at J = 10 kappa.
    print("\nMethod B at J = 10 kappa: U_min / U_A - 1, and g2 at the minimum")
    _, u_a = optimum_from_amplitudes(10.0, 1.0)
    for cutoff in (4, 5, 6):
        for F in (0.08, 0.04, 0.02, 0.01):
            u_b, g2 = optimum_from_master_equation(10.0, 1.0, F, cutoff)
            print(f"  cutoff {cutoff}  F = {F:<5} kappa   {u_b / u_a - 1:+.2e}   g2 = {g2:.2e}")

    # 3. Figure: U_opt against kappa at fixed J = 20, in an arbitrary energy unit.
    J = 20.0
    kappas = np.geomspace(0.25, 4, 33)
    line = [[k, optimum_from_amplitudes(J, k)[1]] for k in kappas]
    printed = [[k, PREFACTOR * k**2 / J**2] for k in (kappas[0], kappas[-1])]
    points = [[k, optimum_from_master_equation(J, k, 0.01 * k, 5)[0]] for k in (0.25, 0.5, 1, 2, 4)]
    figure = {
        "key": "upb-optimal-nonlinearity",
        "x": {"scale": "log"},
        "y": {"scale": "log"},
        "series": [
            {"key": "exact", "kind": "line", "points": line},
            {"key": "printed", "kind": "dashed", "points": printed},
            {"key": "master", "kind": "points", "points": points},
        ],
    }
    print("\nFigure points (kappa, U from master equation, ratio to 2/(3 sqrt 3) kappa^3/J^2):")
    for k, u in points:
        print(f"  {k:<5} {u:.6e}   {u / (PREFACTOR * k**3 / J**2):.4f}")
    if len(sys.argv) > 1:
        with open(sys.argv[1], "w", encoding="utf-8") as out:
            json.dump(figure, out, ensure_ascii=False, indent=1)
            out.write("\n")


if __name__ == "__main__":
    main()
