|
| 1 | +using Test |
| 2 | +using StableRNGs |
| 3 | +using IOCapture |
| 4 | +using QuantumControl: Trajectory |
| 5 | +using LinearAlgebra: dot, norm |
| 6 | +using Random: rand |
| 7 | +using Zygote |
| 8 | + |
| 9 | + |
| 10 | +function J_T(Ψ; Ψtgt, N) |
| 11 | + return 1 - (abs2(dot(Ψ, Ψtgt)) / N) |
| 12 | +end |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +@testset "Gradient w.r.t. trajectory.initial_state" begin |
| 17 | + |
| 18 | + function f(traj; Ψtgt, N) |
| 19 | + return J_T(traj.initial_state; Ψtgt, N) |
| 20 | + end |
| 21 | + |
| 22 | + rng = StableRNG(3143162815) |
| 23 | + N = 4 |
| 24 | + H = nothing |
| 25 | + Ψ = rand(rng, ComplexF64, N) |
| 26 | + Ψ ./ norm(Ψ) |
| 27 | + Ψtgt = zeros(ComplexF64, N) |
| 28 | + Ψtgt[1] = 1.0 |
| 29 | + traj = Trajectory(Ψ, H) |
| 30 | + @test f(traj; Ψtgt, N) > 0.0 |
| 31 | + grad = Zygote.gradient(traj -> f(traj; Ψtgt, N), traj)[1] |
| 32 | + @test grad isa NamedTuple |
| 33 | + @test grad.initial_state isa Vector |
| 34 | + |
| 35 | +end |
| 36 | + |
| 37 | + |
| 38 | +@testset "Gradient w.r.t. trajectory.x" begin |
| 39 | + |
| 40 | + function f(traj; Ψtgt, N) |
| 41 | + return J_T(traj.x; Ψtgt, N) |
| 42 | + end |
| 43 | + |
| 44 | + rng = StableRNG(3143162816) |
| 45 | + N = 4 |
| 46 | + H = nothing |
| 47 | + Ψ = rand(rng, ComplexF64, N) |
| 48 | + Ψ ./ norm(Ψ) |
| 49 | + Ψtgt = zeros(ComplexF64, N) |
| 50 | + Ψtgt[1] = 1.0 |
| 51 | + x = Ψ |
| 52 | + traj = Trajectory(Ψ, H; x) |
| 53 | + @test f(traj; Ψtgt, N) > 0.0 |
| 54 | + captured = IOCapture.capture(rethrow = Union{}) do |
| 55 | + # Without the custom `rrule` in `QuantumControlchainRulesCoreExt`, this |
| 56 | + # test would show a potentially very confusing error, and throw an |
| 57 | + # `UndefRefError`. See also: https://discourse.julialang.org/t/136704/ |
| 58 | + Zygote.gradient(traj -> f(traj; Ψtgt, N), traj)[1] |
| 59 | + end |
| 60 | + grad = captured.value |
| 61 | + @test grad isa NamedTuple |
| 62 | + if grad isa NamedTuple |
| 63 | + @test grad.initial_state isa Nothing |
| 64 | + @test grad.kwargs[:x] isa Vector |
| 65 | + end |
| 66 | + |
| 67 | +end |
0 commit comments