### A Pluto.jl notebook ###
# v1.0.4

using Markdown
using InteractiveUtils

# ╔═╡ 17000000-6790-4870-8d75-380000000001
begin
    import Pkg
    Pkg.activate(joinpath(@__DIR__,".."))
    using CoupledDipole, Rotations, LinearAlgebra, ForwardDiff, CairoMakie
end

# ╔═╡ 17000000-6790-4870-8d75-380000000002
md"""
# Finite arrays: package solvers and differentiation

This notebook runs the package APIs, not saved benchmark prototypes.
Default direct solves use in-place LU. Matrix-free GMRES uses either exact
pairwise summation or finite zero-padded FFT convolution; the latter does
not add periodic images. Chan is an approximate inverse, not a change to
the physical model.

The 20 x 20 array of gold spheres (pitch Λ = 450 nm, medium n = 1.33) is
illuminated at normal incidence so the (±1,0)/(0,±1) Rayleigh anomaly sits at
λ = Λn ≈ 598.5 nm; the collective surface lattice resonance appears just red
of it, strongly enhanced over the single-particle response. Oblique incidence
would split the anomaly to Λn(1 ± sinθ) and push it outside this window.

This array size still permits a direct reference. Do not increase it to
400 x 400 while retaining the direct call: that matrix would need 3.35 TiB.
For large calculations explicitly choose GMRES and consider lower-level
`solve_fields` when angular scattering is unnecessary.
"""

# ╔═╡ 17000000-6790-4870-8d75-380000000003
begin
    cl = cluster_array(400,450.0,50.0,50.0,50.0) # 20 x 20, pitch Λ = 450 nm
    mat = Material(collect(560.0:2.0:680.0),Dict("Au"=>epsilon_Au,"medium"=>_ -> 1.33))
    incidence = [RotMatrix(RotZYZ(0.0,0.0,0.0))] # normal incidence keeps the Rayleigh anomaly at Λn
    single = spectrum_dispersion(cluster_single(50.0,50.0,50.0),mat,incidence;N_sca=8)
    direct = spectrum_dispersion(cl,mat,incidence;N_sca=8)
    plain = spectrum_dispersion(cl,mat,incidence;N_sca=8,
        method="gmres",interaction="fft",solver_rtol=1e-10,
        return_diagnostics=true)
    chan = spectrum_dispersion(cl,mat,incidence;N_sca=8,
        method="gmres",interaction="fft",preconditioner="chan",
        solver_rtol=1e-10,return_diagnostics=true)
    @assert norm(chan.cross_sections.extinction-direct.extinction)/norm(direct.extinction)<1e-7
    # diffractive peak test: the surface lattice resonance must appear just red
    # of the Rayleigh anomaly λ_RA = Λn, strongly enhanced per particle
    λ_RA = 450.0*1.33
    i_peak = argmax(direct.extinction[:,1])
    λ_peak = mat.wavelengths[i_peak]
    enhancement = direct.extinction[i_peak,1]/single.extinction[i_peak,1]
    @assert λ_RA < λ_peak < λ_RA + 50
    @assert enhancement > 3
    (;λ_RA,λ_peak,enhancement)
end

# ╔═╡ 17000000-6790-4870-8d75-380000000004
let
    fig = Figure(size=(950,380))
    spectra = Axis(fig[1,1],xlabel="Wavelength / nm",ylabel="Extinction / particle / nm²")
    iterations = Axis(fig[1,2],xlabel="Wavelength / nm",ylabel="GMRES iterations")
    vlines!(spectra,[λ_RA];color=:grey,linestyle=:dash,label="Rayleigh anomaly Λn")
    lines!(spectra,mat.wavelengths,single.extinction[:,1];color=:grey,label="Single particle")
    lines!(spectra,mat.wavelengths,direct.extinction[:,1];label="Direct")
    scatter!(spectra,mat.wavelengths,chan.cross_sections.extinction[:,1];label="FFT + Chan",markersize=5)
    for (result,label) in ((plain,"None"),(chan,"Chan"))
        first_rhs = filter(d -> d.rhs==1,result.diagnostics)
        lines!(iterations,[d.wavelength for d in first_rhs],[d.iterations for d in first_rhs];label)
    end
    axislegend(spectra); axislegend(iterations)
    fig
