"""The ground state of a rotating quantum fluid: a lattice of quantized vortices.

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.

Model. The Gross-Pitaevskii equation in two dimensions, in a harmonic trap rotating at the
angular frequency Omega, written in the rotating frame and in trap units:

    i dpsi/dt = [ -1/2 laplacian + r^2 / 2 + g |psi|^2 - Omega L_z ] psi

A superfluid cannot rotate as a solid body. It carries its angular momentum in vortices,
each with exactly one quantum of circulation, and in the state of lowest energy they
arrange themselves in a triangular lattice. Nothing in the script knows about triangles:
the starting point is a smooth cloud threaded by vortices at random positions.

Method. Imaginary-time relaxation with a split-step Fourier scheme (the rotation term is
split along x and y). The state is renormalised at every step.

Checks printed at the end: the energy changes by less than 0.03% over the last quarter of
the run (a few defects remain near the edge, as in experiments), and the number of vortices
inside a circle follows Feynman's rule, N = Omega rho^2, the count that makes the fluid
turn on average like a solid body.

Run:  python vortex-lattice.py [output_prefix]      (numpy, scipy and Pillow; a few minutes)
"""

import sys

import numpy as np
from scipy import fft, ndimage

N, HALF = 384, 12.0
G, OMEGA = 1000.0, 0.9
DT = 0.004


def relax(steps, seed=7):
    x = (np.arange(N) - N / 2) * (2 * HALF / N)
    X, Y = np.meshgrid(x, x)
    k = 2 * np.pi * fft.fftfreq(N, 2 * HALF / N)
    trap = 0.5 * (X**2 + Y**2)
    step_x = np.exp(-DT * (0.5 * k[None, :] ** 2 + OMEGA * Y * k[None, :]))  # acts on kx, at fixed y
    step_y = np.exp(-DT * (0.5 * k[:, None] ** 2 - OMEGA * X * k[:, None]))  # acts on ky, at fixed x
    cell = (2 * HALF / N) ** 2

    def energy(psi):
        gy, gx = np.gradient(psi, 2 * HALF / N)
        lz = (np.conj(psi) * (-1j) * (X * gy - Y * gx)).real
        dens = np.abs(psi) ** 2
        return np.sum(0.5 * (np.abs(gx) ** 2 + np.abs(gy) ** 2) + trap * dens + 0.5 * G * dens**2 - OMEGA * lz) * cell

    rng = np.random.default_rng(seed)
    mu = np.sqrt(G * (1 - OMEGA**2) / np.pi)
    psi = np.sqrt(np.maximum(mu - (1 - OMEGA**2) * trap, 0) / G + 1e-6).astype(complex)
    # Thread the cloud with vortices at random positions, about as many as Feynman's rule
    # asks for. The relaxation moves them, and lets some leave or enter through the edge.
    radius = np.sqrt(2 * mu / (1 - OMEGA**2))
    count = int(round(OMEGA * radius**2))
    spots = radius * np.sqrt(rng.random(count)) * np.exp(2j * np.pi * rng.random(count))
    for spot in spots:
        z = (X + 1j * Y) - spot
        psi *= z / np.sqrt(np.abs(z) ** 2 + 0.05)
    psi /= np.sqrt(np.sum(np.abs(psi) ** 2) * cell)
    history = []
    for step in range(steps):
        psi = psi * np.exp(-0.5 * DT * (trap + G * np.abs(psi) ** 2))
        psi = fft.ifft(step_x * fft.fft(psi, axis=1, workers=4), axis=1, workers=4)
        psi = fft.ifft(step_y * fft.fft(psi, axis=0, workers=4), axis=0, workers=4)
        psi = psi * np.exp(-0.5 * DT * (trap + G * np.abs(psi) ** 2))
        psi /= np.sqrt(np.sum(np.abs(psi) ** 2) * cell)
        if (step + 1) % (steps // 4) == 0:
            history.append(energy(psi))
    return psi, X, Y, history


def winding(psi):
    phase = np.angle(psi)
    wrap = lambda d: (d + np.pi) % (2 * np.pi) - np.pi
    dx = wrap(np.roll(phase, -1, 1) - phase)
    dy = wrap(np.roll(phase, -1, 0) - phase)
    return np.rint((dx + np.roll(dy, -1, 1) - np.roll(dx, -1, 0) - dy) / (2 * np.pi))


def save_layer(values, path, size=(1200, 800), shown=336):
    """The central part of the square field, centred on a wider transparent canvas."""
    from PIL import Image

    edge = (N - shown) // 2
    side = size[1]
    field = Image.fromarray((np.clip(values[edge : N - edge, edge : N - edge], 0, 1) * 255).astype(np.uint8), "L")
    alpha = Image.new("L", size, 0)
    alpha.paste(field.resize((side, side), Image.BICUBIC), ((size[0] - side) // 2, 0))
    white = Image.new("L", size, 255)
    Image.merge("RGBA", (white, white, white, alpha)).save(path, quality=90, method=6)


def main():
    prefix = sys.argv[1] if len(sys.argv) > 1 else "vortex-lattice"
    steps = int(sys.argv[2]) if len(sys.argv) > 2 else 40000
    psi, X, Y, history = relax(steps)
    density = np.abs(psi) ** 2
    print("energy at each quarter of the run:", "  ".join(f"{e:.5f}" for e in history))

    rho2 = X**2 + Y**2
    radius = np.sqrt(2 * np.sqrt(G * (1 - OMEGA**2) / np.pi) / (1 - OMEGA**2))
    turns = winding(psi) * (rho2 < (0.95 * radius) ** 2)  # the dilute edge is noise
    for fraction in (0.5, 0.7):
        counted = int(turns[rho2 < (fraction * radius) ** 2].sum())
        print(f"vortices within {fraction:.1f} R: {counted}   (Feynman's rule: {OMEGA * (fraction * radius) ** 2:.1f})")

    save_layer((density / density.max()) ** 0.6, f"{prefix}-ink.webp")
    # Second layer: a dot on the centre of each vortex, where the phase winds once.
    dots = ndimage.gaussian_filter((turns != 0).astype(float), 1.6)
    save_layer((dots / max(dots.max(), 1e-12)) ** 0.8, f"{prefix}-accent.webp")


if __name__ == "__main__":
    main()
