Control Methods
All optimizations in the QuantumControl package are done by calling QuantumControl.optimize, or preferably the high-level wrapper @optimize_or_load. The actual control methods are implemented in separate packages. The module implementing a particular method should be passed to optimize as the method keyword argument.
QuantumControl.optimize — Method
Optimize a quantum control problem.
result = optimize(
problem;
method, # mandatory keyword argument
check=true,
callback=nothing,
print_iters=true,
kwargs...
)optimizes towards a solution of given problem with the given method, which should be a Module implementing the method, e.g.,
using Krotov
result = optimize(problem; method=Krotov)If check is true (default), the initial_state and generator of each trajectory is checked with check_state and check_generator. Additional keyword arguments can be passed to these two check routines by passing a named-tuple as check_state_kwargs and check_generator_kwargs.
The callback can be given as a function to be called after each iteration in order to analyze the progress of the optimization or to modify the state of the optimizer or the current controls. The signature of callback is method-specific, but callbacks should receive a workspace objects as the first parameter as the first argument, the iteration number as the second parameter, and then additional method-specific parameters.
The callback function may return a tuple of values, and an optimization method should store these values fore each iteration in a records field in their Result object. The callback should be called once with an iteration number of 0 before the first iteration. The callback can also be given as a tuple of vector of functions, which are automatically combined via chain_callbacks.
If print_iters is true (default), an automatic callback is created via the method-specific make_print_iters to print the progress of the optimization after each iteration. This automatic callback runs after any manually given callback.
All remaining keyword argument are method-specific and temporarily overrides the corresponding keyword argument in problem. To obtain the documentation for which options a particular method uses, run, e.g.,
? optimize(problem, ::Val{:Krotov})where :Krotov is the name of the module implementing the method. The above is also the method signature that a Module wishing to implement a control method must define.
Optimization methods typically initialize the propagators for each trajectory with init_prop_trajectory, using keyword arguments with a prop_ prefix as options for the propagator, e.g., prop_method. Methods may also use more specific prefixes, e.g., fw_prop_ and bw_prop_ for the forward and backward propagation. The same options can be set as properties of each Trajectory. The precedence of these options is as follows:
- Keyword arguments (given to
optimizeor stored inproblem) take precedence over the properties of a trajectory, regardless of prefix. - Among keyword arguments, or among the properties of a trajectory, a more specific prefix like
fw_prop_takes precedence overprop_.
For example, for a trajectory with the property fw_prop_method = ExpProp, optimize(problem; method, prop_method = Cheby) uses Cheby for the forward propagation. To use different propagation methods for different trajectories, set them as properties of the trajectories and do not pass the corresponding keyword argument. A warning is shown if a keyword argument with the prop_ prefix overrides a trajectory property with a more specific prefix.
The returned result object is specific to the optimization method, but should be a subtype of QuantumControl.AbstractOptimizationResult.
The following methods of optimal control are implemented by packages in the JuliaQuantumControl organization:
Krotov's Method
See the documentation of the Krotov package for more details.
QuantumControl.optimize — Method
using Krotov
result = optimize(problem; method=Krotov, kwargs...)optimizes the given control problem using Krotov's method, by minimizing the functional
\[J(\{ϵ_l(t)\}) = J_T(\{|Ψ_k(T)⟩\}) + ∑_l \int_{0}^{T} \frac{λ_{a,l}}{S_l(t)} [ϵ_l(t) - ϵ_l^{(0)}(t)]^2 \, dt\,,\]
cf. the general form of a quantum control functional. The "reference field" $ϵ_l^{(0)}(t)$ is the guess control for that particular iteration. The above functional implies a first-order update equation
\[Δϵ_l(t) = \frac{S_l(t)}{λ_{a,l}} \Im ∑_k \left[ \Big\langle \chi_k^{(0)}(t) \Big\vert \frac{\partial \hat{H}_k}{\partial ϵ_l(t)} \Big\vert \Psi_k(t) \Big\rangle \right]\,,\]
where $|\chi^{(0)}_k(t)⟩$ is the state backward-propagated under $Ĥ_k^{\dagger}(\{ϵ_l^{(0)}(t)\})$ with the boundary condition $|\chi_k(T)⟩ = \partial J_T / \partial ⟨Ψ_k^{(0)}(T)|$ and $Ĥ_k$ is the generator of the $k$'th trajectory.
Note that the particular control-dependent running cost in the above functional is required to obtain the given Krotov update equation. Other running costs, or state-dependent running costs are not supported in this implementation of Krotov's method (even though some running costs are mathematically compatible with Krotov's method).
Returns a KrotovResult.
Keyword arguments that control the optimization are taken from the keyword arguments used in the instantiation of problem; any of these can be overridden with explicit keyword arguments to optimize.
Required problem keyword arguments
J_T: A functionJ_T(Ψ, trajectories)that evaluates the final time functional from a listΨof forward-propagated states andproblem.trajectories. The functionJ_Tmay also take a keyword argumenttau. If it does, a vector containing the complex overlaps of the target states (target_stateproperty of each trajectory inproblem.trajectories) with the propagated states will be passed toJ_T.
Recommended problem keyword arguments
lambda_a=1.0: The inverse Krotov step width λₐ for every pulse.update_shape=(t->1.0): A functionS(t)for the "update shape" that scales the update for every pulse.
If different controls require different lambda_a or update_shape, a dict pulse_options must be given instead of a global lambda_a and update_shape; see below.
Optional problem keyword arguments
The following keyword arguments are supported (with default values):
pulse_options: A dictionary that maps every control (as obtained byget_controlsfrom theproblem.trajectories) to the following dict::lambda_a: The value for inverse Krotov step width λₐ.:update_shape: A functionS(t)for the "update shape" that scales the Krotov pulse update.
This overrides the global
lambda_aandupdate_shapearguments.chi: A functionchi(Ψ, trajectories)that receives a listΨof the forward propagated states and returns a vector of states $|χₖ⟩ = -∂J_T/∂⟨Ψₖ|$. If not given, it will be automatically determined fromJ_Tviamake_chiwith the default parameters. Similarly toJ_T, ifchiaccepts a keyword argumenttau, it will be passed a vector of complex overlaps.sigma=nothing: A function that calculates the second-order contribution. If not given, the first-order Krotov method is used.iter_start=0: The initial iteration number.iter_stop=5000: The maximum iteration number.prop_method: The propagation method to use for each trajectory; see below.print_iters=true: Whether to print information after each iteration.store_iter_info=Set(): Which fields fromprint_itersto store inresult.records. A subset ofSet(["iter.", "J_T", "∫gₐ(t)dt", "J", "ΔJ_T", "ΔJ", "secs"]).callback: A function (or tuple of functions) that receives the Krotov workspace, the iteration number, the list of updated pulses, and the list of guess pulses as positional arguments. The function may return a tuple of values which are stored in theKrotovResultobjectresult.records. The function can also mutate any of its arguments, in particular the updated pulses. This may be used, e.g., to apply a spectral filter to the updated pulses or to perform similar manipulations. Note thatprint_iters=true(default) adds an automatic callback to print information after each iteration. Withstore_iter_info, that callback automatically stores a subset of the printed information.check_convergence: A function to check whether convergence has been reached. Receives aKrotovResultobjectresult, and should setresult.convergedtotrueandresult.messageto an appropriate string in case of convergence. Multiple convergence checks can be performed by chaining functions with∘. The convergence check is performed after anycallback.verbose=false: Iftrue, print information during initialization.rethrow_exceptions: By default, any exception ends the optimization but still returns aKrotovResultthat captures the message associated with the exception. This is to avoid losing results from a long-running optimization when an exception occurs in a later iteration. Ifrethrow_exceptions=true, instead of capturing the exception, it will be thrown normally.
Trajectory propagation
Krotov's method involves the forward and backward propagation for every Trajectory in the problem. The keyword arguments for each propagation (see propagate) are determined from any properties of each Trajectory that have a prop_ prefix, cf. init_prop_trajectory.
In situations where different parameters are required for the forward and backward propagation, instead of the prop_ prefix, the fw_prop_ and bw_prop_ prefixes can be used, respectively. These override any setting with the prop_ prefix. This applies both to the properties of each Trajectory and the problem keyword arguments.
Note that the propagation method for each propagation must be specified. In most cases, it is sufficient (and recommended) to pass a global prop_method problem keyword argument.
GRAPE
The Gradient Ascent Pulse Engineering (GRAPE) method is implemented in the GRAPE package. See the GRAPE documentation for details.
QuantumControl.optimize — Method
using GRAPE
result = optimize(problem; method=GRAPE, kwargs...)optimizes the given QuantumControl.ControlProblem using the GRAPE (Gradient-Ascent Pulse Engineering) method.
Delegates to
result = GRAPE.optimize(
problem.trajectories, problem.tlist; problem.kwargs..., kwargs...
)See GRAPE.optimize for details and supported keyword arguments.
Compared to calling GRAPE.optimize directly, the QuantumControl.optimize wrapper adds the following additional keyword arguments:
check=true: Iftrue(default), test that all the objects stored in the trajectories implement the required interfaces correctlyprint_iters=true: Whether to print information after each iteration.print_iter_info=["iter.", "J_T", "ǁ∇Jǁ", "ǁΔϵǁ", "ΔJ", "FG(F)", "secs"]: Which fields to print ifprint_iters=true. Seemake_grape_print_itersstore_iter_info=[]: Which fields to store inresult.records, given as a list of header labels, seeprint_iter_info. Seemake_grape_print_iters
These options still allow for the normal callback argument. With QuantumcControl.optimize, the callback can be a tuple of callback functions that will be combined automatically, which GRAPE.optimize only supports as single callback function.
The GRAPE optimization may also be initiated via QuantumControl.@optimize_or_load, which additionally adds checkpointing, to ensure that an optimization result is dumped to disk in case of an unexpected shutdown.
GRAPE.optimize — Function
Solve a quantum control problem, using the GRAPE method.
using GRAPE
result = GRAPE.optimize(trajectories, tlist; J_T, kwargs...)minimizes a functional
\[J(\{ϵ_{nl}\}) = J_T(\{|Ψ_k(T)⟩\}) + λ_a J_a(\{ϵ_{nl}\}) + λ_b \underbrace{\sum_k \int_{0}^{T} g_b(|Ψ_k(t)⟩)\,dt}_{% = J_b(\{|Ψ_k(t_n)⟩\})}\,,\]
via the GRAPE method, where the final time functional $J_T$ depends explicitly on the forward-propagated states $|Ψ_k(T)⟩$, where $|Ψ_k(t)⟩$ is the time evolution of the initial_state in the $k$th' element of the trajectories. The running cost $J_a$ depends explicitly on pulse values $ϵ_{nl}$ of the l'th control discretized on the n'th interval of the time grid tlist. The running cost $J_b$ depends explicitly on the propagated states $|Ψ_k(t)⟩$ in the given form of the integral over a function $g_b$. This integral is assumed to be discretized according to the trapezoidal rule, see also QuantumControl.Functionals.J_b.
GRAPE performs the minimization by calculating the gradient of the final-time functional
\[\nabla J_T \equiv \frac{\partial J_T}{\partial ϵ_{nl}} = -2 \Re \underbrace{% \underbrace{\bigg\langle χ(T) \bigg\vert \hat{U}^{(k)}_{N_T} \dots \hat{U}^{(k)}_{n+1} \bigg \vert}_{\equiv \bra{\chi(t_n)}\;\text{(bw. prop.)}} \frac{\partial \hat{U}^{(k)}_n}{\partial ϵ_{nl}} }_{\equiv \bra{χ_k^\prime(t_{n-1})}} \underbrace{\bigg \vert \hat{U}^{(k)}_{n-1} \dots \hat{U}^{(k)}_1 \bigg\vert Ψ_k(t=0) \bigg\rangle}_{\equiv |\Psi(t_{n-1})⟩\;\text{(fw. prop.)}}\,,\]
where $\hat{U}^{(k)}_n$ is the time evolution operator for the $n$ the interval, generally assumed to be $\hat{U}^{(k)}_n = \exp[-i \hat{H}_{kn} dt_n]$, where $\hat{H}_{kn}$ is the operator obtained by evaluating trajectories[k].generator on the $n$'th time interval.
The backward-propagation of $|\chi_k(t)⟩$ has the boundary condition
\[ |\chi_k(T)⟩ \equiv - \frac{\partial J_T}{\partial ⟨\Psi_k(T)|}\,.\]
When there is a state-dependent running cost $g_b(Ψ_k(t))$, the backward-propagation and boundary condition contain an additional inhomogeneous term proportional to
\[|\xi_k(t)⟩ = -\frac{\partial g_b(Ψ_k(t))}{\partial ⟨Ψ_k(t)|}\,,\]
leading to a combined gradient $\nabla J_{Tb}$ for the $J_T$ and $J_b$ terms of the functional. The final-time gradient $\nabla J_T$, respectively $\nabla J_{Tb}$, is further combined with the gradient for the running cost $J_a$, and the total gradient is then fed into an optimizer (L-BFGS-B by default) that iteratively changes the values $\{ϵ_{nl}\}$ to minimize $J$. See Background for details.
Returns a GrapeResult.
Positional arguments
trajectories: A vector ofTrajectoryobjects. Each trajectory contains aninitial_stateand a dynamicalgenerator(e.g., time-dependent Hamiltonian). Each trajectory may also contain arbitrary additional attributes liketarget_stateto be used in theJ_Tfunctionaltlist: A vector of time grid values.
Required keyword arguments
J_T: A functionJ_T(Ψ, trajectories)that evaluates the final time functional from a listΨof forward-propagated states andtrajectories. The functionJ_Tmay also take a keyword argumenttau. If it does, a vector containing the complex overlaps of the target states (target_stateproperty of each trajectory intrajectories) with the propagated states will be passed toJ_T.
Optional keyword arguments
chi: A functionchi(Ψ, trajectories)that receives a listΨof the forward propagated states and returns a vector of states $|χₖ⟩ = -∂J_T/∂⟨Ψₖ|$. If not given, it will be automatically determined fromJ_TviaQuantumControl.Functionals.make_chiwith the default parameters. Similarly toJ_T, ifchiaccepts a keyword argumenttau, it will be passed a vector of complex overlaps.chi_min_norm=1e-100: The minimum allowable norm for any $|χₖ(T)⟩$. Smaller norms would mean that the gradient is zero, and will abort the optimization with an error.J_a: A functionJ_a(pulsevals, tlist)that evaluates running costs over the pulse values, wherepulsevalsare the vectorized values $ϵ_{nl}$, wherenare in indices of the time intervals andlare the indices over the controls, i.e.,[ϵ₁₁, ϵ₂₁, …, ϵ₁₂, ϵ₂₂, …](the pulse values for each control are contiguous). If not given, the optimization will not include a running cost.gradient_method=:gradgen: One of:gradgen(default) or:taylor. Withgradient_method=:gradgen, the gradient is calculated using QuantumGradientGenerators. Withgradient_method=:taylor, it is evaluated via a Taylor series, see Eq. (20) in Kuprov and Rogers, J. Chem. Phys. 131, 234108 (2009) [17].taylor_grad_max_order=100: If given withgradient_method=:taylor, the maximum number of terms in the Taylor series. Iftaylor_grad_check_convergence=true(default), if the Taylor series does not convergence within the given number of terms, throw an error. Withtaylor_grad_check_convergence=false, this is the exact order of the Taylor series.taylor_grad_tolerance=1e-16: If given withgradient_method=:taylorandtaylor_grad_check_convergence=true, stop the Taylor series when the norm of the term falls below the given tolerance. Ignored iftaylor_grad_check_convergence=false.taylor_grad_check_convergence=true: If given astrue(default), check the convergence after each term in the Taylor series and stop as soon as the norm of the term drops below the given number. Iffalse, stop after exactlytaylor_grad_max_orderterms.lambda_a=1: A weight for the running costJ_a.grad_J_a: A function to calculate the gradient ofJ_a. If not given, it will be automatically determined. Seemake_grad_J_afor the required interface.g_b: A functiong_b(Ψ, trajectory, tlist, n) -> Float64that evaluates a per-trajectory, per-time-point state-dependent running cost, whereΨis the state $|Ψ(t)⟩$ at $t$ corresponding to the (one-based) time grid pointtlist[n], andtrajectoryis aQuantumControl.Trajectorythat may hold additional data in a custom property that is relevant to the calculation of $g_b$. The full state-dependent running cost is defined implicitly via the trapezoidal discretization described inQuantumControl.Functionals.J_b. If not given, no state-dependent running cost is used.xi: A functionxi(Ψ, trajectory, tlist, n)that evaluates the inhomogeneity in the backward propagation due to a state-dependent running cost. This inhomogeneity is $λ_b Δt_n |ξ_k(t_n)⟩$ with $|ξ_k(t_n)⟩ = -∂g_b(|Ψ_k(t_n)⟩)/∂⟨Ψ_k(t_n)|$, wherekis the index oftrajectoryin the overallproblem.trajectoriesand $t_n$ is the time grid pointtlist[n]. If not given, it will be automatically determined fromg_bviaQuantumControl.Functionals.make_xi.lambda_b=1.0: A weight for the state-dependent running costg_b.upper_bound: An upper bound for the value of any optimized control. Time-dependent upper bounds can be specified viapulse_options.lower_bound: A lower bound for the value of any optimized control. Time-dependent lower bounds can be specified viapulse_options.pulse_options: A dictionary that maps every control (as obtained byget_controlsfrom thetrajectories) to a dict with the following possible keys::upper_bounds: A vector of upper bound values, one for each interval of the time grid, or a single number for all intervals. Values ofInfindicate an unconstrained upper bound for that time interval, respectively the globalupper_bound, if given.:lower_bounds: A vector of lower bound values, one for each interval of the time grid, or a single number for all intervals. Values of-Infindicate an unconstrained lower bound for that time interval, respectively the globallower_bound, if given.
Finite values in
:upper_boundsand:lower_boundstake precedence over the globalupper_boundandlower_bound, even if they are less restrictive.callback: A function that receives the GRAPE workspace and the iteration number. It is called once for the guess, with an iteration number of 0, and then after each iteration. The guess is iteration 0 even if the optimization starts at a later iteration (iter_startorcontinue_from). In that case, the actual starting iteration iswrk.result.iter. The function may return a tuple of values which are stored in theGrapeResultobjectresult.records. The function can also mutate the workspace, in particular the updatedpulsevals. This may be used, e.g., to apply a spectral filter to the updated pulses or to perform similar manipulations. Mutatingpulsevalsis not supported for an Optim.jloptimizer.check_convergence: A function to check whether convergence has been reached. Receives aGrapeResultobjectresult, and must return one of the following:- A boolean (
trueif convergence is reached,falseotherwise) - A string with a reason for the convergence, or an empty string if not converged.
- The original
resultobject ornothing, indicating thatresult.convergedandresult.messagemay have been modified to indicate convergence
The convergence check is performed after any
callback.- A boolean (
prop_method: The propagation method to use for each trajectory, see below.iter_start=0: The initial iteration number.iter_stop=5000: The maximum iteration number. The optimization stops after this iteration. If the starting iteration (iter_start, or the last iteration ofcontinue_from) is not smaller thaniter_stop, only the guess is evaluated.continue_from: A result object from a previous optimization (aGrapeResult, or a result that can be converted to aGrapeResult). The optimization starts from the optimized controls of that result, and the iteration numbers continue from its last iteration (iter_startis ignored). AGrapeResultgiven ascontinue_fromis updated in place and returned.use_threads=false: Iftrue, propagate the different trajectories in parallel, using multiple threads.verbose=false: Iftrue, print information during initializationrethrow_exceptions: By default, any exception ends the optimization, but still returns aGrapeResultthat captures the message associated with the exception. This is to avoid losing results from a long-running optimization when an exception occurs in a later iteration. Ifrethrow_exceptions=true, instead of capturing the exception, it will be thrown normally.
Experimental keyword arguments
The following keyword arguments may change in non-breaking releases:
optimizer: An optional first-order optimizer from Optim.jl (version 2), e.g.,Optim.LBFGS(). If not given, an L-BFGS-B optimizer will be used. An explicitLBFGSB.L_BFGS_B(nmax, mmax)may also be given, wherenmaxmust be the number of control values (the number of controls times the number of time intervals), andmmaxis the number of limited memory corrections, seelbfgsb_m.lbfgsb_m: The number of limited memory corrections for the L-BFGS-B optimizer. Defaults tommaxfor an explicitLBFGSB.L_BFGS_B(nmax, mmax)optimizer, and to 10 otherwise. If given together with an explicitoptimizer, it must not exceedmmax.lbfgsb_factr=10.0,lbfgsb_pgtol=1e-15: Tolerances for the internal convergence checks of the L-BFGS-B optimizer. The defaults are chosen so thatcheck_convergencedetermines convergence. If the L-BFGS-B checks end the optimization, the result is not marked as converged.lbfgsb_iprint=-1: The verbosity of the output of the L-BFGS-B optimizer. For values greater than zero, L-BFGS-B also writes a summary of the iterations to a fileiterate.datin the current working directory.x_abstol=0.0,x_reltol=0.0,f_abstol=0.0,f_reltol=0.0,g_abstol=1e-8: Tolerances for the convergence checks of an Optim.jloptimizer, seeOptim.Options. These checks are in addition tocheck_convergence. If they end the optimization, the result is not marked as converged. The namesx_tol,f_tol, andg_tolare accepted as aliases forx_abstol,f_reltol, andg_abstol.allow_f_increases=false: Whether an Optim.jloptimizercontinues after an iteration that increases the value of the functional. Note that the default differs from that ofOptim.Options. If the optimization stops because of an increase, the result is for that last iteration, not for the iteration with the smallest value of the functional.show_trace=false,extended_trace=false,show_every=1: Options for printing the trace of an Optim.jloptimizer, seeOptim.Options.
Trajectory propagation
GRAPE may involve three types of time propagation, all of which are implemented via the QuantumPropagators as a numerical backend:
- A forward propagation for every
Trajectoryin thetrajectories - A backward propagation for every trajectory
- A backward propagation of a gradient generator for every trajectory.
The keyword arguments for each propagation (see propagate) are determined from any properties of each Trajectory and any keyword arguments that have a prop_ prefix, cf. init_prop_trajectory.
In situations where different parameters are required for the forward and backward propagation, instead of the prop_ prefix, the fw_prop_ and bw_prop_ prefixes can be used, respectively. Similarly, parameters for the backward propagation of the gradient generators can be set with a grad_prop_ prefix (in addition to bw_prop_, which applies to both backward propagations).
If the same parameter is set in more than one way, the following rules determine which setting is used:
- Any keyword argument (including the keyword arguments of the
probleminQuantumControl.optimize) that applies to a propagation overrides any property of aTrajectoryfor that propagation, regardless of the prefix. - Among the keyword arguments, and among the properties of a
Trajectory, afw_prop_,bw_prop_, orgrad_prop_prefix overrides theprop_prefix, and thegrad_prop_prefix overrides thebw_prop_prefix.
For example, a prop_method keyword argument overrides a fw_prop_method property of a Trajectory.
Note that the propagation method for each propagation must be specified. In most cases, it is sufficient (and recommended) to pass a global prop_method keyword argument. Since this overrides any per-trajectory setting, use trajectory properties instead if different trajectories require different propagation methods. GRAPE requires a piecewise propagation method (see init_prop); other methods are rejected.