end

# ╔═╡ 17000000-6790-4870-8d75-380000000005
begin
    function radius_objective(radius,method)
        cluster = cluster_array(9,450.0,radius,radius,radius)
        material = Material([610.0],Dict("Au"=>_ -> -10.0+1im,"medium"=>_ -> 1.33))
        sum(spectrum_dispersion(cluster,material,incidence;N_sca=8,method,
            interaction=method=="gmres" ? "fft" : "pairwise",
            solver_rtol=1e-11,solver_atol=1e-13).extinction)
    end
    gradient_direct = ForwardDiff.derivative(r -> radius_objective(r,"direct"),30.0)
    gradient_gmres = ForwardDiff.derivative(r -> radius_objective(r,"gmres"),30.0)
    @assert isapprox(gradient_direct,gradient_gmres;rtol=1e-6)
    (;gradient_direct,gradient_gmres)
end

# ╔═╡ 62e2cdd7-87f0-4bfd-9b75-b76b504e0de0
md"""
## When is iterative favourable?

Single wavelength (620 nm, on the lattice resonance — worst case for iteration
counts), one incidence (two polarization RHS). Direct LU costs O(N³) time and
O(N²) memory; GMRES + FFT costs O(N log N) per matrix action with O(N) storage.
Note the trade-off direction reverses with many RHS: one LU factorization is
shared by all right-hand sides, while GMRES restarts from zero for each one.
"""

# ╔═╡ 429ff85b-5815-46c7-80d0-61b96bf47e69
crossover = let
    m = Material([620.0],Dict("Au"=>epsilon_Au,"medium"=>_ -> 1.33))
    sides = [5,10,15,20,25,30,40]
    run(L;kwargs...) = spectrum_dispersion(cluster_array(L^2,450.0,50.0,50.0,50.0),
        m,incidence;N_sca=8,kwargs...)
    run(5); run(5;method="gmres",interaction="fft",preconditioner="chan") # warm-up
    rows = map(sides) do L
        t_direct = @elapsed run(L)
        t_gmres = @elapsed r = run(L;method="gmres",interaction="fft",
            preconditioner="chan",return_diagnostics=true)
        (;N=L^2, t_direct, t_gmres,
            iterations=maximum(d.iterations for d in r.diagnostics),
            direct_matrix_GiB=(3L^2)^2*16/2^30)
    end
    rows
end

# ╔═╡ 805bf521-ae5a-4a54-b4c5-844bffea1d2e
md"""
## Convergence under disorder

Chan's approximate inverse is built from the circulant lattice kernel and the
**mean** local tensor, so it degrades gracefully with on-grid size disorder
(FFT propagation stays exact). Positional disorder breaks the Cartesian grid:
the exact solve must switch to the pairwise operator, but Chan can still be
built **on the nominal lattice** (`preconditioner_positions`) — the question
is how much displacement makes it useless. The geometry-agnostic `nearfield`
block-Jacobi is the fallback comparison. Disorder amplitudes are fractions of
the nominal radius (size) or pitch (position); 20 x 20 array at 620 nm, on
the lattice resonance.
"""

