# # Superradiant Laser

# Using symmetry properties of a system can reduce the number of needed equations dramatically. A common approximation for laser systems to handle sufficiently big atom numbers is to assume that several atoms in the system behave completely identically. This means all the identical atoms have the same averages.

# In this example we describe a so-called superradiant laser, where we assume all atoms to be identical. This model has been described in [D. Meiser et al., Phys. Rev. Lett. 102, 163601 (2009):](https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.102.163601) The Hamiltonian of this system is
# ```math
# \begin{equation}
# H = - \hbar \Delta a^\dagger a +  \hbar \sum\limits_{j=1}^{N}  g_j (a^\dagger \sigma^{12}_{j} + a \sigma^{21}_{j}) ,
# \end{equation}
# ```
# where $\Delta = \omega_a - \omega_c$ is the detuning between the cavity ($\omega_c$) and the atomic ($\omega_a$) resonance frequency, the atom cavity coupling of the $j$-th atom is denoted by $g_j$. Additionally there are dissipative processes in the system: Atoms are incoherently pumped with the rate $R$, they decay individually with the rate $\Gamma$ and are affected by individual atomic dephasing with the rate $\nu$. Furthermore, photons leak out of the system with the rate $\kappa$.

# We start by loading the packages.

using QuantumCumulants
using OrdinaryDiffEqTsit5, ModelingToolkitBase
using Plots

# Due to the implementation of symbolic indices and sums we only need to define the Hilbert space for one atom, even though we will simulate a system for several thousand.
# Creating an operator with an $\texttt{Index}$ is done with the constructor $\texttt{IndexedOperator}$.


hc = FockSpace(:cavity)
ha = NLevelSpace(:atom, 2)
h = hc ⊗ ha

@qnumbers a::Destroy(h) # operators
σ(α, β, i) = IndexedOperator(Transition(h, :σ, α, β), i)
nothing # hide

# Now we define the indices and the parameters of the system. An $\texttt{Index}$ needs the system Hilbert space, a symbol, an upper bound and the specific Hilbert space of the indexed operator. $\texttt{IndexedVariable}$ creates indexed variables. Actually we wouldn't need indexed variable in this example, this is just for demonstration purposes.

@variables N Δ κ Γ R ν
g(i) = IndexedVariable(:g, i)

i = Index(h, :i, N, ha)
j = Index(h, :j, N, ha)
nothing # hide

# We define the Hamiltonian using symbolic sums and define the individual dissipative processes. For an indexed jump operator the (symbolic) sum is build in the Liouvillian.


H = -Δ * a'a + Σ(g(i) * (a' * σ(1, 2, i) + a * σ(2, 1, i)), i) # Hamiltonian

J = [a, σ(1, 2, i), σ(2, 1, i), σ(2, 2, i)] # Jump operators with corresponding rates
rates = [κ, Γ, R, ν]
nothing # hide

# First we want to derive the equation for $\langle a^\dagger a \rangle$ and $\langle \sigma_j^{22} \rangle$. Note that you can only use indices on the LHS which haven't been used for the Hamiltonian and the jumps.

