Skip to content

Commit

Permalink
Catch empty controls in optimization
Browse files Browse the repository at this point in the history
Trying to run `optimize` when there were no controls in the problem
would produce a very non-obvious MethodError. Since this is an easy
mistake to make, we can catch this situation with a proper error
message.
  • Loading branch information
goerz committed Mar 26, 2023
1 parent 4399074 commit 8212c85
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/workspace.jl
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ function KrotovWrk(problem::QuantumControlBase.ControlProblem; verbose=false)
objectives = [obj for obj in problem.objectives]
adjoint_objectives = [adjoint(obj) for obj in problem.objectives]
controls = get_controls(objectives)
if length(controls) == 0
error("no controls in objectives: cannot optimize")
end
control_derivs = [get_control_derivs(obj.generator, controls) for obj in objectives]
tlist = problem.tlist
kwargs = Dict(problem.kwargs) # creates a shallow copy; ok to modify
Expand Down
5 changes: 5 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ include(joinpath(@__DIR__, "download_dumps.jl"))
include("test_pulse_optimization.jl")
end

print("\n* Emptry Optimization (test_empty_optimization.jl)")
@time @safetestset "Empty Optimization" begin
include("test_empty_optimization.jl")
end

print("\n* Example 1 (examples/simple_state_to_state.jl):")
@time @safetestset "Example 1" begin
include(joinpath("examples", "simple_state_to_state.jl"))
Expand Down
33 changes: 33 additions & 0 deletions test/test_empty_optimization.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using Test
using StableRNGs
using QuantumControl: hamiltonian, optimize, ControlProblem, Objective
using QuantumControl.Controls: get_controls
using QuantumControlTestUtils.RandomObjects: random_matrix, random_state_vector

@testset "empty optimization" begin

# Test that trying to run an optimization without any controls produces a
# meaningful error message

rng = StableRNG(2264511904)

N = 10
H = random_matrix(N; rng)
objectives = [
Objective(;
initial_state=random_state_vector(N; rng),
generator=H,
target_state=random_state_vector(N; rng)
)
]

@test length(get_controls(objectives)) == 0

tlist = collect(range(0; length=1001, step=1.0))

problem = ControlProblem(; objectives, tlist, pulse_options=Dict())

msg = "no controls in objectives: cannot optimize"
@test_throws ErrorException(msg) optimize(problem; method=:krotov)

end

0 comments on commit 8212c85

Please sign in to comment.