# ╔═╡ 9a2cdef8-b671-45e2-9387-8f606b0b5f42
disorder = let
    m = Material([620.0],Dict("Au"=>epsilon_Au,"medium"=>_ -> 1.33))
    # deterministic hash noise in [-1,1], reproducible without extra packages
    noise(i,channel) = 2*abs(sin(i*12.9898+channel*78.233)*43758.5453 % 1.0) - 1.0
    nominal = cluster_array(400,450.0,50.0,50.0,50.0)
    function disordered(;σ_size=0.0,σ_pos=0.0)
        sizes = [s .* (1 + σ_size*noise(i,1)) for (i,s) in enumerate(nominal.sizes)]
        positions = [typeof(p)(p[1]+450.0*σ_pos*noise(i,2),
            p[2]+450.0*σ_pos*noise(i,3),p[3]) for (i,p) in enumerate(nominal.positions)]
        Cluster(positions,nominal.rotations,sizes,nominal.materials,nominal.types)
    end
    iters(cl;kwargs...) = maximum(d.iterations for d in spectrum_dispersion(cl,m,
        incidence;N_sca=8,method="gmres",solver_rtol=1e-8,return_diagnostics=true,
        kwargs...).diagnostics)
    σ_sizes = [0.0,0.05,0.1,0.2,0.3]
    size_none = [iters(disordered(σ_size=σ);interaction="fft") for σ in σ_sizes]
    size_chan = [iters(disordered(σ_size=σ);interaction="fft",preconditioner="chan") for σ in σ_sizes]
    # positional disorder: pairwise operator; nominal-grid Chan vs fallback vs none
    σ_pos = [0.0,0.02,0.05,0.1,0.15,0.2,0.3]
    pos_none = [iters(disordered(σ_pos=σ);interaction="pairwise") for σ in σ_pos]
    pos_chan = [iters(disordered(σ_pos=σ);interaction="pairwise",
        preconditioner="chan",preconditioner_positions=nominal.positions) for σ in σ_pos]
    pos_nearfield = [iters(disordered(σ_pos=σ);interaction="pairwise",
        preconditioner="nearfield",preconditioner_blocksize=20) for σ in σ_pos]
    # accuracy spot-check of the preconditioned pairwise solve, strongest disorder
    worst = disordered(σ_pos=0.3)
    reference = spectrum_dispersion(worst,m,incidence;N_sca=8)
    offgrid = spectrum_dispersion(worst,m,incidence;N_sca=8,method="gmres",
        interaction="pairwise",preconditioner="chan",
        preconditioner_positions=nominal.positions,solver_rtol=1e-10)
    @assert norm(offgrid.extinction-reference.extinction)/norm(reference.extinction)<1e-7
    (;σ_sizes,size_none,size_chan,σ_pos,pos_none,pos_chan,pos_nearfield)
end

# ╔═╡ f87b6b66-b205-4e74-9817-5ea2b13362cd
let
    fig = Figure(size=(950,350))
    ax1 = Axis(fig[1,1],xlabel="size disorder / nominal radius",ylabel="GMRES iterations",
        title="On-grid size disorder (FFT)")
    scatterlines!(ax1,disorder.σ_sizes,disorder.size_none;label="None")
    scatterlines!(ax1,disorder.σ_sizes,disorder.size_chan;label="Chan")
    ax2 = Axis(fig[1,2],xlabel="position disorder / pitch",ylabel="GMRES iterations",
        title="Positional disorder (pairwise)")
    scatterlines!(ax2,disorder.σ_pos,disorder.pos_none;label="None")
    scatterlines!(ax2,disorder.σ_pos,disorder.pos_chan;label="Chan (nominal grid)")
    scatterlines!(ax2,disorder.σ_pos,disorder.pos_nearfield;label="Near-field (rows)")
    axislegend(ax1,position=:rc); axislegend(ax2,position=:lt)
    fig
end

# ╔═╡ 1ee1dcc5-1a46-4c72-8eb7-c7ad5cffe302
md"""
## How large can a regular array get?

GMRES + FFT + Chan at 620 nm (resonant). The direct-matrix column shows why LU
is abandoned: storage grows as 16(3N)² bytes. The last column extrapolates a
61-wavelength spectrum from the single-wavelength solve. Memory for the
iterative path stays at a few padded complex grids, i.e. O(N).
"""

# ╔═╡ e204e120-1d5d-42e8-96f1-6381d5e1b456
size_limit = let
    m = Material([620.0],Dict("Au"=>epsilon_Au,"medium"=>_ -> 1.33))
    rows = map([20,40,80,120,160,200,300,400]) do L
        t = @elapsed r = spectrum_dispersion(cluster_array(L^2,450.0,50.0,50.0,50.0),
            m,incidence;N_sca=8,method="gmres",interaction="fft",
            preconditioner="chan",return_diagnostics=true)
        (;side=L, N=L^2,
            iterations=maximum(d.iterations for d in r.diagnostics),
            t_one_wavelength_s=round(t,digits=2),
            spectrum_61λ_min=round(61t/60,digits=1),
            direct_matrix_GiB=round((3L^2)^2*16/2^30,digits=1))
    end
    rows
end