ops = [a' * a, σ(2, 2, j)] # Derive equations
eqs = meanfield(ops, H, J; rates = rates, order = 2)

# To get a closed set of equations we automatically complete the system. Since this system is phase invariant we know that all averages with a phase are zero, therefore we exclude these terms with a filter function. To be able to dispatch on all kind of sums containing averages we defined the Union $\texttt{AvgSums}$.

import QuantumCumulants.SecondQuantizedAlgebra as SQA

φ(x) = 0 # custom filter function
function φ(op::SQA.Op)
    SQA.is_destroy(op) && return -1
    SQA.is_create(op) && return 1
    SQA.is_transition(op) && return op.l1 - op.l2
    return 0
end
function φ(q::SQA.QAdd) # walk operator-product expression
    for (term, _) in q.arguments
        p = 0
        for op in term.ops
            p += φ(op)
        end
        return p
    end
    return 0
end
function φ(avg)
    SQA.is_average(avg) || return 0
    return φ(SQA.undo_average(avg))
end
phase_invariant(x) = iszero(φ(x))

eqs_c = complete(eqs; filter_func = phase_invariant) # Complete equations

# As mentioned before, we assume that all atoms behave identically. This means that e.g. the excited state population is equal for all atoms, hence we only need to calculate it for the first $\langle \sigma^{22}_1 \rangle = \langle \sigma^{22}_j \rangle$. Furthermore, it is clear that a sum over $N$ identical objects can be replaced by $N$ times the object. The function $\texttt{scale()}$ uses these rules to simplify the equations.

eqs_sc = scale(eqs_c)

# To calculate the dynamics of the system we create a system of ordinary differential equations, which can be used by [DifferentialEquations.jl](https://diffeq.sciml.ai/stable/).

sys = System(eqs_sc; name = :sys)
sys_c = mtkcompile(sys)
nothing # hide

# Finally we need to define the numerical parameters and the initial value of the system. We will consider $2 \cdot 10^5$ Strontium atoms which are repumped with a rate of $R = 1\text{Hz}$ on the clock transition ($\Gamma = 1 \text{mHz}$). The atom-cavity coupling rate is $g = 1\text{Hz}$, the cavity has a linewidth of $\kappa = 5\text{kHz}$ and is detuned from the atomic resonance by $\Delta = 2.5\text{Hz}$.


u0 = initial_values(eqs_sc) # Initial state

N_ = 2.0e5 # System parameters
Γ_ = 1.0 #Γ=1mHz
Δ_ = 2500Γ_ #Δ=2.5Hz
g_ = 1000Γ_ #g=1Hz
κ_ = 5.0e6 * Γ_ #κ=5kHz
R_ = 1000Γ_ #R=1Hz
ν_ = 1000Γ_ #ν=1Hz

pmap = parameter_map(
    eqs_sc, Dict(
        N => N_, Δ => Δ_, g(i) => g_, κ => κ_, Γ => Γ_, R => R_, ν => ν_,
    )
)
ps = collect(keys(pmap))
p0 = collect(values(pmap))

dict = merge(u0, pmap)
prob = ODEProblem(sys_c, dict, (0.0, 1.0 / 50Γ_))
nothing # hide

#
sol = solve(prob, Tsit5(), maxiters = 1.0e7) # Solve the numeric problem

t = sol.t # Plot time evolution
n = real.(get_solution(sol, a'a, eqs_sc).(t))
s22 = real.(get_solution(sol, σ(2, 2, j(1)), eqs_sc).(t))
p1 = plot(t, n, xlabel = "tΓ", ylabel = "⟨a⁺a⟩", legend = false) # Plot
p2 = plot(t, s22, xlabel = "tΓ", ylabel = "⟨σ22⟩", legend = false)
plot(p1, p2, layout = (1, 2), size = (700, 300))


# ## Frequency Spectrum

# We calculate the spectrum here with the Laplace transform of the two-time correlation function. This is implemented with the function $\texttt{Spectrum}$.

corr = CorrelationFunction(a', a, eqs_c; steady_state = true, filter_func = phase_invariant)
corr_sc = scale(corr)
S = Spectrum(corr_sc, ps)
nothing # hide

# The set of equations for the correlation function is given by

corr_sc.eqs

# The spectrum is then calculated with


ω = [-10:0.01:10;]Γ_
spec = S(ω, sol.u[end], p0)
spec_n = spec ./ maximum(spec)
δ = abs(ω[(findmax(spec)[2])])

plot(ω, spec_n, xlabel = "ω/Γ", legend = false, size = (500, 300))

# Beside the narrow linewidth we can also see another key feature of the superradiant laser here, namely the very weak cavity pulling. At a detunig of $\Delta = 2500\Gamma$ there is only a shift of the laser light from the atomic resonance frequency of $\delta = 1\Gamma$.

# ## Package versions

# These results were obtained using the following versions:

using InteractiveUtils
versioninfo()

using Pkg
Pkg.status(["QuantumCumulants", "OrdinaryDiffEqTsit5"], mode = PKGMODE_MANIFEST)