# ╔═╡ d1819bc7-01ad-4afe-ab49-90e67adba2ee
md"""
## Helix of nanospheres: orientation-averaged circular dichroism

A helix of achiral gold spheres gains CD purely from chiral coupling, so it is
a sensitive end-to-end test of the solver. `spectrum_oa` accepts the same
GMRES options as `spectrum_dispersion`; the helix is off-grid, so the exact
operator is pairwise. Two features target exactly this situation: the
`circulant1d` preconditioner exploits the helix's discrete screw symmetry
(block-Toeplitz in the particle index in a frame co-rotating by δ per
particle), and `rhs_strategy="block"` shares one block Arnoldi basis across
all `2N_inc` right-hand sides, evaluating each O(N²) kernel sweep once for
all 72 columns instead of 72 times.
"""

# ╔═╡ 85aa15cc-1d09-4475-baa9-de4239141c74
begin
    helix_material = Material(collect(480.0:5.0:680.0),
        Dict("Au"=>epsilon_Au,"medium"=>_ -> 1.33))
    helix_cluster(N) = cluster_helix(N,30.0,30.0,30.0,100.0,300.0,π/4)
    helix_direct = spectrum_oa(helix_cluster(16),helix_material;N_inc=36,N_sca=36)
    helix_gmres = spectrum_oa(helix_cluster(16),helix_material;N_inc=36,N_sca=36,
        method="gmres",interaction="pairwise",solver_rtol=1e-10,
        return_diagnostics=true)
    @assert norm(helix_gmres.dichroism.extinction-helix_direct.dichroism.extinction)/
        norm(helix_direct.dichroism.extinction) < 1e-6
    maximum(d.iterations for d in helix_gmres.diagnostics)
end

# ╔═╡ b1a04b25-9655-4eaf-ba1b-e7a068843486
let
    fig = Figure(size=(950,380))
    avg = Axis(fig[1,1],xlabel="Wavelength / nm",ylabel="⟨Extinction⟩ / particle / nm²")
    cd = Axis(fig[1,2],xlabel="Wavelength / nm",ylabel="CD (extinction) / particle / nm²")
    lines!(avg,helix_material.wavelengths,helix_direct.average.extinction;label="Direct")
    scatter!(avg,helix_material.wavelengths,helix_gmres.average.extinction;
        label="GMRES pairwise",markersize=5)
    lines!(cd,helix_material.wavelengths,helix_direct.dichroism.extinction;label="Direct")
    scatter!(cd,helix_material.wavelengths,helix_gmres.dichroism.extinction;
        label="GMRES pairwise",markersize=5)
    hlines!(cd,[0.0];color=:grey,linestyle=:dash)
    axislegend(avg); axislegend(cd)
    fig
end

# ╔═╡ 52e2a83e-368e-495c-bd2f-d3c459d6651e
helix_limit = let
    m = Material([540.0],Dict("Au"=>epsilon_Au,"medium"=>_ -> 1.33))
    run(N;kwargs...) = spectrum_oa(helix_cluster(N),m;N_inc=36,N_sca=8,kwargs...)
    run(16); run(16;method="gmres"); run(64;method="gmres",rhs_strategy="block") # warm-up
    rows = map([64,128,256,512]) do N
        t_direct = @elapsed reference = run(N)
        t_sequential = @elapsed sequential = run(N;method="gmres",
            return_diagnostics=true)
        t_block = @elapsed blocked = run(N;method="gmres",rhs_strategy="block",
            preconditioner="circulant1d",preconditioner_rotation=Matrix(RotZ(π/4)),
            solver_restart=40,return_diagnostics=true)
        @assert isapprox(blocked.dichroism.extinction,
            reference.dichroism.extinction;rtol=1e-5)
        (;N, t_direct=round(t_direct,digits=2),
            t_sequential=round(t_sequential,digits=2),
            t_block=round(t_block,digits=2),
            sequential_iters=maximum(d.iterations for d in sequential.diagnostics),
            block_steps=maximum(d.iterations for d in blocked.diagnostics))
    end
    rows
end

# ╔═╡ a87c4d05-ae44-46e3-b9bf-3a60809d40b7
md"""
## Findings

- **Direct vs iterative (dispersion)**: for a single incidence, GMRES + FFT +
  Chan overtakes dense LU already near N ≈ 50–100 and is orders of magnitude
  faster beyond N ≈ 10³ (×400 at N = 1600). Direct remains attractive when many
  right-hand sides share one factorization and the matrix fits in memory.
- **Disorder**: GMRES convergence is remarkably robust. ±30 % radius disorder
  (on-grid) leaves Chan effective (17→18 iterations, vs ~27 without). For
  positional disorder, **nominal-grid Chan** (`preconditioner_positions`)
  stays worthwhile up to ~10–15 % of the pitch (17→22 iterations), breaks even
  with no preconditioner near ~20 %, and becomes counterproductive by 30 %
  (36 vs 25). The index-row `nearfield` blocks never help on this 2D array —
  its blocks don't capture the two-dimensional resonant coupling.
- **Regular-array ceiling**: iteration counts saturate (~21 on resonance), so
  wall time scales ~linearly: 160 000 particles (400×400) take ≈ 2.4 s per
  wavelength, ≈ 2.5 min for a 61-wavelength spectrum, with O(N) memory —
  whereas direct would need 3.4 TiB. The practical limit is set by patience,
  not memory, well beyond 10⁵ particles.
- **Helix OA CD**: pairwise GMRES reproduces direct CD to <10⁻⁶, but
  sequentially iterating 72 RHS was ~70× slower than one amortized LU.
  `rhs_strategy="block"` + `circulant1d` (screw-symmetry preconditioner,
  `RotZ(δ)`) closes most of that gap: at N = 512 the 72-RHS solve converges in
  **4 block steps** (≈ 5 kernel sweeps instead of 72 × 30), 18.6 s → 1.5 s,
  only ~5× behind direct. Direct still wins while its matrix fits in memory
  (N ≈ 10⁴); past that, block GMRES is now a practical fallback.
"""

# ╔═╡ 17000000-6790-4870-8d75-380000000006
md"""
The ForwardDiff extension solves `F dE = dB - (dF)E`; it does not differentiate
the GMRES iteration history or drop dual components before FFTs. Primal and
tangent residuals must converge. First-order derivatives are supported;
nested duals and reverse rules are not.

On-grid local tensor/radius disorder retains exact FFT propagation.
Position disorder requires `interaction="pairwise"` for now; this removes
dense storage but retains quadratic summation. Independent position
derivatives are explicitly rejected by FFT even at a regular primal grid.

Algorithm sources: Saad & Schultz (1986), doi:10.1137/0907058, via the
MIT-licensed IterativeSolvers dependency; T. F. Chan (1988),
doi:10.1137/0909051, independently extended to two-dimensional tensor blocks.
FFTW.jl's wrapper is MIT licensed; native FFTW has separate GPL terms.
See the finite-solvers documentation for scope and redistribution details.
Infinite-array Ewald/Bloch routines remain experiments, not package APIs.
"""

# ╔═╡ Cell order:
# ╠═17000000-6790-4870-8d75-380000000001
# ╟─17000000-6790-4870-8d75-380000000002
# ╠═17000000-6790-4870-8d75-380000000003
# ╠═17000000-6790-4870-8d75-380000000004
# ╠═17000000-6790-4870-8d75-380000000005
# ╠═62e2cdd7-87f0-4bfd-9b75-b76b504e0de0
# ╠═429ff85b-5815-46c7-80d0-61b96bf47e69
# ╠═805bf521-ae5a-4a54-b4c5-844bffea1d2e
# ╠═9a2cdef8-b671-45e2-9387-8f606b0b5f42
# ╠═f87b6b66-b205-4e74-9817-5ea2b13362cd
# ╠═1ee1dcc5-1a46-4c72-8eb7-c7ad5cffe302
# ╠═e204e120-1d5d-42e8-96f1-6381d5e1b456
# ╠═d1819bc7-01ad-4afe-ab49-90e67adba2ee
# ╠═85aa15cc-1d09-4475-baa9-de4239141c74
# ╠═b1a04b25-9655-4eaf-ba1b-e7a068843486
# ╠═52e2a83e-368e-495c-bd2f-d3c459d6651e
# ╠═a87c4d05-ae44-46e3-b9bf-3a60809d40b7
# ╟─17000000-6790-4870-8d75-380000000006
